Cotton code
171 lines · 11.0 KB · TypeScriptRaw
/** * RULE (coordinator for the owner, 22 Nov 2026: his change log was 2.86 GB of a 6.5 GB file, 99,930 entries at about * 28 KB each): the change log is kept by size as well as by age and count, and its entries are small. * * - A per-account size budget (`change_bytes`, characters of before and after), none until set: once set the log's *   size is counted (newest first, a step an alarm, then kept by triggers) and the oldest go until it fits, a step of *   about 32 MB a call. * - A create keeps only the names of what it wrote, an update the changed columns as they were and the names of what *   they became: list_changes, undo and restore_version still read what a change wrote, worked back from the record. * - A write that says it is an import keeps only that it happened, and cannot be undone. * * Invented records only. */import { env, runInDurableObject } from "cloudflare:test";import { describe, expect, it } from "vitest";import { ADMIN, answer, BOOKS_OPEN, http, NOTES_OPEN, personalObject, tool } from "./personal.ts";import { trimChanges } from "../src/changes.ts";import { SCHEMA, Store } from "../src/store.ts";const laid = (sql: SqlStorage) => {  sql.exec(SCHEMA);};const NOW = new Date("2026-11-22T00:00:00.000Z");/** The log's size as SQLite reads it, every entry. */const actual = (sql: SqlStorage) => Number(sql.exec<{ n: number | null }>("SELECT SUM(coalesce(length(before), 0) + coalesce(length(after), 0)) AS n FROM change").one().n ?? 0);describe("the change log by size", () => {  it("counts its size newest first, keeps it with every write, delete and rewrite, and trims the oldest to the budget", async () => {    await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName("change-budget-store")), (_i, state) => {      const sql = state.storage.sql;      laid(sql);      const store = new Store(sql, () => NOW);      const body = (n: number) => ({ body: "x".repeat(n) });      const add = (i: number, n: number) => store.addChange({ actor: null, via: "test", table: "note", record_id: `n${i}`, kind: "delete", before: body(n), after: null, version: i });      for (let i = 0; i < 300; i++) add(i, 1_000);      expect(store.changeSize()).toEqual({ bytes: 0, ready: false, counting: false });      // Counting walks down from the newest, a step a call; a write meanwhile is counted by the trigger.      expect(store.countChanges(100)).toBe(true);      add(300, 5_000);      expect(store.countChanges(100)).toBe(true);      expect(store.changeSize().ready).toBe(false);      expect(store.countChanges(100)).toBe(false);      expect(store.changeSize()).toEqual({ bytes: actual(sql), ready: true, counting: true });      // A rewrite (the seal's scrub) and a delete outside the trim (an erase) keep it true.      sql.exec("UPDATE change SET before = '{}' WHERE record_id = 'n5'");      sql.exec("DELETE FROM change WHERE record_id = 'n7'");      expect(store.changeSize().bytes).toBe(actual(sql));      // A budget of about 100 entries' worth: the oldest go, a step at most `most` a call, until it fits.      const budget = 100 * 1_015;      let calls = 0;      let more = true;      while (more) {        ({ more } = store.trimChanges("2000-01-01T00:00:00.000Z", 100_000, budget, 60));        calls++;      }      expect(calls).toBeGreaterThan(2);      expect(store.changeSize().bytes).toBe(actual(sql));      expect(actual(sql)).toBeLessThanOrEqual(budget);      expect(actual(sql)).toBeGreaterThan(budget - 1_100);      const left = sql.exec<{ id: string }>("SELECT record_id AS id FROM change ORDER BY id DESC LIMIT 1").one().id;      expect(left, "the newest stays").toBe("n300");      // Without a budget nothing is trimmed by size.      expect(store.trimChanges("2000-01-01T00:00:00.000Z", 100_000, null, 60)).toEqual({ trimmed: 0, more: false });    });  });  it("takes no more than about 32 MB of entries a step, however many fit the count", async () => {    await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName("change-budget-step")), (_i, state) => {      const sql = state.storage.sql;      laid(sql);      sql.exec("DELETE FROM change");      const store = new Store(sql, () => NOW);      const big = { body: "y".repeat(1_000_000) };      for (let i = 0; i < 70; i++) store.addChange({ actor: null, via: "test", table: "note", record_id: `b${i}`, kind: "delete", before: big, after: null, version: i });      // Every entry is older than the window: a step still takes only 31 of them (32 MB).      const window = "2030-01-01T00:00:00.000Z";      expect(store.trimChanges(window, 100_000, null, 10_000)).toEqual({ trimmed: 31, more: true });      expect(store.trimChanges(window, 100_000, null, 10_000)).toEqual({ trimmed: 31, more: true });      expect(store.trimChanges(window, 100_000, null, 10_000)).toEqual({ trimmed: 8, more: false });    });  });  it("is off until the account sets it: then the alarm's pass counts the log and trims it to the budget", async () => {    await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName("change-budget-alarm")), (_i, state) => {      const sql = state.storage.sql;      laid(sql);      sql.exec("DELETE FROM change");      const store = new Store(sql, () => NOW);      for (let i = 0; i < 50; i++) store.addChange({ actor: null, via: "test", table: "note", record_id: `a${i}`, kind: "delete", before: { body: "z".repeat(1_000) }, after: null, version: i });      expect(trimChanges(store, NOW)).toEqual({ trimmed: 0, more: false });      expect(store.changeSize().counting, "nothing is counted without a budget").toBe(false);      store.setMeta("change_bytes", String(10 * 1_015));      expect(trimChanges(store, NOW)).toEqual({ trimmed: 40, more: false });      expect(Number(sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM change").one().n)).toBe(10);      expect(store.changeSize()).toEqual({ bytes: actual(sql), ready: true, counting: true });    });  });  it("AUDIT C 3: the row cap never trims the last 7 days, so a flood of writes cannot flush recent undo", async () => {    await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName("change-floor")), (_i, state) => {      const sql = state.storage.sql;      laid(sql);      sql.exec("DELETE FROM change");      const earlier = new Date(NOW.getTime() - 20 * 86_400_000);      const add = (store: Store, n: number, tag: string) => {        for (let i = 0; i < n; i++) store.addChange({ actor: null, via: "test", table: "note", record_id: `${tag}${i}`, kind: "delete", before: { body: "z" }, after: null, version: i });      };      add(new Store(sql, () => earlier), 20, "old");      const store = new Store(sql, () => NOW);      add(store, 20, "new");      store.setMeta("change_rows", "10");      expect(trimChanges(store, NOW)).toEqual({ trimmed: 20, more: false });      expect(sql.exec<{ record_id: string }>("SELECT record_id FROM change").toArray().every((r) => r.record_id.startsWith("new"))).toBe(true);      expect(Number(sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM change").one().n)).toBe(20);    });  });});describe("a change log entry", () => {  const slug = "change-entries";  it("keeps a create's and an update's values only by name, and still lists, undoes and restores them", async () => {    const { owner } = await personalObject(slug, { open: [...NOTES_OPEN.open, ...BOOKS_OPEN.open] });    const made = await answer<{ change_id: number; record: { id: string } }>(slug, owner, "create_record", { table: "book", data: { title: "Emma", author: "Austen" } });    const one = await answer<{ change_id: number }>(slug, owner, "update_record", { table: "book", id: made.record.id, patch: { title: "Emma (1815)" } });    await answer(slug, owner, "update_record", { table: "book", id: made.record.id, patch: { title: "Emma, a novel" } });    await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (_i, state) => {      const raw = state.storage.sql.exec<{ kind: string; before: string | null; after: string | null }>("SELECT kind, before, after FROM change WHERE record_id = ? ORDER BY id", made.record.id).toArray();      expect(raw.map((r) => [r.kind, r.before ? JSON.parse(r.before) : null, r.after ? JSON.parse(r.after) : null])).toEqual([        ["create", null, { $keys: ["title", "author", "status"] }],        ["update", { title: "Emma" }, { $keys: ["title"] }],        ["update", { title: "Emma (1815)" }, { $keys: ["title"] }],      ]);    });    const log = await answer<{ changes: { kind: string; before: unknown; after: unknown }[] }>(slug, owner, "list_changes", { table: "book", id: made.record.id });    expect(log.changes.map((c) => [c.kind, c.before, c.after])).toEqual([      ["update", { title: "Emma (1815)" }, { title: "Emma, a novel" }],      ["update", { title: "Emma" }, { title: "Emma (1815)" }],      ["create", null, { title: "Emma", author: "Austen", status: "want_to_read" }],    ]);    const restored = await answer<{ record: { data: Record<string, unknown> } }>(slug, owner, "restore_version", { table: "book", id: made.record.id, change_id: one.change_id });    expect(restored.record.data).toMatchObject({ title: "Emma (1815)", author: "Austen" });    const last = (await answer<{ changes: { change_id: number }[] }>(slug, owner, "list_changes", { table: "book", id: made.record.id, limit: 1 })).changes[0]!;    const back = await answer<{ record: { data: Record<string, unknown> } }>(slug, owner, "undo", { change_id: last.change_id });    expect(back.record.data).toMatchObject({ title: "Emma, a novel" });  });  it("of a write said as an import keeps only that it happened, and is not undone", async () => {    // The Mac importer says import with its device credential; a token never says it (SERVER 27 H1, server-27.test.ts).    const { owner, credential } = await personalObject(`${slug}-import`, { open: [...BOOKS_OPEN.open] });    const made = await http<{ change_id: number; made: { id: string } }>(`${slug}-import`, "POST", "/v1/act", { act: "create", args: { table: "book", data: { title: "Persuasion" }, import: true } }, { authorization: `Bearer ${credential}` });    expect(made.status, JSON.stringify(made.body)).toBe(200);    await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(`${slug}-import`)), (_i, state) => {      const raw = state.storage.sql.exec<{ kind: string; via: string; before: string | null; after: string | null }>("SELECT kind, via, before, after FROM change WHERE id = ?", made.body.change_id).one();      expect(raw).toEqual({ kind: "import", via: "create", before: null, after: null });    });    const r = await tool(`${slug}-import`, owner, "undo", { change_id: made.body.change_id });    expect(r.isError).toBe(true);    expect(r.structuredContent?.code).toBe("import_not_undone");  });  it("is kept to the account's size budget, set by the admin", async () => {    expect((await http(slug, "PUT", "/v1/admin/business", { change_bytes: 0 }, ADMIN)).status).toBe(400);    expect((await http(slug, "PUT", "/v1/admin/business", { change_bytes: 500_000_000 }, ADMIN)).status).toBe(200);    expect((await http(slug, "PUT", "/v1/admin/business", { change_bytes: null }, ADMIN)).status).toBe(200);  });});