Cotton code
183 lines · 7.7 KB · TypeScriptRaw
/** * The Rust engine tests' `TestFile`, over a real personal object: the engine * plans against the object's own store through a `Reader`, the changes land * through the object's engine in one write, and the rows are read back from * `rows`. Ids are minted COUNTED, as the Rust file mints them, so a test can * name the id it expects. The owner's number is the Rust fixture's: none, * unless a test gives one. */import { env, runInDurableObject } from "cloudflare:test";import type { Engine, Outcome } from "../src/engine.ts";import { applyChanges, type Applied } from "../src/import/apply.ts";import type { Change } from "../src/import/contacts.ts";import type { ImportBatch } from "../src/import/envelope.ts";import { planImport, planMessageChanges, planReplyLinks, type ChangesReport, type ChatResult, type GroupResult, type MessageChange } from "../src/import/messages.ts";import { Reader } from "../src/import/reader.ts";import type { Store } from "../src/store.ts";import { DATABASE_ID, personalObject, CLEAR_IMPORT_OPEN } from "./personal.ts";export const WORKSPACE = DATABASE_ID;export const NOW = "2026-08-22T00:00:00.000Z";export const RESERVED = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";interface Internals {  store: Store;  importWrite<T>(fn: (engine: Engine, version: number, outcome: Outcome, applied: Applied) => T): { result: T; version: number; applied: Applied };}export interface Row {  id: string;  data: Record<string, unknown>;  created_at: string;}export interface ImportReport {  chats: ChatResult[];  group: GroupResult | null;  totals: { chats: number; inserted: number; skipped: number; unresolvedReplies: number };}let opened = 0;export class TestFile {  readonly slug: string;  /** The object's owner number as the engine reads it; the Rust fixture has none. */  ownerPhone: string | null = null;  private minted = 0;  private constructor(slug: string) {    this.slug = slug;  }  static async open(prefix = "imp"): Promise<TestFile> {    opened += 1;    const file = new TestFile(`${prefix}-${opened}-${Math.random().toString(36).slice(2, 8)}`);    // The object's legacy import routes, over People open (the Mac decides messages, calls and photos itself now; People are sealed by the kit).    // These routes are refused once a table they write is sealed (ROUTES-AUDIT 11), so their tables are opened too.    await personalObject(file.slug, CLEAR_IMPORT_OPEN);    return file;  }  /** A minted row id, shaped like a uuid and counted. */  nextId(): string {    this.minted += 1;    return `00000000-0000-4000-8000-${String(this.minted).padStart(12, "0")}`;  }  within<T>(fn: (o: Internals, reader: Reader) => T): Promise<T> {    const stub = env.BUSINESS.get(env.BUSINESS.idFromName(this.slug));    return runInDurableObject(stub, (instance) => {      const o = instance as unknown as Internals;      return fn(o, new Reader(o.store, this.ownerPhone));    });  }  /** Changes landed in one write, as the route lands them. */  apply(changes: Change[]): Promise<void> {    return this.within((o) => {      o.importWrite((engine, version, outcome, applied) => applyChanges(engine, changes, version, outcome, applied));    });  }  /** One run, applied: the plan, the rows, then the reply pass over what landed. */  import(batch: ImportBatch): Promise<ImportReport> {    return this.within((o, reader) => {      const { result } = o.importWrite((engine, version, outcome, applied) => {        const plan = planImport(reader, { batch, namespace: WORKSPACE, now: NOW, newId: () => this.nextId() });        applyChanges(engine, plan.changes, version, outcome, applied);        let unresolved = 0;        for (const chat of plan.chats) {          const links = planReplyLinks(reader, chat.threadId, batch.channel);          unresolved += links.unresolved;          applyChanges(engine, links.changes, version, outcome, applied);        }        return { plan, unresolved };      });      const { plan, unresolved } = result;      return {        chats: plan.chats,        group: plan.group,        totals: { chats: plan.chats.length, inserted: plan.chats.reduce((n, c) => n + c.inserted, 0), skipped: plan.chats.reduce((n, c) => n + c.skipped, 0), unresolvedReplies: unresolved },      };    });  }  /** The import's refusal, or null when it ran. */  async tryImport(batch: ImportBatch): Promise<Error | null> {    try {      await this.import(batch);      return null;    } catch (error) {      return error as Error;    }  }  messageChanges(channel: string, changes: MessageChange[]): Promise<ChangesReport> {    return this.within((o, reader) => {      const { result } = o.importWrite((engine, version, outcome, applied) => {        const plan = planMessageChanges(reader, WORKSPACE, channel, changes);        applyChanges(engine, plan.changes, version, outcome, applied);        return plan.report;      });      return result;    });  }  /** A row straight into `rows`, as the Rust tests seed a table. */  seed(table: string, id: string, data: Record<string, unknown>, createdAt = NOW): Promise<void> {    return this.within((o) => {      o.store.insert(table, id, data, null, o.store.version(), { created_at: createdAt, updated_at: createdAt });    });  }  seedPerson(id: string, name: string, extra: Record<string, unknown> = {}): Promise<void> {    return this.seed("person", id, { full_name: name, created_at: NOW, updated_at: NOW, ...extra });  }  seedContact(id: string, phone: string, displayName: string | null): Promise<void> {    return this.seed("message_contact", id, { id, phone_e164: phone, display_name: displayName, created_at: NOW, updated_at: NOW });  }  seedPhone(id: string, person: string, normalised: string, kind = "phone"): Promise<void> {    return this.seed("person_handle", id, { person_id: person, kind, value: normalised, normalised, source: "contacts", created_at: NOW, updated_at: NOW });  }  /** Set (or with `undefined`, remove) one data key on every live row of a table. */  set(table: string, key: string, value: unknown): Promise<void> {    return this.within((o) => {      if (value === undefined) o.store.query(`UPDATE rows SET data = json_remove(data, '$.${key}') WHERE table_id = ? AND deleted = 0`, table);      else o.store.query(`UPDATE rows SET data = json_set(data, '$.${key}', json(?)) WHERE table_id = ? AND deleted = 0`, JSON.stringify(value), table);    });  }  rows(table: string): Promise<Row[]> {    return this.within((o) =>      o.store        .query<{ id: string; data: string; created_at: string }>("SELECT id, data, created_at FROM rows WHERE table_id = ? AND deleted = 0 ORDER BY created_at, id", table)        .map((r) => ({ id: r.id, data: JSON.parse(r.data) as Record<string, unknown>, created_at: r.created_at })),    );  }  /** The person the object names as its owner (src/owner.ts): every personal object holds one from its owner's first sign-in. */  owner(): Promise<string | null> {    return this.within((o) => o.store.meta("owner_person_id"));  }  async count(table: string): Promise<number> {    return (await this.rows(table)).length;  }  /** One data column of every live row, sorted by `by` (a data key), as the Rust `column(… ORDER BY …)`. */  async column(table: string, key: string, by?: string): Promise<unknown[]> {    const rows = await this.rows(table);    // SQLite's BINARY collation: code unit order, never a locale's.    const text = (r: Row): string => String(r.data[by!] ?? "");    if (by) rows.sort((a, b) => (text(a) < text(b) ? -1 : text(a) > text(b) ? 1 : 0));    return rows.map((r) => (key === "id" ? r.id : (r.data[key] ?? null)));  }  async one(table: string, where: (r: Row) => boolean = () => true): Promise<Row | undefined> {    return (await this.rows(table)).find(where);  }}