Cotton code
151 lines · 8.3 KB · TypeScriptRaw
/** * ORDER INDEX, PROVEN ON THE DEV WORKER (coordinator for the owner, 24 Nov 2026). An invented account is planted to * the owner's size (3.7 GB: his tables' rows, sealed-shaped, POST /v1/admin/dev/plant-rows), its row counts are let * finish, and then: *   1. with the switch off (the default), a pass from nothing asks for no shadow and none is made; *   2. the switch is turned on (POST /v1/admin/order-shadow {"on": true}); the Worker's own alarms fill the shadows, *      a bounded step each; the script follows their progress and says each shadow's steps and its whole time; *   3. a pass from nothing then walks them: its first pages, timed; *   4. with --off, the switch is turned off again and every shadow goes. * CPU per alarm step is the platform's to say: run `wrangler tail cottondb-dev --format json` beside it and read * each alarm event's cpuTime next to its "cottondb: order shadow <name>: laid <n> rows" line. * Invented data only; refuses any server but the dev Worker. * *   pnpm -s exec tsx scripts/order-shadow-proof.ts --number +1555… [--bytes 3700000000] [--off] * * The sign-in code is read from ~/.cotton-credentials/cotton/dev-otp and never printed. */import { readFileSync } from "node:fs";import { homedir } from "node:os";import { signIn, type Session } from "./dev-seed/client.ts";import { devBase } from "./dev-server";const arg = (name: string, fallback?: string) => {  const i = process.argv.indexOf(`--${name}`);  return i > 0 ? process.argv[i + 1]! : fallback;};const DEV = arg("base", devBase())!;if (DEV !== devBase() && !/^http:\/\/127\.0\.0\.1:\d+$/.test(DEV)) throw new Error("--base is the dev Worker or a local wrangler dev");const NUMBER = arg("number");if (!NUMBER || !/^\+1555\d{7}$/.test(NUMBER)) throw new Error("--number is an invented +1555 number");const TARGET = Number(arg("bytes", "3700000000"));const OFF = process.argv.includes("--off");const STEP = 20_000;/** His tables, in the shares the big invented object holds them (test/big_object.ts personalShape), each row's sealed bytes. */const SHAPE: { table: string; share: number; bytes: number; dated: string; group?: { column: string; prefix: string; of: number } }[] = [  { table: "message", share: 300, bytes: 1200, dated: "sent_at", group: { column: "thread_id", prefix: "thread-", of: 3000 } },  { table: "email", share: 111, bytes: 3000, dated: "sent_at", group: { column: "thread_id", prefix: "mail-", of: 80_000 } },  { table: "photo", share: 120, bytes: 400, dated: "taken_at" },  { table: "event", share: 40, bytes: 500, dated: "starts_at" },  { table: "thread", share: 3, bytes: 200, dated: "last_message_at" },  { table: "email_thread", share: 80, bytes: 150, dated: "last_at" },  { table: "book", share: 80, bytes: 300, dated: "added_on" },];const say = (line: string) => console.log(`[order-shadow] ${new Date().toISOString().slice(11, 19)} ${line}`);const wait = (ms: number) => new Promise((done) => setTimeout(done, ms));async function call<T>(bearer: string, method: string, path: string, body?: unknown): Promise<{ status: number; body: T; ms: number }> {  for (let attempt = 0; ; attempt++) {    const t0 = Date.now();    try {      const res = await fetch(`${DEV}${path}`, { method, headers: { "content-type": "application/json", authorization: `Bearer ${bearer}` }, body: body === undefined ? undefined : JSON.stringify(body) });      const text = await res.text();      if (res.status >= 500 && attempt < 4) throw new Error(`${res.status} ${text.slice(0, 200)}`);      return { status: res.status, body: (text ? JSON.parse(text) : {}) as T, ms: Date.now() - t0 };    } catch (error) {      if (attempt >= 4) throw error;      say(`retry ${method} ${path}: ${error instanceof Error ? error.message : String(error)}`);      await wait(3_000 * (attempt + 1));    }  }}type Progress = { on: boolean; step: number; shadows: { name: string; table: string; ready: boolean; rows: number; steps: number; began: string | null; readyAt: string | null }[] };async function pass(s: Session, pages: number): Promise<{ page: number; rows: number; ms: number }[]> {  const out: { page: number; rows: number; ms: number }[] = [];  let path = "/v1/sync?since=0&limit=5000";  for (let page = 1; page <= pages; page++) {    const r = await call<{ rows: unknown[]; next?: string }>(s.credential, "GET", path);    if (r.status !== 200) throw new Error(`pass page ${page}: ${r.status} ${JSON.stringify(r.body).slice(0, 300)}`);    out.push({ page, rows: r.body.rows.length, ms: r.ms });    if (!r.body.next) break;    path = `/v1/sync?cursor=${encodeURIComponent(r.body.next)}`;  }  return out;}async function main(): Promise<void> {  const code = readFileSync(`${homedir()}/.cotton-credentials/cotton/dev-otp`, "utf8").replace(/\D/g, "");  const s = await signIn(DEV, NUMBER!, code);  say(`signed in ${NUMBER} (database ${s.databaseId.slice(0, 8)}…)`);  // 1. Planted to his size: each table its share, in calls of STEP rows, until the file stands at TARGET.  const total = SHAPE.reduce((a, t) => a + t.share * t.bytes, 0);  let bytes = 0;  const planted: Record<string, number> = {};  for (let round = 0; bytes < TARGET && round < 40; round++) {    for (const t of SHAPE) {      const want = Math.ceil(((t.share * t.bytes) / total) * (TARGET / 2.2) / t.bytes / 20) || 1;      for (let left = want; left > 0 && bytes < TARGET; ) {        const count = Math.min(STEP, left);        const from = planted[t.table] ?? 0;        const r = await call<{ planted: number; bytes: number }>(s.token, "POST", "/v1/admin/dev/plant-rows", { table: t.table, from, count, bytes: t.bytes, dated: t.dated, ...(t.group ? { group: t.group } : {}) });        if (r.status !== 200) throw new Error(`plant ${t.table}: ${r.status} ${JSON.stringify(r.body).slice(0, 300)}`);        planted[t.table] = from + count;        bytes = r.body.bytes;        left -= count;      }    }    say(`planted ${JSON.stringify(planted)}: file ${(bytes / 1e9).toFixed(2)} GB`);  }  // His row counts are long since counted: let the alarm's recount finish first.  for (;;) {    const c = await call<{ ready: boolean; left: unknown[] }>(s.token, "GET", "/v1/admin/row-counts");    if (c.body.ready) break;    say(`row counts: ${c.body.left?.length ?? "?"} tables left`);    await wait(30_000);  }  // 2. Off: a pass from nothing asks for nothing.  const offPass = await pass(s, 2);  const off = await call<Progress>(s.token, "GET", "/v1/admin/order-shadow");  say(`off: ${JSON.stringify(off.body)}; a pass's first pages ${offPass.map((p) => `${p.rows} rows ${p.ms} ms`).join(", ")}`);  if (off.body.on || off.body.shadows.length) throw new Error("shadows stood with the switch off");  // 3. On; a pass asks; the alarms fill.  const on = await call<Progress>(s.token, "POST", "/v1/admin/order-shadow", { on: true });  if (on.status !== 200) throw new Error(`switch: ${on.status} ${JSON.stringify(on.body)}`);  await pass(s, 1);  const begun = Date.now();  let last: Progress | null = null;  for (;;) {    last = (await call<Progress>(s.token, "GET", "/v1/admin/order-shadow")).body;    const ready = last.shadows.filter((x) => x.ready).length;    say(`filling: ${ready} of ${last.shadows.length} ready, ${last.shadows.reduce((a, x) => a + x.steps, 0)} steps, step ${last.step} rows`);    if (last.shadows.length && ready === last.shadows.length) break;    if (Date.now() - begun > 6 * 3_600_000) throw new Error("not ready in six hours");    await wait(30_000);  }  for (const x of last.shadows) say(`  ${x.name}: ${x.rows} rows in ${x.steps} steps, ${x.began && x.readyAt ? `${Math.round((Date.parse(x.readyAt) - Date.parse(x.began)) / 1000)} s` : "-"}`);  const first = last.shadows.map((x) => x.began).filter(Boolean).sort()[0];  const end = last.shadows.map((x) => x.readyAt).filter(Boolean).sort().at(-1);  say(`all ready: ${first && end ? Math.round((Date.parse(end) - Date.parse(first)) / 1000) : "?"} s from the first step to the last`);  // 4. A pass from nothing walks them.  const onPass = await pass(s, 5);  say(`on: a pass's first pages ${onPass.map((p) => `${p.rows} rows ${p.ms} ms`).join(", ")}`);  if (OFF) {    const dropped = await call<Progress>(s.token, "POST", "/v1/admin/order-shadow", { on: false });    say(`off again: ${JSON.stringify(dropped.body)}`);  }}main().catch((error) => {  console.error(`[order-shadow] ${error instanceof Error ? error.message : String(error)}`);  process.exit(1);});