#!/usr/bin/env tsx /** * pnpm tsx scripts/jobs-out-proof.ts [--base ] [--slug ] [--kind ]: JOBS OUT PROOF * (coordinator, 28 Nov 2026). Proves, on the DEV Worker and an invented account, that every step job kind on main runs * beside the account object and not on its alarm. One kind is switched on at a time; for each it shows: * * 1. queue the queue ran it: the object answered the job's steps (job_steps rose) * 2. done the work got done: what the kind had left went to nothing (or its run ended with nothing owed) * 3. alarm the account object did none of it while it was on, neither its alarm (kicked, so alarms ran) nor a * request's own pass (object_did stayed) * 4. fast a request during the job stayed fast (the slowest admin read while it ran, under FAST_MS) * 5. back switched off, new work of the kind is done by the object again (object_did rose): by its alarm, or, * for a kind a request did before (media_drop, artwork, book_files), by the request that laid it * * and prints one line a kind: PASS, FAIL (with the checks that failed) or SKIP (the kind cannot be given invented * work on an invented account, e.g. calendar_sync needs a Google account; the reason is said). * * The kinds are the ones the object names (GET /v1/admin/jobs), so a kind that lands on main later is proved once its * seed is written in Business.seedJob; until then it is a SKIP saying so. Send's is written (invented offers on Send's * own tables, an invented peer, nothing told to another object, no mail). Spotify has no job: its podcast pull went with * Podcasts (TABLE DROP 1), and connect, status and disconnect run inside the owner's request. The account is made here * (POST /v1/admin/dev/invent-personal: the whole personal kit, an invented number) unless --slug names one already made. * Every route it calls answers 404 on any Worker but dev. * * The admin token is BUSINESS_ADMIN_TOKEN (the dev one, kept on the coordinator's Mac), else * ~/.cotton-credentials/cloudflare/business-dev-admin-token. Never printed. Exit 0 when no kind failed, 1 when one * did, 2 when the Worker could not be asked. */ import { existsSync, readFileSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; import { devBase } from "../apps/business/scripts/dev-server"; /** The dev Worker, from config/dev-server.json. */ const DEV_BASE = devBase(); /** A request during a job must answer within this. */ const FAST_MS = 2_000; /** How long a kind's job, and then the alarm, are given to do the work. */ const WAIT_MS = 5 * 60_000; /** How often the script looks, and kicks the alarm so one runs while it waits. */ const LOOK_MS = 2_000; const KICK_EVERY_MS = 15_000; type Kind = { kind: string; on: boolean; owes: boolean; left: number | boolean | null; state: { due_at: string | null; run_until: string | null } | null; job_steps: number; object_did: number }; type View = { kinds: Kind[]; alarm_last: { began: string; ended: string | null; ran: string; error: string | null } | null }; function args(argv: string[]): { base: string; slug: string; only: string | null } { let base = DEV_BASE; let slug = `jobs-proof-${Date.now().toString(36)}`; let only: string | null = null; for (let i = 0; i < argv.length; i++) { const a = argv[i]!; if (a === "--base") base = (argv[++i] ?? "").replace(/\/$/, ""); else if (a === "--slug") slug = argv[++i] ?? ""; else if (a === "--kind") only = argv[++i] ?? null; else throw new Error(`unknown argument ${a}`); } if (!/^[a-z0-9][a-z0-9-]*$/.test(slug)) throw new Error("--slug is an invented account's slug (letters, digits, dashes)"); if (!/dev|localhost|127\.0\.0\.1/.test(base)) throw new Error("the jobs proof runs on the dev Worker only"); return { base, slug, only }; } function adminToken(): string { const env = process.env.BUSINESS_ADMIN_TOKEN?.trim(); if (env) return env; const file = join(homedir(), ".cotton-credentials/cloudflare/business-dev-admin-token"); if (existsSync(file)) return readFileSync(file, "utf8").trim(); throw new Error("no admin token: set BUSINESS_ADMIN_TOKEN or keep ~/.cotton-credentials/cloudflare/business-dev-admin-token"); } const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); async function main(): Promise { const { base, slug, only } = args(process.argv.slice(2)); const token = adminToken(); const at = (path: string) => (base.includes("workers.dev") || base.includes("localhost") ? `${base}/b/${slug}${path}` : `${base}${path}`); const ask = async >(method: string, path: string, body?: unknown): Promise<{ status: number; body: T; ms: number }> => { const started = Date.now(); const res = await fetch(at(path), { method, headers: { authorization: `Bearer ${token}`, "content-type": "application/json", "user-agent": "cotton-jobs-proof/1" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); const text = await res.text(); const ms = Date.now() - started; let parsed: unknown = {}; try { parsed = JSON.parse(text); } catch { parsed = { text: text.slice(0, 200) }; } return { status: res.status, body: parsed as T, ms }; }; const view = async (): Promise<{ v: View; ms: number }> => { const r = await ask("GET", "/v1/admin/jobs"); if (r.status !== 200) throw new Error(`GET /v1/admin/jobs answered ${r.status}: ${JSON.stringify(r.body).slice(0, 200)}`); return { v: r.body, ms: r.ms }; }; const kindOf = (v: View, kind: string) => v.kinds.find((k) => k.kind === kind)!; const switchTo = (kind: string, on: boolean) => ask("PUT", "/v1/admin/business", { jobs: { [kind]: on ? "on" : null } }); const kick = () => ask("POST", "/v1/admin/alarm/kick", {}); /** Nothing left of the kind's work: a count at or under where it began, false, or (no measure) nothing owed. */ const done = (k: Kind, from: number | boolean | null) => (typeof k.left === "number" ? k.left <= (typeof from === "number" ? from : 0) : k.left === null ? !k.owes : k.left === false); const made = await ask<{ personal?: boolean; tables?: number }>("POST", "/v1/admin/dev/invent-personal", {}); if (made.status !== 200 || !made.body.personal) { console.log(`could not make the invented account ${slug}: ${made.status} ${JSON.stringify(made.body).slice(0, 200)}`); return 2; } console.log(`jobs proof on ${slug} (${made.body.tables} tables), ${base.replace(/^https?:\/\//, "")}`); const first = (await view()).v; const kinds = first.kinds.map((k) => k.kind).filter((k) => !only || k === only); // Every kind off to begin with: the alarm's, as before. for (const k of first.kinds) if (k.on) await switchTo(k.kind, false); let failed = 0; for (const kind of kinds) { const fails: string[] = []; const before = kindOf((await view()).v, kind); // On, then the work laid: the object asks the queue for a run. const on = await switchTo(kind, true); if (on.status !== 200) { console.log(`FAIL ${kind}: could not switch it on (${on.status} ${JSON.stringify(on.body).slice(0, 160)})`); failed++; continue; } const seed = await ask<{ seeded?: boolean; why?: string; left?: number | boolean | null }>("POST", "/v1/admin/dev/jobs-seed", { kind }); if (seed.status !== 200 || !seed.body.seeded) { await switchTo(kind, false); console.log(`SKIP ${kind}: ${seed.body.why ?? `the seed answered ${seed.status}`}`); continue; } const baseline = before.left; const alarmFrom = before.object_did; const stepsFrom = before.job_steps; const alarmsBefore = (await view()).v.alarm_last?.began ?? ""; // While the job runs: look, time each read, and kick the alarm now and then so alarms run beside the job. let slowest = 0; let lastKick = 0; let now = kindOf((await view()).v, kind); let alarmsRan = false; const until = Date.now() + WAIT_MS; while (Date.now() < until) { if (Date.now() - lastKick > KICK_EVERY_MS) { await kick(); lastKick = Date.now(); } await sleep(LOOK_MS); const { v, ms } = await view(); slowest = Math.max(slowest, ms); now = kindOf(v, kind); if ((v.alarm_last?.began ?? "") > alarmsBefore) alarmsRan = true; if (now.job_steps > stepsFrom && done(now, baseline) && !now.state?.run_until && alarmsRan) break; } if (!(now.job_steps > stepsFrom)) fails.push("queue: no step was asked of the object"); if (!done(now, baseline)) fails.push(`done: left ${JSON.stringify(now.left)} (began at ${JSON.stringify(baseline)})`); if (now.object_did !== alarmFrom) fails.push(`alarm: the object did it ${now.object_did - alarmFrom} times while on`); if (!alarmsRan) fails.push("alarm: no alarm ran while it was on (cannot tell)"); if (slowest > FAST_MS) fails.push(`fast: a read took ${slowest} ms`); // Off, and new work laid: the alarm does it again. await switchTo(kind, false); const offFrom = kindOf((await view()).v, kind).object_did; const again = await ask<{ seeded?: boolean; left?: number | boolean | null }>("POST", "/v1/admin/dev/jobs-seed", { kind }); let back = false; if (again.status === 200 && again.body.seeded) { const until2 = Date.now() + WAIT_MS; lastKick = 0; while (Date.now() < until2) { if (Date.now() - lastKick > KICK_EVERY_MS) { await kick(); lastKick = Date.now(); } await sleep(LOOK_MS); const k = kindOf((await view()).v, kind); if (k.object_did > offFrom && done(k, baseline)) { back = true; break; } } } if (!back) fails.push("back: switched off, the object did not take the work again"); if (fails.length) { failed++; console.log(`FAIL ${kind}: ${fails.join("; ")}`); } else { console.log(`PASS ${kind}: ${now.job_steps - stepsFrom} job steps, the object none while on; slowest read ${slowest} ms; off, the object again`); } } return failed ? 1 : 0; } main().then( (code) => process.exit(code), (error: unknown) => { console.log(`jobs proof could not run: ${error instanceof Error ? error.message : String(error)}`); process.exit(2); }, );