Cotton code
139 lines · 8.8 KB · TypeScriptRaw
/** * MAIL PREDICATE phase 2 (decision 6; the eight rules of NEXT-PHASE2-RULES): * the Worker's mirror (src/mail/predicate.ts) answers every shared case exactly * as the phone's SQL does (cotton-rules mail/cuts.rs runs the same file), and * the object stamps a mail's landing time itself, which no import can set. */import { env, runInDurableObject } from "cloudflare:test";import { describe, expect, it } from "vitest";import file from "../../../crates/cotton-rules/src/mail/cut_cases.json";import { Store, wire } from "../src/store.ts";import { http, personalObject } from "./personal.ts";import { binnedAt, archivedMail, checkCutAt, cutAt, isPinned, mailState, normaliseKey, normaliseTime, refusedKey, threadState, unreadMail, type MailCut, type MailRow } from "../src/mail/predicate.ts";type Mail = Record<string, unknown> & { id: string; thread_id: string; sealed?: boolean; data?: Record<string, unknown>; landed_at?: string | null; expect: { state: string; unread: boolean | null; binned_at: string | null; archived: boolean } };/** The stored row a reader holds: the mail's fields as data, its landing time the row's own. A sealed one as stored. */function stored(m: Mail): MailRow {  if (m.sealed) return { id: m.id, data: m.data ?? {}, landed_at: m.landed_at ?? null };  const { expect: _e, landed_at, id, ...data } = m;  return { id, data, landed_at: landed_at ?? null };}describe("the mail predicate's TypeScript mirror", () => {  it("holds the cases the review names", () => {    const names = file.cases.map((c) => c.name).join("\n");    for (const must of ["sealed row not yet opened", "a cut then undo", "read cut overlapping a bin cut", "edited after the cut", "one second after", "no landing time is never covered", "restored after the cut", "two overlapping bin cuts", "unread after a read cut", "archive with bin", "upper-case cut key", "+tag"]) expect(names).toContain(must);  });  for (const c of file.cases) {    it(c.name, () => {      const cuts = { bin: c.bin as MailCut[], read: c.read as MailCut[], archive: c.archive as MailCut[], own: ((c as { own?: string[] }).own ?? []).map(normaliseKey) };      const mails = c.mails as Mail[];      for (const m of mails) {        const row = stored(m);        expect([m.id, mailState(row, cuts)]).toEqual([m.id, m.expect.state]);        expect([m.id, unreadMail(row, cuts)]).toEqual([m.id, m.expect.unread]);        expect([m.id, binnedAt(row, cuts)]).toEqual([m.id, m.expect.binned_at]);        expect([m.id, archivedMail(row, cuts)]).toEqual([m.id, m.expect.archived]);      }      for (const t of (c as { threads?: { id: string; state: string }[] }).threads ?? []) {        expect([t.id, threadState(mails.filter((m) => m.thread_id === t.id).map(stored), cuts)]).toEqual([t.id, t.state]);      }    });  }  it("normalises keys and times, refuses keys and takes the cut moment as the Rust does", () => {    for (const [given, want] of file.keys) expect([given, normaliseKey(given!)]).toEqual([given, want]);    for (const [given, want] of file.refused_keys) expect([given, refusedKey(given!)]).toEqual([given, want]);    for (const [given, want] of file.times) expect([given, normaliseTime(given!)]).toEqual([given, want]);    for (const c of file.cut_at) expect(cutAt(c.shown_landed)).toBe(c.at);    for (const c of file.check_cut_at) expect([c, checkCutAt(c.at, c.newest_known)]).toEqual([c, c.refused]);  });});describe("a mail's landing time (rule 3)", () => {  it("is the object's own clock, pinned; an import's created_at does not move it; only a mail carries it on the wire", async () => {    const stub = env.BUSINESS.get(env.BUSINESS.idFromName("landed-at-invented"));    await runInDurableObject(stub, (instance) => {      const store = (instance as unknown as { store: Store }).store;      const made = store.insert("email", "e-imported", { subject: "old" }, null, 1, { created_at: "2001-01-01T00:00:00.000Z" });      expect(made.created_at).toBe("2001-01-01T00:00:00.000Z");      expect(isPinned(made.landed_at!)).toBe(true);      expect(made.landed_at! > "2026-01-01").toBe(true);      const read = store.any("email", "e-imported")!;      expect(read.landed_at).toBe(made.landed_at);      expect(wire(read, false).landed_at).toBe(made.landed_at);      const note = store.insert("note", "n-1", { title: "x" }, null, 1);      expect(wire(note, false).landed_at).toBeUndefined();    });  });  it("rows held before the column read the moment it came, with no rewrite", async () => {    const stub = env.BUSINESS.get(env.BUSINESS.idFromName("landed-at-old-rows"));    await runInDurableObject(stub, (_instance, state) => {      const sql = state.storage.sql;      sql.exec("DROP TABLE IF EXISTS rows_landed_probe");      const has = () => sql.exec<{ name: string }>("PRAGMA table_info(rows)").toArray().some((c) => c.name === "landed_at");      if (has()) sql.exec("ALTER TABLE rows DROP COLUMN landed_at");      sql.exec("INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) VALUES ('email', 'e-old', '{}', NULL, 1, 0, '2001-01-01T00:00:00.000Z', '2001-01-01T00:00:00.000Z')");      const store = new Store(sql, () => new Date());      const fresh = store.insert("email", "e-new", {}, null, 2);      const old = store.any("email", "e-old")!;      expect(isPinned(old.landed_at!)).toBe(true);      expect(old.landed_at! <= fresh.landed_at!).toBe(true);      expect(old.landed_at! > "2026-01-01").toBe(true);    });  });});describe("a mail's landing time is kept, reset and backfilled (review of the rules, 6)", () => {  it("an update keeps it; a deleted row written again lands again; a rows table rebuilt under the store gets the column back", async () => {    const stub = env.BUSINESS.get(env.BUSINESS.idFromName("landed-at-kept"));    await runInDurableObject(stub, (_instance, state) => {      let clock = Date.parse("2026-11-27T10:00:00.000Z");      const store = new Store(state.storage.sql, () => new Date(clock));      const made = store.insert("email", "e-kept", { subject: "a" }, null, 1);      expect(made.landed_at).toBe("2026-11-27T10:00:00.000Z");      clock += 60_000;      store.update(made, { subject: "b" }, null, 2, { updated_at: "2026-11-27T10:01:00.000Z" });      expect(store.any("email", "e-kept")!.landed_at).toBe("2026-11-27T10:00:00.000Z");      state.storage.sql.exec("UPDATE rows SET deleted = 1 WHERE table_id = 'email' AND id = 'e-kept'");      clock += 60_000;      expect(store.insert("email", "e-kept", { subject: "c" }, null, 3).landed_at).toBe("2026-11-27T10:02:00.000Z");      expect(store.any("email", "e-kept")!.landed_at).toBe("2026-11-27T10:02:00.000Z");      // The store already added the column once; the table loses it beneath it (a rebuild): the next write adds it again.      state.storage.sql.exec("ALTER TABLE rows DROP COLUMN landed_at");      clock += 60_000;      expect(store.insert("email", "e-after-rebuild", {}, null, 4).landed_at).toBe("2026-11-27T10:03:00.000Z");      expect(store.any("email", "e-after-rebuild")!.landed_at).toBe("2026-11-27T10:03:00.000Z");    });  });  it("GET /v1/landed pages every live mail's id and landing time, never its data, to the owner alone", async () => {    const SLUG = "landed-backfill";    const { credential } = await personalObject(SLUG);    await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(SLUG)), (instance, state) => {      const store = (instance as unknown as { store: Store }).store;      for (let i = 0; i < 7; i++) store.insert("email", `e-${i}`, { subject: `secret ${i}` }, null, 1);      state.storage.sql.exec("UPDATE rows SET deleted = 1 WHERE table_id = 'email' AND id = 'e-3'");      store.insert("note", "n-1", { title: "not mail" }, null, 1);    });    const page = (q: string) => http<{ rows: [string, string][]; after?: string }>(SLUG, "GET", `/v1/landed${q}`, undefined, { authorization: `Bearer ${credential}` });    const first = await page("?limit=4");    expect(first.status, JSON.stringify(first.body)).toBe(200);    expect(first.body.rows.map((r) => r[0])).toEqual(["e-0", "e-1", "e-2", "e-4"]);    expect(first.body.after).toBe("e-4");    expect(first.body.rows.every((r) => isPinned(r[1]))).toBe(true);    expect(JSON.stringify(first.body)).not.toContain("secret");    const second = await page(`?limit=4&after=${first.body.after}`);    expect(second.body.rows.map((r) => r[0])).toEqual(["e-5", "e-6"]);    expect(second.body.after).toBeUndefined();    expect((await http(SLUG, "GET", "/v1/landed?limit=0", undefined, { authorization: `Bearer ${credential}` })).status).toBe(400);    // Named mail alone (the phone's daily re-ask): live mail it holds, an unknown or deleted id left out.    const named = await page("?id=e-1&id=e-3&id=e-9&id=n-1");    expect(named.status, JSON.stringify(named.body)).toBe(200);    expect(named.body.rows.map((r) => r[0])).toEqual(["e-1"]);  });});