Cotton code
284 lines · 19.3 KB · TypeScriptRaw
import { env, runInDurableObject } from "cloudflare:test";import { describe, expect, it } from "vitest";import { lastMeasure, measureNow, measureStep } from "../src/storage_measure.ts";import type { Store } from "../src/store.ts";import { BIG } from "./big_object.ts";import { http, mint, personalObject } from "./personal.ts";/** * COTTON DATA'S ROUTES (assets/design/data/CONTRACT.md "The Worker", 25 Nov 2026): `GET /v1/data/*`, the owner's own * devices only, never a sealed value nor anything the object does not already hold in clear. An invented object: * sealed notes and projects (their blobs carry SECRET, which no answer but a page of rows may carry), notes and todos * linking a project, links to a project that is gone or deleted, and a change log of three writers. */const SECRET = "SECRET-otter-blob";const sealed = (n: string): Record<string, unknown> => ({ sealed_enc: `s1:${SECRET}-${n}`, dek_enc: `d1:${SECRET}-dek-${n}`, seal_v: 1 });const at = (n: number): string => new Date(Date.UTC(2026, 0, 1) + n * 3_600_000).toISOString();interface Inside {  store: Store;  definitions(): unknown;}async function plant(slug: string, tokenName: string): Promise<{ tokenId: string; ownerId: string }> {  return runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (instance, state) => {    const inside = instance as unknown as Inside;    inside.definitions();    const store = inside.store;    const sql = state.storage.sql;    let version = Number(sql.exec<{ v: number | null }>("SELECT MAX(version) AS v FROM rows").one().v ?? 0) + 1000;    const made = (table: string, id: string, data: Record<string, unknown>, n: number) => {      const row = store.insert(table, id, data, null, ++version);      sql.exec("UPDATE rows SET created_at = ? WHERE table_id = ? AND id = ?", at(n), table, id);      return row;    };    made("project", "p-1", sealed("p1"), 0);    store.tombstone(made("project", "p-2", sealed("p2"), 1), ++version);    // 12 notes over 6 moments (two a moment), all on p-1; the fourth binned.    for (let n = 0; n < 12; n++) {      const row = made("note", `n-${String(n).padStart(2, "0")}`, { ...sealed(`n${n}`), project: "p-1" }, 10 + Math.floor(n / 2));      if (n === 4) store.tombstone(row, ++version);    }    made("todo", "t-1", { ...sealed("t1"), project: "p-1" }, 30);    made("todo", "t-2", { ...sealed("t2"), project: "p-1" }, 31);    // Three notes pointing at nothing: two at a project never made, one at the deleted p-2.    made("note", "n-gone-1", { ...sealed("g1"), project: "p-nowhere" }, 40);    made("note", "n-gone-2", { ...sealed("g2"), project: "p-nowhere" }, 41);    made("note", "n-gone-3", { ...sealed("g3"), project: "p-2" }, 42);    // A retired table's rows, held until erased.    sql.exec("INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at) VALUES ('recipe', 'r-1', ?, NULL, ?, 0, ?, ?)", JSON.stringify(sealed("r1")), ++version, at(50), at(50));    const tokenId = sql.exec<{ id: string }>("SELECT id FROM rows WHERE table_id = 'mcp_token' AND json_extract(data, '$.name') = ?", tokenName).one().id;    const ownerId = sql.exec<{ id: string }>("SELECT id FROM people WHERE role = 'owner'").one().id;    // The change log: the owner's hand, an app's machine write, an assistant's token; each before and after carries SECRET.    const log = (actor: string | null, via: string, table: string, record: string) =>      sql.exec("INSERT INTO change (at, actor, via, table_id, record_id, kind, before, after, version) VALUES (?, ?, ?, ?, ?, 'update', ?, ?, 1)", at(60), actor, via, table, record, JSON.stringify({ body: SECRET }), JSON.stringify({ body: SECRET }));    for (let n = 0; n < 5; n++) log(ownerId, "update", "note", `n-0${n}`);    for (let n = 0; n < 4; n++) log(null, "alarm", "todo", `t-${n}`);    for (let n = 0; n < 3; n++) log(tokenId, "update_record", "note", `n-1${n}`);    log(null, "mint_token", "mcp_token", tokenId);    return { tokenId, ownerId };  });}describe("GET /v1/data/*: Cotton Data's read-only routes", () => {  const SLUG = "data-routes";  const routes = ["/v1/data/tables", "/v1/data/page?table=note", "/v1/data/points?table=project&id=p-1", "/v1/data/changes", "/v1/data/leftovers"];  it("answers the owner's own devices alone", async () => {    const slug = `${SLUG}-who`;    const { credential } = await personalObject(slug);    const assistant = await mint(slug, credential, "Claude (invented)", ["owner"]);    const made = await http(slug, "POST", "/v1/act", { act: "set_role", args: { phone: "+919000000041", role: "staff", name: "Invented helper" } }, { authorization: `Bearer ${credential}` });    expect(made.status, JSON.stringify(made.body)).toBe(200);    const code = await http<{ challenge_id: string }>(slug, "POST", "/v1/code", { phone: "+919000000041", device_id: "helper" });    const helper = await http<{ credential: string; person: { role: string } }>(slug, "POST", "/v1/sign-in", { challenge_id: code.body.challenge_id, code: "123456", device_id: "helper" });    expect(helper.body.person.role).toBe("staff");    for (const route of routes) {      expect((await http(slug, "GET", route, undefined, { authorization: `Bearer ${credential}` })).status, route).toBe(200);      const byToken = await http<{ code: string }>(slug, "GET", route, undefined, { authorization: `Bearer ${assistant}` });      expect(byToken.status, `${route} by a token`).toBe(403);      expect(["owner_only", "token_scopes"]).toContain(byToken.body.code);      const byStaff = await http<{ code: string }>(slug, "GET", route, undefined, { authorization: `Bearer ${helper.body.credential}` });      expect([byStaff.status, byStaff.body.code], `${route} by staff`).toEqual([403, "owner_only"]);      expect((await http(slug, "GET", route)).status, `${route} with no credential`).toBe(403);      expect((await http(slug, "GET", route, undefined, { authorization: "Bearer test-admin-token" })).status, `${route} by the admin`).toBe(403);    }    expect((await http(slug, "GET", "/v1/data/nothing", undefined, { authorization: `Bearer ${credential}` })).status).toBe(404);  }, 180_000);  it("answers each route's shape, pages newest first, and leaks no sealed blob but in a page of rows", async () => {    const { credential } = await personalObject(SLUG);    await mint(SLUG, credential, "Claude (invented)", ["owner"]);    const { tokenId } = await plant(SLUG, "Claude (invented)");    const get = async <T = Record<string, unknown>>(route: string): Promise<T> => {      const res = await http<T>(SLUG, "GET", route, undefined, { authorization: `Bearer ${credential}` });      expect(res.status, `${route}: ${JSON.stringify(res.body)}`).toBe(200);      return res.body;    };    const clean = (route: string, body: unknown) => expect(JSON.stringify(body), `${route} carries no sealed value`).not.toContain(SECRET);    // Tables: the measure's figures, oldest and newest of live rows.    type Tables = { database: { bytes: number; cap: number }; measured: { at: string } | null; parts: { parts: unknown[] } | null; tables: { table: string; rows: number; tombstones: number | null; bytes: number | null; oldest: string | null; newest: string | null }[] };    const tables = await get<Tables>("/v1/data/tables");    clean("tables", tables);    expect(tables.database.bytes).toBeGreaterThan(0);    expect(tables.database.cap).toBeGreaterThan(tables.database.bytes);    expect(tables.measured?.at).toEqual(expect.any(String));    expect(tables.parts?.parts.length).toBeGreaterThan(5);    const note = tables.tables.find((t) => t.table === "note")!;    expect(note).toMatchObject({ rows: 14, tombstones: 1, oldest: at(10), newest: at(42) });    expect(note.bytes).toBeGreaterThan(0);    expect(tables.tables.find((t) => t.table === "project")).toMatchObject({ rows: 1, tombstones: 1, oldest: at(0), newest: at(0) });    // Page: every live note once, newest first by created_at then id, a page at a time.    type Page = { table: string; rows: { id: string; created_at: string; updated_at: string; data: Record<string, unknown> }[]; more: boolean };    const seen: string[] = [];    let route = "/v1/data/page?table=note&limit=4";    for (;;) {      const p = await get<Page>(route);      expect(p.table).toBe("note");      seen.push(...p.rows.map((r) => r.id));      if (!p.more) break;      const last = p.rows[p.rows.length - 1]!;      route = `/v1/data/page?table=note&limit=4&before=${encodeURIComponent(last.created_at)}&id=${encodeURIComponent(last.id)}`;    }    const live = ["n-gone-3", "n-gone-2", "n-gone-1", "n-11", "n-10", "n-09", "n-08", "n-07", "n-06", "n-05", "n-03", "n-02", "n-01", "n-00"];    expect(seen).toEqual(live);    const first = await get<Page>("/v1/data/page?table=note&limit=1");    expect(first.rows[0]!.data.sealed_enc, "a page carries rows as a sync page does, sealed as stored").toBe(`s1:${SECRET}-g3`);    expect((await get<Page>(`/v1/data/page?table=note&before=${encodeURIComponent(at(11))}`)).rows.map((r) => r.id)).toEqual(["n-01", "n-00"]);    const phone = { authorization: `Bearer ${credential}` };    // Sort and dates: a made range (from inclusive, to exclusive), recently changed, and the rows per year.    expect((await get<Page>(`/v1/data/page?table=note&from=${encodeURIComponent(at(11))}&to=${encodeURIComponent(at(13))}`)).rows.map((r) => r.id)).toEqual(["n-05", "n-03", "n-02"]);    await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(SLUG)), (_i, state) => {      state.storage.sql.exec("UPDATE rows SET updated_at = ? WHERE table_id = 'note' AND id = 'n-00'", "2099-01-01T00:00:00.000Z");    });    const changed = await get<Page & { order: string }>("/v1/data/page?table=note&order=changed&limit=2");    expect(changed.order).toBe("changed");    expect(changed.rows[0]!.id, "the row changed last comes first").toBe("n-00");    const second = await get<Page>(`/v1/data/page?table=note&order=changed&limit=2&before=${encodeURIComponent(changed.rows[1]!.updated_at)}&id=${encodeURIComponent(changed.rows[1]!.id)}`);    expect(second.rows.map((r) => r.id)).not.toContain("n-00");    expect((await http(SLUG, "GET", "/v1/data/page?table=note&order=title", undefined, phone)).status).toBe(400);    expect((await http(SLUG, "GET", "/v1/data/page?table=note&from=soon", undefined, phone)).status).toBe(400);    expect(await get("/v1/data/years?table=note")).toEqual({ table: "note", years: [{ year: 2026, rows: 14 }] });    expect((await http(SLUG, "GET", "/v1/data/page?table=mcp_token", undefined, phone)).status, "an internal table").toBe(404);    expect((await http(SLUG, "GET", "/v1/data/page?table=recipe", undefined, phone)).status, "a retired table").toBe(404);    expect((await http(SLUG, "GET", "/v1/data/page?table=no_such", undefined, phone)).status).toBe(404);    expect((await http(SLUG, "GET", "/v1/data/page?table=note&limit=501", undefined, phone)).status).toBe(400);    // Points: notes and todos naming p-1 by their single-valued link, the binned note left out.    type Points = { points: { table: string; column: string; count: number; ids: string[] }[] };    const points = await get<Points>("/v1/data/points?table=project&id=p-1&limit=3");    clean("points", points);    expect(points.points.map((p) => [p.table, p.column, p.count, p.ids.length])).toEqual([      ["note", "project", 11, 3],      ["todo", "project", 2, 2],    ]);    expect(points.points[0]!.ids).not.toContain("n-04");    expect((await get<Points>("/v1/data/points?table=project&id=p-1")).points[0]!.ids.sort()).toEqual(live.filter((id) => !id.startsWith("n-gone")).sort());    expect((await get<Points>("/v1/data/points?table=project&id=p-none")).points).toEqual([]);    expect((await http(SLUG, "GET", "/v1/data/points?table=project&id=p-1&limit=201", undefined, phone)).status).toBe(400);    expect((await http(SLUG, "GET", "/v1/data/points?table=project", undefined, phone)).status).toBe(400);    // Changes: heads only, newest first, each writer told apart, internal tables left out, paged by id.    type Changes = { changes: { id: number; at: string; actor: string; actor_kind: string; via: string; table: string; record: string; kind: string }[]; more: boolean };    const all = await get<Changes>("/v1/data/changes?limit=500");    clean("changes", all);    const planted = all.changes.filter((c) => c.at === at(60));    expect(planted).toHaveLength(12);    expect(all.changes.some((c) => c.table === "mcp_token"), "an internal table's changes are left out").toBe(false);    expect(Object.keys(planted[0]!).sort()).toEqual(["actor", "actor_kind", "at", "id", "kind", "record", "table", "via"]);    const ids = all.changes.map((c) => c.id);    expect(ids).toEqual([...ids].sort((a, b) => b - a));    expect(planted.slice(0, 3).map((c) => [c.actor_kind, c.actor, c.record])).toEqual([      ["assistant", "Claude (invented)", "n-12"],      ["assistant", "Claude (invented)", "n-11"],      ["assistant", "Claude (invented)", "n-10"],    ]);    expect(planted.filter((c) => c.actor_kind === "app").map((c) => [c.via, c.actor])).toEqual(Array(4).fill(["alarm", "the owner"]));    expect(planted.filter((c) => c.actor_kind === "person")).toHaveLength(5);    const by = async (who: string) => (await get<Changes>(`/v1/data/changes?who=${who}&limit=500`)).changes.filter((c) => c.at === at(60));    expect((await by("assistants")).map((c) => c.record)).toEqual(["n-12", "n-11", "n-10"]);    expect((await by("apps")).map((c) => c.record)).toEqual(["t-3", "t-2", "t-1", "t-0"]);    expect((await by("you")).map((c) => c.record)).toEqual(["n-04", "n-03", "n-02", "n-01", "n-00"]);    expect((await get<Changes>("/v1/data/changes?table=todo&limit=500")).changes.every((c) => c.table === "todo")).toBe(true);    const walked: number[] = [];    let before = "";    for (;;) {      const p = await get<Changes>(`/v1/data/changes?limit=5${before}`);      walked.push(...p.changes.map((c) => c.id));      if (!p.more) break;      before = `&before=${p.changes[p.changes.length - 1]!.id}`;    }    expect(walked).toEqual(ids);    expect(tokenId).toEqual(expect.any(String));    expect((await http(SLUG, "GET", "/v1/data/changes?who=everyone", undefined, phone)).status).toBe(400);    expect((await http(SLUG, "GET", "/v1/data/changes?limit=501", undefined, phone)).status).toBe(400);    // Leftovers: the retired table's rows, and the notes pointing at nothing.    type Leftovers = { measured: { at: string } | null; retired: { table: string; rows: number }[]; dangling: { table: string; column: string; target: string; count: number }[] | null };    const left = await get<Leftovers>("/v1/data/leftovers");    clean("leftovers", left);    expect(left.retired).toEqual([{ table: "recipe", rows: 1 }]);    expect(left.dangling?.filter((d) => d.table === "note" || d.table === "todo")).toEqual([{ table: "note", column: "project", target: "project", count: 3 }]);  }, 180_000);  it("measures oldest, newest and dangling in steps, as one pass does", async () => {    const slug = `${SLUG}-measure`;    const { credential } = await personalObject(slug);    await mint(slug, credential, "Claude (invented)", ["owner"]);    await plant(slug, "Claude (invented)");    const { whole, stepped, steps, old } = await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (instance, state) => {      const store = (instance as unknown as Inside).store;      const sql = state.storage.sql;      const links = store.linkTargets();      const now = new Date("2026-11-25T10:00:00Z");      const whole = measureNow(sql, now, links);      const kept = new Map<string, string | null>();      const host = { sql, meta: (k: string) => kept.get(k) ?? null, setMeta: (k: string, v: string | null) => void kept.set(k, v), links };      let steps = 0;      while (measureStep(host, now, 0, 3)) steps += 1;      // A plan kept by the shape before this one (no oldest, newest or dangling) is begun again, never finished short.      const older = new Map<string, string | null>([["storage_measure_plan", JSON.stringify({ at: now.toISOString(), job: 999, after: null, figures: {}, tables: {}, changes: {} })]]);      const host2 = { sql, meta: (k: string) => older.get(k) ?? null, setMeta: (k: string, v: string | null) => void older.set(k, v), links };      while (measureStep(host2, now, 1_000, 1_000_000));      return { whole, stepped: lastMeasure(host)!, steps, old: lastMeasure(host2)! };    });    expect(steps).toBeGreaterThan(20);    expect(stepped.tables).toEqual(whole.tables);    expect(stepped.dangling).toEqual(whole.dangling);    expect(old.dangling).toEqual(whole.dangling);    expect(whole.tables.find((t) => t.table === "note")).toMatchObject({ rows: 14, tombstones: 1, oldest: at(10), newest: at(42) });    expect(whole.tables.find((t) => t.table === "recipe")).toMatchObject({ rows: 1, oldest: at(50), newest: at(50) });    expect(whole.dangling?.find((d) => d.table === "note" && d.column === "project")).toEqual({ table: "note", column: "project", target: "project", count: 3 });    expect(whole.dangling?.some((d) => d.table === "todo")).toBe(false);  }, 180_000);  /**   * What counting dangling links adds to the measure: one pass with it and one without, timed from outside the object   * (a Worker's clock stands still inside synchronous work). Links written straight into the index, every tenth to a   * row never made. `BIG_OBJECT=1` writes 2,000,000 links, about what an object of the owner's size holds.   */  it("times the dangling count over many links", async () => {    const slug = `${SLUG}-timed`;    await personalObject(slug);    const stub = env.BUSINESS.get(env.BUSINESS.idFromName(slug));    const N = BIG ? 2_000_000 : 50_000;    for (let start = 1; start <= N; start += 50_000) {      const end = Math.min(N, start + 49_999);      await runInDurableObject(stub, (_i, state) => {        const sql = state.storage.sql;        sql.exec(          `WITH RECURSIVE c(x) AS (SELECT ? UNION ALL SELECT x + 1 FROM c WHERE x < ?)           INSERT INTO rows (table_id, id, data, owner, version, deleted, created_at, updated_at)           SELECT 'project', printf('p-%08d', x), '{}', NULL, 1000000 + x, 0, '2025-01-01T00:00:00Z', '2025-01-01T00:00:00Z' FROM c WHERE x % 10 <> 0`,          start,          end,        );        sql.exec(          `WITH RECURSIVE c(x) AS (SELECT ? UNION ALL SELECT x + 1 FROM c WHERE x < ?)           INSERT INTO links (table_id, id, column, target) SELECT 'note', printf('n-%08d', x), 'project', printf('p-%08d', x) FROM c`,          start,          end,        );      });    }    const pass = async (withLinks: boolean): Promise<{ ms: number; dangling: number }> => {      const t0 = Date.now();      const d = await runInDurableObject(stub, (instance, state) => {        const store = (instance as unknown as Inside).store;        const m = measureNow(state.storage.sql, new Date(), withLinks ? store.linkTargets() : []);        return m.dangling?.find((x) => x.table === "note" && x.column === "project")?.count ?? 0;      });      return { ms: Date.now() - t0, dangling: d };    };    await pass(false);    const without = await pass(false);    const withIt = await pass(true);    const line = `dangling over ${N} links: measure ${without.ms} ms without, ${withIt.ms} ms with (${(((withIt.ms - without.ms) / N) * 10_000).toFixed(1)} ms a 10,000-link step)`;    console.log(line);    if ((env as unknown as { SAY?: string }).SAY === "1") throw new Error(`SAY ${line}`);    expect(withIt.dangling).toBe(N / 10);  }, 1_800_000);});