Cotton code
350 lines · 17.7 KB · TypeScriptRaw
/** * THE ARTWORK ENGINE IN THE OBJECT (owner, 30 Oct 2026: "for both of these * we need a way to make that picture automatically"): a book's cover and a * film's poster are filled by the object itself, as the classifier fills an * event's kind (src/classify.ts) — a typed value, never a sentence. The * picture column is the one the table's slip draws (`slip.photo`: a book's * `cover`, a film's `poster`), and only an empty one is filled. * * - A book is looked up on Open Library (no key): by its ISBN when the row *   carries one (`isbn`), else by its title and author *   (`https://openlibrary.org/search.json`); the first match with a cover *   gives `https://covers.openlibrary.org/b/id/<cover_i>-L.jpg`. * - A film or a series is looked up on Wikidata (no key; TMDB needs one): *   `wbsearchentities` by its title, then the candidates' claims; the one *   that is a film or a series (its instance-of, or a description that says *   so), of the row's year where it has one, gives its film poster (P3383) *   or else its image (P18), drawn by Commons at POSTER_WIDTH. * * The picture is fetched, kept as the object's media under * `<database id>/photos/<sha256>.<ext>` (counted against the object's media, * as any upload is), and named in the row's picture column, in a write said * as `artwork`. One line is logged per fill and per miss. * * ONE TRY PER ROW (`artwork_seen`): each row is tried once for the words it * is looked up by (its basis: a book's title, author and ISBN, a film's * title, year and kind), and what came of it is kept — `filled`, `missing` * (the source knows no picture for it: never asked again until those words * change) or `failed` (the source did not answer, or answered no picture: * asked again after RETRY_MS, by the alarm). A row whose status or rating * changes is not asked again; a row whose title is corrected is. * * It runs where the classifier runs: off the request that wrote a book or a * film (src/business.ts `kickArtwork`), and on the object's alarm for rows * still waiting. A pass tries at most PER_PASS rows, the newest changed * first; one that stopped at its bound says so and the alarm carries on soon. */import type { Engine, Outcome } from "./engine.ts";import type { Store } from "./store.ts";/** Rows tried in one pass: each is two or three requests to a source and one picture. */export const PER_PASS = 10;/** A source that failed to answer is asked again after this long. */export const RETRY_MS = 24 * 60 * 60 * 1000;/** The width Commons draws a poster at (it snaps to its own steps). */export const POSTER_WIDTH = 1000;/** The largest picture kept: a cover or a poster, never a print master. */export const PICTURE_MAX_BYTES = 15 * 1024 * 1024;/** Who asks, as Open Library and Wikimedia ask a client to say. */export const USER_AGENT = "Cotton/1.0 (https://cottondb.com; artwork engine)";/** What a pass fetches with: the Worker's fetch, or a stub in a test. */export type Fetcher = (url: string, init?: RequestInit) => Promise<Response>;/** What the engine needs of the object: its store and SQL, its database id, one write in its own transaction and version, and the media it keeps pictures in. */export interface ArtworkHost {  store: Store;  sql: SqlStorage;  databaseId: string;  write<T>(fn: (engine: Engine, version: number, outcome: Outcome) => T): T;  /** Keeps `bytes` under the media key `key`, counted as an upload is. */  keep(key: string, bytes: Uint8Array, contentType: string): Promise<void>;}/** Where a picture was found, and how the log names it. */export interface Found {  url: string;  said: string;}/** A source of pictures for one table: what a row is looked up by, and how. */interface Source {  table: string;  /** The source's name, for the log. */  name: string;  /** The columns a row is looked up by, in the basis's order; the first is its title. */  by: string[];  /** The picture for `row`, null when the source knows none; throws when the source does not answer. */  find(row: Record<string, string>, fetcher: Fetcher): Promise<Found | null>;}export const SCHEMA = `CREATE TABLE IF NOT EXISTS artwork_seen (table_id TEXT NOT NULL, id TEXT NOT NULL, basis TEXT NOT NULL, outcome TEXT NOT NULL, wrote TEXT, at INTEGER NOT NULL, PRIMARY KEY (table_id, id));`;const KEY = /^[a-z][a-z0-9_]*$/;const headers = { "user-agent": USER_AGENT, accept: "application/json" };async function asked(fetcher: Fetcher, url: string): Promise<Record<string, unknown>> {  const res = await fetcher(url, { headers });  if (!res.ok) throw new Error(`${new URL(url).host} answered ${res.status}`);  return (await res.json()) as Record<string, unknown>;}// ── Open Library ─────────────────────────────────────────────────────────const OPEN_LIBRARY = "https://openlibrary.org/search.json";export const openLibrary: Source = {  table: "book",  name: "Open Library",  by: ["title", "author", "isbn"],  async find(row, fetcher) {    const isbn = (row.isbn ?? "").replace(/[^0-9Xx]/g, "");    const query = new URLSearchParams({ fields: "key,title,cover_i", limit: "5" });    if (isbn) query.set("isbn", isbn);    else {      query.set("title", row.title!);      if (row.author) query.set("author", row.author);    }    const answer = await asked(fetcher, `${OPEN_LIBRARY}?${query}`);    const docs = Array.isArray(answer.docs) ? (answer.docs as Record<string, unknown>[]) : [];    const doc = docs.find((d) => typeof d.cover_i === "number" && d.cover_i > 0);    if (!doc) return null;    return { url: `https://covers.openlibrary.org/b/id/${doc.cover_i as number}-L.jpg?default=false`, said: `${isbn ? `ISBN ${isbn}` : "title and author"}, ${String(doc.key)} cover ${doc.cover_i as number}` };  },};// ── Wikidata ─────────────────────────────────────────────────────────────const WIKIDATA = "https://www.wikidata.org/w/api.php";/** Instance-of classes that make an item a film or a series. */export const FILM_CLASSES = new Set([  "Q11424", // film  "Q24862", // short film  "Q24869", // feature film  "Q202866", // animated film  "Q17517379", // animated short film  "Q506240", // television film  "Q93204", // documentary film  "Q226730", // silent film  "Q229390", // 3D film  "Q5398426", // television series  "Q581714", // animated television series  "Q1259759", // miniseries  "Q63952888", // anime television series  "Q117467246", // animated television series (as some items say it)]);/** A description that says what the item is: "2010 computer-generated short film", "American television series". */const SAYS_FILM = /\b(film|movie|series|miniseries)$/i;type Claims = Record<string, { mainsnak?: { datavalue?: { value?: unknown } } }[]>;function values(claims: Claims, property: string): unknown[] {  return (claims[property] ?? []).map((c) => c.mainsnak?.datavalue?.value).filter((v) => v !== undefined);}export const wikidata: Source = {  table: "film",  name: "Wikidata",  by: ["title", "year", "kind"],  async find(row, fetcher) {    const search = await asked(fetcher, `${WIKIDATA}?${new URLSearchParams({ action: "wbsearchentities", format: "json", language: "en", uselang: "en", type: "item", limit: "7", search: row.title! })}`);    const hits = Array.isArray(search.search) ? (search.search as { id?: unknown; description?: unknown }[]) : [];    const ids = hits.map((h) => h.id).filter((id): id is string => typeof id === "string" && /^Q\d+$/.test(id));    if (!ids.length) return null;    const got = await asked(fetcher, `${WIKIDATA}?${new URLSearchParams({ action: "wbgetentities", format: "json", props: "claims", ids: ids.join("|") })}`);    const entities = (got.entities ?? {}) as Record<string, { claims?: Claims }>;    const year = /^\d{4}$/.test(row.year ?? "") ? row.year! : null;    const candidates = ids.flatMap((id, order) => {      const claims = entities[id]?.claims ?? {};      const description = String(hits[order]?.description ?? "").trim();      const classes = values(claims, "P31").map((v) => (v as { id?: string }).id);      const film = classes.some((c) => c && FILM_CLASSES.has(c)) || SAYS_FILM.test(description);      const file = [...values(claims, "P3383"), ...values(claims, "P18")].find((v): v is string => typeof v === "string" && v !== "");      if (!film || !file) return [];      const years = values(claims, "P577").map((v) => String((v as { time?: string }).time ?? "").slice(1, 5));      const ofYear = year !== null && (years.includes(year) || description.startsWith(year));      return [{ id, file, poster: values(claims, "P3383").length > 0, ofYear, order }];    });    // A row that says its year takes only a film of that year (never another film of its title); then a film poster over an image, then the search's own order.    const rank = (c: (typeof candidates)[number]): number => (c.poster ? 0 : 10) + c.order;    const best = candidates.filter((c) => year === null || c.ofYear).sort((a, b) => rank(a) - rank(b))[0];    if (!best) return null;    const name = best.file.replace(/ /g, "_");    return { url: `https://commons.wikimedia.org/wiki/Special:FilePath/${encodeURIComponent(name)}?width=${POSTER_WIDTH}`, said: `${best.id} ${best.poster ? "P3383" : "P18"} ${best.file}` };  },};export const SOURCES: Source[] = [openLibrary, wikidata];// ── the pass ─────────────────────────────────────────────────────────────/** The engine's own table, made where it is not. */export function ready(host: Pick<ArtworkHost, "sql">): void {  host.sql.exec(SCHEMA);}/** Whether rows of a table the engine fills were written since `version`. */export function touched(store: Store, version: number): boolean {  const tables = SOURCES.map((s) => `'${s.table}'`).join(", ");  // 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 IN (${tables}) LIMIT 1)`, version)[0]!.n > 0;}/** A table the engine fills, as the object defines it: the picture column its slip draws and the title it is looked up by. */interface Target {  source: Source;  picture: string;  /** The row's column for each of the source's `by`, null where the table has none. */  columns: (string | null)[];}function targets(store: Store): Target[] {  const defs = store.definitions("table");  return SOURCES.flatMap((source) => {    const def = defs.find((t) => t.id === source.table);    if (!def) return [];    const columns = Array.isArray(def.columns) ? (def.columns as Record<string, unknown>[]) : [];    const keys = new Set(columns.map((c) => c.key));    const slip = (def.slip ?? {}) as Record<string, unknown>;    const picture = typeof slip.photo === "string" ? slip.photo : null;    const title = typeof def.title === "string" ? def.title : null;    if (!picture || !KEY.test(picture) || columns.find((c) => c.key === picture)?.type !== "photo" || !title || !KEY.test(title) || !keys.has(title)) return [];    const by = source.by.map((k, i) => (i === 0 ? title : keys.has(k) && KEY.test(k) ? k : null));    return [{ source, picture, columns: by }];  });}/** The basis a row is looked up by, as SQL builds it and as it is kept. */function basisSql(target: Target): string {  return `json_array(${target.columns.map((c) => (c ? `trim(COALESCE(json_extract(r.data, '$.${c}'), ''))` : "''")).join(", ")})`;}interface Due {  id: string;  basis: string;}function due(host: ArtworkHost, target: Target, now: number, limit: number): Due[] {  const basis = basisSql(target);  return host.store.query<{ id: string; basis: string }>(    `SELECT r.id AS id, ${basis} AS basis FROM rows r LEFT JOIN artwork_seen s ON s.table_id = r.table_id AND s.id = r.id      WHERE r.table_id = ? AND r.deleted = 0        AND COALESCE(json_extract(r.data, '$.${target.picture}'), '') = ''        AND trim(COALESCE(json_extract(r.data, '$.${target.columns[0]}'), '')) != ''        AND (s.basis IS NULL OR s.basis != ${basis} OR (s.outcome = 'failed' AND s.at <= ?))      ORDER BY r.version DESC, r.id LIMIT ?`,    target.source.table,    now - RETRY_MS,    limit,  );}/** Whether any row waits for its picture. */export function pending(host: ArtworkHost, now = Date.now()): boolean {  ready(host);  return targets(host.store).some((t) => due(host, t, now, 1).length > 0);}function mark(host: Pick<ArtworkHost, "sql">, table: string, id: string, basis: string, outcome: "filled" | "missing" | "failed", wrote: string | null, at: number): void {  host.sql.exec(    "INSERT INTO artwork_seen (table_id, id, basis, outcome, wrote, at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (table_id, id) DO UPDATE SET basis = excluded.basis, outcome = excluded.outcome, wrote = excluded.wrote, at = excluded.at",    table,    id,    basis,    outcome,    wrote,    at,  );}const EXTENSIONS: Record<string, string> = { "image/jpeg": "jpg", "image/png": "png", "image/webp": "webp", "image/gif": "gif" };async function sha256(bytes: Uint8Array): Promise<string> {  const digest = await crypto.subtle.digest("SHA-256", bytes);  return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");}/** The picture at `url`, fetched and kept; its media key. Throws when it is not a picture the object keeps. */export async function picture(host: Pick<ArtworkHost, "databaseId" | "keep">, url: string, fetcher: Fetcher): Promise<string> {  return kept(host, await fetcher(url, { headers: { "user-agent": USER_AGENT, accept: "image/*" } }), url);}/** The picture `res` answered for `url`, kept as `picture` keeps one (a caller that reads the answer's status itself fetches it); its media key. Throws when it is not a picture the object keeps. */export async function kept(host: Pick<ArtworkHost, "databaseId" | "keep">, res: Response, url: string): Promise<string> {  if (!res.ok) throw new Error(`${new URL(url).host} answered ${res.status} for the picture`);  const type = (res.headers.get("content-type") ?? "").split(";")[0]!.trim().toLowerCase();  const ext = EXTENSIONS[type];  if (!ext) throw new Error(`${new URL(url).host} answered ${type || "no type"}, not a picture`);  const bytes = new Uint8Array(await res.arrayBuffer());  if (!bytes.byteLength || bytes.byteLength > PICTURE_MAX_BYTES) throw new Error(`the picture weighs ${bytes.byteLength} bytes`);  const key = `${host.databaseId}/photos/${await sha256(bytes)}.${ext}`;  await host.keep(key, bytes, type);  return key;}/** What a pass did. */export interface ArtworkAnswer {  /** Rows whose picture was written. */  filled: number;  /** Rows the source knows no picture for: not asked again until their words change. */  missing: number;  /** Rows the source did not answer for: asked again after RETRY_MS. */  failed: number;  /** The pass stopped at its bound with rows still to try. */  more: boolean;}/** One pass over every table the engine fills (see above). Never throws: a row that fails is marked and said. */export async function pass(host: ArtworkHost, fetcher: Fetcher, now = Date.now()): Promise<ArtworkAnswer> {  ready(host);  const answer: ArtworkAnswer = { filled: 0, missing: 0, failed: 0, more: false };  let left = PER_PASS;  for (const target of targets(host.store)) {    const rows = due(host, target, now, left + 1);    if (rows.length > left) answer.more = true;    for (const { id, basis } of rows.slice(0, left)) {      left--;      const words = JSON.parse(basis) as string[];      const row = Object.fromEntries(target.source.by.map((k, i) => [k, words[i] ?? ""]));      const named = `${target.source.table} ${id}`;      let found: Found | null;      let key: string;      try {        found = await target.source.find(row, fetcher);        if (!found) {          mark(host, target.source.table, id, basis, "missing", null, now);          answer.missing++;          console.log(`cottondb: artwork ${named}: ${target.source.name} knows no ${target.picture}; not asked again until its words change`);          continue;        }        key = await picture(host, found.url, fetcher);      } catch (error) {        mark(host, target.source.table, id, basis, "failed", null, now);        answer.failed++;        console.error(`cottondb: artwork ${named}: ${target.source.name} failed (${error instanceof Error ? error.message : String(error)}); asked again after a day`);        continue;      }      const wrote = host.write((engine, version, outcome) => {        const held = engine.store.get(target.source.table, id);        const value = held?.data[target.picture];        // Gone, given a picture meanwhile, or its words changed while it was looked up: the next pass sees it as it is.        if (!held || (typeof value === "string" && value !== "")) return false;        const still = host.store.query<{ basis: string }>(`SELECT ${basisSql(target)} AS basis FROM rows r WHERE r.table_id = ? AND r.id = ?`, target.source.table, id)[0]?.basis;        if (still !== basis) return false;        engine.update(held, { [target.picture]: key }, version, outcome);        return true;      });      if (!wrote) continue;      mark(host, target.source.table, id, basis, "filled", key, now);      answer.filled++;      console.log(`cottondb: artwork ${named}: ${target.picture} from ${target.source.name} (${found.said}) kept as ${key}`);    }    if (left <= 0) break;  }  if (left <= 0 && !answer.more) answer.more = targets(host.store).some((t) => due(host, t, now, 1).length > 0);  return answer;}