Public: anyone can read this; the crew can change it.

Nightly drill on the vxrail: the one-click path against production, loud on the step that broke #16843

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/2931-nightly-drill-on-the-vxrail-the-one-clic → main 0 commits fork 2 threads · 2 unresolved

  • Merged. scout/2931-nightly-drill-on-the-vxrail-the-one-clic was merged into main as 3a83699.

Review

Sign in to review this change.
8 files changed +684 −7
docs/features/one-click-drill.md added +32
@@ -0,0 +1,32 @@
1 ---
2 topic: What a forge is
3 row: Does a stranger still reach their own forge in one click, tonight?
4 ---
5 # The nightly one-click drill
6
7 A maintenance duty, `one-click-drill` (#2931), walks the path of `test/one-click.test.ts` (#2930) against the
8 production forge itself once a night, with a drill account (`drillbot-<8 hex>`) and a throwaway forge
9 (`drill-<8 hex>`), then removes both, pass or fail. It needs `FORGE_URL`; without it the duty skips and says so.
10 The walk is `src/release/one_click_drill.ts`; the forge's own router answers in process, so the egress gate is
11 never asked.
12
13 The steps, each named: 1 signup (an account and a token), 2 make a forge (made and claimed in one call), 3 forge
14 live (the live watcher's event, held to the 180 s budget), 4 included app (the spawn's own proofs from outside),
15 5 clean up (the forge and the account removed). A failure reads `step 3 (forge live) failed: …`.
16
17 - **The result** goes on the event outbox as `drill.one_click` (pass, or the step and why, and time to live in
18 ms); that event is the record, and no file is written. The duty's row on /maintenance shows when it
19 last ran.
outdated

This still says the newest result is kept in <data>/drill/one-click.json, but that write was removed. Say the outbox event is the record.

20 - **A failure** opens one issue on the forge's own repository, "The nightly one-click drill failed", that names the
21 step; while it is open a later failure comments on it. A pass files nothing.
22 - **Its forge's events** carry `drill`, so the boards keep it as its own series (`forge.spawn.live` with
23 `drill: 1`). The request carries a key only this boot holds (`DRILL_HEADER`), so no stranger's allowance is spent.
24 - **An included app**: set `FORGE_DRILL_APP=owner/name` (a public app) and step 4 wants a proof for it.
25
26 Left out: the child's own `/health` and its claimed token are not fetched from here; the egress gate refuses
27 the children's hosts, and the spawn's proofs and the watcher's event stand for them. Terminal: `/maintenance`
28 (`src/tui/screens/maintenance.ts`) lists the duty and its last run like any other.
29
30 A run that dies midway (a timeout, a restart) can leave a forge or account behind. The next run
31 first removes any `drill-<8 hex>` forge and `drillbot-<8 hex>` account it finds, by the same shape
32 checks; one that cannot be removed fails step 5.
src/maintain/duties/one_click_drill.ts added +56
@@ -0,0 +1,56 @@
1 /**
2 * The nightly one-click drill (#2931): `release/one_click_drill.ts` walks the production forge's
3 * one-click path with a drill account and a throwaway forge name, then removes both. The result
4 * (pass, or the step that failed and why, and time to live) goes on the event outbox as
5 * `drill.one_click`, the only record kept; no file is written. A failure opens one
outdated

The header comment still promises <data>/drill/one-click.json, which nothing writes now. Drop the clause.

6 * issue on the forge's own repository that names the step; while it is open a later failure
7 * comments on it instead of opening another, and a pass says nothing. It spends no money: one
8 * forge made and removed, one account made and removed.
9 */
10 import { fileIssueOnce } from "../../checks/flake.ts";
11 import { addComment } from "../../core/issues.ts";
12 import { getRepo } from "../../core/repos.ts";
13 import { ownRepoPath } from "../../kernel/own_repo.ts";
14 import { publicOrigin } from "../../core/public_origin.ts";
15 import { runDrill, words } from "../../release/one_click_drill.ts";
16 import type { realHands } from "../../release/one_click_hands.ts";
17 import type { Duty } from "../duty.ts";
18
19 export const TITLE = "The nightly one-click drill failed";
20
21 /** The duty, with the hands it walks with injectable so a test stands in for the forge. */
22 export const oneClickDrill = (make?: typeof realHands): Duty => ({
23 name: "one-click-drill",
24 intervalMs: 86_400_000,
25 timeoutMs: 240_000,
26 budget: { runsPerDay: 3, dollarsPerDay: 1, reason: "one a night; two more for a retry after a restart, and it spends no money: a throwaway forge and account, both removed" },
27 async run({ db, bus, now, app }) {
28 const url = app?.config.url;
29 if (app === undefined || url === undefined || url === "") return { findings: [], actions: ["skipped: this forge does not know its public origin (FORGE_URL)"] };
30 const { hands, close } = await (make ?? (await import("../../release/one_click_hands.ts")).realHands)(app, publicOrigin(url, ""), process.env["FORGE_DRILL_APP"]?.trim() || undefined);
31 let result;
32 try {
33 result = await runDrill(hands);
34 } finally {
35 close();
36 }
37 bus.append({
38 kind: "drill.one_click",
39 payload: { ok: result.ok, forge: result.forge, cleaned: result.cleaned, ...(result.ms === undefined ? {} : { ms: result.ms }), ...(result.ok ? {} : { step: result.step, stepName: result.stepName, why: result.why }) },
40 });
41 if (result.ok) return { findings: [], actions: [words(result)] };
42 const [owner = "", name = ""] = ownRepoPath().split("/");
43 const repo = getRepo(db, owner, name);
44 const finding = { summary: words(result), probe: { kind: "measurement" as const, what: `the one-click drill's failed step (${result.stepName})`, number: result.step ?? 0, at: now.toISOString() } };
45 if (repo === undefined) return { findings: [finding], actions: ["no forge repository to file the failure on"] };
46 const body = `_Filed by the nightly one-click drill, not written by a person._\n\n**${words(result)}**\n\n- Forge: ${result.forge}\n- At: ${result.at}\n- Removed: ${result.cleaned ? "the forge and the account are gone" : "not everything was removed; look for drill- forges and drillbot- accounts"}\n\nThe steps are in \`src/release/one_click_drill.ts\`: signup, make a forge, forge live, included app, clean up.`;
47 const filed = fileIssueOnce(db, bus, repo, { title: TITLE, body });
48 if (!filed.opened && filed.number > 0) {
49 const issue = db.query<{ id: string }, [string, number]>("SELECT id FROM issue WHERE repo_id = ?1 AND number = ?2").get(repo.id, filed.number);
50 if (issue !== null) addComment(db, { issueId: issue.id, authorId: repo.ownerId, body });
51 }
52 return { findings: [finding], actions: [filed.opened ? `filed issue #${filed.number}: ${words(result)}` : `commented on issue #${filed.number}: ${words(result)}`] };
53 },
54 });
55
56 export const duty: Duty = oneClickDrill();
src/release/one_click_drill.ts added +157
@@ -0,0 +1,157 @@
1 /**
2 * The nightly one-click drill (#2931): the path of `test/one-click.test.ts` (#2930) walked against
3 * the production forge itself: an account, a token, a forge made and claimed in one call, live,
4 * its first proofs from outside. Then the throwaway forge is removed and the account deleted,
5 * pass or fail. Each step is named, so a failure reads `step 3 (forge live) failed: …`.
6 *
7 * Plain data in, plain data out: `Hands` is everything the walk touches (the router, the clock,
8 * the removals), so a test stands in for each. The duty (`maintain/duties/one_click_drill.ts`) is
9 * the clock, the issue and the record: the `drill.one_click` event on the outbox, no file.
10 *
11 * Left out, said plainly: the child's own `/health` and the claimed token are not fetched from
12 * here (the forge's egress gate refuses its children's hosts); the spawn's reach proofs, made from
13 * outside by the spawn itself, and the live watcher's event stand for them.
14 */
15
16 /** The budget for a forge to answer: the boards' own (`boards/sources.ts` `SPAWN_BUDGET_MS`). */
17 export const LIVE_BUDGET_MS = 180_000;
18 /** One request's own limit. */
19 export const CALL_MS = 60_000;
20 /** Names the drill makes; only these are ever removed. */
21 export const FORGE_SHAPE = /^drill-[0-9a-f]{8}$/;
22 export const ACCOUNT_SHAPE = /^drillbot-[0-9a-f]{8}$/;
23
24 export const STEPS = ["signup", "make a forge", "forge live", "included app", "clean up"] as const;
25
26 export interface Hands {
27 /** One request to the forge's own router, same-origin; the drill header is the caller's. */
28 readonly call: (method: string, path: string, body: unknown, token?: string) => Promise<{ status: number; body: unknown }>;
29 /**
30 * Waits for the drill's `forge.spawn.live` (its ms) or `forge.spawn.failed` after `since`;
31 * undefined on timeout.
32 */
33 readonly settled: (since: string, waitMs: number) => Promise<{ live: true; ms: number } | { live: false; why: string } | undefined>;
34 /** An event-outbox position now, to read what came after. */
35 readonly mark: () => string;
36 readonly removeForge: (name: string) => Promise<boolean>;
37 readonly removeAccount: (username: string) => Promise<boolean>;
38 /**
39 * Names an earlier run left (a timeout or a restart mid-walk): forges and accounts that may be
40 * the drill's. The walk removes only those of the drill's own shape.
41 */
42 readonly leftovers?: () => Promise<{ forges: readonly string[]; accounts: readonly string[] }>;
43 readonly now: () => number;
44 readonly random: () => string;
45 /** A public app (`owner/name`) the forge is made with; none when unset. */
46 readonly app?: string | undefined;
47 }
48
49 export interface DrillResult {
50 readonly ok: boolean;
51 /** The step that failed (1-based) and its name; absent on a pass. */
52 readonly step?: number;
53 readonly stepName?: string;
54 readonly why?: string;
55 /** Time to live in ms, when the forge came up. */
56 readonly ms?: number;
57 readonly forge: string;
58 readonly at: string;
59 /** Whether the forge and the account are both gone. */
60 readonly cleaned: boolean;
61 }
62
63 const one = (text: string): string => text.replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ").trim().slice(0, 300);
64 function must(ok: unknown, said: string): asserts ok {
65 if (!ok) throw new Error(said);
66 }
67 const field = (v: unknown, key: string): unknown => (typeof v === "object" && v !== null ? (v as Record<string, unknown>)[key] : undefined);
68
69 class StepError extends Error {
70 constructor(readonly n: number, readonly named: string, message: string) {
71 super(message);
72 }
73 }
74 async function step<T>(n: number, run: () => Promise<T>): Promise<T> {
75 try {
76 return await run();
77 } catch (error) {
78 throw new StepError(n, STEPS[n - 1]!, one(error instanceof Error ? error.message : String(error)));
79 }
80 }
81
82 /** Removes what an earlier run left, by the drill's own shapes only; names what could not go. */
83 export async function sweep(h: Hands): Promise<string[]> {
84 const left = await (h.leftovers?.() ?? Promise.resolve({ forges: [], accounts: [] })).catch(() => ({ forges: [], accounts: [] }));
85 const stuck: string[] = [];
86 for (const name of left.forges) if (FORGE_SHAPE.test(name) && !(await h.removeForge(name).catch(() => false))) stuck.push(`leftover forge ${name}`);
87 for (const name of left.accounts) if (ACCOUNT_SHAPE.test(name) && !(await h.removeAccount(name).catch(() => false))) stuck.push(`leftover account ${name}`);
88 return stuck;
89 }
90
91 export async function runDrill(h: Hands): Promise<DrillResult> {
92 const stale = await sweep(h);
93 const id = h.random();
94 const forge = `drill-${id}`;
95 const account = `drillbot-${id}`;
96 const password = `${h.random()}${h.random()}${h.random()}-drill`;
97 const at = new Date(h.now()).toISOString();
98 let failure: StepError | undefined;
99 let ms: number | undefined;
100 let made = false;
101 let signed = false;
102 try {
103 const token = await step(1, async () => {
104 const user = await h.call("POST", "/api/v1/users", { username: account, password });
105 signed = user.status === 201 || user.status === 202;
106 must(user.status === 201, `the account answered ${user.status}: ${one(JSON.stringify(user.body))}`);
107 const minted = await h.call("POST", "/api/v1/tokens", { username: account, password, scope: "rw", name: "drill" });
108 must(minted.status === 201 && typeof field(minted.body, "token") === "string", `the token answered ${minted.status}`);
109 return field(minted.body, "token") as string;
110 });
111 const since = h.mark();
112 const spawned = await step(2, async () => {
113 const res = await h.call("POST", "/api/v1/forges", { name: forge, apps: h.app === undefined ? [] : [h.app], dryRun: false, claim: "token" }, token);
114 made = res.status === 201 || res.status === 200;
115 must(res.status === 201, `the spawn answered ${res.status}: ${one(JSON.stringify(res.body))}`);
116 must(typeof field(res.body, "token") === "string", `no token for the claimed forge (${one(String(field(res.body, "claimError") ?? "no reason given"))})`);
117 return res.body;
118 });
119 await step(3, async () => {
120 const seen = await h.settled(since, LIVE_BUDGET_MS);
121 must(seen !== undefined, `no answer in ${LIVE_BUDGET_MS} ms`);
122 if (!seen.live) throw new Error(`the watcher gave up: ${seen.why}`);
123 ms = seen.ms;
124 must(seen.ms < LIVE_BUDGET_MS, `time to live ${seen.ms} ms is over the ${LIVE_BUDGET_MS} ms budget`);
125 });
126 await step(4, async () => {
127 const proofs = field(field(spawned, "reach"), "proofs");
128 must(Array.isArray(proofs) && proofs.length > 0, "the spawn made no proof from outside");
129 for (const p of proofs) must(field(p, "ok") === true, `${String(field(p, "label"))}: ${one(String(field(p, "says")))}`);
130 if (h.app !== undefined) must(proofs.some((p) => field(p, "label") === h.app!.split("/")[1]), `no proof for ${h.app}`);
131 });
132 } catch (error) {
133 failure = error instanceof StepError ? error : new StepError(0, "drill", one(String(error)));
134 }
135 // Pass or fail, the throwaway goes: only names of the drill's own shape reach the removals.
136 let cleaned = true;
137 const gone: string[] = [...stale];
138 if (made && FORGE_SHAPE.test(forge) && !(await h.removeForge(forge).catch(() => false))) gone.push(`forge ${forge}`);
139 if (signed && ACCOUNT_SHAPE.test(account) && !(await h.removeAccount(account).catch(() => false))) gone.push(`account ${account}`);
140 if (gone.length > 0) {
141 cleaned = false;
142 failure ??= new StepError(5, STEPS[4], `${gone.join(" and ")} could not be removed`);
143 }
144 return {
145 ok: failure === undefined,
146 ...(failure === undefined ? {} : { step: failure.n, stepName: failure.named, why: failure.message }),
147 ...(ms === undefined ? {} : { ms }),
148 forge,
149 at,
150 cleaned,
151 };
152 }
153
154 /** `step 3 (forge live) failed: …`, or the pass in a line. */
155 export function words(r: DrillResult): string {
156 return r.ok ? `one-click drill passed: ${r.forge} live in ${r.ms} ms, removed` : `step ${r.step} (${r.stepName}) failed: ${r.why}`;
157 }
src/release/one_click_hands.ts added +79
@@ -0,0 +1,79 @@
1 /**
2 * The drill's hands on the running forge (#2931): its own router in process, because the egress
3 * gate refuses the forge's own host, and the removals the forge already has
4 * (`spawn/manage.ts` `removeForge`, `actions/accounts.ts` `removeAccount`).
5 */
6 import type { App } from "../app.ts";
7 import { getUserById } from "../core/users.ts";
8 import { ACCOUNT_SHAPE, CALL_MS, FORGE_SHAPE, type Hands } from "./one_click_drill.ts";
9 import { DRILL_HEADER, drillKey } from "./prober.ts";
10
11 const POLL_MS = 500;
12
13 /**
14 * Imported when the drill runs, not at load: the router and the actions reach back into the duty
15 * roster.
16 */
17 export async function realHands(app: App, base: string, appName: string | undefined): Promise<{ hands: Hands; close: () => void }> {
18 const { forgeHttp } = await import("../http/server.ts");
19 const { removeAccount } = await import("../actions/accounts.ts");
20 const { listChildren } = await import("../actions/spawn.ts");
21 const { removeForge } = await import("../spawn/manage.ts");
22 const http = forgeHttp(app);
23 const origin = new URL(base).origin;
24 const hands: Hands = {
25 app: appName,
26 async call(method, path, body, token) {
27 const headers: Record<string, string> = { "content-type": "application/json", origin, [DRILL_HEADER]: drillKey(app.hookSecret) };
28 if (token !== undefined) headers["authorization"] = `Bearer ${token}`;
29 const res = await http.handle(new Request(`${origin}${path}`, { method, headers, body: JSON.stringify(body), signal: AbortSignal.timeout(CALL_MS) }));
30 const text = await res.text();
31 let parsed: unknown = text;
32 try {
33 parsed = JSON.parse(text);
34 } catch {
35 // Not JSON (an error page, say): the text itself is the body, as parsed above.
36 }
37 return { status: res.status, body: parsed };
38 },
39 mark: () => (app.db.query<{ id: string | null }, []>("SELECT MAX(id) AS id FROM event").get()?.id ?? ""),
40 async settled(since, waitMs) {
41 const until = Date.now() + waitMs;
42 while (Date.now() < until && !app.closing.signal.aborted) {
43 const rows = app.db
44 .query<{ kind: string; payload: string }, [string]>(
45 "SELECT kind, payload FROM event WHERE kind IN ('forge.spawn.live', 'forge.spawn.failed') AND id > ?1 AND json_extract(payload, '$.drill') = 1 ORDER BY id LIMIT 1",
46 )
47 .all(since);
48 const row = rows[0];
49 if (row !== undefined) {
50 const p = JSON.parse(row.payload) as { ms?: number; step?: string };
51 return row.kind === "forge.spawn.live" ? { live: true, ms: Number(p.ms ?? 0) } : { live: false, why: `its ${p.step ?? "health"} never answered` };
52 }
53 await Bun.sleep(POLL_MS);
54 }
55 return undefined;
56 },
57 async removeForge(name) {
58 if (!FORGE_SHAPE.test(name)) return false;
59 const done = await removeForge(app, name);
60 return done.ok;
61 },
62 async removeAccount(username) {
63 if (!ACCOUNT_SHAPE.test(username)) return false;
64 const admin = app.db.query<{ id: string }, []>("SELECT id FROM user WHERE is_admin = 1 AND kind = 'user' AND removed_at IS NULL ORDER BY created_at LIMIT 1").get();
65 const actor = admin === null ? undefined : getUserById(app.db, admin.id);
66 const gone = await removeAccount(app, actor, username);
67 if (!gone.ok) app.log.warn(`the drill account was not removed: ${String(gone.error)}`);
68 return gone.ok;
69 },
70 async leftovers() {
71 const forges = (await listChildren(app)).map((c) => c.name);
72 const accounts = app.db.query<{ username: string }, []>("SELECT username FROM user WHERE username LIKE 'drillbot-%' AND removed_at IS NULL").all().map((r) => r.username);
73 return { forges, accounts };
74 },
75 now: () => Date.now(),
76 random: () => crypto.randomUUID().replace(/-/g, "").slice(0, 8),
77 };
78 return { hands, close: http.close };
79 }
src/release/prober.ts +18 −4
@@ -19,8 +19,22 @@ export const proberKey = (hookSecret: string): string =>
1919 * Whether `request` carries this boot's prober key (constant-time); anything else, forged or
2020 * missing, is a stranger.
2121 */
22 export function isProber(hookSecret: string, request: Request): boolean {
23 const given = Buffer.from(request.headers.get(PROBER_HEADER) ?? "");
24 const want = Buffer.from(proberKey(hookSecret));
25 return hookSecret.length > 0 && given.length === want.length && timingSafeEqual(given, want);
22 export const isProber = (hookSecret: string, request: Request): boolean => carries(hookSecret, request, PROBER_HEADER, proberKey(hookSecret));
23
24 /** Whether `header` holds `key`, in constant time; never when there is no secret. */
25 function carries(hookSecret: string, request: Request, header: string, key: string): boolean {
26 const seen = (v: string) => createHmac("sha256", "carries").update(v).digest();
27 return hookSecret.length > 0 && timingSafeEqual(seen(request.headers.get(header) ?? ""), seen(key));
2628 }
29
30 /**
31 * The header the nightly one-click drill (`release/one_click_drill.ts`) sets on its own host's
32 * requests.
33 */
34 export const DRILL_HEADER = "x-forge-drill";
35
36 /** This boot's drill key: an HMAC of the hook secret under its own label, never the prober's. */
37 export const drillKey = (hookSecret: string): string => createHmac("sha256", hookSecret).update("one-click-drill").digest("hex");
38
39 /** Whether `request` carries this boot's drill key (constant-time); anything else is a stranger. */
40 export const isDrill = (hookSecret: string, request: Request): boolean => carries(hookSecret, request, DRILL_HEADER, drillKey(hookSecret));
src/spawn/door.ts +7 −3
@@ -51,7 +51,7 @@ import { bootHostedChild, wakeLimits } from "./host.ts";
5151 import { cellChildren, cellPlacement, ownsBody } from "./cell.ts";
5252 import { cellsAvailable } from "../apps/contain.ts";
5353 import { isSealed } from "./sealed.ts";
54 import { isProber } from "../release/prober.ts";
54 import { isDrill, isProber } from "../release/prober.ts";
5555 import { takePlace } from "./births.ts";
5656 import { reserveAnonSpawn, type Reserved } from "./rate.ts";
5757 import { readdirSync, readFileSync } from "node:fs";
@@ -270,7 +270,10 @@ export async function spawnDoor(
270270 // The forge's own release prober (`release/prober.ts`) is no stranger: its walk spends no
271271 // stranger's allowance.
272272 const paid = opts.paid === true;
273 const prober = isProber(ctx.app.hookSecret, ctx.request);
273 // The nightly drill (`release/one_click_drill.ts`) is the forge asking itself too: no stranger's
274 // allowance is spent, and its spawn events carry `drill`.
275 const drilling = isDrill(ctx.app.hookSecret, ctx.request);
276 const prober = isProber(ctx.app.hookSecret, ctx.request) || drilling;
274277 const counted = !paid && !prober;
275278 const anon = user === undefined;
276279 if (!anon && user.kind !== "user") return spawnWords({ kind: "forbidden" });
@@ -568,6 +571,7 @@ export async function spawnDoor(
568571 made = await spawnForge(ctx.app, user, input, source, {
569572 ...(gift === undefined && !paid ? {} : { gift: true }),
570573 placement: placementFor(ctx.app),
574 ...(drilling ? { drill: true } : {}),
571575 request: ctx.request,
572576 url: ctx.url,
573577 ...(typeof modelKey === "string" ? { modelKey } : {}),
@@ -595,7 +599,7 @@ export async function spawnDoor(
595599 let watching = false;
596600 try {
597601 up = bootHostedChild(ctx.app, made.value.name);
598 watching = startWatch(ctx.app, { name: made.value.name, startedAt, ...templateOfInput(raw["template"]), probe: (probes.get(ctx.app) ?? watchProbe)(made.value.url), onSettled: place.release });
602 watching = startWatch(ctx.app, { name: made.value.name, startedAt, ...templateOfInput(raw["template"]), probe: (probes.get(ctx.app) ?? watchProbe)(made.value.url), ...(drilling ? { drill: true } : {}), onSettled: place.release });
599603 } finally {
600604 if (!watching) place.release();
601605 }
test/one-click-drill-door.test.ts added +90
@@ -0,0 +1,90 @@
1 /**
2 * The spawn door and the nightly drill (#2931): a request with this boot's drill key spends no
3 * stranger's allowance and its spawn events carry `drill: 1`; a wrong key, the prober's, or none
4 * spends the allowance and its events carry no `drill`.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { serve, type Servers } from "../src/http/server.ts";
12 import { ok } from "../src/kernel/result.ts";
13 import { usePlacement } from "../src/spawn/door.ts";
14 import { resetAnonSpawns } from "../src/spawn/rate.ts";
15 import { DRILL_HEADER, PROBER_HEADER, drillKey, proberKey } from "../src/release/prober.ts";
16
17 let dataDir: string;
18 let app: App;
19 let servers: Servers;
20 beforeAll(async () => {
21 dataDir = await mkdtemp(join(tmpdir(), "forge-drill-door-"));
22 app = createApp({ dataDir, port: 0 });
23 servers = await serve(app);
24 usePlacement(app, {
25 place: async (plan) => ok({ url: `https://${plan.name}.fake.test`, bodyId: `fake-${plan.name}` }),
26 retire: async () => ok(),
27 });
28 });
29 afterAll(async () => {
30 await servers.stop?.();
31 app.close();
32 await rm(dataDir, { recursive: true, force: true });
33 });
34
35 const make = (name: string, headers: Record<string, string>) =>
36 fetch(`${servers.url}/api/v1/forges`, {
37 method: "POST",
38 headers: { "content-type": "application/json", origin: servers.url, ...headers },
39 body: JSON.stringify({ name, dryRun: false }),
40 });
41 const spent = (): number => (app.db.query("SELECT COUNT(*) AS n FROM anon_spawn").get() as { n: number }).n;
42 const events = (kind: string): { drill?: number }[] =>
43 app.db.query<{ payload: string }, [string]>("SELECT payload FROM event WHERE kind = ?1 ORDER BY id").all(kind).map((r) => JSON.parse(r.payload));
44 /** Resolves at the next `forge.spawn.live` the bus carries; subscribe before the request. */
45 const nextLive = (): Promise<void> => {
46 const { promise, resolve } = Promise.withResolvers<void>();
47 const off = app.bus.subscribe((e) => {
48 if (e.kind !== "forge.spawn.live") return;
49 off();
50 resolve();
51 });
52 return promise;
53 };
54
55 test("the drill key spends no allowance and tags the spawn events drill", async () => {
56 resetAnonSpawns(app.db);
57 const live = nextLive();
58 const res = await make("drill-0a1b2c3d", { [DRILL_HEADER]: drillKey(app.hookSecret) });
59 expect(res.status).toBe(201);
60 expect(spent()).toBe(0);
61 await live;
62 expect(events("forge.spawn.started").at(-1)).toEqual({ drill: 1 });
63 expect(events("forge.spawn.live").at(-1)?.drill).toBe(1);
64 });
65
66 test.each([
67 ["a wrong key", () => ({ [DRILL_HEADER]: "0".repeat(64) })],
68 ["the prober's key in the drill's header", () => ({ [DRILL_HEADER]: proberKey(app.hookSecret) })],
69 ["no key", () => ({})],
70 ])("%s spends the allowance and tags nothing", async (_, headers) => {
71 resetAnonSpawns(app.db);
72 const liveBefore = events("forge.spawn.live").length;
73 const live = nextLive();
74 const res = await make(`other-${Math.random().toString(16).slice(2, 10)}`, headers());
75 expect(res.status).toBe(201);
76 expect(spent()).toBe(1);
77 await live;
78 expect(events("forge.spawn.live").length).toBeGreaterThan(liveBefore);
79 expect(events("forge.spawn.live").at(-1)?.drill).toBeUndefined();
80 });
81
82 test("the prober's own key is no drill: it spends nothing but tags nothing", async () => {
83 resetAnonSpawns(app.db);
84 const live = nextLive();
85 const res = await make("probe-9f8e7d6c", { [PROBER_HEADER]: proberKey(app.hookSecret) });
86 expect(res.status).toBe(201);
87 expect(spent()).toBe(0);
88 await live;
89 expect(events("forge.spawn.live").at(-1)?.drill).toBeUndefined();
90 });
test/one-click-drill.test.ts added +245
@@ -0,0 +1,245 @@
1 /**
2 * The nightly one-click drill (#2931): the walk names the step that failed, removes what it made
3 * pass or fail, and the duty puts the verdict on the outbox and files one issue that names the
4 * step. The real hands are tried against a real forge's router: an account is made and removed.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { createRepo } from "../src/core/repos.ts";
12 import { createUser, getUserByName } from "../src/core/users.ts";
13 import { oneClickDrill, TITLE } from "../src/maintain/duties/one_click_drill.ts";
14 import { ACCOUNT_SHAPE, FORGE_SHAPE, runDrill, sweep, words, type Hands } from "../src/release/one_click_drill.ts";
15 import { DRILL_HEADER, PROBER_HEADER, drillKey, isDrill, isProber, proberKey } from "../src/release/prober.ts";
16 import { realHands } from "../src/release/one_click_hands.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18
19 quietLogs();
20
21 const PROOFS = [{ label: "home", ok: true, says: "answers" }];
22 /** Hands that stand in for the forge; `breakAt` names the call that goes wrong. */
23 function fake(o: { signup?: number; token?: number; spawn?: number; live?: "live" | "failed" | "never"; proofs?: unknown[]; removeForge?: boolean; removeAccount?: boolean } = {}) {
24 const removed: string[] = [];
25 const calls: string[] = [];
26 let n = 0;
27 const hands: Hands = {
28 async call(method, path, body) {
29 calls.push(`${method} ${path}`);
30 if (path === "/api/v1/users") return { status: o.signup ?? 201, body: {} };
31 if (path === "/api/v1/tokens") return { status: o.token ?? 201, body: { token: "t" } };
32 return { status: o.spawn ?? 201, body: { token: "child-token", reach: { proofs: o.proofs ?? PROOFS }, sent: body } };
33 },
34 mark: () => "0",
35 async settled() {
36 return o.live === "never" ? undefined : o.live === "failed" ? { live: false, why: "its health never answered" } : { live: true, ms: 4200 };
37 },
38 async removeForge(name) {
39 removed.push(`forge:${name}`);
40 return o.removeForge ?? true;
41 },
42 async removeAccount(name) {
43 removed.push(`account:${name}`);
44 return o.removeAccount ?? true;
45 },
46 now: () => 1_700_000_000_000,
47 random: () => (++n).toString(16).padStart(8, "0"),
48 };
49 return { hands, removed, calls };
50 }
51
52 describe("the walk", () => {
53 test("a pass reports the time to live and removes the forge and the account", async () => {
54 const { hands, removed } = fake();
55 const r = await runDrill(hands);
56 expect(r).toMatchObject({ ok: true, ms: 4200, cleaned: true });
57 expect(FORGE_SHAPE.test(r.forge)).toBe(true);
58 expect(removed).toEqual([`forge:${r.forge}`, `account:${r.forge.replace("drill-", "drillbot-")}`]);
59 expect(words(r)).toContain("live in 4200 ms");
60 });
61
62 test.each([
63 [{ signup: 429 }, 1, "signup", /account answered 429/],
64 [{ token: 500 }, 1, "signup", /token answered 500/],
65 [{ spawn: 503 }, 2, "make a forge", /spawn answered 503/],
66 [{ live: "failed" as const }, 3, "forge live", /health never answered/],
67 [{ live: "never" as const }, 3, "forge live", /no answer in/],
68 [{ proofs: [{ label: "home", ok: false, says: "no answer" }] }, 4, "included app", /home: no answer/],
69 [{ proofs: [] }, 4, "included app", /no proof from outside/],
70 ])("%j fails at step %i (%s) and says why", async (o, n, name, why) => {
71 const { hands } = fake(o);
72 const r = await runDrill(hands);
73 expect(r).toMatchObject({ ok: false, step: n, stepName: name });
74 expect(r.why).toMatch(why);
75 expect(words(r)).toBe(`step ${n} (${name}) failed: ${r.why}`);
76 });
77
78 test("a failed spawn still removes the account, and nothing is removed that was never made", async () => {
79 const failed = fake({ spawn: 503 });
80 await runDrill(failed.hands);
81 expect(failed.removed.map((x) => x.split(":")[0])).toEqual(["account"]);
82 const refused = fake({ signup: 403 });
83 await runDrill(refused.hands);
84 expect(refused.removed).toEqual([]);
85 });
86
87 test("a forge or account that cannot be removed is step 5, even after a pass", async () => {
88 const r = await runDrill(fake({ removeAccount: false }).hands);
89 expect(r).toMatchObject({ ok: false, step: 5, stepName: "clean up", cleaned: false });
90 expect(r.why).toMatch(/account drillbot-/);
91 });
92
93 test("an included app must have its own proof", async () => {
94 const { hands } = fake();
95 const r = await runDrill({ ...hands, app: "alice/bakery" });
96 expect(r).toMatchObject({ ok: false, step: 4 });
97 expect(r.why).toContain("no proof for alice/bakery");
98 });
99 });
100
101 describe("what an earlier run left", () => {
102 test("a drill-shaped forge and account are removed before the walk; nothing of another shape is", async () => {
103 const { hands, removed } = fake();
104 const r = await runDrill({
105 ...hands,
106 leftovers: async () => ({ forges: ["drill-deadbeef", "drill-DEADBEEF", "alice", "drill-deadbeef-x"], accounts: ["drillbot-cafef00d", "drillbot-x", "boss"] }),
107 });
108 expect(r.ok).toBe(true);
109 expect(removed.slice(0, 2)).toEqual(["forge:drill-deadbeef", "account:drillbot-cafef00d"]);
110 expect(removed).toHaveLength(4);
111 });
112
113 test("a leftover that cannot be removed fails step 5", async () => {
114 const { hands } = fake();
115 const r = await runDrill({ ...hands, removeForge: async (n) => n !== "drill-deadbeef", leftovers: async () => ({ forges: ["drill-deadbeef"], accounts: [] }) });
116 expect(r).toMatchObject({ ok: false, step: 5, cleaned: false });
117 expect(r.why).toContain("leftover forge drill-deadbeef");
118 });
119 });
120
121 describe("the duty", () => {
122 let dir = "";
123 let app: App;
124 beforeAll(async () => {
125 dir = await mkdtemp(join(tmpdir(), "forge-one-click-drill-"));
126 app = createApp({ dataDir: dir, port: 0, url: "https://forge.test" });
127 const boss = await createUser(app.db, { username: "trevato", email: "[email protected]", password: "a-good-passphrase", origin: "seed", trusted: true, isAdmin: true });
128 if (!boss.ok) throw new Error("user");
129 const repo = await createRepo(app.db, app.reposRoot, { ownerId: boss.value.id, name: "forge", visibility: "public", description: "f" });
130 if (!repo.ok) throw new Error("repo");
131 });
132 afterAll(async () => {
133 app.close();
134 await rm(dir, { recursive: true, force: true });
135 });
136 const walk = (o: Parameters<typeof fake>[0]) => oneClickDrill(async () => ({ hands: fake(o).hands, close: () => {} })).run({ db: app.db, bus: app.bus, now: new Date(), app });
137 const outbox = () => app.db.query<{ payload: string }, []>("SELECT payload FROM event WHERE kind = 'drill.one_click' ORDER BY id").all().map((r) => JSON.parse(r.payload));
138 const issues = () => app.db.query<{ id: string; body: string }, [string]>("SELECT id, body FROM issue WHERE title = ?1 AND state = 'open'").all(TITLE);
139
140 test("a pass is on the outbox, and files nothing", async () => {
141 const res = await walk({});
142 expect(res.findings).toEqual([]);
143 expect(outbox().at(-1)).toMatchObject({ ok: true, ms: 4200 });
144 expect(issues()).toEqual([]);
145 });
146
147 test("a failure opens one issue naming the step; the next night comments instead of opening another", async () => {
148 const first = await walk({ live: "failed" });
149 expect(first.findings[0]!.summary).toMatch(/^step 3 \(forge live\) failed/);
150 expect(first.actions[0]).toMatch(/^filed issue #/);
151 expect(outbox().at(-1)).toMatchObject({ ok: false, step: 3, stepName: "forge live" });
152 expect(issues()).toHaveLength(1);
153 expect(issues()[0]!.body).toContain("step 3 (forge live) failed");
154 const second = await walk({ spawn: 503 });
155 expect(second.actions[0]).toMatch(/^commented on issue #/);
156 expect(issues()).toHaveLength(1);
157 const comments = app.db.query<{ body: string }, [string]>("SELECT body FROM comment WHERE issue_id = ?1").all(issues()[0]!.id);
158 expect(comments).toHaveLength(1);
159 expect(comments[0]!.body).toContain("step 2 (make a forge) failed");
160 });
161
162 test("a forge that does not know its public origin skips and says so", async () => {
163 const bare = createApp({ dataDir: await mkdtemp(join(tmpdir(), "forge-one-click-bare-")), port: 0 });
164 try {
165 const res = await oneClickDrill(() => { throw new Error("no hands"); }).run({ db: bare.db, bus: bare.bus, now: new Date(), app: { ...bare, config: { ...bare.config, url: "" } } as App });
166 expect(res.actions[0]).toMatch(/^skipped/);
167 } finally {
168 bare.close();
169 }
170 });
171 });
172
173 describe("the real hands", () => {
174 let dir = "";
175 let app: App;
176 beforeAll(async () => {
177 dir = await mkdtemp(join(tmpdir(), "forge-one-click-hands-"));
178 app = createApp({ dataDir: dir, port: 0, url: "https://forge.test" });
179 const rootMade = await createUser(app.db, { username: "boss", email: "[email protected]", password: "a-good-passphrase", origin: "seed", trusted: true, isAdmin: true });
180 if (!rootMade.ok) throw new Error(`admin: ${String(rootMade.error)}`);
181 });
182 afterAll(async () => {
183 app.close();
184 await rm(dir, { recursive: true, force: true });
185 });
186
187 test("an account is made through the router, and removed; a name of another shape is never removed", async () => {
188 const { hands, close } = await realHands(app, "https://forge.test", undefined);
189 try {
190 const name = "drillbot-0a1b2c3d";
191 expect(ACCOUNT_SHAPE.test(name)).toBe(true);
192 const made = await hands.call("POST", "/api/v1/users", { username: name, password: "a-long-drill-passphrase" });
193 expect(made.status).toBe(201);
194 expect(getUserByName(app.db, name)).toBeDefined();
195 expect(await hands.removeAccount("boss")).toBe(false);
196 expect(await hands.removeForge("alice")).toBe(false);
197 expect(await hands.removeAccount(name)).toBe(true);
198 const after = getUserByName(app.db, name);
199 expect(after === undefined || typeof after.removedAt === "string").toBe(true);
200 } finally {
201 close();
202 }
203 });
204
205 test("the real leftovers are the forge's children and drill accounts, and the sweep removes the account", async () => {
206 const { hands, close } = await realHands(app, "https://forge.test", undefined);
207 try {
208 const made = await hands.call("POST", "/api/v1/users", { username: "drillbot-0badf00d", password: "a-long-drill-passphrase" });
209 expect(made.status).toBe(201);
210 expect((await hands.leftovers!()).accounts).toContain("drillbot-0badf00d");
211 expect(await sweep(hands)).toEqual([]);
212 expect((await hands.leftovers!()).accounts).not.toContain("drillbot-0badf00d");
213 } finally {
214 close();
215 }
216 });
217
218 test("the real settled reads the drill's own live event and ignores one without drill", async () => {
219 const { hands, close } = await realHands(app, "https://forge.test", undefined);
220 try {
221 const since = hands.mark();
222 app.bus.append({ kind: "forge.spawn.live", payload: { ms: 111 } });
223 expect(await hands.settled(since, 50)).toBeUndefined();
224 app.bus.append({ kind: "forge.spawn.live", payload: { ms: 4321, drill: 1 } });
225 expect(await hands.settled(since, 2000)).toEqual({ live: true, ms: 4321 });
226 const later = hands.mark();
227 app.bus.append({ kind: "forge.spawn.failed", payload: { step: "health" } });
228 expect(await hands.settled(later, 50)).toBeUndefined();
229 app.bus.append({ kind: "forge.spawn.failed", payload: { step: "health", drill: 1 } });
230 expect(await hands.settled(later, 2000)).toEqual({ live: false, why: "its health never answered" });
231 } finally {
232 close();
233 }
234 });
235
236 test("the drill key is this boot's own and is not the prober's", () => {
237 const key = drillKey(app.hookSecret);
238 const ask = (headers: Record<string, string>) => new Request("https://forge.test/", { headers });
239 expect(isDrill(app.hookSecret, ask({ [DRILL_HEADER]: key }))).toBe(true);
240 expect(isDrill(app.hookSecret, ask({ [DRILL_HEADER]: proberKey(app.hookSecret) }))).toBe(false);
241 expect(isDrill(app.hookSecret, ask({ [PROBER_HEADER]: key }))).toBe(false);
242 expect(isDrill(app.hookSecret, ask({}))).toBe(false);
243 expect(isProber(app.hookSecret, ask({ [DRILL_HEADER]: key }))).toBe(false);
244 });
245 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs