Cotton code
230 lines · 10.0 KB · TypeScriptRaw
/** * From what life.db holds to the rows the object's import takes, in an order * it accepts: every row whose link names a row that will not be there is * dealt with BEFORE anything is sent, and said. * * - A required link (or a required value) that is missing drops the row; the *   drop can cascade (a dropped session drops its prompts) and every drop is *   counted by its reason. * - An optional link whose target is not coming is cleared, and counted. * - A project link files a record by kind (a thread, a person, an email…); *   it comes only when that record comes. A journal entry is a note. A group *   member is a todo of a todo list. * - A mail date outside 1900–2100 is not a date (crates/cotton-mac's *   mail_date): the old app stored a header's year as it read it before it *   bounded them, so an email dated outside them is dropped — the Mac's mail import *   does not ingest a message with no believable date either — and a mail *   thread's first_at / last_at outside them is cleared; both are counted. * - Rows go targets first (a row-level topological order over the links), so *   the object's link check passes inside one batch and across batches. */import type { Candidate, ColumnJson, DefinitionJson, Source, TableJson } from "./source.ts";import { Refusal } from "./refusal.ts";export interface ImportRow {  verb: "put";  table: string;  id: string;  data: Record<string, unknown>;  created_at?: string;  updated_at?: string;}export interface TableReport {  table: string;  seen: number;  /** Rows dropped, by reason. */  dropped: Map<string, number>;  /** Links cleared, by column. */  cleared: Map<string, number>;  /** Mail dates cleared as not believable, by column. */  undated: Map<string, number>;  /** How many rows go to the object. */  sent: number;}export interface Plan {  workspaceId: string;  rows: ImportRow[];  /** The made tables' definitions the package does not ship, for POST /v1/admin/definitions/tables. */  definitions: TableJson[];  /** The owner's tools, for POST /v1/admin/definitions/tools. */  tools: DefinitionJson[];  /** The owner's boards, for POST /v1/admin/definitions/boards. */  boards: DefinitionJson[];  report: TableReport[];  left: string[];}/** The table a project link's record_kind files: its own name, but a journal entry is a note. */const filedTable = (kind: string): string => (kind === "journal" ? "note" : kind);const empty = (v: unknown): boolean => v === undefined || v === null || v === "";/** The years a mail date may carry (crates/cotton-mac/src/mail/mail_date.rs `YEARS`). */export const MAIL_YEARS = { first: 1900, last: 2100 } as const;/** Whether a stored mail date is one: an ISO date inside {@link MAIL_YEARS}. */export function believableMailDate(v: unknown): boolean {  if (typeof v !== "string") return false;  const ms = Date.parse(v);  if (Number.isNaN(ms)) return false;  const year = new Date(ms).getUTCFullYear();  return year >= MAIL_YEARS.first && year <= MAIL_YEARS.last;}export const UNBELIEVABLE_MAIL_DATE = `dated outside ${MAIL_YEARS.first}–${MAIL_YEARS.last}`;/** The mail thread's dates, drawn from its emails' and cleared when not believable. */const THREAD_DATES = ["first_at", "last_at"] as const;export function planImport(source: Source, packageTables: Map<string, TableJson>): Plan {  const defs = new Map<string, TableJson>();  for (const t of source.tables) defs.set(t.table, packageTables.get(t.table)!);  for (const m of source.made) defs.set(m.definition.id, m.definition);  const links = (table: string): ColumnJson[] => (defs.get(table)?.columns ?? []).filter((c) => c.type === "link" && c.link_to && !c.computed && defs.has(c.link_to));  const required = (table: string): ColumnJson[] => (defs.get(table)?.columns ?? []).filter((c) => c.required && !c.computed);  const groups = [...source.tables, ...source.made.map((m) => ({ table: m.definition.id, rows: m.rows }))];  const reports = new Map<string, TableReport>(groups.map((g) => [g.table, { table: g.table, seen: g.rows.length, dropped: new Map(), cleared: new Map(), undated: new Map(), sent: 0 }]));  const drop = (c: Candidate, reason: string): void => {    const r = reports.get(c.table)!;    r.dropped.set(reason, (r.dropped.get(reason) ?? 0) + 1);  };  // Live rows by table and id; a row leaves this map when it is dropped.  const live = new Map<string, Map<string, Candidate>>(groups.map((g) => [g.table, new Map()]));  for (const g of groups) {    for (const c of g.rows) {      const data = { ...c.data };      const row: Candidate = { ...c, data };      if (g.table === "note" && !empty(data.trashed_at)) {        drop(row, "in the bin");        continue;      }      const missing = required(g.table).filter((col) => empty(data[col.key]));      if (missing.length) {        drop(row, `no ${missing.map((m) => m.key).join(", ")}`);        continue;      }      if (g.table === "email" && !empty(data.sent_at) && !believableMailDate(data.sent_at)) {        drop(row, UNBELIEVABLE_MAIL_DATE);        continue;      }      if (g.table === "email_thread") {        for (const key of THREAD_DATES) {          if (empty(data[key]) || believableMailDate(data[key])) continue;          data[key] = null;          const r = reports.get(g.table)!;          r.undated.set(key, (r.undated.get(key) ?? 0) + 1);        }      }      if (live.get(g.table)!.has(row.id)) throw new Refusal(`life.db holds two ${g.table} rows with id ${row.id}`);      live.get(g.table)!.set(row.id, row);    }  }  const has = (table: string, id: unknown): boolean => typeof id === "string" && (live.get(table)?.has(id) ?? false);  // Until nothing moves: a row whose required target went goes too; an optional link to a missing row is cleared.  for (let moved = true; moved; ) {    moved = false;    for (const [table, rows] of live) {      for (const row of [...rows.values()]) {        let reason: string | null = null;        for (const col of links(table)) {          const v = row.data[col.key];          if (empty(v) || has(col.link_to!, v)) continue;          if (col.required) {            reason = `its ${col.key} is not there`;            break;          }          row.data[col.key] = null;          const r = reports.get(table)!;          r.cleared.set(col.key, (r.cleared.get(col.key) ?? 0) + 1);          moved = true;        }        if (!reason && table === "project_link") {          const kind = String(row.data.record_kind);          const filed = live.has(filedTable(kind)) ? filedTable(kind) : null;          if (!filed) reason = `files a ${kind}, which the personal database does not hold`;          else if (!has(filed, row.data.record_id)) reason = `its ${kind} is not there`;        }        if (!reason && table === "group_member" && !has("todo", row.data.record_id)) reason = "its todo is not there";        if (reason) {          drop(row, reason);          rows.delete(row.id);          moved = true;        }      }    }  }  // Targets first: a depth-first walk over each row's links, in table order —  // with its own stack, as a chain of replies runs deeper than the call stack.  const ordered: Candidate[] = [];  const state = new Map<string, "visiting" | "done">();  const keyOf = (row: Candidate): string => `${row.table}/${row.id}`;  const targets = (row: Candidate): Candidate[] =>    links(row.table)      .map((col) => live.get(col.link_to!)?.get(row.data[col.key] as string))      .filter((t): t is Candidate => t !== undefined);  for (const g of groups) {    for (const start of live.get(g.table)!.values()) {      if (state.get(keyOf(start)) === "done") continue;      const stack: { row: Candidate; next: Candidate[] }[] = [{ row: start, next: targets(start) }];      state.set(keyOf(start), "visiting");      while (stack.length) {        const top = stack[stack.length - 1]!;        const target = top.next.shift();        if (!target) {          state.set(keyOf(top.row), "done");          ordered.push(top.row);          stack.pop();          continue;        }        const s = state.get(keyOf(target));        if (s === "done") continue;        if (s === "visiting") {          const path = [...stack.slice(stack.findIndex((f) => keyOf(f.row) === keyOf(target))).map((f) => keyOf(f.row)), keyOf(target)];          throw new Refusal(`rows link in a circle (${path.join(" → ")}); the object cannot take them in any order`);        }        state.set(keyOf(target), "visiting");        stack.push({ row: target, next: targets(target) });      }    }  }  const rows: ImportRow[] = ordered.map((c) => {    reports.get(c.table)!.sent += 1;    const out: ImportRow = { verb: "put", table: c.table, id: c.id, data: c.data };    if (c.created_at) out.created_at = c.created_at;    if (c.updated_at) out.updated_at = c.updated_at;    return out;  });  // A tool's picture is a photo record: it draws on the object only when that photo comes.  const left = [...source.left];  for (const tool of source.tools) {    const photo = (tool.picture as { photo?: unknown } | null | undefined)?.photo;    if (typeof photo === "string" && !has("photo", photo)) left.push(`tool ${tool.id}: its picture names ${photo}, which is not coming, so the object has no picture for it`);  }  return { workspaceId: source.workspaceId, rows, definitions: source.made.filter((m) => !m.packaged).map((m) => m.definition), tools: source.tools, boards: source.boards, report: [...reports.values()], left };}/** Import calls of at most `maxRows` rows and about `maxBytes` of JSON each, in order. */export function batches(rows: ImportRow[], maxRows = 5000, maxBytes = 8_000_000): ImportRow[][] {  const out: ImportRow[][] = [];  let current: ImportRow[] = [];  let bytes = 0;  for (const row of rows) {    const size = Buffer.byteLength(JSON.stringify(row));    if (current.length && (current.length >= maxRows || bytes + size > maxBytes)) {      out.push(current);      current = [];      bytes = 0;    }    current.push(row);    bytes += size;  }  if (current.length) out.push(current);  return out;}