/** * MAIL FETCH AS A JOB (JOBS OUT 1, assets/design/shared/JOBS-OUT.md): one run of Cotton's fetcher for one mailbox, * beside the account object instead of inside its alarm. It holds the IMAP connection (and, when the mailbox is up * to date, IDLE on it for a window); the object only answers short calls at its door: * * POST /v1/jobs/mail/begin {} → { run, address, host, port, password, cursor } * POST /v1/jobs/mail/arrive raw message, meta header → { kept, trash } (one message, kept as today) * POST /v1/jobs/mail/cursor { run, cursor } → { ok } (a message skipped: too large or gone) * POST /v1/jobs/mail/alive { run } → { ok } (between IDLE slices: still wanted?) * POST /v1/jobs/mail/end { run, state, count, code, more, watched } → { next_ms } * * Every call carries the job's credential (src/jobs/token.ts) and nothing else. The job holds no key of the * Worker's: the door hands it this one mailbox's password for this run, and keeping a message (sealing it to the * arrival key, its rows, its file) is the object's, exactly as own-domain mail is. The job reads no row back. * * Imports: the IMAP client and the pure helpers alone. Never the object, its store or a binding (a test says so). */ import { fromAddress, headerBlock } from "../mail/acts.ts"; import { cursorOf, factsOf, MAX_BYTES, type Cursor } from "../mail/fetcher.ts"; import { Imap, ImapError, type Dial } from "../mail/imap.ts"; import { JOB_SCHEME } from "./token.ts"; export interface MailJobMessage { kind: "mail_fetch"; slug: string; account: string; token: string; } export function isMailJob(body: unknown): body is MailJobMessage { const b = body as Partial | null; return !!b && b.kind === "mail_fetch" && typeof b.slug === "string" && typeof b.account === "string" && typeof b.token === "string"; } /** Everything a run is given: the object's door, a socket, and its clock. Nothing else. */ export interface MailJobDeps { /** One request at the account object's door, as a phone's goes (src/index.ts `front`). */ door(slug: string, path: string, init: RequestInit): Promise; dial: Dial; now?: () => number; /** How long a run reads before it stops and asks to carry on (default READ_FOR_MS). */ readForMs?: number; /** How long a run holds IDLE once up to date (default IDLE_WINDOW_MS). */ idleWindowMs?: number; /** IDLE is held in slices this long, the door asked between them whether the mailbox is still wanted. */ sliceMs?: number; } /** A queue consumer may run 15 minutes of wall time: reading stops at 9, so IDLE and the end still fit. */ export const READ_FOR_MS = 9 * 60_000; /** Messages one run reads at most, new and history together. */ export const PER_RUN = 2000; /** IDLE once up to date (Gmail ends an IDLE after about 29 minutes). */ export const IDLE_WINDOW_MS = 4 * 60_000; /** Removing the password reaches a run in IDLE within this. */ export const SLICE_MS = 60_000; /** Wall time a run may use in all (Queues: 15 minutes per consumer invocation). */ const RUN_LIMIT_MS = 14 * 60_000; const CHUNK = 10; const HISTORY_WINDOW = 2000; const LOOPBACK = "127.0.0.1"; /** ran: the run went (well or not) and the object was told; busy: another run holds the mailbox; gone: the door refused the credential. */ export type MailJobOutcome = "ran" | "busy" | "gone"; class Refused extends Error { readonly status: number; readonly code: string; constructor(status: number, code: string) { super(`the door answered ${status} ${code}`); this.status = status; this.code = code; } /** The door no longer takes this run: its credential, the switch, the mailbox or the account went. */ get gone(): boolean { return this.status === 401 || this.status === 410; } } async function refusedBy(r: Response): Promise { const said = (await r.json().catch(() => ({}))) as { code?: unknown }; return new Refused(r.status, typeof said.code === "string" && /^[a-z_]{1,40}$/.test(said.code) ? said.code : "refused"); } /** One run. Throws only when the object could not be told how it ended (the queue retries it). */ export async function runMailJob(d: MailJobDeps, m: MailJobMessage): Promise { const now = d.now ?? (() => Date.now()); const started = now(); const auth = { authorization: `${JOB_SCHEME}${m.token}` }; const call = async (path: string, body: unknown): Promise => { const r = await d.door(m.slug, path, { method: "POST", headers: { ...auth, "content-type": "application/json" }, body: JSON.stringify(body) }); if (r.status >= 500) throw new Error(`the door answered ${r.status}`); if (!r.ok) throw await refusedBy(r); return (await r.json()) as T; }; const readFor = d.readForMs ?? READ_FOR_MS; /** Whether this run has read as long as it may: it stops, ends cleanly, and the next run carries on. */ const late = () => now() - started >= readFor; let cut = false; let begun: { run: string; address: string; host: string; port: number; password: string; cursor: string | null; trash?: { validity: number; uid: number }[] }; try { begun = await call("/v1/jobs/mail/begin", {}); } catch (e) { if (e instanceof Refused) return e.status === 409 && e.code === "job_busy" ? "busy" : "gone"; throw e; } const run = begun.run; let count = 0; /** What this run moved to Trash (or found stale), for `end` to take off the object's pending list. */ const trashed: { validity: number; uid: number }[] = []; let more = false; let watched = false; let code: string | null = null; let state = "idle" as "idle" | "refused"; let imap: Imap | null = null; try { imap = await Imap.open(await d.dial(begun.host, begun.port, begun.host !== LOOPBACK)); try { await imap.login(begun.address, begun.password); } catch (e) { if (e instanceof ImapError && e.kind === "no") { state = "refused"; code = "refused"; throw e; } throw e; } const gmail = imap.gmail; const box = gmail ? ((await imap.special("\\All")) ?? "INBOX") : "INBOX"; const selected = await imap.select(box, true); let c: Cursor | null = cursorOf(begun.cursor); if (!c || c.box !== box || c.validity !== selected.uidvalidity) { const top = selected.uidnext !== null ? selected.uidnext - 1 : Math.max(0, ...(await imap.search("ALL"))); c = { box, validity: selected.uidvalidity, high: top, low: top + 1 }; await call("/v1/jobs/mail/cursor", { run, cursor: JSON.stringify(c) }); } const cur = c; const toTrash: number[] = []; // Left to move by the alarm's fetcher or an earlier run (JOBS OUT 3, L-b): this mailbox's now, or stale (renumbered). for (const t of begun.trash ?? []) { if (t.validity === cur.validity) toTrash.push(t.uid); else trashed.push(t); } const conn = imap; const keep = async (uids: number[], side: "new" | "history") => { for (let i = 0; i < uids.length; i += CHUNK) { if (late()) { cut = true; return; } const chunk = uids.slice(i, i + CHUNK); const meta = new Map((await conn.fetch(chunk, false)).map((x) => [x.uid, x])); for (const uid of chunk) { const x = meta.get(uid); if (side === "new") cur.high = Math.max(cur.high, uid); else cur.low = Math.min(cur.low, uid); const cursor = JSON.stringify(cur); const whole = x && (x.size ?? 0) <= MAX_BYTES ? (await conn.fetch([uid], true))[0] : undefined; if (!whole?.body) { // Gone since the search, or too large: moved past, never read again. await call("/v1/jobs/mail/cursor", { run, cursor }); continue; } // Only the sender's address goes in the meta, and only for new mail: the door checks it against the // account's own list (a keyed mark; the job holds no key) and says whether it goes to Trash instead. const from = side === "new" ? fromAddress(headerBlock(whole.body)) : null; const said = { run, uid, side, box, validity: cur.validity, received: whole.internal ?? now(), fetched: factsOf(whole, gmail), msgid: whole.msgid ?? null, from, cursor }; const r = await d.door(m.slug, "/v1/jobs/mail/arrive", { method: "POST", headers: { ...auth, "content-type": "message/rfc822", "cotton-job-meta": encodeURIComponent(JSON.stringify(said)) }, body: whole.body }); if (r.status >= 500) throw new Error(`the door answered ${r.status}`); if (r.status === 413) { // Its body ran past the door's cap though the server called it smaller: moved past, named in the log // (JOBS OUT 3, L-c), and the run carries on. await r.body?.cancel(); await call("/v1/jobs/mail/skipped", { run, uid, msgid: whole.msgid ?? null, cursor }); continue; } if (!r.ok) throw await refusedBy(r); const answer = (await r.json()) as { kept: string; trash: boolean }; if (answer.trash) toTrash.push(uid); else if (answer.kept !== "too_large") count++; } } }; const readNew = async (budget: number) => { const fresh = (await conn.search(`UID ${cur.high + 1}:*`)).filter((u) => u > cur.high).slice(0, budget); await keep(fresh, "new"); return fresh.length; }; let budget = PER_RUN - (await readNew(PER_RUN)); while (budget > 0 && cur.low > 1 && !late()) { const from = Math.max(1, cur.low - HISTORY_WINDOW); const older = (await conn.search(`UID ${from}:${cur.low - 1}`)).filter((u) => u < cur.low).reverse().slice(0, Math.min(budget, 200)); if (!older.length) { cur.low = from; await call("/v1/jobs/mail/cursor", { run, cursor: JSON.stringify(cur) }); continue; } await keep(older, "history"); budget -= older.length; } more = cur.low > 1 || cut; const trash = async () => { if (!toTrash.length) return; // Opened to be written for this alone; never expunged. const uses = await conn.uses(); const where = uses.trash ?? (gmail ? "[Gmail]/Trash" : null); if (where && (conn.capabilities.has("MOVE") || gmail)) { await conn.select(box); await conn.move(toTrash.join(","), where, !conn.capabilities.has("MOVE")); await conn.select(box, true); } // Moved, or on a server that cannot move without erasing (as the alarm's fetcher leaves those): off the list. for (const uid of toTrash) trashed.push({ validity: cur.validity, uid }); toTrash.length = 0; }; await trash(); // Up to date: IDLE for a window, in slices, reading at once when the server says new mail exists. if (!more && !late()) { const end = Math.min(now() + (d.idleWindowMs ?? IDLE_WINDOW_MS), started + RUN_LIMIT_MS); const slice = d.sliceMs ?? SLICE_MS; watched = true; while (now() < end) { const woke = await conn.idle(Math.min(slice, end - now())); if (woke) { await readNew(PER_RUN); await trash(); if (cut) { more = true; break; } } if (now() >= end) break; await call("/v1/jobs/mail/alive", { run }); } } // LOGOUT closes the connection itself. imap = null; await conn.logout(); } catch (e) { if (e instanceof Refused && e.gone) { // The door no longer takes this run (the mailbox removed, the switch off, the account deleted): stop, tell nobody. imap?.close(); imap = null; return "gone"; } if (e instanceof Refused) { // The object would not keep a message for now (no arrival key yet, a bad call): the run ends and says why, and the // object logs it and asks for the next run in the usual five minutes. code = e.code; } else if (state !== "refused") { // Never the server's words: they may name the mailbox. Only the kind. const said = (e as { code?: unknown }).code; code = e instanceof ImapError ? e.kind : typeof said === "string" && /^[a-z_]{1,40}$/.test(said) ? said : "error"; } watched = false; } finally { imap?.close(); } try { await call("/v1/jobs/mail/end", { run, state, count, code, more, watched, trashed }); } catch (e) { if (e instanceof Refused) return "gone"; throw e; } return "ran"; }