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

The operator's standby drill script: scripts/drills/run.ts <domain> says what fault to cause, listens to /api/v1/health, and posts the result when the forge is back #1929

Parked opened this
Closed without merging

scout/forge:scout/1852-the-operator-s-standby-drill-script-scri → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
4 files changed +291 −0
docs/DOMAINS.md +14
@@ -9,6 +9,20 @@ Minutes back are estimates, not measurements. A drill named here is the name
99 issue #1195 will build. Today the restore drill exists, and `POST /api/v1/drills`
1010 keeps a drill's verdict for any domain here (see the README).
1111
12 ## Running a standby drill
13
14 A drill that needs a person outside the forge (kill the pod, stop the runner)
15 is a script the operator runs from another machine:
16
17 FORGE_TOKEN=… bun scripts/drills/run.ts <domain> --forge https://your.forge
18
19 `FORGE_TOKEN` is a site admin person's token. The script refuses a domain
20 whose drill is `none`, prints the fault to cause, and waits for Enter. It then
21 reads `/api/v1/health` and `/` once a second, keeps each distinct line they
22 said while the forge was not well, and when the forge is well again posts the
23 lines and the seconds since Enter to `POST /api/v1/drills`. It prints the
24 verdict and exits 0 for green, 2 for red, 1 for a refusal.
25
1226 | Domain | What breaks | The forge says | Minutes back | The owner | Drill |
1327 | --- | --- | --- | --- | --- | --- |
1428 | Compute (the pod) | Nothing answers until the pod is rescheduled. | nothing yet | 2 | Wait for the platform to restart it; read the pod's events if it does not. | kill-pod |
scripts/drills/run.ts added +203
@@ -0,0 +1,203 @@
1 /**
2 * The operator's standby drill (#1852): `bun scripts/drills/run.ts <domain>
3 * --forge <url>` for a domain whose drill needs a person outside the forge
4 * (kill the pod, cut the tunnel). It prints the fault to cause, waits for
5 * Enter, then reads `/api/v1/health` and `/` once a second, keeping each
6 * distinct line they said while the forge was not well. When the forge is
7 * well again it posts what it saw and the seconds it took to
8 * `POST /api/v1/drills`, with the token in `FORGE_TOKEN`.
9 *
10 * Nothing is run from user text: the script only prints, reads and fetches.
11 */
12
13 import { DOMAINS, type Domain } from "../../src/kernel/domains.ts";
14
15 /** The server keeps at most this much of each observation. */
16 const SEEN_MAX = 8_000;
17
18 export interface DrillIo {
19 fetch: (url: string, init?: RequestInit) => Promise<Response>;
20 /** Resolves when the operator has pressed Enter. */
21 enter: () => Promise<void>;
22 sleep: (ms: number) => Promise<void>;
23 now: () => number;
24 say: (line: string) => void;
25 }
26
27 export interface DrillArgs {
28 readonly domain: string;
29 readonly forge: string;
30 readonly token: string;
31 }
32
33 /** The words in a health answer: a JSON body's strings, else its text. */
34 export function healthLines(body: string): string[] {
35 try {
36 const out: string[] = [];
37 const walk = (v: unknown, key: string) => {
38 if (typeof v === "string") out.push(`${key}: ${v}`);
39 else if (typeof v === "boolean" || typeof v === "number") out.push(`${key}: ${v}`);
40 else if (Array.isArray(v)) v.forEach((x) => walk(x, key));
41 else if (v && typeof v === "object")
42 for (const [k, x] of Object.entries(v)) walk(x, k);
43 };
44 walk(JSON.parse(body), "health");
45 return out;
46 } catch {
47 return textLines(body);
48 }
49 }
50
51 /** The visible text of a page, one trimmed non-empty line per run of text. */
52 export function textLines(html: string): string[] {
53 return html
54 .replace(/<(script|style)[\s\S]*?<\/\1>/gi, "\n")
55 .replace(/<[^>]*>/g, "\n")
56 .split("\n")
57 .map((l) => l.replace(/\s+/g, " ").trim())
58 .filter(Boolean);
59 }
60
61 interface Look {
62 well: boolean;
63 health: string[];
64 board: string[];
65 }
66
67 async function look(forge: string, io: DrillIo): Promise<Look> {
68 let healthOk = false;
69 let boardOk = false;
70 let health: string[] = [];
71 let board: string[] = [];
72 try {
73 const r = await io.fetch(`${forge}/api/v1/health`);
74 const text = await r.text();
75 health = healthLines(text);
76 let ok = false;
77 try {
78 ok = (JSON.parse(text) as { ok?: unknown }).ok === true;
79 } catch {}
80 healthOk = r.ok && ok;
81 if (!r.ok) health.unshift(`health: HTTP ${r.status}`);
82 } catch (e) {
83 health = [`health: no answer (${(e as Error).message})`];
84 }
85 try {
86 const r = await io.fetch(`${forge}/`);
87 const text = await r.text();
88 board = textLines(text);
89 boardOk = r.ok;
90 if (!r.ok) board.unshift(`board: HTTP ${r.status}`);
91 } catch (e) {
92 board = [`board: no answer (${(e as Error).message})`];
93 }
94 return { well: healthOk && boardOk, health, board };
95 }
96
97 const joinSeen = (lines: Set<string>): string => {
98 let out = "";
99 for (const line of lines) {
100 if (out.length + line.length + 1 > SEEN_MAX) break;
101 out += (out ? "\n" : "") + line;
102 }
103 return out;
104 };
105
106 /** Judge the arguments; the domain it names, or why not. */
107 export function pickDomain(key: string): { domain: Domain } | { error: string } {
108 const domain = DOMAINS.find((d) => d.key === key);
109 if (!domain) return { error: `unknown domain "${key}"; one of ${DOMAINS.map((d) => d.key).join(", ")}` };
110 if (domain.drill.name === null) return { error: `${domain.key} has no drill: ${domain.drill.why}` };
111 return { domain };
112 }
113
114 /** Run one drill; the exit code. */
115 export async function runDrill(args: DrillArgs, io: DrillIo): Promise<number> {
116 const picked = pickDomain(args.domain);
117 if ("error" in picked) {
118 io.say(picked.error);
119 return 1;
120 }
121 const { domain } = picked;
122 io.say(`Drill ${domain.drill.name} for ${domain.name}.`);
123 io.say(`Cause this fault: ${domain.breaks}`);
124 io.say(`The forge should say: ${domain.says.length ? domain.says.map((s) => `"${s}"`).join("; ") : "nothing yet"}`);
125 io.say(`It should be back within ${domain.backMinutes} minutes. Press Enter when the fault is caused.`);
126 await io.enter();
127
128 const started = io.now();
129 const health = new Set<string>();
130 const board = new Set<string>();
131 let sawTrouble = false;
132 for (;;) {
133 const seen = await look(args.forge, io);
134 if (!seen.well) {
135 if (!sawTrouble) io.say("The forge is not well; waiting for it to come back.");
136 sawTrouble = true;
137 for (const l of seen.health) health.add(l);
138 for (const l of seen.board) board.add(l);
139 } else if (sawTrouble) {
140 const backSeconds = Math.max(0, Math.round((io.now() - started) / 1000));
141 io.say(`The forge is well again after ${backSeconds}s. Posting the result.`);
142 const res = await io.fetch(`${args.forge}/api/v1/drills`, {
143 method: "POST",
144 headers: { authorization: `Bearer ${args.token}`, "content-type": "application/json" },
145 body: JSON.stringify({
146 domain: domain.key,
147 seen: { health: joinSeen(health), board: joinSeen(board) },
148 backSeconds,
149 }),
150 });
151 const text = await res.text();
152 if (res.status !== 201) {
153 io.say(`The forge refused the result (${res.status}): ${text}`);
154 return 1;
155 }
156 const kept = JSON.parse(text) as { green: boolean; why: string };
157 io.say(`${kept.green ? "GREEN" : "RED"}: ${kept.why}`);
158 return kept.green ? 0 : 2;
159 }
160 await io.sleep(1000);
161 }
162 }
163
164 /** Read the command line; the arguments, or what to tell the operator. */
165 export function parseArgs(argv: readonly string[], env: Record<string, string | undefined>): DrillArgs | string {
166 const usage = "usage: FORGE_TOKEN=… bun scripts/drills/run.ts <domain> --forge <url>";
167 let domain = "";
168 let forge = "";
169 for (let i = 0; i < argv.length; i++) {
170 if (argv[i] === "--forge") forge = argv[++i] ?? "";
171 else if (!domain && !argv[i]!.startsWith("-")) domain = argv[i]!;
172 else return usage;
173 }
174 if (!domain || !forge) return usage;
175 let url: URL;
176 try {
177 url = new URL(forge);
178 } catch {
179 return `--forge must be a URL; ${usage}`;
180 }
181 if (url.protocol !== "http:" && url.protocol !== "https:") return `--forge must be http or https; ${usage}`;
182 const token = env.FORGE_TOKEN ?? "";
183 if (!token) return `FORGE_TOKEN is not set; ${usage}`;
184 return { domain, forge: url.origin, token };
185 }
186
187 if (import.meta.main) {
188 const args = parseArgs(process.argv.slice(2), process.env);
189 if (typeof args === "string") {
190 console.error(args);
191 process.exit(1);
192 }
193 const code = await runDrill(args, {
194 fetch: (url, init) => fetch(url, init),
195 enter: async () => {
196 for await (const _ of console) return;
197 },
198 sleep: (ms) => Bun.sleep(ms),
199 now: () => Date.now(),
200 say: (line) => console.log(line),
201 });
202 process.exit(code);
203 }
scripts/gate.ts +1
@@ -28,6 +28,7 @@ export type Exclusion = {
2828
2929 export const GATE: readonly string[] = [
3030 "test/domain-drill.test.ts",
31 "test/drill-run.test.ts",
3132 "test/accounts-retire.test.ts",
3233 "test/client-home.test.ts",
3334 "test/cloud-use.test.ts",
test/drill-run.test.ts added +73
@@ -0,0 +1,73 @@
1 import { afterAll, describe, expect, test } from "bun:test";
2 import { parseArgs, pickDomain, runDrill, type DrillIo } from "../scripts/drills/run.ts";
3
4 let sick = false;
5 let posted: { auth: string | null; body: any } | null = null;
6 const stub = Bun.serve({
7 port: 0,
8 async fetch(req) {
9 const path = new URL(req.url).pathname;
10 if (path === "/api/v1/health")
11 return Response.json(sick ? { ok: false, rollout: { reason: "The restore drill failed at x" } } : { ok: true });
12 if (path === "/") return new Response(sick ? "<main><p>Runs wait behind one lane</p></main>" : "<main>Home</main>");
13 if (path === "/api/v1/drills" && req.method === "POST") {
14 posted = { auth: req.headers.get("authorization"), body: await req.json() };
15 return Response.json({ id: 1, green: true, why: "fine" }, { status: 201 });
16 }
17 return new Response("no", { status: 404 });
18 },
19 });
20 afterAll(() => stub.stop(true));
21
22 const forge = `http://127.0.0.1:${stub.port}`;
23
24 describe("the standby drill", () => {
25 test("refuses a domain with no drill, and an unknown one", () => {
26 expect("error" in pickDomain("state")).toBe(true);
27 expect("error" in pickDomain("nope")).toBe(true);
28 expect("domain" in pickDomain("compute")).toBe(true);
29 });
30
31 test("waits for Enter, keeps distinct unwell lines, posts when well again", async () => {
32 let clock = 0;
33 let polls = 0;
34 const said: string[] = [];
35 const io: DrillIo = {
36 fetch: (u, i) => fetch(u, i),
37 enter: async () => { sick = true; },
38 sleep: async () => {
39 clock += 1000;
40 if (++polls === 3) sick = false;
41 },
42 now: () => clock,
43 say: (l) => said.push(l),
44 };
45 const code = await runDrill({ domain: "runner", forge, token: "tok" }, io);
46 expect(code).toBe(0);
47 expect(said[1]).toContain("Cause this fault");
48 expect(posted!.auth).toBe("Bearer tok");
49 expect(posted!.body.domain).toBe("runner");
50 expect(posted!.body.backSeconds).toBe(3);
51 expect(posted!.body.seen.health).toContain("ok: false");
52 expect(posted!.body.seen.health).toContain("The restore drill failed at x");
53 expect(posted!.body.seen.board).toBe("Runs wait behind one lane");
54 expect(posted!.body.seen.health.split("\n").length).toBe(new Set(posted!.body.seen.health.split("\n")).size);
55 });
56
57 test("refuses without a drill and posts nothing", async () => {
58 posted = null;
59 const said: string[] = [];
60 const code = await runDrill({ domain: "edge", forge, token: "t" }, {
61 fetch: (u, i) => fetch(u, i), enter: async () => {}, sleep: async () => {}, now: () => 0, say: (l) => said.push(l),
62 });
63 expect(code).toBe(1);
64 expect(posted).toBeNull();
65 });
66
67 test("arguments", () => {
68 expect(parseArgs(["compute", "--forge", forge], { FORGE_TOKEN: "t" })).toEqual({ domain: "compute", forge, token: "t" });
69 expect(typeof parseArgs(["compute", "--forge", forge], {})).toBe("string");
70 expect(typeof parseArgs(["compute", "--forge", "ftp://x"], { FORGE_TOKEN: "t" })).toBe("string");
71 expect(typeof parseArgs(["compute"], { FORGE_TOKEN: "t" })).toBe("string");
72 });
73 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs