Cotton code
568 lines · 36.4 KB · TypeScriptRaw
/** * JOBS OUT 1 (src/jobs/mail_job.ts, src/mail/fetch_job.ts, assets/design/shared/JOBS-OUT.md): with the account's * switch on, a mailbox is read by a job beside the account object, which reaches the object only through its door * with its own credential. Invented mailboxes, passwords and mail only; the IMAP server is the in-memory fake. */import { env, runInDurableObject, SELF } from "cloudflare:test";import { describe, expect, it } from "vitest";import * as accountDelete from "../src/account_delete.ts";import type { Business } from "../src/business.ts";import type { Dial, Wire } from "../src/mail/imap.ts";import { runMailJob, type MailJobMessage } from "../src/jobs/mail_job.ts";import { consume } from "../src/jobs/run.ts";import { senderMark } from "../src/mail/fetch.ts";import { DATABASE_ID } from "./personal.ts";import wranglerSource from "../wrangler.jsonc?raw";import { mintJobToken } from "../src/jobs/token.ts";import { FakeImap, type FakeMessage } from "./fake-imap.ts";import mailJobSource from "../src/jobs/mail_job.ts?raw";import runSource from "../src/jobs/run.ts?raw";import tokenSource from "../src/jobs/token.ts?raw";import { ADMIN, http, personalObject } from "./personal.ts";const stub = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug));const PASSWORD = "invented-app-password-heron-2290";const ACCOUNT = "acct-job";const ADDRESS = "mira@example.test";function note(uid: number, words: string): FakeMessage {  const raw = [`From: Orrin <orrin@example.org>`, `To: Mira <${ADDRESS}>`, `Subject: Note ${uid}`, "Date: Mon, 5 Oct 2026 09:30:00 +0000", `Message-ID: <note.${uid}@example.org>`, "MIME-Version: 1.0", "Content-Type: text/plain; charset=utf-8", "", words, ""].join("\r\n");  return { uid, raw, flags: [], msgid: String(1790000000000000000n + BigInt(uid)), labels: ["\\Inbox"] };}function server(count: number): FakeImap {  return new FakeImap({ gmail: true, user: ADDRESS, password: PASSWORD })    .box("INBOX", { validity: 7, messages: [] })    .box("[Gmail]/All Mail", { validity: 9, flags: ["\\HasNoChildren", "\\All"], messages: Array.from({ length: count }, (_, i) => note(i + 1, `Invented note number ${i + 1}.`)) });}/** The door, as the queue's consumer reaches it: through the front Worker, on /b/<slug>/…. */const door = (slug: string, path: string, init: RequestInit) => SELF.fetch(`https://jobs.internal/b/${slug}${path}`, init);async function given(slug: string, jobs: boolean, arrival = true): Promise<Record<string, string>> {  const { credential } = await personalObject(slug, { arrival });  const phone = { authorization: `Bearer ${credential}` };  if (jobs) {    const on = await http(slug, "PUT", "/v1/admin/business", { mail_jobs: "on" }, ADMIN);    expect(on.status, JSON.stringify(on.body)).toBe(200);  }  const r = await http(slug, "POST", "/v1/mail/fetch", { account: ACCOUNT, address: ADDRESS, host: "imap.example.test", port: 993, password: PASSWORD }, phone);  expect(r.status, JSON.stringify(r.body)).toBe(200);  return phone;}const messageOf = (slug: string, account = ACCOUNT) => runInDurableObject(stub(slug), (instance: Business) => instance.mailJobMessage(account));const jobRow = (slug: string) => runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<Record<string, SqlStorageValue>>("SELECT * FROM mail_fetch_job").toArray());const emails = (slug: string) => runInDurableObject(stub(slug), (_i, state) => Number(state.storage.sql.exec("SELECT count(*) AS n FROM rows WHERE table_id = 'email'").one().n));const quick = { idleWindowMs: 0, sliceMs: 50 };describe("mail fetch as a job beside the account object", { timeout: 120_000 }, () => {  it("is switched per account by the coordinator alone, and the switch says what it needs", async () => {    const slug = "mail-job-switch";    const { credential } = await personalObject(slug, { arrival: true });    const owner = await http(slug, "PUT", "/v1/admin/business", { mail_jobs: "on" }, { authorization: `Bearer ${credential}` });    expect(owner.status).toBe(403);    expect((await http(slug, "PUT", "/v1/admin/business", { mail_jobs: "yes" }, ADMIN)).status).toBe(400);    expect((await http(slug, "PUT", "/v1/admin/business", { mail_jobs: "on" }, ADMIN)).status).toBe(200);    expect((await http(slug, "PUT", "/v1/admin/business", { mail_jobs: null }, ADMIN)).status).toBe(200);  });  it("reads the mailbox through the door: sealed rows, the cursor, the log, and the next run scheduled by the object", async () => {    const slug = "mail-job-read";    const phone = await given(slug, true);    // Giving the mailbox scheduled its first run on the queue.    const [first] = await jobRow(slug);    expect(first).toMatchObject({ account: ACCOUNT });    expect(first!.sent_at).not.toBeNull();    const fake = server(5);    expect(await runMailJob({ door, dial: fake.dial, ...quick }, await messageOf(slug))).toBe("ran");    expect(await emails(slug)).toBe(5);    expect(fake.said).toContain("EXAMINE [Gmail]/All Mail");    expect(fake.said.join("\n")).not.toContain(PASSWORD);    expect(fake.closed).toBe(fake.opened);    const st = await http<Record<string, unknown>>(slug, "GET", `/v1/mail/fetch/state?account=${ACCOUNT}`, undefined, phone);    expect(st.body).toMatchObject({ state: "idle", path: "job", run_until: null });    const log = await http<{ log: { kind: string; count: number }[] }>(slug, "GET", `/v1/mail/fetch/log?account=${ACCOUNT}`, undefined, phone);    expect(log.body.log[0]).toMatchObject({ kind: "fetched", count: 5 });    // The object scheduled the next: it held IDLE to its window's end, so at once.    const [after] = await jobRow(slug);    expect(Number(after!.due_at)).toBeLessThanOrEqual(Date.now());    expect(after!.run).toBeNull();    // New mail since: the next run reads only that; a message already kept keeps nothing more.    fake.deliver("[Gmail]/All Mail", note(6, "A sixth invented note."));    expect(await runMailJob({ door, dial: fake.dial, ...quick }, await messageOf(slug))).toBe("ran");    expect(await emails(slug)).toBe(6);  });  it("hears new mail in IDLE and reads it in the same run", async () => {    const slug = "mail-job-idle";    await given(slug, true);    const fake = server(1);    const run = runMailJob({ door, dial: fake.dial, idleWindowMs: 1500, sliceMs: 200 }, await messageOf(slug));    // Once the run is in IDLE, mail arrives.    for (let i = 0; i < 100 && !fake.said.some((c) => /IDLE/.test(c)); i++) await new Promise((r) => setTimeout(r, 20));    fake.deliver("[Gmail]/All Mail", note(2, "Arrived while idling."));    expect(await run).toBe("ran");    expect(await emails(slug)).toBe(2);  });  it("opens nothing with a credential for another account, an old giving, an expired claim, or with the switch off", async () => {    const slug = "mail-job-refused";    const phone = await given(slug, true);    const good = await messageOf(slug);    const begin = (m: MailJobMessage, headers?: Record<string, string>) => door(m.slug, "/v1/jobs/mail/begin", { method: "POST", headers: headers ?? { authorization: `CottonJob ${m.token}`, "content-type": "application/json" }, body: "{}" });    // No credential, a phone's credential, a forged one, one for another object.    expect((await begin(good, { "content-type": "application/json" })).status).toBe(401);    expect((await begin(good, { ...phone, "content-type": "application/json" })).status).toBe(401);    const forged = await mintJobToken("some-other-key-that-is-long-enough-000000", { v: 1, slug, kind: "mail_fetch", account: ACCOUNT, gen: "x", nonce: "x", exp: Date.now() + 60_000 });    expect((await begin({ ...good, token: forged })).status).toBe(401);    expect((await begin({ ...good, slug: "mail-job-read" })).status).toBe(401);    // Expired (signed with the right key).    const gen = String((await jobRow(slug))[0]!.gen);    const expired = await mintJobToken(env.JOB_TOKEN_KEY, { v: 1, slug, kind: "mail_fetch", account: ACCOUNT, gen, nonce: "x", exp: Date.now() - 1 });    expect((await begin({ ...good, token: expired })).status).toBe(401);    // The password the door hands a run goes only to a run that holds the mailbox; a second delivery is told busy.    const r1 = await begin(good);    expect(r1.status).toBe(200);    const b1 = (await r1.json()) as { run: string; password: string };    expect(b1.password).toBe(PASSWORD);    expect((await begin(good)).status).toBe(409);    // Removed and given again: the old credential is gone (410), the run's calls too.    expect((await http(slug, "DELETE", "/v1/mail/fetch", { account: ACCOUNT }, phone)).status).toBe(200);    expect((await begin(good)).status).toBe(410);    await http(slug, "POST", "/v1/mail/fetch", { account: ACCOUNT, address: ADDRESS, host: "imap.example.test", port: 993, password: PASSWORD }, phone);    expect((await begin(good)).status).toBe(410);    expect((await door(slug, "/v1/jobs/mail/alive", { method: "POST", headers: { authorization: `CottonJob ${good.token}`, "content-type": "application/json" }, body: JSON.stringify({ run: b1.run }) })).status).toBe(410);    // The switch off: even a fresh credential is told the job is not wanted, and the run stops quietly.    const fresh = await messageOf(slug);    expect((await http(slug, "PUT", "/v1/admin/business", { mail_jobs: null }, ADMIN)).status).toBe(200);    expect((await begin(fresh)).status).toBe(410);    expect(await runMailJob({ door, dial: server(1).dial, ...quick }, fresh)).toBe("gone");    expect(await emails(slug)).toBe(0);  });  it("stops a run in IDLE once the mailbox is removed, and a refused password stops the mailbox", async () => {    const slug = "mail-job-stop";    const phone = await given(slug, true);    const fake = server(1);    const run = runMailJob({ door, dial: fake.dial, idleWindowMs: 60_000, sliceMs: 100 }, await messageOf(slug));    for (let i = 0; i < 100 && !fake.said.some((c) => /IDLE/.test(c)); i++) await new Promise((r) => setTimeout(r, 20));    await http(slug, "DELETE", "/v1/mail/fetch", { account: ACCOUNT }, phone);    expect(await run).toBe("gone");    expect(fake.closed).toBe(fake.opened);    await http(slug, "POST", "/v1/mail/fetch", { account: ACCOUNT, address: ADDRESS, host: "imap.example.test", port: 993, password: "not-the-password" }, phone);    expect(await runMailJob({ door, dial: fake.dial, ...quick }, await messageOf(slug))).toBe("ran");    const st = await http<Record<string, unknown>>(slug, "GET", `/v1/mail/fetch/state?account=${ACCOUNT}`, undefined, phone);    expect(st.body).toMatchObject({ state: "refused" });    // A refused mailbox is not scheduled again, and its credential opens nothing until it is given again.    expect((await door(slug, "/v1/jobs/mail/begin", { method: "POST", headers: { authorization: `CottonJob ${(await messageOf(slug)).token}`, "content-type": "application/json" }, body: "{}" })).status).toBe(410);  });  // A measurement for the report, never a gate (JOBS OUT 2): HEAVY=1 runs it; it asserts nothing about time.  it.runIf((env as unknown as { HEAVY?: string }).HEAVY === "1")("answers sync and frees the alarm while a long fetch runs beside it (and says how the old path did)", async () => {    // A slow mail server: every answer it sends comes 15 ms late; 30 messages of history wait, then IDLE for 4 s.    const WINDOW = 4000;    const slowly = (fake: FakeImap): Dial => async (h, p, t) => {      const wire: Wire = await fake.dial(h, p, t);      return { write: (b) => wire.write(b), read: async () => (await new Promise((r) => setTimeout(r, 15)), wire.read()), close: () => wire.close() };    };    /** A phone's pull, as phones pull: from the version it last saw. */    const puller = (slug: string, phone: Record<string, string>) => {      let since = 0;      return async () => {        const t = Date.now();        const r = await SELF.fetch(`https://example.test/b/${slug}/v1/sync?since=${since}`, { headers: phone });        const b = (await r.json()) as { version: number };        expect(r.status).toBe(200);        since = b.version;        return Date.now() - t;      };    };    const said = (times: number[]) => {      const t = [...times].sort((a, b) => a - b);      return t.length ? { n: t.length, median: t[t.length >> 1]!, p90: t[Math.floor(t.length * 0.9)]!, worst: t[t.length - 1]! } : { n: 0 };    };    /** Pulls every 25 ms while `work` runs, split by whether the server was in IDLE; and the alarm's time, once IDLE began. */    const watch = async (slug: string, fake: FakeImap, pull: () => Promise<number>, work: Promise<unknown>, alarm: boolean) => {      let done = false;      void work.finally(() => (done = true));      const reading: number[] = [];      const idling: number[] = [];      let alarmMs: number | null = null;      while (!done) {        const idle = fake.said.some((c) => /IDLE/.test(c));        (idle ? idling : reading).push(await pull());        if (idle && alarm && alarmMs === null) {          const t = Date.now();          await runInDurableObject(stub(slug), (instance: Business) => instance.alarm());          alarmMs = Date.now() - t;        }        await new Promise((r) => setTimeout(r, 25));      }      await work;      return { reading: said(reading), idling: said(idling), alarmMs };    };    const settle = async (slug: string, pull: () => Promise<number>) => {      // A new object's first answers carry its kit, its first alarm and the engines' first passes: let them go.      for (let i = 0; i < 5; i++) await pull();      await runInDurableObject(stub(slug), (instance: Business) => instance.alarm());      for (let i = 0; i < 5; i++) await pull();    };    // The job beside the object.    const slug = "mail-job-sync";    const phone = await given(slug, true);    const pull = puller(slug, phone);    await settle(slug, pull);    const jobFake = server(30);    const job = await watch(slug, jobFake, pull, runMailJob({ door, dial: slowly(jobFake), idleWindowMs: WINDOW, sliceMs: 1000 }, await messageOf(slug)), true);    expect(await emails(slug)).toBe(30);    // The same mailbox read the old way, on the object: the alarm's pass, then its IDLE window (as alarmPass runs them).    const old = "mail-job-sync-old";    const oldPhone = await given(old, false);    const oldPull = puller(old, oldPhone);    await settle(old, oldPull);    const oldFake = server(30);    const t = Date.now();    const inside = await watch(old, oldFake, oldPull, runInDurableObject(stub(old), async (instance: Business) => {      await instance.fetchMailPass(slowly(oldFake));      await instance.fetchMailWatch(slowly(oldFake), WINDOW);    }), false);    const oldAlarmMs = Date.now() - t;    expect(await emails(old)).toBe(30);    console.log(`JOBS OUT 1 pulls (ms) as a job: reading ${JSON.stringify(job.reading)}, idling ${JSON.stringify(job.idling)}, the alarm took ${job.alarmMs} ms during the job's IDLE; on the object: reading ${JSON.stringify(inside.reading)}, idling ${JSON.stringify(inside.idling)}, the alarm's mail part held ${oldAlarmMs} ms`);    expect(job.alarmMs).not.toBeNull();  }, 240_000);  it("an account marked for deletion opens no door to its job, and schedules nothing", async () => {    const slug = "mail-job-deleted";    await given(slug, true);    const m = await messageOf(slug);    // The deletion's own row, as POST /v1/account/delete leaves it (src/account_delete.ts): pending, thirty days.    await runInDurableObject(stub(slug), (_i, state) => {      state.storage.sql.exec(accountDelete.SCHEMA);      state.storage.sql.exec("INSERT INTO account_delete (id, phase, started_at, by, database_id, slug, owner_phone, tries, receipt, erase_at) VALUES (1, 'pending', ?, 'app', NULL, ?, NULL, 0, '{}', ?)", new Date().toISOString(), slug, new Date(Date.now() + 86_400_000).toISOString());    });    const sent = Number((await jobRow(slug))[0]!.sent_at);    expect(await runMailJob({ door, dial: server(2).dial, ...quick }, m)).toBe("gone");    expect(await emails(slug)).toBe(0);    expect(Number((await jobRow(slug))[0]!.sent_at)).toBe(sent);  });  it("the object's watchdog asks again for a run that never began", async () => {    const slug = "mail-job-watchdog";    await given(slug, true);    await runInDurableObject(stub(slug), (_i, state) => void state.storage.sql.exec("UPDATE mail_fetch_job SET due_at = ?, sent_at = ?", Date.now() - 3_600_000, Date.now() - 3_600_000));    const before = Number((await jobRow(slug))[0]!.sent_at);    await runInDurableObject(stub(slug), (instance: Business) => instance.alarm());    const after = await jobRow(slug);    expect(Number(after[0]!.sent_at)).toBeGreaterThan(before);    expect(Number(after[0]!.due_at)).toBeGreaterThan(Date.now() - 60_000);  });  it("job code reaches no object, store or binding: only its door", () => {    for (const [file, text] of Object.entries({ mail_job: mailJobSource as string, run: runSource as string, token: tokenSource as string })) {      const imports = [...text.matchAll(/from "([^"]+)"/g)].map((m) => m[1]);      for (const i of imports) expect(["../mail/acts.ts", "../mail/fetcher.ts", "../mail/imap.ts", "./token.ts", "./mail_job.ts", "./step_job.ts"], `${file} imports ${i}`).toContain(i);      expect(text, file).not.toMatch(/env\.(BUSINESS|MEDIA|DIRECTORY|JOB_TOKEN_KEY|MAIL_FETCH_KEY)|SqlStorage|storage\./);    }  });});// ── JOBS OUT 2: the reviewer's findings, and the cases found missing ──const auth = (m: MailJobMessage) => ({ authorization: `CottonJob ${m.token}` });const call = (m: MailJobMessage, step: string, body: BodyInit, headers: Record<string, string> = {}) => door(m.slug, `/v1/jobs/mail/${step}`, { method: "POST", headers: { ...auth(m), "content-type": "application/json", ...headers }, body });const logOf = async (slug: string, phone: Record<string, string>) => (await http<{ log: { kind: string; count: number; code: string | null }[] }>(slug, "GET", `/v1/mail/fetch/log?account=${ACCOUNT}`, undefined, phone)).body.log;/** A queue message as the consumer is handed it, its ack and retry counted. */function queued(body: unknown) {  const said: { acked: number; retried: number[] } = { acked: 0, retried: [] };  const message = { id: crypto.randomUUID(), timestamp: new Date(), attempts: 1, body, ack: () => void said.acked++, retry: (o?: { delaySeconds?: number }) => void said.retried.push(o?.delaySeconds ?? -1) };  return { said, batch: { queue: "cotton-dev-jobs", messages: [message], ackAll() {}, retryAll() {} } as unknown as MessageBatch<unknown> };}describe("JOBS OUT 2: the door, refusals, and the run's chain", () => {  it("M1: reads no byte before the call is a job's, shuts with the switch off, and caps what it reads", async () => {    const slug = "mail-job-door-cap";    await given(slug, true);    const m = await messageOf(slug);    const big = new Uint8Array(1024 * 1024);    // No scheme: refused, the body never read.    expect((await door(slug, "/v1/jobs/mail/arrive", { method: "POST", headers: { "content-type": "message/rfc822" }, body: big })).status).toBe(401);    // A declared length past the cap: refused before the credential is opened.    expect((await call(m, "begin", "{}", { "content-length": String(1024 * 1024) })).status).toBe(413);    // A streamed body with no length that runs past the cap: refused at the cap.    const stream = new ReadableStream<Uint8Array>({ start(c) { for (let i = 0; i < 4; i++) c.enqueue(new Uint8Array(32 * 1024)); c.close(); } });    expect((await door(slug, "/v1/jobs/mail/begin", { method: "POST", headers: auth(m), body: stream, duplex: "half" } as RequestInit)).status).toBe(413);    // The switch off: the door answers at once, unread, whatever the credential.    expect((await http(slug, "PUT", "/v1/admin/business", { mail_jobs: null }, ADMIN)).status).toBe(200);    expect((await door(slug, "/v1/jobs/mail/arrive", { method: "POST", headers: { ...auth(m), "content-type": "message/rfc822" }, body: big })).status).toBe(410);  }, 120_000);  it("M2: a message too large is logged and skipped, and the run carries on", async () => {    const slug = "mail-job-too-large";    const phone = await given(slug, true);    const m = await messageOf(slug);    const begun = (await (await call(m, "begin", "{}")).json()) as { run: string };    const meta = (uid: number) => encodeURIComponent(JSON.stringify({ run: begun.run, uid, side: "history", box: "INBOX", validity: 1, received: Date.now(), fetched: { labels: [], flags: [], inbox: true }, msgid: null, from: null, cursor: JSON.stringify({ box: "INBOX", validity: 1, high: 5, low: uid }) }));    const tooBig = new Uint8Array(25 * 1024 * 1024 + 10);    const r = await call(m, "arrive", tooBig, { "content-type": "message/rfc822", "cotton-job-meta": meta(4) });    expect(r.status).toBe(200);    expect(await r.json()).toEqual({ kept: "too_large", trash: false });    expect((await logOf(slug, phone))[0]).toMatchObject({ kind: "failed", code: "too_large" });    // Moved past: the cursor says so, and the run still holds the mailbox.    const st = await runInDurableObject(stub(slug), (_i, state) => String(state.storage.sql.exec("SELECT cursor FROM mail_fetch_account").one().cursor));    expect(JSON.parse(st)).toMatchObject({ low: 4 });    expect((await call(m, "alive", JSON.stringify({ run: begun.run }))).status).toBe(200);  }, 120_000);  it("M2: with no arrival key yet, the run ends, says why, frees the mailbox and comes again in five minutes", async () => {    const slug = "mail-job-no-key";    const phone = await given(slug, true, false);    const fake = server(2);    expect(await runMailJob({ door, dial: fake.dial, ...quick }, await messageOf(slug))).toBe("ran");    expect(await emails(slug)).toBe(0);    expect((await logOf(slug, phone))[0]).toMatchObject({ kind: "failed", code: "no_arrival_key" });    const [r] = await jobRow(slug);    expect(r!.run).toBeNull();    expect(Number(r!.due_at)).toBeGreaterThan(Date.now() + 4 * 60_000);    expect(fake.closed).toBe(fake.opened);    const st = await http<Record<string, unknown>>(slug, "GET", `/v1/mail/fetch/state?account=${ACCOUNT}`, undefined, phone);    expect(st.body).toMatchObject({ state: "idle" });  }, 120_000);  it("L2: one scheduled message begins one run: a second delivery, or a message the next schedule replaced, begins nothing", async () => {    const slug = "mail-job-once";    await given(slug, true);    const fake = server(1);    const m = await messageOf(slug);    expect(await runMailJob({ door, dial: fake.dial, ...quick }, m)).toBe("ran");    // The same message delivered again after the run ended: gone, nothing dialled.    const dials = fake.dials;    expect(await runMailJob({ door, dial: fake.dial, ...quick }, m)).toBe("gone");    expect(fake.dials).toBe(dials);    // A watchdog's re-send carries the nonce still waiting (JOBS OUT 3, M-a): whichever copy comes first begins, the    // other is told busy; once that run ends, its end mints the next nonce and both copies begin nothing.    const first = await messageOf(slug);    const resent = await messageOf(slug);    const begun = await call(resent, "begin", "{}");    expect(begun.status).toBe(200);    expect((await call(first, "begin", "{}")).status).toBe(409);    const run = ((await begun.json()) as { run: string }).run;    expect((await call(resent, "end", JSON.stringify({ run, state: "idle", count: 0, code: null, more: false, watched: false }))).status).toBe(200);    expect((await call(first, "begin", "{}")).status).toBe(410);    expect((await call(resent, "begin", "{}")).status).toBe(410);  }, 120_000);  it("L3: a run that reaches its time stops reading, ends cleanly and asks to carry on soon", async () => {    const slug = "mail-job-budget";    await given(slug, true);    const fake = server(30);    expect(await runMailJob({ door, dial: fake.dial, ...quick, readForMs: 0 }, await messageOf(slug))).toBe("ran");    const [r] = await jobRow(slug);    expect(r!.run).toBeNull();    // More is left: the next run within seconds, not five minutes, and IDLE was not held.    expect(Number(r!.due_at)).toBeLessThan(Date.now() + 60_000);    expect(fake.said.some((c) => /IDLE/.test(c))).toBe(false);    expect(await runMailJob({ door, dial: fake.dial, ...quick }, await messageOf(slug))).toBe("ran");    expect(await emails(slug)).toBe(30);  }, 120_000);  it("a lease past its time lets a new run begin, and the old run's calls are refused", async () => {    const slug = "mail-job-lease";    await given(slug, true);    const first = await messageOf(slug);    const a = (await (await call(first, "begin", "{}")).json()) as { run: string };    await runInDurableObject(stub(slug), (_i, state) => void state.storage.sql.exec("UPDATE mail_fetch_job SET lease_until = ?", Date.now() - 1));    const second = await messageOf(slug);    const b = await call(second, "begin", "{}");    expect(b.status).toBe(200);    expect((await call(first, "alive", JSON.stringify({ run: a.run }))).status).toBe(410);  }, 120_000);  it("L1: the switch thrown on while the alarm's fetcher holds IDLE closes it at once", async () => {    const slug = "mail-job-flip";    await given(slug, false);    const fake = server(1);    await runInDurableObject(stub(slug), (instance: Business) => instance.fetchMailPass(fake.dial));    const started = Date.now();    const watching = runInDurableObject(stub(slug), (instance: Business) => instance.fetchMailWatch(fake.dial, 120_000));    for (let i = 0; i < 200 && !fake.said.some((c) => /IDLE/.test(c)); i++) await new Promise((r) => setTimeout(r, 20));    expect((await http(slug, "PUT", "/v1/admin/business", { mail_jobs: "on" }, ADMIN)).status).toBe(200);    await watching;    // Ended by the switch, far inside its two-minute window (a closed socket ends IDLE; nothing waits for the window).    expect(Date.now() - started).toBeLessThan(60_000);    expect(fake.closed).toBe(fake.opened);    // And the job reads on from where the alarm's fetcher left the cursor: nothing twice.    fake.deliver("[Gmail]/All Mail", note(2, "After the switch."));    expect(await runMailJob({ door, dial: fake.dial, ...quick }, await messageOf(slug))).toBe("ran");    expect(await emails(slug)).toBe(2);  }, 120_000);  it("a new UIDVALIDITY reads the mailbox again from the top, keeping nothing twice", async () => {    const slug = "mail-job-validity";    await given(slug, true);    const fake = server(3);    expect(await runMailJob({ door, dial: fake.dial, ...quick }, await messageOf(slug))).toBe("ran");    expect(await emails(slug)).toBe(3);    fake.boxes.get("[Gmail]/All Mail")!.validity = 10;    expect(await runMailJob({ door, dial: fake.dial, ...quick }, await messageOf(slug))).toBe("ran");    expect(await emails(slug)).toBe(3);    const cursor = await runInDurableObject(stub(slug), (_i, state) => String(state.storage.sql.exec("SELECT cursor FROM mail_fetch_account").one().cursor));    expect(JSON.parse(cursor)).toMatchObject({ validity: 10, low: 1 });  }, 120_000);  it("new mail from a sender on the account's own list goes to Trash, unkept", async () => {    const slug = "mail-job-blocked";    await given(slug, true);    const fake = server(1).box("[Gmail]/Trash", { validity: 11, flags: ["\\HasNoChildren", "\\Trash"], messages: [] });    expect(await runMailJob({ door, dial: fake.dial, ...quick }, await messageOf(slug))).toBe("ran");    const mark = await senderMark(env, DATABASE_ID, ACCOUNT, "orrin@example.org");    await runInDurableObject(stub(slug), (_i, state) => void state.storage.sql.exec("INSERT INTO mail_fetch_blocked (account, mark, at) VALUES (?, ?, ?)", ACCOUNT, mark, Date.now()));    fake.deliver("[Gmail]/All Mail", note(2, "Unwanted."));    expect(await runMailJob({ door, dial: fake.dial, ...quick }, await messageOf(slug))).toBe("ran");    expect(await emails(slug)).toBe(1);    expect(fake.boxes.get("[Gmail]/Trash")!.messages.some((x) => x.uid === 2 || x.raw.includes("note.2@"))).toBe(true);  }, 120_000);  it("the real consumer: a run acknowledged, a lost end retried in a minute, a stranger message dropped; retries and the dead letters configured", async () => {    const slug = "mail-job-consume";    await given(slug, true);    const fake = server(2);    const front = (request: Request) => SELF.fetch(request);    const ok = queued(await messageOf(slug));    await consume(ok.batch, front, "dev", fake.dial, quick);    expect(ok.said).toEqual({ acked: 1, retried: [] });    expect(await emails(slug)).toBe(2);    // The object could not be told how the run ended (it answered 500 to `end`): retried, not acknowledged.    const lost = queued(await messageOf(slug));    const failing = async (request: Request) => (new URL(request.url).pathname.endsWith("/end") ? new Response("{}", { status: 500 }) : SELF.fetch(request));    await consume(lost.batch, failing, "dev", fake.dial, quick);    expect(lost.said).toEqual({ acked: 0, retried: [60] });    const stranger = queued({ kind: "something_else" });    await consume(stranger.batch, front, "dev", fake.dial, quick);    expect(stranger.said.acked).toBe(1);    // After max_retries a message goes to the dead letters (Cloudflare's, by this config); the watchdog asks again either way.    for (const q of ["cotton-jobs", "cotton-dev-jobs"]) expect(wranglerSource as string).toMatch(new RegExp(`"queue": "${q}", "max_batch_size": 1,[^}]*"max_retries": 5,[^}]*"dead_letter_queue": "${q}-dead"`));  }, 120_000);});// ── JOBS OUT 3 ──describe("JOBS OUT 3: late delivery, the old pass letting go, a refused body, the stranger, the log", () => {  it("M-a: a message delivered after the watchdog re-sent it still begins the run, and the re-sent copy begins nothing more", async () => {    const slug = "mail-job-late";    await given(slug, true);    const late = await messageOf(slug);    // The queue lags: the run is ten minutes late, and the watchdog sends again.    await runInDurableObject(stub(slug), (_i, state) => void state.storage.sql.exec("UPDATE mail_fetch_job SET due_at = ?, sent_at = ?", Date.now() - 3_600_000, Date.now() - 3_600_000));    await runInDurableObject(stub(slug), (instance: Business) => instance.alarm());    expect(Number((await jobRow(slug))[0]!.sent_at)).toBeGreaterThan(Date.now() - 60_000);    const resent = await messageOf(slug);    // The late copy arrives first: it begins (its nonce was not replaced), and reads.    const fake = server(2);    expect(await runMailJob({ door, dial: fake.dial, ...quick }, late)).toBe("ran");    expect(await emails(slug)).toBe(2);    expect(await runMailJob({ door, dial: fake.dial, ...quick }, resent)).toBe("gone");  }, 120_000);  it("L-a: a table an earlier build made gains the new columns, and the door answers", async () => {    const slug = "mail-job-columns";    await given(slug, true);    await runInDurableObject(stub(slug), (_i, state) => {      state.storage.sql.exec("DROP TABLE mail_fetch_job");      state.storage.sql.exec("CREATE TABLE mail_fetch_job (account TEXT PRIMARY KEY, gen TEXT NOT NULL, run TEXT, lease_until INTEGER, due_at INTEGER, sent_at INTEGER)");      state.storage.sql.exec("INSERT INTO mail_fetch_job (account, gen) VALUES (?, ?)", ACCOUNT, "old-gen");    });    // A fresh instance runs the start-up again (as a deploy does).    await runInDurableObject(stub(slug), (_i, state) => state.abort("restart")).catch(() => undefined);    const m = await messageOf(slug);    expect((await call(m, "begin", "{}")).status).toBe(200);  }, 120_000);  it("L-b: the switch thrown mid-pass stops the alarm's pass before its next message and before any new login; its Trash moves go to the job", async () => {    const slug = "mail-job-midpass";    await given(slug, false);    const fake = server(20).box("[Gmail]/Trash", { validity: 11, flags: ["\\HasNoChildren", "\\Trash"], messages: [] });    // A pass reading slowly; the switch goes on part way through.    const slow: Dial = async (h, p, t) => {      const wire: Wire = await fake.dial(h, p, t);      return { write: (b) => wire.write(b), read: async () => (await new Promise((r) => setTimeout(r, 10)), wire.read()), close: () => wire.close() };    };    const pass = runInDurableObject(stub(slug), (instance: Business) => instance.fetchMailPass(slow));    for (let i = 0; i < 400 && (await emails(slug)) < 3; i++) await new Promise((r) => setTimeout(r, 25));    expect((await http(slug, "PUT", "/v1/admin/business", { mail_jobs: "on" }, ADMIN)).status).toBe(200);    await pass.catch(() => undefined);    const stoppedAt = await emails(slug);    expect(stoppedAt).toBeLessThan(20);    // No new login after the switch: another pass or watch does not dial.    const dials = fake.dials;    await runInDurableObject(stub(slug), (instance: Business) => instance.fetchMailPass(fake.dial));    await runInDurableObject(stub(slug), (instance: Business) => instance.fetchMailWatch(fake.dial, 60_000));    expect(fake.dials).toBe(dials);    // A Trash move left pending (as a pass cut by the switch leaves it) is made by the job, and leaves the list.    await runInDurableObject(stub(slug), (_i, state) => void state.storage.sql.exec("INSERT INTO mail_fetch_trash (account, validity, uid, at) VALUES (?, 9, 1, ?)", ACCOUNT, Date.now()));    expect(await runMailJob({ door, dial: fake.dial, ...quick }, await messageOf(slug))).toBe("ran");    expect(await emails(slug)).toBe(20);    expect(fake.boxes.get("[Gmail]/Trash")!.messages.some((x) => x.uid === 1 || x.raw.includes("note.1@"))).toBe(true);    expect(await runInDurableObject(stub(slug), (_i, state) => Number(state.storage.sql.exec("SELECT count(*) AS n FROM mail_fetch_trash").one().n))).toBe(0);  }, 180_000);  it("L-c and L-e: a body the door refuses (413) is skipped by name, sealed in the log, and the run carries on", async () => {    const slug = "mail-job-413";    const phone = await given(slug, true);    const fake = server(3);    // The door refuses message 2's body whole, as it does a body past its cap.    const refusing = async (s: string, path: string, init: RequestInit) => {      const meta = new Headers(init.headers).get("cotton-job-meta");      if (path.endsWith("/arrive") && meta && JSON.parse(decodeURIComponent(meta)).uid === 2) return new Response(JSON.stringify({ code: "too_large" }), { status: 413 });      return door(s, path, init);    };    expect(await runMailJob({ door: refusing, dial: fake.dial, ...quick }, await messageOf(slug))).toBe("ran");    expect(await emails(slug)).toBe(2);    const log = await logOf(slug, phone);    const skipped = log.find((l) => l.code === "too_large") as { ref: { id: string; sealed: string } | null } | undefined;    expect(skipped?.ref?.sealed).toMatch(/^a2:/);    expect(JSON.stringify(log)).not.toContain("1790000000000000002");    // Not stuck: the next run starts past it.    const st = await runInDurableObject(stub(slug), (_i, state) => String(state.storage.sql.exec("SELECT cursor FROM mail_fetch_account").one().cursor));    expect(JSON.parse(st)).toMatchObject({ low: 1 });  }, 120_000);  it("L-e: a failure that repeats (no arrival key every five minutes) is one log entry, its time moving", async () => {    const slug = "mail-job-repeat";    const phone = await given(slug, true, false);    for (let i = 0; i < 3; i++) expect(await runMailJob({ door, dial: server(1).dial, ...quick }, await messageOf(slug))).toBe("ran");    const log = await logOf(slug, phone);    expect(log.filter((l) => l.code === "no_arrival_key").length).toBe(1);  }, 120_000);  it("L-d: a slug with no database answers a job's call as a shut door does", async () => {    const slug = "mail-job-shut";    await given(slug, true);    const m = await messageOf(slug);    expect((await http(slug, "PUT", "/v1/admin/business", { mail_jobs: null }, ADMIN)).status).toBe(200);    const shut = await call(m, "begin", "{}");    const stranger = await call({ ...m, slug: "mail-job-nobody-here" }, "begin", "{}");    expect([stranger.status, await stranger.json()]).toEqual([shut.status, await shut.json()]);  }, 120_000);  it("a forged credential is refused before the body is read", async () => {    const slug = "mail-job-forged";    await given(slug, true);    const m = await messageOf(slug);    const forged = await mintJobToken("some-other-key-that-is-long-enough-000000", { v: 1, slug, kind: "mail_fetch", account: ACCOUNT, gen: "x", nonce: "x", exp: Date.now() + 60_000 });    let pulled = 0;    const body = new ReadableStream<Uint8Array>({ pull(c) { if (pulled++ < 400) c.enqueue(new Uint8Array(64 * 1024)); else c.close(); } });    const r = await door(slug, "/v1/jobs/mail/arrive", { method: "POST", headers: { authorization: `CottonJob ${forged}`, "content-type": "message/rfc822" }, body, duplex: "half" } as RequestInit);    expect(r.status).toBe(401);    // Of 25 MiB offered, at most what the platform buffers in flight was pulled: the door read none of it.    expect(pulled).toBeLessThan(400);    expect(m.slug).toBe(slug);  }, 120_000);});