Cotton code
132 lines · 7.7 KB · TypeScriptRaw
/** * Narrowing a clear list never refuses a person's write (LOCK TABLES 2, H1; the rule for every narrowing: * assets/design/shared/SEALING-CONTRACT.md). * * A table's clear list narrows when a definition moves a column from clear to sealed, or seals a table that was open. * A phone still holding the older definitions seals under the wider list and sends the moved columns in the clear: its * pass posts its writes before it pulls definitions, and an offline phone saved them long before. Refusing such a write * (`sealed_in_clear`, a 400) dropped it from the phone's queue for good. * * So the object keeps, per table, every column an earlier list of its kept clear (`seal_was_clear`, recorded as the * definitions move, never removed but by the owner's word), and a device's write that names one in the clear is taken: * * - an empty value (null, "", [] or {}) is simply dropped; * - any other value is stored as said, and the row is marked "sealed wide" (`seal_wide`): it then holds a sealed column *   in the clear beside its seal, as a row sealed before the narrowing does (`clear_left` in seal-check), and the Mac's *   reseal (`seal-migrate`) opens it, seals it whole again and the commit drops the clear copy and the mark; * - the act's answer says `definitions_stale: true`, and the phone asks for the definitions before its next write. * * There is no clock on it: the acceptance stays until the owner removes it, once every device of every account has * pulled the narrower lists. */import { sealedColumns, type SealedTable } from "./seal.ts";export const SCHEMA = `CREATE TABLE IF NOT EXISTS seal_list (table_id TEXT PRIMARY KEY, clear TEXT, columns TEXT NOT NULL);CREATE TABLE IF NOT EXISTS seal_was_clear (table_id TEXT NOT NULL, col TEXT NOT NULL, at TEXT NOT NULL, PRIMARY KEY (table_id, col));CREATE TABLE IF NOT EXISTS seal_wide (table_id TEXT NOT NULL, id TEXT NOT NULL, columns TEXT NOT NULL, at TEXT NOT NULL, PRIMARY KEY (table_id, id));`;/** * The columns LOCK TABLES 1 moved from clear to sealed, recorded on every object whatever the order its definitions * moved in: an object whose kit keep ran before this record existed holds the narrower lists already, with nothing * left to compare them to. */export const LOCK_TABLES_1: Readonly<Record<string, readonly string[]>> = {  film: ["subtitles", "subtitle_note"],  film_episode: ["subtitles", "subtitle_note"],  story_draft_scene: ["setting", "place"],  meetings_meeting: ["marks"],};/** * LOCK TABLES 2 part 4's moves (assets/design/shared/LOCK-TABLES.md §6), recorded the same way: an object first started * on a build that already serves the narrower lists still takes an old phone's write of them. */export const LOCK_TABLES_4: Readonly<Record<string, readonly string[]>> = {  event: ["ical_uid", "timezone"],  meetings_meeting: ["speakers", "languages", "call", "languages_chosen"],  story_answer: ["question"],  assistant_ask: ["client"],  outbox: ["account"],  film: ["sha256", "oshash", "original_sha256", "minutes", "height", "bitrate"],  film_episode: ["sha256", "oshash", "original_sha256", "minutes", "height", "bitrate"],};/** The record of each lock round's narrowing, once (an object's first start on this build). */export function seed(sql: SqlStorage, now: string): void {  for (const round of [LOCK_TABLES_1, LOCK_TABLES_4]) for (const [table, columns] of Object.entries(round)) for (const col of columns) sql.exec("INSERT OR IGNORE INTO seal_was_clear (table_id, col, at) VALUES (?, ?, ?)", table, col, now);}/** * Hold each table's clear list as the object now serves it, and record every column a held list kept clear that the * served one seals. Run each time the definitions are read again after any of them moved (src/business.ts * `definitions`), so a kit keep, an admin write, a `definition` act and either lock are all seen. */export function note(sql: SqlStorage, tables: Iterable<SealedTable>, now: string): void {  const held = new Map<string, { clear: string | null; columns: string }>();  for (const r of sql.exec<{ table_id: string; clear: string | null; columns: string }>("SELECT table_id, clear, columns FROM seal_list")) held.set(r.table_id, { clear: r.clear, columns: r.columns });  for (const t of tables) {    const clear = t.seal ? JSON.stringify(t.seal.clear) : null;    const columns = JSON.stringify(t.columns.filter((c) => !c.computed).map((c) => c.key));    const was = held.get(t.id);    if (was && was.clear === clear && was.columns === columns) continue;    if (was && t.seal) {      // An open table kept every column it had clear.      const keptClear = new Set(JSON.parse(was.clear ?? was.columns) as string[]);      for (const col of sealedColumns(t)) if (keptClear.has(col)) sql.exec("INSERT OR IGNORE INTO seal_was_clear (table_id, col, at) VALUES (?, ?, ?)", t.id, col, now);    }    sql.exec("INSERT INTO seal_list (table_id, clear, columns) VALUES (?, ?, ?) ON CONFLICT (table_id) DO UPDATE SET clear = excluded.clear, columns = excluded.columns", t.id, clear, columns);  }}/** The sealed columns of `table` an earlier clear list kept clear. */export function wasClear(sql: SqlStorage, table: string): Set<string> {  return new Set(sql.exec<{ col: string }>("SELECT col FROM seal_was_clear WHERE table_id = ?", table).toArray().map((r) => r.col));}/** An empty value: what a phone's whole-row write says for a column it holds nothing in. */export function empty(value: unknown): boolean {  if (value === null || value === undefined || value === "") return true;  if (Array.isArray(value)) return value.length === 0;  return typeof value === "object" && Object.keys(value as object).length === 0;}export interface Admitted {  /** The write with its empty newly sealed columns dropped. */  data: Record<string, unknown>;  /** Newly sealed columns it says a value of, taken in the clear. */  kept: string[];  /** Newly sealed columns it said empty, dropped. */  dropped: string[];  /** Sealed columns no earlier list kept clear: still refused. */  refused: string[];}/** Sort a device's clear sealed columns (`clear`) by the rule above. The write itself is not changed. */export function admit(data: Record<string, unknown>, clear: readonly string[], was: ReadonlySet<string>): Admitted {  const out: Admitted = { data: { ...data }, kept: [], dropped: [], refused: [] };  for (const k of clear) {    if (!was.has(k)) out.refused.push(k);    else if (empty(data[k])) {      out.dropped.push(k);      delete out.data[k];    } else out.kept.push(k);  }  return out;}/** Mark a sealed row as holding `columns` in the clear beside its seal, or clear its mark when it holds none. */export function mark(sql: SqlStorage, table: string, id: string, columns: readonly string[], now: string): void {  if (columns.length) sql.exec("INSERT INTO seal_wide (table_id, id, columns, at) VALUES (?, ?, ?, ?) ON CONFLICT (table_id, id) DO UPDATE SET columns = excluded.columns, at = excluded.at", table, id, JSON.stringify(columns), now);  else sql.exec("DELETE FROM seal_wide WHERE table_id = ? AND id = ?", table, id);}/** Live rows marked sealed wide in `table`, and when the last was taken: counts only, never a value (seal-check). */export function standing(sql: SqlStorage, table: string): { wide: number; wide_last: string | null; was_clear: string[] } {  // A deleted row keeps its mark (an undo brings it back as it was) and is not counted.  const r = sql    .exec<{ n: number; last: string | null }>("SELECT count(*) AS n, max(w.at) AS last FROM seal_wide w JOIN rows r ON r.table_id = w.table_id AND r.id = w.id WHERE w.table_id = ? AND r.deleted = 0", table)    .one();  return { wide: Number(r.n), wide_last: r.last ?? null, was_clear: [...wasClear(sql, table)].sort() };}