Files
2026-11-22 14:20:34 +00:00

86 lines
2.8 KiB
TypeScript

import { query } from "./db";
type Recipient = { emailAddress?: string; email_address?: string };
export type SesEvent = {
eventType: string;
mail?: { messageId?: string; destination?: string[] };
bounce?: { bounceType?: string; bouncedRecipients?: Recipient[] };
complaint?: { complainedRecipients?: Recipient[] };
};
function recipientsOf(event: SesEvent): string[] {
const list = event.bounce?.bouncedRecipients ?? event.complaint?.complainedRecipients ?? [];
const fromEvent = list
.map((item) => item.emailAddress ?? item.email_address ?? "")
.filter(Boolean)
.map((value) => value.toLowerCase());
if (fromEvent.length) return fromEvent;
return (event.mail?.destination ?? []).map((value) => value.toLowerCase());
}
export async function handleSesNotification(message: string, snsMessageId: string): Promise<void> {
let event: SesEvent;
try {
event = JSON.parse(message) as SesEvent;
} catch {
return;
}
const providerId = event.mail?.messageId;
if (!providerId) return;
const { rows } = await query<{ id: string; status: string }>(
`select id, status from messages where provider_message_id = $1 limit 1`,
[providerId],
);
const messageId = rows[0]?.id ?? null;
const inserted = await query(
`insert into message_events (message_id, sns_message_id, type, payload)
values ($1,$2,$3,$4)
on conflict (sns_message_id) do nothing
returning id`,
[messageId, snsMessageId, event.eventType, event],
);
if (!inserted.rows[0] || !messageId) return;
let next: string | null = null;
if (event.eventType === "Delivery") next = "delivered";
if (event.eventType === "Bounce") next = "bounced";
if (event.eventType === "Complaint") next = "complained";
if (event.eventType === "Reject") next = "failed";
if (!next) return;
await query(
`update messages
set status = case
when status in ('complained','bounced') then status
when $2 = 'complained' then 'complained'
when $2 = 'bounced' then 'bounced'
when $2 = 'delivered' then 'delivered'
when $2 = 'failed' and status <> 'delivered' then 'failed'
else status
end,
completed_at = case
when $2 in ('delivered','bounced','complained','failed') then now()
else completed_at
end
where id = $1`,
[messageId, next],
);
const permanent = event.eventType === "Complaint" || event.bounce?.bounceType === "Permanent";
if (permanent) {
const recipients = recipientsOf(event);
if (recipients.length) {
await query(
`insert into suppressions (email, reason)
select unnest($1::text[]), $2
on conflict (email) do update set reason = excluded.reason`,
[recipients, event.eventType === "Complaint" ? "complaint" : "hard_bounce"],
);
}
}
}