Public: anyone can read this; the crew can change it.
watchDrill(fetch, sleep) polls a forge until it is healthy again and returns each distinct line it said while unhealthy #2402
scout/forge:scout/2393-watchdrill-fetch-sleep-polls-a-forge-unt → main 2 commits fork
4 files
changed +225
−85
scripts/drills/run.ts +23 −84
| @@ -9,6 +9,7 @@ | ||
| 9 | 9 | */ |
| 10 | 10 | |
| 11 | 11 | import { DOMAINS } from "../../src/kernel/domains.ts"; |
| 12 | import { watchDrill } from "./watch.ts"; | |
| 12 | 13 | |
| 13 | 14 | export interface DrillRun { |
| 14 | 15 | domain: string; |
| @@ -30,70 +31,11 @@ const DEFAULT_CEILING_MS = 3_600_000; | ||
| 30 | 31 | /** C0 and C1 control characters out (tab stays): the forge's words never drive the terminal. */ |
| 31 | 32 | export const clean = (s: string): string => s.replace(/[\x00-\x08\x0a-\x1f\x7f-\x9f]/g, ""); |
| 32 | 33 | |
| 33 | /** Every string in a JSON value, or the text's own lines when it is not JSON. */ | |
| 34 | function linesOf(text: string, contentType: string): string[] { | |
| 35 | return rawLinesOf(text, contentType).map(clean).filter((l) => l.trim() !== ""); | |
| 36 | } | |
| 34 | const cap = (lines: string[]): string => lines.join("\n").slice(0, SEEN_MAX); | |
| 37 | 35 | |
| 38 | function rawLinesOf(text: string, contentType: string): string[] { | |
| 39 | if (contentType.includes("json")) { | |
| 40 | try { | |
| 41 | const out: string[] = []; | |
| 42 | const walk = (v: unknown): void => { | |
| 43 | if (typeof v === "string") out.push(v); | |
| 44 | else if (Array.isArray(v)) v.forEach(walk); | |
| 45 | else if (v && typeof v === "object") Object.values(v).forEach(walk); | |
| 46 | }; | |
| 47 | walk(JSON.parse(text)); | |
| 48 | return out; | |
| 49 | } catch { | |
| 50 | /* fall through to plain lines */ | |
| 51 | } | |
| 52 | } | |
| 53 | return text | |
| 54 | .replace(/<(script|style)[\s\S]*?<\/\1>/gi, " ") | |
| 55 | .replace(/<[^>]*>/g, "\n") | |
| 56 | .replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">") | |
| 57 | .replace(/"/g, '"').replace(/�?39;/g, "'") | |
| 58 | .split("\n") | |
| 59 | .map((l) => l.trim()) | |
| 60 | .filter((l) => l !== ""); | |
| 61 | } | |
| 62 | ||
| 63 | interface Look { | |
| 64 | healthy: boolean; | |
| 65 | health: string[]; | |
| 66 | board: string[]; | |
| 67 | } | |
| 68 | ||
| 69 | async function look(forge: string, token: string): Promise<Look> { | |
| 70 | const get = async (path: string): Promise<{ ok: boolean; lines: string[]; json: unknown }> => { | |
| 71 | try { | |
| 72 | const res = await fetch(`${forge}${path}`, { | |
| 73 | headers: { authorization: `Bearer ${token}` }, | |
| 74 | redirect: "manual", | |
| 75 | signal: AbortSignal.timeout(5_000), | |
| 76 | }); | |
| 77 | const type = res.headers.get("content-type") ?? ""; | |
| 78 | const text = await res.text(); | |
| 79 | let json: unknown = null; | |
| 80 | if (type.includes("json")) { | |
| 81 | try { json = JSON.parse(text); } catch { /* not JSON */ } | |
| 82 | } | |
| 83 | return { ok: res.status < 400, lines: linesOf(text, type), json }; | |
| 84 | } catch { | |
| 85 | return { ok: false, lines: [], json: null }; | |
| 86 | } | |
| 87 | }; | |
| 88 | const [h, b] = await Promise.all([get("/api/v1/health"), get("/")]); | |
| 89 | const reported = (h.json as { ok?: unknown } | null)?.ok === true; | |
| 90 | return { healthy: h.ok && b.ok && reported, health: h.lines, board: b.lines }; | |
| 91 | } | |
| 92 | ||
| 93 | /** A line with its numbers blanked, so a clock or a counter is not a new line. */ | |
| 94 | const shape = (l: string): string => l.replace(/\d+/g, "#"); | |
| 95 | ||
| 96 | const cap = (lines: Iterable<string>): string => [...lines].join("\n").slice(0, SEEN_MAX); | |
| 36 | /** The forge's fetch with the admin token, no redirect followed and a ceiling per request. */ | |
| 37 | const forgeFetch = (token: string) => (url: string): Promise<Response> => | |
| 38 | fetch(url, { headers: { authorization: `Bearer ${token}` }, redirect: "manual", signal: AbortSignal.timeout(5_000) }); | |
| 97 | 39 | |
| 98 | 40 | /** Runs the drill; resolves to the process exit code. */ |
| 99 | 41 | export async function runDrill(run: DrillRun): Promise<number> { |
| @@ -116,29 +58,26 @@ export async function runDrill(run: DrillRun): Promise<number> { | ||
| 116 | 58 | run.say(`The forge should be back within ${domain.backMinutes} minutes. Press Enter when you have caused it.`); |
| 117 | 59 | await run.enter(); |
| 118 | 60 | |
| 119 | const started = now(); | |
| 120 | const health = new Map<string, string>(); | |
| 121 | const board = new Map<string, string>(); | |
| 122 | let sawDown = false; | |
| 123 | for (;;) { | |
| 124 | const seen = await look(run.forge, run.token); | |
| 125 | if (seen.healthy && sawDown) break; | |
| 126 | if (!seen.healthy) { | |
| 127 | sawDown = true; | |
| 128 | for (const l of seen.health) if (!health.has(shape(l))) { health.set(shape(l), l); run.say(`health: ${l}`); } | |
| 129 | for (const l of seen.board) if (!board.has(shape(l))) { board.set(shape(l), l); run.say(`board: ${l}`); } | |
| 130 | } | |
| 131 | if (now() - started >= ceilingMs) { | |
| 132 | const ceilingS = Math.round(ceilingMs / 1000); | |
| 133 | run.say(`The forge did not come back within the ceiling of ${ceilingS}s; nothing was posted.`); | |
| 134 | run.say(JSON.stringify({ domain: domain.key, backSeconds: null, posted: false, ceilingSeconds: ceilingS })); | |
| 135 | return 0; | |
| 136 | } | |
| 137 | await sleep(intervalMs); | |
| 61 | const watched = await watchDrill({ | |
| 62 | url: run.forge, | |
| 63 | fetch: forgeFetch(run.token), | |
| 64 | sleep, | |
| 65 | now, | |
| 66 | intervalMs, | |
| 67 | limit: Math.ceil(ceilingMs / intervalMs) + 1, | |
| 68 | onLine: (l) => run.say(l), | |
| 69 | }); | |
| 70 | if ("timeout" in watched) { | |
| 71 | const ceilingS = Math.round(ceilingMs / 1000); | |
| 72 | run.say(`The forge did not come back within the ceiling of ${ceilingS}s; nothing was posted.`); | |
| 73 | run.say(JSON.stringify({ domain: domain.key, backSeconds: null, posted: false, ceilingSeconds: ceilingS })); | |
| 74 | return 0; | |
| 138 | 75 | } |
| 139 | 76 | |
| 140 | const backSeconds = Math.max(0, Math.round((now() - started) / 1000)); | |
| 141 | const body = { domain: domain.key, seen: { health: cap(health.values()), board: cap(board.values()) }, backSeconds }; | |
| 77 | const backSeconds = Math.max(0, Math.round((watched.healthyAt - watched.startedAt) / 1000)); | |
| 78 | const only = (name: string): string[] => | |
| 79 | watched.lines.filter((l) => l.startsWith(`${name}: `)).map((l) => l.slice(name.length + 2)); | |
| 80 | const body = { domain: domain.key, seen: { health: cap(only("health")), board: cap(only("board")) }, backSeconds }; | |
| 142 | 81 | let res: Response; |
| 143 | 82 | try { |
| 144 | 83 | res = await fetch(`${run.forge}/api/v1/drills`, { |
scripts/drills/watch.ts added +106
| @@ -0,0 +1,106 @@ | ||
| 1 | /** | |
| 2 | * `watchDrill`: polls a forge's `/api/v1/health` and `/` once per tick until | |
| 3 | * it is healthy again, keeping each distinct status and text it said while | |
| 4 | * unhealthy. Pure: the fetch, the sleep and the clock come in as arguments; | |
| 5 | * it reads no stdin, posts nothing and touches no globals. | |
| 6 | */ | |
| 7 | ||
| 8 | export interface WatchInput { | |
| 9 | /** The forge's origin, no trailing path. */ | |
| 10 | url: string; | |
| 11 | fetch: (url: string) => Promise<Response>; | |
| 12 | sleep: (ms: number) => Promise<void>; | |
| 13 | /** The most ticks to poll before giving up. */ | |
| 14 | limit: number; | |
| 15 | /** Milliseconds between ticks; one second by default. */ | |
| 16 | intervalMs?: number; | |
| 17 | now?: () => number; | |
| 18 | /** Called with each new distinct line as it appears. */ | |
| 19 | onLine?: (line: string) => void; | |
| 20 | /** The most distinct lines kept; later ones are dropped. */ | |
| 21 | maxLines?: number; | |
| 22 | } | |
| 23 | ||
| 24 | export type WatchResult = | |
| 25 | | { startedAt: number; healthyAt: number; lines: string[] } | |
| 26 | | { startedAt: number; timeout: true; lines: string[] }; | |
| 27 | ||
| 28 | const LINE_MAX = 300; | |
| 29 | const LINES_MAX = 200; | |
| 30 | ||
| 31 | /** Control characters out, so the forge's words never drive a terminal. */ | |
| 32 | const clean = (s: string): string => s.replace(/[\x00-\x08\x0a-\x1f\x7f-\x9f\u2028\u2029]/g, "").trim().slice(0, LINE_MAX); | |
| 33 | ||
| 34 | /** A line with its numbers blanked, so a clock or a counter is not a new line. */ | |
| 35 | const shape = (l: string): string => l.replace(/\d+/g, "#"); | |
| 36 | ||
| 37 | /** Every string in a JSON value, or the visible text lines of anything else. */ | |
| 38 | function wordsOf(text: string, type: string): string[] { | |
| 39 | if (type.includes("json")) { | |
| 40 | try { | |
| 41 | const out: string[] = []; | |
| 42 | const walk = (v: unknown): void => { | |
| 43 | if (typeof v === "string") out.push(v); | |
| 44 | else if (Array.isArray(v)) v.forEach(walk); | |
| 45 | else if (v && typeof v === "object") Object.values(v).forEach(walk); | |
| 46 | }; | |
| 47 | walk(JSON.parse(text)); | |
| 48 | return out; | |
| 49 | } catch { /* plain lines below */ } | |
| 50 | } | |
| 51 | return text | |
| 52 | .replace(/<(script|style)[\s\S]*?<\/\1>/gi, " ") | |
| 53 | .replace(/<[^>]*>/g, "\n") | |
| 54 | .replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">") | |
| 55 | .replace(/"/g, '"').replace(/�?39;/g, "'") | |
| 56 | .split("\n"); | |
| 57 | } | |
| 58 | ||
| 59 | interface Probe { | |
| 60 | ok: boolean; | |
| 61 | lines: string[]; | |
| 62 | } | |
| 63 | ||
| 64 | async function probe(name: string, get: WatchInput["fetch"], url: string, needOk: boolean): Promise<Probe> { | |
| 65 | try { | |
| 66 | const res = await get(url); | |
| 67 | const type = res.headers.get("content-type") ?? ""; | |
| 68 | const text = await res.text(); | |
| 69 | let ok = res.status < 400; | |
| 70 | if (ok && needOk) { | |
| 71 | try { ok = (JSON.parse(text) as { ok?: unknown } | null)?.ok === true; } catch { ok = false; } | |
| 72 | } | |
| 73 | const lines = [`${name}: status ${res.status}`, ...wordsOf(text, type).map((w) => `${name}: ${clean(w)}`)]; | |
| 74 | return { ok, lines: lines.filter((l) => !l.endsWith(": ")) }; | |
| 75 | } catch (e) { | |
| 76 | return { ok: false, lines: [`${name}: unreachable (${clean(e instanceof Error ? e.message : String(e))})`] }; | |
| 77 | } | |
| 78 | } | |
| 79 | ||
| 80 | export async function watchDrill(input: WatchInput): Promise<WatchResult> { | |
| 81 | const now = input.now ?? Date.now; | |
| 82 | const interval = input.intervalMs ?? 1_000; | |
| 83 | const maxLines = input.maxLines ?? LINES_MAX; | |
| 84 | const base = input.url.replace(/\/+$/, ""); | |
| 85 | const startedAt = now(); | |
| 86 | const seen = new Map<string, string>(); | |
| 87 | let sawDown = false; | |
| 88 | for (let tick = 0; tick < input.limit; tick++) { | |
| 89 | const [health, board] = await Promise.all([ | |
| 90 | probe("health", input.fetch, `${base}/api/v1/health`, true), | |
| 91 | probe("board", input.fetch, `${base}/`, false), | |
| 92 | ]); | |
| 93 | if (health.ok && board.ok) { | |
| 94 | if (sawDown) return { startedAt, healthyAt: now(), lines: [...seen.values()] }; | |
| 95 | } else { | |
| 96 | sawDown = true; | |
| 97 | for (const l of [...(health.ok ? [] : health.lines), ...(board.ok ? [] : board.lines)]) { | |
| 98 | if (seen.size >= maxLines || seen.has(shape(l))) continue; | |
| 99 | seen.set(shape(l), l); | |
| 100 | input.onLine?.(l); | |
| 101 | } | |
| 102 | } | |
| 103 | await input.sleep(interval); | |
| 104 | } | |
| 105 | return { startedAt, timeout: true, lines: [...seen.values()] }; | |
| 106 | } |
test/drill-run.test.ts +1 −1
| @@ -156,7 +156,7 @@ test("control characters the forge sends are removed before printing or posting; | ||
| 156 | 156 | }); |
| 157 | 157 | const h = harness(state); |
| 158 | 158 | expect(await h.run("runner", `http://127.0.0.1:${server.port}`)).toBe(0); |
| 159 | const said = h.lines.find((l) => l.startsWith("health: "))!; | |
| 159 | const said = h.lines.find((l) => l.includes("RED"))!; | |
| 160 | 160 | expect(said).toBe("health: bad[31mRED\tx"); |
| 161 | 161 | expect(said).not.toContain("\x1b"); |
| 162 | 162 | expect(JSON.stringify(state.posts[0]!.body)).not.toContain("\\u001b"); |
test/drill-watch.test.ts added +95
| @@ -0,0 +1,95 @@ | ||
| 1 | import { expect, test } from "bun:test"; | |
| 2 | import { watchDrill } from "../scripts/drills/watch.ts"; | |
| 3 | ||
| 4 | function forge(script: ("up" | "down" | "gone")[]) { | |
| 5 | let tick = 0; | |
| 6 | const calls: string[] = []; | |
| 7 | const get = async (url: string): Promise<Response> => { | |
| 8 | const path = new URL(url).pathname; | |
| 9 | calls.push(path); | |
| 10 | const state = script[Math.min(Math.floor((calls.length - 1) / 2), script.length - 1)]!; | |
| 11 | tick++; | |
| 12 | if (state === "gone") throw new Error("connect refused"); | |
| 13 | if (state === "up") return path === "/" ? new Response("<p>Board</p>") : Response.json({ ok: true }); | |
| 14 | return path === "/" | |
| 15 | ? new Response("<p>The runner is stuck</p>", { status: 503, headers: { "content-type": "text/html" } }) | |
| 16 | : Response.json({ ok: false, note: `Disk is ${90 + tick}% full` }, { status: 503 }); | |
| 17 | }; | |
| 18 | return { get, calls }; | |
| 19 | } | |
| 20 | ||
| 21 | test("returns each distinct line while unhealthy, with no real wait", async () => { | |
| 22 | const f = forge(["up", "down", "down", "gone", "up"]); | |
| 23 | const sleeps: number[] = []; | |
| 24 | let clock = 1000; | |
| 25 | const t0 = performance.now(); | |
| 26 | const r = await watchDrill({ | |
| 27 | url: "http://forge.test/", | |
| 28 | fetch: f.get, | |
| 29 | sleep: async (ms) => { sleeps.push(ms); clock += ms; }, | |
| 30 | limit: 10, | |
| 31 | now: () => clock, | |
| 32 | }); | |
| 33 | expect(performance.now() - t0).toBeLessThan(500); | |
| 34 | expect(r).toEqual({ | |
| 35 | startedAt: 1000, | |
| 36 | healthyAt: 5000, | |
| 37 | lines: [ | |
| 38 | "health: status 503", | |
| 39 | expect.stringMatching(/^health: Disk is \d+% full$/), | |
| 40 | "board: status 503", | |
| 41 | "board: The runner is stuck", | |
| 42 | "health: unreachable (connect refused)", | |
| 43 | "board: unreachable (connect refused)", | |
| 44 | ], | |
| 45 | }); | |
| 46 | expect(sleeps).toEqual([1000, 1000, 1000, 1000]); | |
| 47 | expect(f.calls.slice(0, 2).sort()).toEqual(["/", "/api/v1/health"]); | |
| 48 | }); | |
| 49 | ||
| 50 | test("a counter that moves is one line, not many", async () => { | |
| 51 | const f = forge(["down", "down", "down", "up"]); | |
| 52 | const r = await watchDrill({ url: "http://forge.test", fetch: f.get, sleep: async () => {}, limit: 10 }); | |
| 53 | if ("timeout" in r) throw new Error("timed out"); | |
| 54 | expect(r.lines.filter((l) => l.startsWith("health: Disk"))).toHaveLength(1); | |
| 55 | }); | |
| 56 | ||
| 57 | test("times out when the forge never comes back, and when it never went down", async () => { | |
| 58 | const down = await watchDrill({ url: "http://forge.test", fetch: forge(["down"]).get, sleep: async () => {}, limit: 3 }); | |
| 59 | expect("timeout" in down && down.lines.length).toBeGreaterThan(0); | |
| 60 | const up = await watchDrill({ url: "http://forge.test", fetch: forge(["up"]).get, sleep: async () => {}, limit: 3 }); | |
| 61 | expect(up).toMatchObject({ timeout: true, lines: [] }); | |
| 62 | }); | |
| 63 | ||
| 64 | test("a health body that does not say ok is unhealthy", async () => { | |
| 65 | let n = 0; | |
| 66 | const get = async (url: string) => | |
| 67 | new URL(url).pathname === "/" ? new Response("hi") : new Response(++n < 2 ? "{}" : '{"ok":true}'); | |
| 68 | const r = await watchDrill({ url: "http://f.test", fetch: get, sleep: async () => {}, limit: 5 }); | |
| 69 | expect(r).toMatchObject({ healthyAt: expect.any(Number) }); | |
| 70 | }); | |
| 71 | ||
| 72 | test("a board-only outage is unhealthy while health passes", async () => { | |
| 73 | let n = 0; | |
| 74 | const get = async (url: string) => { | |
| 75 | if (new URL(url).pathname === "/api/v1/health") return Response.json({ ok: true }); | |
| 76 | return ++n < 3 ? new Response("<p>Board broken</p>", { status: 500, headers: { "content-type": "text/html" } }) : new Response("ok"); | |
| 77 | }; | |
| 78 | const r = await watchDrill({ url: "http://f.test", fetch: get, sleep: async () => {}, limit: 10 }); | |
| 79 | expect(r).toMatchObject({ healthyAt: expect.any(Number), lines: ["board: status 500", "board: Board broken"] }); | |
| 80 | }); | |
| 81 | ||
| 82 | test("a random word per tick is capped, onLine hears each kept line, U+2028 is removed", async () => { | |
| 83 | let n = 0; | |
| 84 | const get = async (url: string) => | |
| 85 | new URL(url).pathname === "/" | |
| 86 | ? new Response("ok") | |
| 87 | : Response.json({ ok: false, id: `id-${"abcdefghij"[n++ % 10]}${n}x\u2028y` }, { status: 503 }); | |
| 88 | const heard: string[] = []; | |
| 89 | const r = await watchDrill({ | |
| 90 | url: "http://f.test", fetch: get, sleep: async () => {}, limit: 50, maxLines: 5, onLine: (l) => heard.push(l), | |
| 91 | }); | |
| 92 | expect(r.lines).toHaveLength(5); | |
| 93 | expect(heard).toEqual(r.lines); | |
| 94 | expect(r.lines.join("")).not.toContain("\u2028"); | |
| 95 | }); |
new above
offline