Cotton code
100 lines · 6.0 KB · TypeScriptRaw
import { env, runInDurableObject } from "cloudflare:test";import { describe, expect, it } from "vitest";import { declarations, firstProblem, planFirst } from "../src/first.ts";import { Store, type FirstAt, type FirstPlan, type StoredRow, type SyncScope } from "../src/store.ts";/** * A LATE TABLE WAITS BEHIND THE CHATS (Comms' mail, 21 Nov 2026, * assets/design/chat/MAIL.md): Comms pulls mail beside its chats, and mail must * not slow the chats arriving. Mail is declared `late`: its first rows (the * newest conversations of mail and their newest messages) come after every * chat's newest messages, and its long tail after the chats' older messages. * Every row still comes, once. Invented rows. */const DECLS = declarations({  comms: {    first: {      thread: { by: "last_message_at", unless: ["trashed_at"] },      message: { by: "sent_at", per: "thread_id", of: "thread", rows: 3, early: 2 },      email_thread: { by: "last_at", rows: 4, unless: ["trashed_at"], late: true },      email: { by: "sent_at", per: "thread_id", of: "email_thread", rows: 2, groups: 4, late: true },    },  },});const at = (n: number): string => new Date(Date.UTC(2026, 0, 1) + n * 3_600_000).toISOString().replace(".000", "");function build(store: Store): number {  let version = 0;  const write = (table: string, id: string, data: Record<string, unknown>): void => {    store.insert(table, id, data, null, ++version);  };  // Mail written first, so change order alone would carry it before the chats.  for (let t = 0; t < 10; t++) write("email_thread", `et-${t}`, { last_at: at(100 + t * 10) });  for (let m = 0; m < 40; m++) write("email", `e-${String(m).padStart(3, "0")}`, { thread_id: `et-${m % 10}`, sent_at: at(m * 3) });  for (let t = 0; t < 6; t++) write("thread", `th-${t}`, { last_message_at: at(200 + t) });  for (let m = 0; m < 60; m++) write("message", `m-${String(m).padStart(3, "0")}`, { thread_id: `th-${m % 6}`, sent_at: at(m * 2) });  for (let p = 0; p < 5; p++) write("person", `p-${p}`, { n: p });  return version;}function pull(store: Store, upto: number, limit: number): StoredRow[] {  const scope: SyncScope = { kind: "all", except: new Set() };  const held = new Map<string, number>();  for (const table of ["thread", "message", "email_thread", "email", "person"]) held.set(table, table === "person" ? 5 : 1000);  const specs = planFirst((t) => held.get(t) ?? 0, "2026-11-21", 10, DECLS);  store.firstIndexes(specs);  store.firstPass("late", 1000, 0);  const small = store.smallFirst({ since: 0, upto, scope, windows: [], most: 10 }).filter((t) => !specs.some((s) => s.table === t));  let cursor: { plan: FirstPlan; at: FirstAt | null } = { plan: { pass: "late", small, specs, cuts: specs.map(() => null) }, at: null };  const carried: StoredRow[] = [];  for (;;) {    const got = store.firstPage({ since: 0, upto, limit, scope, windows: [], ...cursor });    carried.push(...got.rows);    if (!got.more) return carried;    cursor = JSON.parse(JSON.stringify({ plan: got.plan, at: got.at })) as typeof cursor;  }}describe("a late table's rows wait behind the tables that are not late", () => {  it("reads late as a word of first, and sorts late tables last", () => {    expect(firstProblem("email", { by: "sent_at", late: "yes" })).toBe("email: late is true or false");    const specs = planFirst(() => 1000, "2026-11-21", 10, DECLS);    expect(specs.map((s) => s.table)).toEqual(["thread", "message", "email_thread", "email"]);    expect(specs.map((s) => s.late)).toEqual([false, false, true, true]);  });  for (const limit of [1, 3, 7, 50]) {    it(`carries the chats' first rows, then mail's, then the chats' tail, then mail's (pages of ${limit})`, async () => {      const stub = env.BUSINESS.get(env.BUSINESS.idFromName(`sync-first-late-${limit}`));      await runInDurableObject(stub, (_instance, state) => {        const store = new Store(state.storage.sql, () => new Date("2026-11-21T10:00:00Z"));        const upto = build(store);        const carried = pull(store, upto, limit);        const order = carried.map((r) => `${r.table}/${r.id}`);        expect(new Set(order).size, "nothing comes twice").toBe(order.length);        expect(order.length, "every row comes").toBe(10 + 40 + 6 + 60 + 5);        const place = (table: string, id: string): number => order.indexOf(`${table}/${id}`);        // Each chat's newest 3 messages: the chats' first rows.        const chatsFirst = [...Array(6).keys()].flatMap((t) =>          carried.filter((r) => r.table === "message" && r.data.thread_id === `th-${t}`).sort((a, b) => String(b.data.sent_at).localeCompare(String(a.data.sent_at))).slice(0, 3),        );        const lastChatFirst = Math.max(...chatsFirst.map((r) => place("message", r.id)), ...[...Array(6).keys()].map((t) => place("thread", `th-${t}`)));        const mail = carried.map((r, i) => ({ r, i })).filter(({ r }) => r.table === "email" || r.table === "email_thread");        expect(Math.min(...mail.map(({ i }) => i)), "no mail before every chat's newest messages").toBeGreaterThan(lastChatFirst);        // Mail's first rows: the 4 newest conversations of mail, then their newest 2 messages, before the chats' tail.        const newestMail = ["et-9", "et-8", "et-7", "et-6"];        expect(newestMail.map((id) => place("email_thread", id))).toEqual([...newestMail.map((id) => place("email_thread", id))].sort((a, b) => a - b));        const chatTail = carried.map((r, i) => ({ r, i })).filter(({ r }) => r.table === "message" && !chatsFirst.includes(r));        const firstChatTail = Math.min(...chatTail.map(({ i }) => i));        expect(Math.max(...newestMail.map((id) => place("email_thread", id))), "mail's newest conversations before the chats' older messages").toBeLessThan(firstChatTail);        const lastChatTail = Math.max(...chatTail.map(({ i }) => i));        const mailTail = mail.filter(({ r }) => r.table === "email_thread" && !newestMail.includes(r.id));        expect(Math.min(...mailTail.map(({ i }) => i)), "mail's long tail after the chats' older messages").toBeGreaterThan(lastChatTail);      });    });  }});