Cotton code
175 lines · 9.0 KB · TypeScriptRaw
/** * COTTON DATA'S ROUTES (assets/design/data/CONTRACT.md "The Worker", 25 Nov 2026): a read-only window on the whole * database for the owner's own devices. Each is a GET, refused to any token, member or admin, and none answers a * sealed value or anything the object does not already hold in clear: a page of rows is what a sync page carries * (sealed blobs and clear columns), and every other answer is ids, table and column names, counts, sizes and dates. * * - `GET /v1/data/tables`: room and rows per table, from the storage measure (src/storage_measure.ts), as *   storage_summary says it, with each table's oldest and newest live row. * - `GET /v1/data/page?table=<t>[&order=made|changed][&from=<iso>][&to=<iso>][&before=<at>[&id=<id>]][&limit=<n>]`: any *   table's live rows, newest first by when made (or last changed), within a made range; `before` is the last row's *   created_at (updated_at for `changed`). * - `GET /v1/data/years?table=<t>`: the table's live rows per year made. * - `GET /v1/data/points?table=<t>&id=<id>[&limit=<n>]`: the rows whose single-valued link names this row. * - `GET /v1/data/changes?[before=<id>][&table=<t>][&who=you|apps|assistants][&limit=<n>]`: the change log's heads. * - `GET /v1/data/leftovers`: retired tables' rows, and links that point at nothing (the measure's). */import { machineWrite, MACHINE_WRITERS } from "./changes.ts";import type { Definitions, TableDef } from "./definitions.ts";import { integer, refuse } from "./http.ts";import { GONE_TABLES } from "./retired.ts";import { wire, type Store } from "./store.ts";import { TOKEN_TABLE } from "./tokens.ts";type Data = Record<string, unknown>;export interface DataHost {  store: Store;  defs: Definitions;  /** The file's size and its cap. */  database: { bytes: number; cap: number };  now: Date;}export const PAGE_LIMIT = { fallback: 50, most: 500 };export const POINTS_LIMIT = { fallback: 50, most: 200 };export const CHANGES_LIMIT = { fallback: 100, most: 500 };const WHO = ["you", "apps", "assistants"] as const;type Who = (typeof WHO)[number];/** Answers the route at `path`, or null when it is none of Data's. */export function dataRoute(h: DataHost, path: string, params: URLSearchParams): Data | null {  switch (path) {    case "/v1/data/tables":      return tables(h);    case "/v1/data/page":      return page(h, params);    case "/v1/data/years":      return years(h, params);    case "/v1/data/points":      return points(h, params);    case "/v1/data/changes":      return changes(h, params);    case "/v1/data/leftovers":      return leftovers(h);    default:      return null;  }}function limitOf(params: URLSearchParams, l: { fallback: number; most: number }): number {  const n = params.has("limit") ? integer(params.get("limit"), "limit", l.fallback) : l.fallback;  if (n < 1 || n > l.most) refuse(400, "bad_request", `limit is 1 to ${l.most}`);  return n;}/** A table a device may page: one the object defines, never its own internal ones (nor a retired one, which it no longer serves). */function tableOf(h: DataHost, params: URLSearchParams): TableDef {  const table = params.get("table") ?? refuse(400, "bad_request", "name the table: table=<table>");  const t = h.defs.table(table);  if (!t || t.raw.internal === true) refuse(404, "no_such_table", `no table ${table}`);  return t;}function tables(h: DataHost): Data {  // The measure reads the whole file: a big object's is its alarm's last, said with when; until the first, the rows as  // row_counts holds them and the rest null (storage_summary's rule, src/mcp/tools/records/summary.ts).  const { measure, measuring } = h.store.storageMeasure(h.now);  const tables = measure    ? measure.tables.map((t) => ({ table: t.table, rows: t.rows, tombstones: t.tombstones, bytes: t.bytes, oldest: t.oldest ?? null, newest: t.newest ?? null }))    : h.store.countsProgress().ready      ? Object.entries(h.store.counts()).map(([table, rows]) => ({ table, rows, tombstones: null, bytes: null, oldest: null, newest: null }))      : [];  const out: Data = { database: h.database, measured: measure ? { at: measure.at } : null, parts: measure ? measure.parts : null, tables };  if (measuring) out.measuring = measuring;  return out;}function page(h: DataHost, params: URLSearchParams): Data {  const t = tableOf(h, params);  const before = params.get("before");  if (before !== null && (before.length === 0 || before.length > 40)) refuse(400, "bad_request", "before is a created_at");  const id = params.get("id") ?? "";  if (id.length > 200) refuse(400, "bad_request", "id is a row's id");  const limit = limitOf(params, PAGE_LIMIT);  const order = params.get("order") ?? "made";  if (order !== "made" && order !== "changed") refuse(400, "bad_request", "order is made or changed");  const instant = (key: string): string | null => {    const v = params.get(key);    if (v === null) return null;    if (v.length > 40 || Number.isNaN(Date.parse(v))) refuse(400, "bad_request", `${key} is an ISO instant`);    return v;  };  const rows = h.store.madePage(t.id, before === null ? null : [before, id], limit + 1, { order, from: instant("from"), to: instant("to") });  return { table: t.id, order, rows: rows.slice(0, limit).map((r) => wire(r, false)), more: rows.length > limit };}/** `GET /v1/data/years?table=<t>`: the table's live rows per year made, for Sort and dates' bars. */function years(h: DataHost, params: URLSearchParams): Data {  const t = tableOf(h, params);  return { table: t.id, years: h.store.madeYears(t.id) };}function points(h: DataHost, params: URLSearchParams): Data {  const t = tableOf(h, params);  const id = params.get("id") ?? refuse(400, "bad_request", "name the row: id=<id>");  if (!id || id.length > 200) refuse(400, "bad_request", "id is a row's id");  const limit = limitOf(params, POINTS_LIMIT);  const out: Data[] = [];  // The links index holds a link column's value when it is one id (src/store.ts writeLinks): a link of several values  // is not indexed, so it is not asked.  for (const from of h.defs.tables.values()) {    if (from.raw.internal === true) continue;    for (const c of from.columns) {      if (c.type !== "link" || c.computed || c.multiple || c.link_to !== t.id) continue;      const { count, ids } = h.store.pointing(from.id, c.key, id, limit);      if (count) out.push({ table: from.id, column: c.key, count, ids });    }  }  out.sort((a, b) => Number(b.count) - Number(a.count) || String(a.table).localeCompare(String(b.table)) || String(a.column).localeCompare(String(b.column)));  return { points: out };}/** Who wrote a change, as Data groups it: an assistant's token, an app's own machine write (MACHINE_WRITERS), or a person by hand. */export function actorKind(actor: string | null, via: string | null, tokens: ReadonlySet<string>): "person" | "app" | "assistant" {  if (actor !== null && tokens.has(actor)) return "assistant";  if (via !== null && machineWrite(via)) return "app";  return "person";}function changes(h: DataHost, params: URLSearchParams): Data {  const beforeText = params.get("before");  const before = beforeText === null ? null : integer(beforeText, "before");  let table: string | null = null;  if (params.has("table")) table = tableOf(h, params).id;  const whoText = params.get("who");  if (whoText !== null && !(WHO as readonly string[]).includes(whoText)) refuse(400, "bad_request", "who is you, apps or assistants");  const who = whoText as Who | null;  const limit = limitOf(params, CHANGES_LIMIT);  const tokens = h.store.allIds(TOKEN_TABLE);  const tokenSet = new Set(tokens);  const heads = h.store.changeHeads({ before, table, hidden: [...h.defs.internalTables()], who, tokens, machine: Object.keys(MACHINE_WRITERS), limit: limit + 1 });  // Bylines as list_changes says them (src/mcp/tools/records/changes.ts): the token's name, the person's, or the owner's own hand.  const said = new Map<string, string>();  const byline = (actor: string | null): string => {    if (actor === null) return "the owner";    let name = said.get(actor);    if (name === undefined) {      const token = tokenSet.has(actor) ? h.store.any(TOKEN_TABLE, actor) : null;      name = typeof token?.data.name === "string" && token.data.name ? token.data.name : (h.store.person(actor)?.name ?? actor);      said.set(actor, name);    }    return name;  };  return {    changes: heads.slice(0, limit).map((c) => ({ id: c.id, at: c.at, actor: byline(c.actor), actor_kind: actorKind(c.actor, c.via, tokenSet), via: c.via, table: c.table, record: c.record_id, kind: c.kind })),    more: heads.length > limit,  };}function leftovers(h: DataHost): Data {  const { measure } = h.store.storageMeasure(h.now);  const held = new Map<string, number>(measure ? measure.tables.map((t) => [t.table, t.rows]) : h.store.countsProgress().ready ? Object.entries(h.store.counts()) : []);  const retired = GONE_TABLES.map((table) => ({ table, rows: held.get(table) ?? 0 })).filter((t) => t.rows > 0);  return { measured: measure ? { at: measure.at } : null, retired, dangling: measure?.dangling ?? null };}