Cotton code
267 lines · 12.8 KB · TypeScriptRaw
/** * A BOOK'S OWN FILE FILLS ITS EMPTY COLUMNS IN THE OBJECT (lane * books-opf-rule, 7 Nov 2026): whoever writes a `book` row naming an EPUB * (the phone, Cotton Fetch, MCP, an import), the object reads the EPUB's * package document from its media and fills what the row leaves empty, by * the one OPF rule the phone's core and the Mac fetcher run * (crates/cotton-rules opf.rs, as WASM: `book.container` finds the package, * `book.opf` reads it). Every column it fills is the book's (author, * publisher, description, subjects, ISBN, DOI, Open Library work and edition, * language, year, series and its number), and only an empty one: what a * person or another source wrote stays. The title is never written here (a * book always has one), nor the cover (the artwork engine's) or the rating. * * Each fill says itself in the book's `filled_from` as `opf`, beside what * other sources said (books.ts `stampFilled`); a pass that fills nothing * writes nothing, so no stamp. * * ONE READ PER FILE (`book_file_seen`): each book is read once for the file * it names, and what came of it is kept: `filled`, `nothing` (the package * filled nothing empty), `unreadable` (no zip, no package: never read again * until its file changes), `absent` (the media holds no such file yet: the * row came before its upload) or `failed` (the media did not answer); those * two are read again after RETRY_MS. It runs off the request that wrote a * book (src/business.ts `kickBookFiles`) and on the object's alarm; a pass * reads at most PER_PASS books, the newest written first. */import type { Engine, Outcome } from "./engine.ts";import { stampFilled } from "./books.ts";import { tryRule } from "./rules/index.ts";import type { Store } from "./store.ts";export const BOOK = "book";/** Books read in one pass: each is three or four ranged reads of its file. */export const PER_PASS = 10;/** A file not there yet, or a read the media did not answer, is tried again after this long. */export const RETRY_MS = 60 * 60 * 1000;/** The most a container or a package document may inflate to: metadata, never megabytes (as the core reads it). */export const MOST_PACKAGE_BYTES = 4 * 1024 * 1024;const SCHEMA = "CREATE TABLE IF NOT EXISTS book_file_seen (id TEXT PRIMARY KEY, file TEXT NOT NULL, outcome TEXT NOT NULL, at INTEGER NOT NULL)";/** A file read by range: its size, and `length` bytes at `offset`. */export interface Ranged {  size: number;  read(offset: number, length: number): Promise<Uint8Array>;}/** What the pass needs of the object: its store and SQL, one write in its own transaction and version, and a book's file by its media key (null when the media holds none). */export interface BookFileHost {  store: Store;  sql: SqlStorage;  write<T>(fn: (engine: Engine, version: number, outcome: Outcome) => T): T;  open(key: string): Promise<Ranged | null>;}/** A file that is no EPUB this reads: said, and not read again until the row names another file. */export class Unreadable extends Error {}/** The book's file is sealed on the person's device (R6): the object reads nothing of it, and the device's core fills the columns itself. */export class Sealed extends Error {}// ── the zip ──────────────────────────────────────────────────────────────interface Entry {  name: string;  method: number;  flags: number;  compressed: number;  size: number;  local: number;}const EOCD = 0x06054b50;const CENTRAL = 0x02014b50;const LOCAL = 0x04034b50;/** The end record (22 bytes) and the longest comment a zip may carry. */const TAIL = 22 + 0xffff;/** Every entry the zip's central directory names. A ZIP64 or a split archive is no EPUB this reads. */export async function entries(file: Ranged): Promise<Entry[]> {  if (file.size < 22) throw new Unreadable("it is too short to be a zip");  const tailAt = Math.max(0, file.size - TAIL);  const tail = await file.read(tailAt, file.size - tailAt);  const tv = new DataView(tail.buffer, tail.byteOffset, tail.byteLength);  let end = -1;  for (let i = tail.byteLength - 22; i >= 0; i--) {    if (tv.getUint32(i, true) === EOCD) {      end = i;      break;    }  }  if (end < 0) throw new Unreadable("it is not a zip");  const count = tv.getUint16(end + 10, true);  const length = tv.getUint32(end + 12, true);  const offset = tv.getUint32(end + 16, true);  if (count === 0xffff || length === 0xffffffff || offset === 0xffffffff) throw new Unreadable("it is a ZIP64, which this does not read");  if (offset + length > file.size) throw new Unreadable("its directory lies past its end");  const dir = await file.read(offset, length);  const dv = new DataView(dir.buffer, dir.byteOffset, dir.byteLength);  const names = new TextDecoder();  const out: Entry[] = [];  let at = 0;  for (let n = 0; n < count; n++) {    if (at + 46 > dir.byteLength || dv.getUint32(at, true) !== CENTRAL) throw new Unreadable("its directory does not read");    const nameLength = dv.getUint16(at + 28, true);    const extra = dv.getUint16(at + 30, true);    const comment = dv.getUint16(at + 32, true);    out.push({      flags: dv.getUint16(at + 8, true),      method: dv.getUint16(at + 10, true),      compressed: dv.getUint32(at + 20, true),      size: dv.getUint32(at + 24, true),      local: dv.getUint32(at + 42, true),      name: names.decode(dir.subarray(at + 46, at + 46 + nameLength)),    });    at += 46 + nameLength + extra + comment;  }  return out;}/** One entry's bytes as text: stored or deflated, never encrypted, at most MOST_PACKAGE_BYTES. */export async function entryText(file: Ranged, entry: Entry): Promise<string> {  if (entry.flags & 1) throw new Unreadable(`its ${entry.name} is encrypted`);  if (entry.size > MOST_PACKAGE_BYTES || entry.compressed > MOST_PACKAGE_BYTES) throw new Unreadable(`its ${entry.name} is larger than a package document is`);  const header = await file.read(entry.local, 30);  const hv = new DataView(header.buffer, header.byteOffset, header.byteLength);  if (header.byteLength < 30 || hv.getUint32(0, true) !== LOCAL) throw new Unreadable(`its ${entry.name} does not read`);  const start = entry.local + 30 + hv.getUint16(26, true) + hv.getUint16(28, true);  const data = entry.compressed ? await file.read(start, entry.compressed) : new Uint8Array();  if (entry.method === 0) return new TextDecoder().decode(data);  if (entry.method !== 8) throw new Unreadable(`its ${entry.name} is packed a way this does not read (method ${entry.method})`);  try {    const inflated = new Blob([data]).stream().pipeThrough(new DecompressionStream("deflate-raw"));    return await new Response(inflated).text();  } catch {    throw new Unreadable(`its ${entry.name} will not inflate`);  }}/** The facts `book.opf` answers that the pass uses: the book columns they fill. */interface OpfAnswer {  columns: Record<string, string | number>;}function ruled<T>(name: string, input: unknown): T {  const out = tryRule<T>(name, input);  if ("error" in out) throw new Unreadable(out.error);  return out.ok;}/** What the EPUB says of itself, by the rule: the book columns its package fills. */export async function packageColumns(file: Ranged): Promise<Record<string, string | number>> {  const all = await entries(file);  const named = (name: string) => all.find((e) => e.name === name);  const container = named("META-INF/container.xml");  if (!container) throw new Unreadable("it names no package document (META-INF/container.xml)");  const { opf_path } = ruled<{ opf_path: string | null }>("book.container", { xml: await entryText(file, container) });  if (!opf_path) throw new Unreadable("its container names no package document");  const opf = named(opf_path);  if (!opf) throw new Unreadable(`its package names ${opf_path}, which it does not hold`);  return ruled<OpfAnswer>("book.opf", { opf: await entryText(file, opf) }).columns;}// ── the pass ─────────────────────────────────────────────────────────────type Seen = "filled" | "nothing" | "unreadable" | "absent" | "failed" | "sealed";export function ready(host: Pick<BookFileHost, "sql">): void {  host.sql.exec(SCHEMA);}/** Whether book rows were written since `version`. */export function touched(store: Store, version: number): boolean {  // Along rows_cursor: only the rows written since (a few). By the table's own index it read every row of the table, after every write (LIVE CPU 2, 23 Nov 2026: 50,000 events on an object of his shape).  return store.query<{ n: number }>("SELECT count(*) AS n FROM (SELECT 1 FROM rows INDEXED BY rows_cursor WHERE version > ? AND table_id = ? LIMIT 1)", version, BOOK)[0]!.n > 0;}function due(host: BookFileHost, now: number, limit: number): { id: string; file: string }[] {  return host.store.query<{ id: string; file: string }>(    `SELECT r.id AS id, json_extract(r.data, '$.file') AS file FROM rows r LEFT JOIN book_file_seen s ON s.id = r.id      WHERE r.table_id = ? AND r.deleted = 0        AND lower(COALESCE(json_extract(r.data, '$.file'), '')) LIKE '%.epub'        AND (s.file IS NULL OR s.file != json_extract(r.data, '$.file') OR (s.outcome IN ('absent', 'failed') AND s.at <= ?))      ORDER BY r.version DESC, r.id LIMIT ?`,    BOOK,    now - RETRY_MS,    limit,  );}/** Whether any book waits for its file to be read. */export function pending(host: BookFileHost, now = Date.now()): boolean {  ready(host);  return due(host, now, 1).length > 0;}function mark(host: Pick<BookFileHost, "sql">, id: string, file: string, outcome: Seen, at: number): void {  host.sql.exec(    "INSERT INTO book_file_seen (id, file, outcome, at) VALUES (?, ?, ?, ?) ON CONFLICT (id) DO UPDATE SET file = excluded.file, outcome = excluded.outcome, at = excluded.at",    id,    file,    outcome,    at,  );}const empty = (value: unknown): boolean => value === null || value === undefined || (typeof value === "string" && !value.trim());/** The book's empty columns its package fills, as the object defines the table; the row unchanged when it names another file now. */function fill(engine: Engine, version: number, outcome: Outcome, id: string, file: string, columns: Record<string, string | number>): string[] | null {  const row = engine.store.get(BOOK, id);  if (!row || row.data.file !== file) return null;  const defined = new Set((engine.defs.table(BOOK)?.columns ?? []).map((c) => c.key));  const patch = Object.fromEntries(Object.entries(columns).filter(([k]) => k !== "title" && defined.has(k) && empty(row.data[k])));  if (!Object.keys(patch).length) return [];  engine.update(row, { ...patch, ...stampFilled(engine, row.data.filled_from, Object.keys(patch), "opf") }, version, outcome);  return Object.keys(patch);}/** What a pass did. */export interface BookFileAnswer {  filled: number;  nothing: number;  unreadable: number;  /** Books whose file is sealed: never read here, never again until it changes. */  sealed: number;  absent: number;  failed: number;  /** The pass stopped at its bound with books still to read. */  more: boolean;}/** One pass over the books whose file waits to be read (see above). Never throws: a book that fails is marked and said. */export async function pass(host: BookFileHost, now = Date.now()): Promise<BookFileAnswer> {  ready(host);  const answer: BookFileAnswer = { filled: 0, nothing: 0, unreadable: 0, absent: 0, failed: 0, sealed: 0, more: false };  const rows = due(host, now, PER_PASS + 1);  if (rows.length > PER_PASS) answer.more = true;  for (const { id, file } of rows.slice(0, PER_PASS)) {    const named = `book ${id}`;    let seen: Seen;    try {      const opened = await host.open(file);      if (!opened) {        seen = "absent";        console.log(`cottondb: book file ${named}: ${file} is not in the media yet; read again in an hour`);      } else {        const columns = await packageColumns(opened);        const wrote = host.write((engine, version, outcome) => fill(engine, version, outcome, id, file, columns));        if (wrote === null) continue; // it names another file now: the next pass reads that one        seen = wrote.length ? "filled" : "nothing";        if (wrote.length) console.log(`cottondb: book file ${named}: filled ${wrote.join(", ")}`);      }    } catch (error) {      const words = error instanceof Error ? error.message : String(error);      if (error instanceof Sealed) {        mark(host, id, file, "sealed", now);        answer.sealed++;        continue;      }      seen = error instanceof Unreadable ? "unreadable" : "failed";      console.log(`cottondb: book file ${named}: ${seen === "unreadable" ? `${file} cannot be read: ${words}` : `the media did not answer: ${words}; read again in an hour`}`);    }    mark(host, id, file, seen, now);    answer[seen]++;  }  return answer;}