Cotton code
360 lines · 21.1 KB · TypeScriptRaw
/** * MAIL FETCH AS A JOB, the object's half (JOBS OUT 1, assets/design/shared/JOBS-OUT.md; the job's half is * src/jobs/mail_job.ts). Behind the per-account switch `mail_jobs` (PUT /v1/admin/business, admin token): on, the * object's alarm no longer reads any mailbox; it schedules a run on the JOBS queue and answers the run's short calls * at its door. Off (the default), Cotton's fetcher runs on the alarm as before (src/mail/fetcher.ts). * * THE JOB ROW (`mail_fetch_job`, one a mailbox): `gen`, new each time the mailbox is given or the switch thrown on * (a credential names it, so an old one opens nothing once the mailbox is removed or given again); `run` and * `lease_until`, the one run that may call the door now (a second delivery of the same message is told busy); * `due_at`, when the next run was asked for; `sent_at`, when it was put on the queue. * * WHO SCHEDULES. Only this object: when the mailbox is given, when a run ends (its `end` call says how it went and * the object decides when the next comes), and the alarm's watchdog (a run that never ended, a message the queue * dropped). The job never schedules itself and never mints a credential. */import type { Env } from "../env.ts";import { refuse, Refused } from "../http.ts";import type { MailJobMessage } from "../jobs/mail_job.ts";import { JOB_SCHEME, mintJobToken, openJobToken, usableKey } from "../jobs/token.ts";import * as fetch from "./fetch.ts";import { sealValueAtArrival } from "../arrival.ts";import { CARRY_ON_MS, cursorOf, EVERY_MS, pendTrash, type FetcherHost } from "./fetcher.ts";export const SCHEMA = "CREATE TABLE IF NOT EXISTS mail_fetch_job (account TEXT PRIMARY KEY, gen TEXT NOT NULL, run TEXT, lease_until INTEGER, due_at INTEGER, sent_at INTEGER, nonce TEXT);";/** The most a JSON call to the door may carry, and an `arrive` (a message of at most 25 MiB, as own-domain mail). */export const JSON_MOST = 64 * 1024;export const ARRIVE_MOST = 25 * 1024 * 1024 + 64 * 1024;/** The account's switch, in meta. */export const SWITCH = "mail_jobs";/** A run holds the mailbox this long at most (a queue consumer runs 15 minutes). */export const LEASE_MS = 16 * 60_000;/** A run asked for and not begun this long after its time is asked for again by the watchdog. */export const OVERDUE_MS = 10 * 60_000;/** A credential lives this long past the run's time. */const TOKEN_SLACK_MS = 20 * 60_000;/** The watchdog's alarm comes at least this often while the switch is on and a mailbox is held. */export const WATCH_EVERY_MS = 15 * 60_000;export interface JobHost extends FetcherHost {  slug: string;  /** The owner's arrival public key, or null before a phone handed it: what a skipped message's name is sealed to. */  arrivalPub?(): Uint8Array | null;  /** Whether the account's switch is on. */  on(): boolean;}interface JobRow {  account: string;  gen: string;  run: string | null;  lease_until: number | null;  due_at: number | null;  sent_at: number | null;  /** The one scheduled message a run may begin with: used up by `begin`, replaced by the next schedule. */  nonce: string | null;}function row(sql: SqlStorage, account: string): JobRow | null {  const r = sql.exec<{ account: string; gen: string; run: string | null; lease_until: SqlStorageValue; due_at: SqlStorageValue; sent_at: SqlStorageValue; nonce: string | null }>("SELECT account, gen, run, lease_until, due_at, sent_at, nonce FROM mail_fetch_job WHERE account = ?", account).toArray()[0];  if (!r) return null;  const n = (v: SqlStorageValue) => (v === null ? null : Number(v));  return { account: String(r.account), gen: String(r.gen), run: r.run === null ? null : String(r.run), lease_until: n(r.lease_until), due_at: n(r.due_at), sent_at: n(r.sent_at), nonce: r.nonce === null ? null : String(r.nonce) };}/** What the switch needs to be thrown on: the queue and the key that signs a job's credential. */export function ready(env: Env): string | null {  if (!env.JOBS) return "this Worker has no JOBS queue bound";  if (!usableKey(env.JOB_TOKEN_KEY)) return "this Worker holds no JOB_TOKEN_KEY";  return null;}/** A new generation for a mailbox: every earlier credential for it opens nothing from now on. */export function renew(sql: SqlStorage, account: string): void {  sql.exec("INSERT INTO mail_fetch_job (account, gen, run, lease_until, due_at, sent_at) VALUES (?, ?, NULL, NULL, NULL, NULL) ON CONFLICT (account) DO UPDATE SET gen = excluded.gen, run = NULL, lease_until = NULL, due_at = NULL, sent_at = NULL, nonce = NULL", account, crypto.randomUUID());}/** The mailbox removed (or the switch thrown off): its row goes, and with it every credential for it. */export function drop(sql: SqlStorage, account: string | null): void {  if (account === null) sql.exec("DELETE FROM mail_fetch_job");  else sql.exec("DELETE FROM mail_fetch_job WHERE account = ?", account);}/** The columns a later build added, the additive way, to a table an earlier build made (JOBS OUT 3, L-a). */export function ensureColumns(sql: SqlStorage): void {  const have = new Set(sql.exec<{ name: string }>("PRAGMA table_info(mail_fetch_job)").toArray().map((c) => c.name));  if (!have.has("nonce")) sql.exec("ALTER TABLE mail_fetch_job ADD COLUMN nonce TEXT");}/** * The message a run is scheduled with: its credential minted here, for this generation alone. Its nonce is the one * waiting to be used (JOBS OUT 3, M-a): a watchdog re-send of a late message carries the same nonce, so whichever copy * the queue delivers first begins the run and the other is told busy or gone; only `fresh` (a run's end, or a mailbox * with no nonce waiting) mints a new one, which the copies before it cannot use. */export async function message(host: JobHost, account: string, delayMs: number, fresh = false): Promise<MailJobMessage> {  const r = row(host.sql, account) ?? refuse(404, "no_job", "no job is held for this mailbox");  const nonce = !fresh && r.nonce ? r.nonce : crypto.randomUUID();  if (nonce !== r.nonce) host.sql.exec("UPDATE mail_fetch_job SET nonce = ? WHERE account = ?", nonce, r.account);  const token = await mintJobToken(host.env.JOB_TOKEN_KEY, { v: 1, slug: host.slug, kind: "mail_fetch", account, gen: r.gen, nonce, exp: host.now() + delayMs + TOKEN_SLACK_MS });  return { kind: "mail_fetch", slug: host.slug, account, token };}/** Put the mailbox's next run on the queue, `delayMs` from now. A queue that refuses is logged; the watchdog asks again. */export async function schedule(host: JobHost, account: string, delayMs: number, fresh = false): Promise<boolean> {  if (!row(host.sql, account)) renew(host.sql, account);  const due = host.now() + delayMs;  host.sql.exec("UPDATE mail_fetch_job SET due_at = ? WHERE account = ?", due, account);  try {    const queue = host.env.JOBS ?? refuse(503, "jobs_unavailable", "no JOBS queue");    await queue.send(await message(host, account, delayMs, fresh), { delaySeconds: Math.min(Math.ceil(Math.max(0, delayMs) / 1000), 86_400) });    host.sql.exec("UPDATE mail_fetch_job SET sent_at = ? WHERE account = ?", host.now(), account);    return true;  } catch (error) {    console.log(`cottondb: job mail_fetch ${host.slug} not sent: ${error instanceof Error ? error.message : String(error)}`);    return false;  }}/** * The alarm's watchdog, with the switch on: every mailbox that should be read and has no live run and no run asked * for in time is scheduled now. Answers when the watchdog wants to look again (ms), or null with no mailbox held. */export async function watchdog(host: JobHost): Promise<number | null> {  const held = fetch.accounts(host.sql).filter((a) => a.state !== "refused" && a.state !== "stopped");  const now = host.now();  for (const a of held) {    const r = row(host.sql, a.account);    const leased = r?.run && (r.lease_until ?? 0) > now;    const overdue = !r || r.due_at === null || r.sent_at === null || now > r.due_at + OVERDUE_MS;    if (!leased && overdue) await schedule(host, a.account, 0);  }  return held.length ? WATCH_EVERY_MS : null;}/** What `GET /v1/mail/fetch/state` adds while the switch is on: the path, the next run's time, a run's lease. */export function stateOf(sql: SqlStorage, account: string): { path: "job"; due_at: string | null; run_until: string | null } | null {  const r = row(sql, account);  if (!r) return null;  const iso = (n: number | null) => (n === null ? null : new Date(n).toISOString());  return { path: "job", due_at: iso(r.due_at), run_until: r.run ? iso(r.lease_until) : null };}// ── the door ───────────────────────────────────────────────────────────/** The job's credential, opened and checked against this object: its slug, the switch, the mailbox's generation. */async function admit(host: JobHost, request: Request): Promise<{ account: string; row: JobRow; held: fetch.Held; nonce: string }> {  const header = request.headers.get("authorization") ?? "";  const claim = await openJobToken(host.env.JOB_TOKEN_KEY, header.slice(JOB_SCHEME.length), host.now());  // A step job's credential (JOBS OUT M1, C1) opens nothing at the mail door.  if (!claim || claim.slug !== host.slug || claim.kind !== "mail_fetch") refuse(401, "job_credential", "this credential opens nothing here");  // From here on the credential is genuine: a refusal says the job is not wanted any more (410), and it stops.  const r = row(host.sql, claim.account);  if (!r || r.gen !== claim.gen) refuse(410, "job_gone", "this mailbox was removed or given again");  const held = fetch.held(host.sql, claim.account);  if (!held || held.state === "refused" || held.state === "stopped") refuse(410, "job_gone", "this mailbox is not read");  return { account: claim.account, row: r, held, nonce: claim.nonce };}function sameRun(host: JobHost, r: JobRow, run: unknown): void {  if (typeof run !== "string" || r.run !== run || (r.lease_until ?? 0) <= host.now()) refuse(410, "job_gone", "this run no longer holds the mailbox");}/** The body, read a chunk at a time and refused the moment it passes `most` bytes. */async function capped(request: Request, most: number, step: string): Promise<Uint8Array> {  if (!request.body) return new Uint8Array(0);  const reader = request.body.getReader();  const parts: Uint8Array[] = [];  let size = 0;  for (;;) {    const { done, value } = await reader.read();    if (done) break;    size += value.byteLength;    if (size > most) {      await reader.cancel().catch(() => undefined);      refuse(413, "too_large", `a job's ${step} carries at most ${most} bytes`);    }    parts.push(value);  }  const out = new Uint8Array(size);  let at = 0;  for (const p of parts) {    out.set(p, at);    at += p.byteLength;  }  return out;}function parsed(raw: Uint8Array): Record<string, unknown> {  try {    const b = JSON.parse(new TextDecoder().decode(raw)) as unknown;    return b && typeof b === "object" ? (b as Record<string, unknown>) : {};  } catch {    refuse(400, "bad_request", "a JSON body");  }}const STEPS = new Set(["begin", "arrive", "cursor", "skipped", "alive", "end"]);/** A message to Trash the run is to move, by the mailbox's UIDVALIDITY. */function pendingTrash(sql: SqlStorage, account: string): { validity: number; uid: number }[] {  return sql.exec<{ validity: number; uid: number }>("SELECT validity, uid FROM mail_fetch_trash WHERE account = ? ORDER BY uid", account).toArray().map((r) => ({ validity: Number(r.validity), uid: Number(r.uid) }));}/** A skipped message's UID and message id, sealed at arrival for the log (src/mail/fetch.ts `ref`); null with no arrival key. */async function sealedRef(host: JobHost, uid: number, msgid: string | null): Promise<{ id: string; sealed: string } | null> {  const pub = host.arrivalPub?.() ?? null;  if (!pub) return null;  const id = crypto.randomUUID();  return { id, sealed: await sealValueAtArrival(pub, host.databaseId, `mail_fetch_log:${id}`, JSON.stringify({ uid, msgid })) };}/** * `POST /v1/jobs/mail/<step>`: the job's door. Every answer is short; nothing here waits on a mail server. Nothing is * read of the body until the call is known to be a job's (its scheme, the switch, its declared length, then its * credential); a call refused before that has its body cancelled unread. */export async function door(host: JobHost, request: Request, step: string): Promise<unknown> {  try {    return await doorIn(host, request, step);  } catch (error) {    try {      if (request.body && !request.bodyUsed) await request.body.cancel();    } catch {      // already read, or gone    }    throw error;  }}/** The door's answer where no account object reads mail by jobs: the same 410 as a switch thrown off, nothing read. */export async function shut(env: { JOB_TOKEN_KEY?: string }, request: Request, step: string): Promise<never> {  try {    if (request.body && !request.bodyUsed) await request.body.cancel();  } catch {    // already gone  }  precheck(request, step);  // AUDIT F, F2: a credential that is not genuine is refused as a real door refuses it.  if (!(await openJobToken(env.JOB_TOKEN_KEY, (request.headers.get("authorization") ?? "").slice(JOB_SCHEME.length), Date.now()))) refuse(401, "job_credential", "this credential opens nothing here");  refuse(410, "job_gone", "this account reads its mail on its own object now");}/** What every door call is asked first, wherever it lands: a POST, a step the door has, the job's scheme. */function precheck(request: Request, step: string): void {  if (request.method !== "POST") refuse(405, "method_not_allowed", "a job's call is a POST");  if (!STEPS.has(step)) refuse(404, "not_found", "no such job call");  if (!(request.headers.get("authorization") ?? "").startsWith(JOB_SCHEME)) refuse(401, "job_credential", "a job's call carries its credential");}async function doorIn(host: JobHost, request: Request, step: string): Promise<unknown> {  precheck(request, step);  // The credential opened first (AUDIT F, F1): only a genuine one for this object learns whether mail jobs are on.  // Off, the door is then shut: answered at once, nothing read.  const claim = await openJobToken(host.env.JOB_TOKEN_KEY, (request.headers.get("authorization") ?? "").slice(JOB_SCHEME.length), host.now());  if (!claim || claim.slug !== host.slug || claim.kind !== "mail_fetch") refuse(401, "job_credential", "this credential opens nothing here");  if (!host.on()) refuse(410, "job_gone", "this account reads its mail on its own object now");  const most = step === "arrive" ? ARRIVE_MOST : JSON_MOST;  const said = request.headers.get("content-length");  if (said !== null && !(Number(said) <= most)) refuse(413, "too_large", `a job's ${step} carries at most ${most} bytes`);  const { account, row: r, held, nonce } = await admit(host, request);  // Read only now, and never past `most`, whatever the length said.  const raw = await capped(request, most, step);  const bytes = step === "arrive" ? raw : null;  const b = step === "arrive" ? {} : parsed(raw);  const now = host.now();  if (step === "begin") {    if (r.run && (r.lease_until ?? 0) > now) refuse(409, "job_busy", "another run holds this mailbox");    // Only the latest scheduled message begins a run, and only once.    if (!r.nonce || r.nonce !== nonce) refuse(410, "job_gone", "this message was already run, or another replaced it");    const run = crypto.randomUUID();    host.sql.exec("UPDATE mail_fetch_job SET run = ?, lease_until = ?, nonce = NULL WHERE account = ?", run, now + LEASE_MS, account);    fetch.setState(host, account, "live");    const sealed = fetch.passwordEnc(host.sql, account) ?? refuse(410, "job_gone", "this mailbox is not read");    const password = await fetch.openPassword(host.env, host.databaseId, account, sealed);    return { run, address: held.address, host: held.host, port: held.port, password, cursor: held.cursor, trash: pendingTrash(host.sql, account) };  }  if (step === "arrive") {    const raw = request.headers.get("cotton-job-meta") ?? "";    let meta: Record<string, unknown>;    try {      meta = JSON.parse(decodeURIComponent(raw)) as Record<string, unknown>;    } catch {      refuse(400, "bad_request", "cotton-job-meta: the message's place, as JSON");    }    sameRun(host, r, meta.run);    const cursor = typeof meta.cursor === "string" ? cursorOf(meta.cursor) : null;    const uid = Number(meta.uid);    const validity = Number(meta.validity);    if (!cursor || !Number.isInteger(uid) || !Number.isInteger(validity) || typeof meta.box !== "string" || (meta.side !== "new" && meta.side !== "history")) refuse(400, "bad_request", "cotton-job-meta: run, uid, side, box, validity, cursor");    // A sender on this account's own list (an unsubscribe with no one-click): to Trash, not kept (as src/mail/fetcher.ts).    if (meta.side === "new" && typeof meta.from === "string" && meta.from) {      const blocked = host.sql.exec("SELECT 1 FROM mail_fetch_blocked WHERE account = ? AND mark = ?", account, await fetch.senderMark(host.env, host.databaseId, account, meta.from)).toArray().length > 0;      if (blocked) {        // Kept until the run says it moved it (`end`'s `trashed`), so a run cut short leaves it for the next.        pendTrash(host.sql, account, validity, uid, now);        fetch.setCursor(host.sql, account, JSON.stringify(cursor));        return { kept: "trash", trash: true };      }    }    const received = Number.isFinite(Number(meta.received)) ? Number(meta.received) : now;    let arrived: Awaited<ReturnType<FetcherHost["arrive"]>>;    try {      arrived = await host.arrive(bytes!, held.address, received, meta.fetched as Parameters<FetcherHost["arrive"]>[3]);    } catch (error) {      // A message the object will not keep (too large): logged as the alarm's fetcher logs a failure, moved past, and      // the run carries on. Anything else (no arrival key yet) is answered to the run, which ends and comes again.      if (error instanceof Refused && error.code === "too_large") {        fetch.log(host, account, "failed", 0, "too_large", await sealedRef(host, uid, typeof meta.msgid === "string" ? meta.msgid : null));        fetch.setCursor(host.sql, account, JSON.stringify(cursor));        return { kept: "too_large", trash: false };      }      throw error;    }    if (arrived.email) host.sql.exec("INSERT INTO mail_fetch_index (account, email_id, box, validity, uid, msgid) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (account, email_id) DO UPDATE SET box = excluded.box, validity = excluded.validity, uid = excluded.uid, msgid = excluded.msgid", account, arrived.email, meta.box, validity, uid, typeof meta.msgid === "string" ? meta.msgid : null);    fetch.setCursor(host.sql, account, JSON.stringify(cursor));    return { kept: arrived.kept, trash: false };  }  sameRun(host, r, b.run);  if (step === "cursor") {    const cursor = typeof b.cursor === "string" ? cursorOf(b.cursor) : null;    if (!cursor) refuse(400, "bad_request", "cursor: { box, validity, high, low }");    fetch.setCursor(host.sql, account, JSON.stringify(cursor));    return { ok: true };  }  // A message the door refused whole (413: its body ran past the cap though the server said it was smaller): the run  // moves past it and says so, and it is logged by name (sealed), as a message too large to keep is (JOBS OUT 3, L-c).  if (step === "skipped") {    const cursor = typeof b.cursor === "string" ? cursorOf(b.cursor) : null;    const uid = Number(b.uid);    if (!cursor || !Number.isInteger(uid)) refuse(400, "bad_request", "skipped: run, uid, msgid, cursor");    fetch.log(host, account, "failed", 0, "too_large", await sealedRef(host, uid, typeof b.msgid === "string" ? b.msgid : null));    fetch.setCursor(host.sql, account, JSON.stringify(cursor));    return { ok: true };  }  if (step === "alive") return { ok: true };  if (step === "end") {    const refused = b.state === "refused";    const count = Number.isInteger(b.count) && (b.count as number) >= 0 ? (b.count as number) : 0;    const code = typeof b.code === "string" && /^[a-z_]{1,40}$/.test(b.code) ? b.code : null;    host.sql.exec("UPDATE mail_fetch_job SET run = NULL, lease_until = NULL WHERE account = ?", account);    // What the run moved to Trash leaves the pending list.    if (Array.isArray(b.trashed)) for (const t of b.trashed as { validity?: unknown; uid?: unknown }[]) if (Number.isInteger(t?.validity) && Number.isInteger(t?.uid)) host.sql.exec("DELETE FROM mail_fetch_trash WHERE account = ? AND validity = ? AND uid = ?", account, t.validity as number, t.uid as number);    if (refused) {      fetch.setState(host, account, "refused", true);      fetch.log(host, account, "failed", 0, "refused");      return { next_ms: null };    }    fetch.setState(host, account, "idle", true);    if (code) fetch.log(host, account, "failed", count, code);    else if (count) fetch.log(host, account, "fetched", count, null);    // A failure waits the usual five minutes; history left carries on soon; a run that held IDLE to its end comes again at once.    const next = code ? EVERY_MS : b.more === true ? CARRY_ON_MS : b.watched === true ? 0 : EVERY_MS;    // A run's end mints the next nonce: copies scheduled before it begin nothing.    await schedule(host, account, next, true);    return { next_ms: next };  }  refuse(404, "not_found", "no such job call");}