Cotton code
156 lines · 10.2 KB · TypeScriptRaw
/** * The import end to end against `wrangler dev`, on a synthetic life.db: * *   cd apps/business && pnpm -s exec tsx scripts/__tests__/e2e-import.ts [--messages <n>] * * `--messages <n>` adds n invented messages to the file and times the import * and a whole owner sync, paged as the phone pages it: the object's * throughput at a personal database's volume. * Starts the Worker on a free port with its storage in a temp dir, onboards * the personal object (pnpm onboard), signs the owner in with the fixed * code, mints an owner token, runs `pnpm import-personal` twice and checks * through /v1/admin/export that the rows arrived as they were and the second * run changed nothing. A secret with a value stays on the Mac, named. A run * without its token file is refused and writes * nothing. wrangler dev is stopped and the temp dir removed however it ends. */import { type ChildProcess } from "node:child_process";import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { check, pnpm, startDevWorker, stop } from "./dev-worker.ts";import { PERSONAL } from "../../src/kits.ts";import { buildLifeDb, HOME_BOARD, WS } from "./fixture.ts";import { personalSlug } from "../dev-server";const tmp = mkdtempSync(join(tmpdir(), "e2e-import-"));let wrangler: ChildProcess | null = null;const cleanup = (): void => {  stop(wrangler);  wrangler = null;  rmSync(tmp, { recursive: true, force: true });};process.on("SIGINT", () => {  cleanup();  process.exit(130);});const bulkAt = process.argv.indexOf("--messages");const bulk = bulkAt >= 0 ? Number(process.argv[bulkAt + 1]) : 0;try {  const fixture = buildLifeDb(tmp, { messages: bulk });  const { base, api, credential } = await startDevWorker(tmp, WS, (child) => {    wrangler = child;  });  const minted = await api<{ token?: string }>("POST", "/v1/act", { act: "mint_token", args: { name: "e2e import", scopes: ["owner"], allow: "all" } }, credential);  check(minted.token?.startsWith(`ctn_${WS}_`), "an owner token is minted for the database");  const tokenFile = join(tmp, "token");  writeFileSync(tokenFile, `${minted.token!}\n`);  chmodSync(tokenFile, 0o600);  type Exported = { version: number; tables: { id: string }[]; tools: { id: string }[]; boards: { id: string }[]; rows: { table: string; id: string; data: Record<string, unknown>; created_at: string; updated_at: string; version: number }[]; next: string | null };  // Every page of the export: the meta from the first, the rows of all.  const exported = async (): Promise<Exported> => {    const first = await api<Exported>("GET", "/v1/admin/export", undefined, minted.token!);    for (let page = first; page.next; ) {      page = await api<Exported>("GET", `/v1/admin/export?after=${encodeURIComponent(page.next)}`, undefined, minted.token!);      first.rows.push(...page.rows);    }    return first;  };  const before = await exported();  const refused = pnpm(["import-personal", "--from", fixture.path, "--base", base, "--token", `${tokenFile}.missing`]);  check(refused.status === 1, "a run whose token file is missing is refused");  check((await exported()).version === before.version, "and a refused run writes nothing");  const args = ["import-personal", "--from", fixture.path, "--base", base, "--token", tokenFile, "--media-root", fixture.mediaRoot];  const importStarted = Date.now();  const first = pnpm(args);  const importSeconds = (Date.now() - importStarted) / 1000;  console.log(first.out.replace(/^/gm, "    | "));  check(first.status === 0, `the first import runs${first.status ? `\n${first.err}` : ""}`);  check(!first.out.includes("sk-invented") && !first.out.includes("invented-password") && !first.err.includes("invented-password"), "no secret value is printed");  const one = await exported();  const count = (table: string): number => one.rows.filter((r) => r.table === table).length;  const expected: Record<string, number> = {    project: 2, memory: 2, note: 3, todo: 2, secret: 1, device: 1, agent_account: 1, project_link: 6,    record_group: 1, group_member: 1, session: 2, prompt: 1, session_task: 1, session_message: 1, quota: 2,    // The Mac tools' own tables.    person: 1, person_handle: 1, message_contact: 1, thread: 1, thread_member: 1, message: 3 + bulk, message_reaction: 1, message_settings: 1,    photo: 2, video: 1, meeting: 1, meeting_utterance: 1, event: 1, note_attachment: 1, story: 1, email_thread: 1, email: 1,  };  for (const [table, n] of Object.entries(expected)) check(count(table) === n, `${table}: ${n} rows arrived (got ${count(table)})`);  const get = (table: string, id: string) => one.rows.find((r) => r.table === table && r.id === id);  const project = get("project", "p-cotton");  check(project?.created_at === "2026-09-01T08:00:00.000Z" && project.updated_at === "2026-10-20T10:30:00.000Z", "a row keeps its own id and times");  check(JSON.stringify(project?.data.repos) === JSON.stringify(["https://git.example.test/acme/cotton.git"]), "a JSON column arrives parsed");  check(get("quota", "q-1")?.data.session_pct === 42 && get("quota", "q-2")?.data.name === "Codex" && get("quota", "q-1")?.data.live === undefined, "a made table the package ships brings its rows under the package's columns");  check(one.tables.some((t) => t.id === "quota") && one.tables.some((t) => t.id === "reading"), "the made tables' definitions arrive");  // The object holds the whole kit (src/kit_keep.ts): the owner's tools arrive beside the kit's and the package's own, and the owner's Home over the shell's.  const toolIds = [...PERSONAL.tools.map((t) => String(t.id)), "chores", "garden", "seeds", "personal"].sort();  check(JSON.stringify(one.tools.map((t) => t.id)) === JSON.stringify(toolIds), `the owner's tools arrive beside the kit's and the package's own (got ${one.tools.map((t) => t.id).join(", ")})`);  const boards = PERSONAL.boards.map((b) => (b.id === "home" ? HOME_BOARD : b)).sort((a, b) => String(a.id).localeCompare(String(b.id)));  check(JSON.stringify(one.boards) === JSON.stringify(boards), `and the boards (got ${one.boards.map((b) => b.id).join(", ")})`);  check(/tool seeds: its picture names photo:f+, which is not coming/.test(first.out), "a tool whose picture is not coming is said");  // k1 sealing is removed (sealing plan §7 step 6): a secret with a value stays on the Mac, named; one with none arrives.  check(!get("secret", "s-key") && !get("secret", "s-login"), "a secret with a value is not brought");  check(/secret s-key .*stays on the Mac/.test(first.out) && /secret s-login .*stays on the Mac/.test(first.out), "and the summary names each one left");  check(get("secret", "s-empty")?.data.sealed === null, "a secret with no value arrives with none");  check(!get("prompt", "pr-orphan") && !get("project_link", "l-call") && get("session", "se-2")?.data.project === null && get("message", "mm-3")?.data.reply_to_id === null, "orphans dropped, a dangling optional link cleared");  check(get("project_link", "l-thread")?.data.record_id === "th-1", "a project files a chat");  check(Array.isArray(get("message", "mm-2")?.data.media) && get("message_contact", "c-asha")?.data.vip === true, "a Mac tool's row arrives with its real columns, JSON parsed and 0/1 a bool");  check(/prompt: dropped 1 — its session is not there/.test(first.out), "the summary says what was dropped");  // The media: every file a row names, under the row's own key, for the owner alone.  const keys = Object.keys(fixture.media);  check(new RegExp(`media: the rows name ${keys.length + 1}; 0 held already, ${keys.length} sent`).test(first.out), "the first run sends every named file");  check(/media: 1 named but not in/.test(first.out), "and says which named file the store does not hold");  const fetchMedia = (key: string, query = "", bearer: string | null = minted.token!) =>    fetch(`${base}/b/${personalSlug()}/v1/media/${key.split("/").map(encodeURIComponent).join("/")}${query}`, { headers: bearer ? { authorization: `Bearer ${bearer}` } : {} });  let same = 0;  for (const key of keys) {    const r = await fetchMedia(key);    if (r.ok && Buffer.from(await r.arrayBuffer()).equals(fixture.media[key]!)) same += 1;  }  check(same === keys.length, `every file reads back byte for byte (${same} of ${keys.length})`);  const photoKey = keys.find((k) => k.includes("/photos/"))!;  const drawn = await fetchMedia(photoKey, "?width=32");  check(drawn.status === 200 && drawn.headers.get("content-type") === "image/webp", "a photo is drawn at the width the phone asks");  check((await fetchMedia(photoKey, "", null)).status === 403, "and no one but the owner reads it");  const second = pnpm(args);  console.log(second.out.replace(/^/gm, "    | "));  check(second.status === 0, "the second import runs");  const two = await exported();  check(two.version === one.version, `the second import moves no version (${one.version} → ${two.version})`);  check(JSON.stringify(two.rows) === JSON.stringify(one.rows), "and changes no row");  check(JSON.stringify([two.tools, two.boards, two.tables]) === JSON.stringify([one.tools, one.boards, one.tables]), "nor any tool, board or table");  check(/\(unchanged: nothing differed\)/.test(second.out), "and says so");  check(new RegExp(`${keys.length} held already, 0 sent`).test(second.out), "and sends no media again");  if (bulk) {    // The whole database as the owner's phone pulls it: page after page from nothing.    const syncStarted = Date.now();    let pages = 0;    let rows = 0;    for (let query = "since=0"; ; ) {      const page = await api<{ rows: unknown[]; next?: string }>("GET", `/v1/sync?${query}`, undefined, credential);      pages += 1;      rows += page.rows.length;      if (!page.next) break;      query = `cursor=${page.next}`;    }    const syncSeconds = (Date.now() - syncStarted) / 1000;    check(rows >= one.rows.length, `a whole sync brings every row (${rows})`);    console.log(`\nvolume: ${one.rows.length} rows imported in ${importSeconds.toFixed(1)} s (${Math.round(one.rows.length / importSeconds)} rows/s, reading and planning included); a whole owner sync: ${rows} rows in ${pages} pages, ${syncSeconds.toFixed(1)} s`);  }  console.log("e2e import: passed");} catch (error) {  console.error((error as Error).message);  process.exitCode = 1;} finally {  cleanup();}