fix race condition by setting email id (#188)

This commit is contained in:
KM Koushik
2025-07-26 22:25:38 +10:00
committed by GitHub
parent dc625bdbb6
commit 6fd258b282
3 changed files with 32 additions and 1 deletions

View File

@@ -123,6 +123,7 @@ export async function sendRawEmail({
unsubUrl, unsubUrl,
isBulk, isBulk,
inReplyToMessageId, inReplyToMessageId,
emailId,
}: Partial<EmailContent> & { }: Partial<EmailContent> & {
region: string; region: string;
configurationSetName: string; configurationSetName: string;
@@ -134,6 +135,7 @@ export async function sendRawEmail({
unsubUrl?: string; unsubUrl?: string;
isBulk?: boolean; isBulk?: boolean;
inReplyToMessageId?: string; inReplyToMessageId?: string;
emailId?: string;
}) { }) {
const sesClient = getSesClient(region); const sesClient = getSesClient(region);
@@ -155,6 +157,7 @@ export async function sendRawEmail({
bcc, bcc,
headers: { headers: {
"X-Entity-Ref-ID": nanoid(), "X-Entity-Ref-ID": nanoid(),
...(emailId ? { "X-Unsend-Email-ID": emailId } : {}),
...(unsubUrl ...(unsubUrl
? { ? {
"List-Unsubscribe": `<${unsubUrl}>`, "List-Unsubscribe": `<${unsubUrl}>`,

View File

@@ -381,6 +381,7 @@ async function executeEmail(job: QueueEmailJob) {
unsubUrl, unsubUrl,
isBulk, isBulk,
inReplyToMessageId, inReplyToMessageId,
emailId: email.id,
}); });
logger.info( logger.info(

View File

@@ -32,12 +32,39 @@ export async function parseSesHook(data: SesEvent) {
const mailData = getEmailData(data); const mailData = getEmailData(data);
const email = await db.email.findUnique({ let email = await db.email.findUnique({
where: { where: {
sesEmailId, sesEmailId,
}, },
}); });
// Handle race condition: If email not found by sesEmailId, try to find by custom header
if (!email) {
const emailIdHeader = data.mail.headers.find(
(h) => h.name === "X-Unsend-Email-ID"
);
if (emailIdHeader?.value) {
email = await db.email.findUnique({
where: {
id: emailIdHeader.value,
},
});
// If found, update the sesEmailId to fix the missing reference
if (email) {
await db.email.update({
where: { id: email.id },
data: { sesEmailId },
});
logger.info(
{ emailId: email.id, sesEmailId },
"Updated email with sesEmailId from webhook (race condition resolved)"
);
}
}
}
logger.setBindings({ logger.setBindings({
sesEmailId, sesEmailId,
mailId: email?.id, mailId: email?.id,