/** * THE WORKER'S `email` HANDLER (OWN-MAIL.md "Receiving"): Cloudflare's Email * Routing hands every message sent to a person's own domain here (the * domain's catch-all rule, "send to a Worker"). * * 1. The Directory says whose domain it is; none, and the message is refused * with a permanent error the sender sees ("No such mailbox here"). * 2. The person's object says whether the address is theirs and where a copy * also goes (stage 1: their present mailbox). * 3. The copy goes first, before anything of ours can fail. * 4. The object keeps the message sealed at arrival (src/mail/mail.ts). * * When keeping fails after the copy went, the message is safe in the present * mailbox and the handler ends quietly (the object counted it). When it fails * with no copy, the handler throws: what Cloudflare then tells the sender is * not stated in its documentation, and is measured on dev before forwarding * ever stops. */import { directory } from"../directory.ts";importtype { Env } from"../env.ts";import { addressOf, domainOf } from"./mail.ts";exportconst NO_SUCH_MAILBOX = "No such mailbox here";exportasyncfunction receive(message: ForwardableEmailMessage, env: Env): Promise<void> {const to = addressOf(message.to);if (!to) return message.setReject(NO_SUCH_MAILBOX);const slug = await directory(env).mailDomainOf(domainOf(to));if (!slug) return message.setReject(NO_SUCH_MAILBOX);const object = env.BUSINESS.get(env.BUSINESS.idFromName(slug), { locationHint: "apac" });const plan = await object.mailPlan(to);if (!plan.accept) return message.setReject(NO_SUCH_MAILBOX);const raw = newUint8Array(awaitnewResponse(message.raw).arrayBuffer());let forwarded: "ok" | "failed" | "none" = "none";if (plan.forwardTo) {try {await message.forward(plan.forwardTo); forwarded = "ok"; } catch (error) { forwarded = "failed"; console.error("mail: the copy to the present mailbox did not go", { slug, code: (error as { code?: string }).code ?? null }); } }try {await object.mailArrive({ raw, to, forwarded, received: Date.now() }); } catch (error) {if (forwarded === "ok") { console.error("mail: kept nowhere in Cotton, but its copy went to the present mailbox", { slug, error: String(error) });return; }throw error; }}