Cotton code
172 lines · 9.9 KB · TypeScriptRaw
/** * SNAPSHOTS 1 PROOF on DEV (coordinator for the owner, 27 Nov 2026): the cost and the restore of sealed snapshots, * measured on a throwaway invented account of 300,000 rows. * *   1. sign in an invented +1555 number; plant 300,000 invented sealed-shaped rows (plant-rows, dev only) *   2. snapshots on; a weekly full written to its end: time, parts, bytes, rows *   3. 1% of the rows changed (3,000 planted more); a daily written: time, bytes, rows *   4. the cost per month at list prices: 4 weeklies and 7 dailies stored, the writes, the rows read *   5. freeze; restore from the full and the daily; every live row checked against the hashes taken before; unfreeze * *   pnpm -s exec tsx scripts/snapshots-proof.ts [--base <the dev Worker's address (config/dev-server.json)>] [--rows 300000] *       [--bytes 600] [--admin-token-file …] [--code-file …] [--skip-restore] * * Refuses any base but the dev Worker. Prints counts, sizes, times and hashes; never a token, a code or a key. */import { createHash, randomBytes } from "node:crypto";import { readFileSync } from "node:fs";import { homedir } from "node:os";import { devBase } from "./dev-server";const DEV_BASE = devBase();const arg = (name: string, fallback?: string): string | undefined => {  const i = process.argv.indexOf(`--${name}`);  return i > 0 ? process.argv[i + 1] : fallback;};const home = (p: string) => p.replace(/^~(?=\/)/, homedir());const BASE = (arg("base", DEV_BASE) ?? "").replace(/\/$/, "");if (BASE !== DEV_BASE) {  console.error(`snapshots-proof: ${BASE} is not the dev Worker; nothing was asked`);  process.exit(2);}const ADMIN = readFileSync(home(arg("admin-token-file", "~/.cotton-credentials/cloudflare/business-dev-admin-token")!), "utf8").trim();const CODE = readFileSync(home(arg("code-file", "~/.cotton-credentials/cotton/dev-otp")!), "utf8").replace(/\D/g, "");const ROWS = Number(arg("rows", "300000"));const BYTES = Number(arg("bytes", "600"));const RESTORE = !process.argv.includes("--skip-restore");// List prices (assets/design/shared/RESTORE.md, read 27 Nov 2026).const R2_GB_MONTH = 0.015;const R2_CLASS_A_PER_M = 4.5;const DO_ROWS_READ_PER_M = 0.001;const t0 = Date.now();const say = (line: string) => console.log(`[snapshots-proof +${String(Math.round((Date.now() - t0) / 1000)).padStart(5)}s] ${line}`);const wait = (ms: number) => new Promise((done) => setTimeout(done, ms));const fail = (what: string): never => {  throw new Error(what);};type Answer = { status: number; body: Record<string, unknown> };async function call(method: string, path: string, body?: unknown, bearer?: string, tries = 5): Promise<Answer> {  for (let attempt = 0; ; attempt++) {    try {      const res = await fetch(`${BASE}${path}`, { method, headers: { "content-type": "application/json", "user-agent": "cotton-snapshots-proof/1", ...(bearer ? { authorization: `Bearer ${bearer}` } : {}) }, body: body === undefined ? undefined : JSON.stringify(body) });      const text = await res.text();      if (res.status >= 500 && attempt < tries - 1) throw new Error(`${res.status} ${text.slice(0, 160)}`);      let parsed: Record<string, unknown> = {};      try {        parsed = text ? (JSON.parse(text) as Record<string, unknown>) : {};      } catch {        parsed = { text: text.slice(0, 160) };      }      return { status: res.status, body: parsed };    } catch (error) {      if (attempt >= tries - 1) throw error;      await wait(3_000 * (attempt + 1));    }  }}const brief = (a: Answer) => `${a.status}${typeof a.body.code === "string" ? ` ${a.body.code}` : ""}`;const mb = (n: number) => `${(n / 1_048_576).toFixed(1)} MB`;let database = "";const admin = (method: string, path: string, body?: unknown) => call(method, `/b/p-${database}/v1/admin${path}`, body, ADMIN);type Manifest = { kind: string; stamp: string; base: number; upto: number; rows: number; bytes: number; parts: unknown[] };async function runSnapshot(kind: "full" | "daily"): Promise<{ manifest: Manifest; ms: number; calls: number }> {  const started = Date.now();  for (let n = 1; n < 2_000; n++) {    const got = await admin("POST", "/snapshots/run", { ...(n === 1 ? { kind } : {}), budget_ms: 20_000 });    if (got.status !== 200) fail(`snapshot ${kind}: ${brief(got)}`);    if (got.body.done === true) return { manifest: got.body.manifest as Manifest, ms: Date.now() - started, calls: n };  }  return fail("the copy never finished");}async function hashes(): Promise<{ rows: number; hash: string }> {  const all = createHash("sha256");  let rows = 0;  let after: string | null = null;  for (let page = 0; page < 10_000; page++) {    const got = await admin("GET", `/export?limit=10000${after ? `&after=${encodeURIComponent(after)}` : ""}`);    if (got.status !== 200) fail(`export: ${brief(got)}`);    for (const r of (got.body.rows ?? []) as { table: string; id: string; version: number; data: unknown; created_at: string; updated_at: string }[]) {      all.update(`${createHash("sha256").update(JSON.stringify([r.table, r.id, r.version, r.data, r.created_at, r.updated_at])).digest("hex")}\n`);      rows++;    }    after = (got.body.next as string | null) ?? null;    if (!after) break;  }  return { rows, hash: all.digest("hex").slice(0, 16) };}async function main(): Promise<number> {  const number = `+1555${String(Math.floor(1_000_000 + Math.random() * 8_999_999))}`;  const device = randomBytes(32).toString("base64url");  const asked = await call("POST", "/v1/code", { phone: number, device_id: device });  const signed = asked.status === 200 ? await call("POST", "/v1/sign-in", { database_id: asked.body.database_id, challenge_id: asked.body.challenge_id, code: CODE, device_id: device }) : asked;  if (signed.status !== 200) {    say(`could not sign in an invented number: ${brief(signed)}`);    return 2;  }  database = String(asked.body.database_id);  const credential = String(signed.body.credential);  say(`throwaway account: database ${database.slice(0, 8)}…`);  const minted = await call("POST", "/v1/act", { act: "mint_token", args: { name: "snapshots proof", scopes: ["owner"], expires_in_days: 1 } }, credential);  const token = typeof minted.body.token === "string" ? minted.body.token : fail(`mint: ${brief(minted)}`);  const plantStarted = Date.now();  for (let from = 0; from < ROWS; from += 20_000) {    const planted = await call("POST", "/v1/admin/dev/plant-rows", { table: "note", from, count: Math.min(20_000, ROWS - from), bytes: BYTES }, token);    if (planted.status !== 200) fail(`plant: ${brief(planted)}`);  }  say(`planted ${ROWS} invented note rows of about ${BYTES} sealed bytes in ${Math.round((Date.now() - plantStarted) / 1000)}s`);  const on = await admin("POST", "/snapshots", { on: true });  if (on.status !== 200) fail(`snapshots on: ${brief(on)}`);  const full = await runSnapshot("full");  say(`weekly full: ${full.manifest.rows} rows, ${full.manifest.parts.length} parts, ${mb(full.manifest.bytes)} sealed, in ${Math.round(full.ms / 1000)}s over ${full.calls} calls`);  const changed = Math.round(ROWS / 100);  await call("POST", "/v1/admin/dev/plant-rows", { table: "note", from: ROWS, count: changed, bytes: BYTES }, token);  await call("POST", "/v1/act", { act: "revoke_token", args: { id: String((minted.body.made as { id?: string } | undefined)?.id ?? "") } }, credential);  const daily = await runSnapshot("daily");  say(`daily changes (1%, ${changed} rows): ${daily.manifest.rows} rows, ${mb(daily.manifest.bytes)} sealed, in ${Math.round(daily.ms / 1000)}s`);  // The cost per month for this account at list prices.  const storedBytes = 4 * full.manifest.bytes + 7 * daily.manifest.bytes;  const storage = (storedBytes / 1_073_741_824) * R2_GB_MONTH;  const writes = ((52 / 12) * (full.manifest.parts.length + 1) + 30 * (daily.manifest.parts.length + 1) + 30 * 3) * (R2_CLASS_A_PER_M / 1_000_000);  const reads = (((52 / 12) * full.manifest.rows + 30 * daily.manifest.rows) / 1_000_000) * DO_ROWS_READ_PER_M;  say(`cost a month: stored ${mb(storedBytes)} (4 weeklies + 7 dailies) $${storage.toFixed(4)}; writes $${writes.toFixed(5)}; rows read $${reads.toFixed(5)}; total $${(storage + writes + reads).toFixed(4)}`);  const perGb = full.manifest.bytes / Math.max(1, full.manifest.rows);  say(`scaled: ${perGb.toFixed(0)} sealed bytes a row in the copy; rows of 4 GB stored would cost about $${((4 * 4 + 7 * 0.04) * R2_GB_MONTH).toFixed(2)} a month this way (4 weeklies of 4 GB, 7 dailies at 1%)`);  if (!RESTORE) return 0;  const before = await hashes();  say(`before the restore: ${before.rows} live rows, hash ${before.hash}`);  await admin("POST", "/restore/freeze", { reason: "snapshots proof" });  // The invented phone never posts with x-cotton-generation (it only signs in and mints): said plainly, not hidden.  const begun = await admin("POST", "/snapshots/restore/begin", { full: full.manifest.stamp, override_devices: true });  if (begun.status !== 200) fail(`restore begin: ${brief(begun)}`);  const started = Date.now();  let step: Answer = { status: 0, body: {} };  for (let n = 0; n < 2_000; n++) {    step = await admin("POST", "/snapshots/restore/step", { budget_ms: 20_000 });    if (step.status !== 200) fail(`restore step: ${brief(step)}`);    if (step.body.done === true) break;  }  say(`restored from ${String(begun.body.snapshots)} snapshots (${String(begun.body.parts)} parts): ${String(step.body.rows)} rows in ${Math.round((Date.now() - started) / 1000)}s; version ${String(step.body.version)}`);  await admin("POST", "/restore/unfreeze");  const after = await hashes();  const ok = after.rows === before.rows && after.hash === before.hash;  say(`${ok ? "HELD  " : "FAILED"} restore from snapshots row for row: ${after.rows} rows, hash ${after.hash} (before ${before.hash})`);  return ok ? 0 : 1;}main().then(  (code) => process.exit(code),  (error: unknown) => {    console.error(`snapshots-proof: ${error instanceof Error ? error.message : String(error)}`);    process.exit(2);  },);