39 lines · 1.5 KB · TypeScriptRaw
/** * Cloudflare's word on mail it sent (OWN-MAIL.md "Bounces and complaints"): * the sending domain's `message.bounced`, `message.failed` and * `message.complained` events, delivered to a Queue this Worker consumes. * Each names the mail's message id; the Directory says whose it was, and the * person's object keeps the word beside the draft's ledger row. */import { directory } from "../directory.ts";import type { Env } from "../env.ts";export interface SendingEvent { type: string; payload: { messageId?: string; recipient?: string; bounce?: { type?: string; reason?: string }; delivery?: { smtpResponse?: string } };}export function deliveryOf(type: string): "bounced" | "complained" | "failed" | "delivered" | null { const kind = type.replace(/^cf\.email\.sending\.message\./, ""); return kind === "bounced" || kind === "complained" || kind === "failed" || kind === "delivered" ? kind : null;}export async function sendingEvents(batch: MessageBatch<SendingEvent>, env: Env): Promise<void> { for (const m of batch.messages) { const event = m.body; const delivery = deliveryOf(event?.type ?? ""); const id = event?.payload?.messageId; if (!delivery || !id) { m.ack(); continue; } const slug = await directory(env).mailSentOf(id); if (!slug) { m.ack(); continue; } const words = event.payload.bounce?.reason ?? event.payload.delivery?.smtpResponse ?? null; await env.BUSINESS.get(env.BUSINESS.idFromName(slug), { locationHint: "apac" }).mailDelivered(id, delivery, words); m.ack(); }}