Cotton code
332 lines · 15.7 KB · TypeScriptRaw
/** * The migration of open rows into sealed ones (sealing plan §7, lane L9). * The sweeper is a DEVICE (the Mac importer for bulk, Q21): it alone holds * the data key, so it seals; the object only keeps what it is handed and * never holds a key that opens a row (it never sees the VMK, the DK or a TK * here). * * TWO STEPS, so a clear row stays until its sealed twin is verified: * *   1. `seal_stage { table, rows: [{ id, expect_version, data, blind? }] }` *      keeps each sealed twin BESIDE its clear row, in the internal table *      `seal_twin` (never synced, never in `rows`, never journalled). The *      clear row is not touched. Answers each twin's id. *   2. The device reads the twins back as stored (`GET /v1/seal/twins`), *      opens each with its own key and holds it to the clear row it read *      (and its blind tokens to the ones it makes again). *   3. `seal_commit { table, twins: [twin ids] }` puts each verified twin in *      place of its row, only while the row is still at the version the *      device read: an edit since drops the twin (`version_moved`) and the *      row, now at a later version, comes again in the device's next pull. *      The row's clear copies of sealed columns go from `rows` and from its *      logged changes (Engine.update's scrub). * * Then `seal_purge { table }` takes the sealed columns out of the act log's * earlier args for that table (§7 step 4), and `GET /v1/admin/seal-check` * counts what is left open, by table, never saying any content (§7 step 7). * * Resumable by construction: a twin is replaced by a later stage of the same * row and taken by its commit, so a sweep cut anywhere leaves either a clear * row (sealed again next run) or a sealed one (skipped next run). */import { refuse } from "./http.ts";import { ARRIVAL_PATCHES } from "./arrival_seam.ts";import { blindArg, blindBudget, checkSealFields, KEEP_OPEN, scrubData, SEAL_FIELDS, SEALED_ENC, sealedColumns, SCRUBBED, type SealedTable } from "./seal.ts";import * as sealWide from "./seal_wide.ts";export const SCHEMA = `CREATE TABLE IF NOT EXISTS seal_twin (  twin TEXT PRIMARY KEY, table_id TEXT NOT NULL, id TEXT NOT NULL, expect_version INTEGER NOT NULL,  data TEXT NOT NULL, blind TEXT NOT NULL, staged_at TEXT NOT NULL, UNIQUE (table_id, id));`;/** Rows one stage or commit carries (§7 step 3: "pages 500 rows per act"). */export const SEAL_BATCH = 500;/** What a commit or stage left, row by row: `version_moved`, `no_such_record`, `no_such_twin`. */export interface Left {  id: string;  code: string;}export interface Twin {  twin: string;  id: string;  expect_version: number;  data: Record<string, unknown>;  blind: string[];}interface HeldRow {  version: number;  data: Record<string, unknown>;}/** What the store gives the migration: a row as held, and the internal tables' SQL. */export interface MigrationHost {  sql: SqlStorage;  row(table: string, id: string): HeldRow | null;  now(): string;}/** The act's own refusals before any row is looked at: a device's batch that is not one. */export function batchOf(said: unknown, name: string): unknown[] {  if (!Array.isArray(said) || !said.length) refuse(400, "bad_args", `${name} is a list of at most ${SEAL_BATCH}`);  if (said.length > SEAL_BATCH) refuse(413, "too_many", `at most ${SEAL_BATCH} ${name} an act`);  return said;}/** * Keep each row's sealed twin beside it. A row the object lacks, or one at * another version than the device read, is left by name; a twin in the wrong * shape refuses the whole act (the device's fault, never a row's). */export function stage(  host: MigrationHost,  t: SealedTable,  rows: unknown[],  check: (data: Record<string, unknown>) => void,): { staged: { id: string; twin: string }[]; left: Left[] } {  blindBudget(rows);  const parsed = rows.map((r, i) => {    if (!r || typeof r !== "object" || Array.isArray(r)) refuse(400, "bad_args", `rows[${i}] is { id, expect_version, data, blind? }`);    const row = r as Record<string, unknown>;    if (typeof row.id !== "string" || !row.id) refuse(400, "bad_args", `rows[${i}].id is the row's id`);    const expect = row.expect_version;    if (typeof expect !== "number" || !Number.isInteger(expect) || expect < 0) refuse(400, "bad_args", `rows[${i}].expect_version is the row's version as the device read it`);    const data = row.data;    if (!data || typeof data !== "object" || Array.isArray(data)) refuse(400, "bad_args", `rows[${i}].data is the row's clear columns and its seal`);    check(data as Record<string, unknown>);    if (!checkSealFields(t, data as Record<string, unknown>)) refuse(400, "seal_column_missing", `rows[${i}]: a seal carries sealed_enc, dek_enc and seal_v`);    return { id: row.id, expect, data: data as Record<string, unknown>, blind: blindArg(row.blind ?? [], t.id) };  });  if (new Set(parsed.map((p) => p.id)).size !== parsed.length) refuse(400, "bad_args", "each row comes once in a stage");  const staged: { id: string; twin: string }[] = [];  const left: Left[] = [];  for (const p of parsed) {    const held = host.row(t.id, p.id);    if (!held) {      left.push({ id: p.id, code: "no_such_record" });      continue;    }    if (held.version !== p.expect) {      left.push({ id: p.id, code: "version_moved" });      continue;    }    const twin = crypto.randomUUID();    host.sql.exec("DELETE FROM seal_twin WHERE table_id = ? AND id = ?", t.id, p.id);    host.sql.exec(      "INSERT INTO seal_twin (twin, table_id, id, expect_version, data, blind, staged_at) VALUES (?, ?, ?, ?, ?, ?, ?)",      twin,      t.id,      p.id,      p.expect,      JSON.stringify(p.data),      JSON.stringify(p.blind),      host.now(),    );    staged.push({ id: p.id, twin });  }  return { staged, left };}/** The twins named, as stored, for the device to open and hold to its clear rows. A twin no longer kept is not answered. */export function twins(sql: SqlStorage, table: string, ids: string[]): Twin[] {  // The object's SQL binds at most a hundred values a statement, and a batch names up to SEAL_BATCH twins.  const out: Twin[] = [];  for (let i = 0; i < ids.length; i += TWINS_A_READ) {    const some = ids.slice(i, i + TWINS_A_READ);    const marks = some.map(() => "?").join(", ");    for (const r of sql.exec<{ twin: string; id: string; expect_version: number; data: string; blind: string }>(      `SELECT twin, id, expect_version, data, blind FROM seal_twin WHERE table_id = ? AND twin IN (${marks})`,      table,      ...some,    ))      out.push({ twin: r.twin, id: r.id, expect_version: Number(r.expect_version), data: JSON.parse(r.data) as Record<string, unknown>, blind: JSON.parse(r.blind) as string[] });  }  return out.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));}/** Twins named in one statement: under the hundred values the object's SQL binds. */const TWINS_A_READ = 90;/** * Put each verified twin in place of its row: `apply` writes the row (the * engine's update, which drops the clear copies of sealed columns from the * row and its logged changes) and its blind tokens. A row that moved since * the stage, or is gone, drops its twin and is left by name. */export function commit(  host: MigrationHost,  t: SealedTable,  ids: unknown[],  apply: (id: string, data: Record<string, unknown>, blind: string[]) => void,): { sealed: string[]; left: Left[] } {  const named = ids.map((x, i) => (typeof x === "string" && x ? x : refuse(400, "bad_args", `twins[${i}] is a twin's id, as seal_stage answered it`)));  const kept = new Map(twins(host.sql, t.id, named).map((tw) => [tw.twin, tw]));  const sealed: string[] = [];  const left: Left[] = [];  for (const name of named) {    const tw = kept.get(name);    if (!tw) {      left.push({ id: name, code: "no_such_twin" });      continue;    }    host.sql.exec("DELETE FROM seal_twin WHERE twin = ?", name);    const held = host.row(t.id, tw.id);    if (!held) {      left.push({ id: tw.id, code: "no_such_record" });      continue;    }    if (held.version !== tw.expect_version) {      left.push({ id: tw.id, code: "version_moved" });      continue;    }    apply(tw.id, tw.data, tw.blind);    sealed.push(tw.id);  }  return { sealed, left };}/** * The act log's earlier args for `table`, its sealed columns taken out * (§7 step 4). `scrub` is the act log's own rule for a new act (so an old * act ends as a new one is logged); an args text the log cut at its length * limit does not read as JSON and is replaced whole by a mark. An act whose * args name the table (`"table":"<id>"`) is found by that; one that writes it * by its own table rule without naming it (`ownActs`: the business `message` * act → business_message) is found by its act. With `dry`, nothing is * written: the count is what a purge would change. */export function purgeActs(sql: SqlStorage, table: string, ownActs: readonly string[], scrub: (act: string, args: Record<string, unknown>) => Record<string, unknown>, dry = false): number {  let changed = 0;  // JSON.stringify writes `"table":"<id>"` with no space; a table id is a plain word (definitions refuse quotes).  const like = `%"table":${JSON.stringify(table).replace(/[%_\\]/g, (c) => `\\${c}`)}%`;  // Read one act at a time: a big object's act log does not fit the isolate's memory whole. The writes wait until  // the read is done (a statement is not changed under its own cursor), and only the acts that change are held.  const seen = new Set<string>();  const writes: { id: string; args: string }[] = [];  const take = (a: { id: string; act: string; args: string }) => {    if (seen.has(a.id)) return;    seen.add(a.id);    let next: string;    try {      next = JSON.stringify(scrub(a.act, JSON.parse(a.args) as Record<string, unknown>)).slice(0, 4000);    } catch {      next = JSON.stringify({ table, args: `${SCRUBBED} (cut by the log's length, held a sealed table)` });    }    if (next === a.args) return;    changed++;    if (!dry) writes.push({ id: a.id, args: next });  };  for (const a of sql.exec<{ id: string; act: string; args: string }>("SELECT id, act, args FROM acts WHERE args LIKE ? ESCAPE '\\'", like)) take(a);  if (ownActs.length) for (const a of sql.exec<{ id: string; act: string; args: string }>(`SELECT id, act, args FROM acts WHERE act IN (${ownActs.map(() => "?").join(", ")})`, ...ownActs)) take(a);  for (const w of writes) sql.exec("UPDATE acts SET args = ? WHERE id = ?", w.args, w.id);  return changed;}/** One sealed table's standing, as counts only (§7 step 7). */export interface Standing {  table: string;  /** Live rows. */  rows: number;  /** Live rows held sealed. */  sealed: number;  /** Live rows still open, not kept open: what a sweep has yet to seal. */  open: number;  /** Live open rows the person keeps open for good (Q3). */  keep_open: number;  /** Twins staged and not yet committed. */  twins: number;  /** Logged changes of sealed rows that still hold a sealed column in the clear (always 0: the commit scrubs them). */  change_plain: number;  /** Earlier acts whose args still hold a sealed column of this table: what `seal_purge` takes out. */  acts_plain: number;  /**   * Live sealed rows that still hold a sealed column in the clear beside their seal: rows sealed under a wider clear   * list than the table's now (LOCK TABLES 1). The migration reseals them whole (crates/cotton-client seal::migrate).   */  clear_left: number;  /**   * Live rows holding a key that is no column of the table (one a definition has since dropped), not null, but the seal's   * own fields, the arrival patches and the keep-open mark (LOCK TABLES 2 M1). A sealed one is also in `clear_left`.   */  stray: number;  /** Rows a phone holding an older, wider clear list wrote since the narrowing, marked for the reseal (src/seal_wide.ts). */  wide: number;  /** When the last of them was taken: the acceptance is removed only once none has come for long. */  wide_last: string | null;  /** The sealed columns an earlier clear list kept clear: the ones a phone may still say in the clear. */  was_clear: string[];}export function standing(sql: SqlStorage, t: SealedTable, ownActs: readonly string[], scrub: (act: string, args: Record<string, unknown>) => Record<string, unknown>): Standing {  // Counted in SQL along the table's own index, one row at a time and no row parsed here: a table of 300,000  // sealed messages read into the isolate (and its ids held in a set) took seconds and hundreds of megabytes  // (audit, 21 Nov 2026). A sealed row holds `sealed_enc` as text (isSealedRow).  const counted = sql    .exec<{ rows: number; sealed: number | null; keep: number | null }>(      `SELECT COUNT(*) AS rows, SUM(json_type(data, '$.${SEALED_ENC}') = 'text') AS sealed, SUM(json_type(data, '$.${SEALED_ENC}') IS NOT 'text' AND json_type(data, '$.keep_open') = 'true') AS keep FROM rows WHERE table_id = ? AND deleted = 0`,      t.id,    )    .one();  const rows = Number(counted.rows);  const sealed = Number(counted.sealed ?? 0);  const keep = Number(counted.keep ?? 0);  const columns = sealedColumns(t);  let changePlain = 0;  // The changes of rows held sealed now, each read as it comes.  for (const c of sql.exec<{ before: string | null; after: string | null }>(    `SELECT c.before, c.after FROM change c JOIN rows r ON r.table_id = c.table_id AND r.id = c.record_id WHERE c.table_id = ? AND r.deleted = 0 AND json_type(r.data, '$.${SEALED_ENC}') = 'text'`,    t.id,  )) {    const holds = (text: string | null) => text !== null && columns.some((k) => k in (JSON.parse(text) as Record<string, unknown>));    if (holds(c.before) || holds(c.after)) changePlain++;  }  const twinCount = Number(sql.exec<{ n: number }>("SELECT count(*) AS n FROM seal_twin WHERE table_id = ?", t.id).one().n);  // Counted in SQL as the rows above: a sealed row holding, not null, outside its seal, any key the table's clear list  // does not keep but the seal's own fields, the id, the arrival patches and the keep-open mark. The same set as  // cotton-client seal::migrate `clear_left` (LOCK TABLES 2 M1), so this count is what the reseal takes up.  const notSealed = JSON.stringify([...(t.seal?.clear ?? []), "id", ...SEAL_FIELDS, ARRIVAL_PATCHES, KEEP_OPEN]);  const clearLeft = Number(    sql      .exec<{ n: number }>(        `SELECT count(*) AS n FROM rows r WHERE r.table_id = ? AND r.deleted = 0 AND json_type(r.data, '$.${SEALED_ENC}') = 'text' AND EXISTS (SELECT 1 FROM json_each(r.data) j WHERE j.type != 'null' AND j.key NOT IN (SELECT value FROM json_each(?)))`,        t.id,        notSealed,      )      .one().n,  );  const noColumn = JSON.stringify([...t.columns.map((c) => c.key), "id", ...SEAL_FIELDS, ARRIVAL_PATCHES, KEEP_OPEN]);  const stray = Number(    sql      .exec<{ n: number }>(        `SELECT count(*) AS n FROM rows r WHERE r.table_id = ? AND r.deleted = 0 AND EXISTS (SELECT 1 FROM json_each(r.data) j WHERE j.type != 'null' AND j.key NOT IN (SELECT value FROM json_each(?)))`,        t.id,        noColumn,      )      .one().n,  );  return {    table: t.id,    rows,    sealed,    open: rows - sealed - keep,    keep_open: keep,    twins: twinCount,    change_plain: changePlain,    acts_plain: purgeActs(sql, t.id, ownActs, scrub, true),    clear_left: clearLeft,    stray,    ...sealWide.standing(sql, t.id),  };}/** A sealed table's act args as the log keeps them: its data's sealed columns marked, its blind tokens counted. */export function scrubRow(t: SealedTable, row: Record<string, unknown>): Record<string, unknown> {  const out: Record<string, unknown> = { ...row };  if (row.data && typeof row.data === "object" && !Array.isArray(row.data)) out.data = scrubData(t, row.data as Record<string, unknown>);  if ("blind" in row && !(typeof row.blind === "string" && row.blind.endsWith("tokens"))) out.blind = Array.isArray(row.blind) ? `${row.blind.length} tokens` : "‹blind›";  return out;}