Public: anyone can read this; the crew can change it.
A drill for each failure domain: kill the pod, cut the tunnel, lose the runner, expire a token; the forge's own words recorded and compared to docs/DOMAINS.md #1720
scout/forge:scout/1195-a-drill-for-each-failure-domain-kill-the → main 10 commits fork 11 threads · 11 unresolved
README.md +14
| @@ -554,6 +554,20 @@ into scratch, opens it, counts what is there and unseals a value; the page | ||
| 554 | 554 | waits for it, up to 10 minutes, and the last drill shows there as one line. |
| 555 | 555 | Only one runs at a time. See `docs/SNAPSHOT.md`. |
| 556 | 556 | |
| 557 | **Failure-domain drills** (`docs/DOMAINS.md`) kill one thing at a time and | |
| 558 | record what the forge said and how long it took to come back. Three are | |
| 559 | drilled: `compute` (the pod), `edge` (the tunnel) and `runner`. The operator | |
| 560 | runs one from a standby script, because the fault is theirs to cause: | |
| 561 | `FORGE_URL=… FORGE_TOKEN=<admin token> bun scripts/drills/run.ts compute|edge|runner`. | |
| 562 | The forge judges the words against the map: green or red with the reason. | |
| 563 | **Settings → Resilience** shows each domain's last drill; so do | |
| 564 | `GET /api/v1/drills` and the MCP `drills` tool (admins only), and the script | |
| 565 | reports with `POST /api/v1/drills`. In the terminal an admin has a **Drills** | |
| 566 | command (palette) showing the same map, each last verdict and the overdue | |
| 567 | line; a guest or non-admin is not offered it. The runner drill needs a check | |
| 568 | queued (push something while the runner is stopped); a drill that never saw | |
| 569 | the forge go down posts nothing and exits non-zero. | |
| 570 | ||
| 557 | 571 | `docs/EXTRACT.md` is the forge on a machine of its own, and the platform it |
| 558 | 572 | grew up in switched off: what a host owes it, the moves in order, and what is |
| 559 | 573 | given up. |
docs/DOMAINS.md added +38
| @@ -0,0 +1,38 @@ | ||
| 1 | # Failure domains | |
| 2 | ||
| 3 | One place to manage, many places to fail. Each row: what breaks, how the forge | |
| 4 | says so (a phrase that must appear in what `/api/v1/health` or the board said | |
| 5 | during the drill), how long until it is back, what the owner does, and the | |
| 6 | drill. The same map is data in `src/kernel/domains.ts`; `test/domains.test.ts` | |
| 7 | fails when the two disagree. | |
| 8 | ||
| 9 | | Domain | Breaks | The forge says | Back in | The owner | Drill | | |
| 10 | | --- | --- | --- | --- | --- | --- | | |
| 11 | | Compute (the pod) | Every page and the API until the pod is replaced. | "unreachable", "502", "503" or "504" | 5 min | Wait for the pod to be rescheduled; if it is not back, restart the deployment. | Delete the forge's pod. | | |
| 12 | | State (the volume) | The database, repositories and keys; the forge cannot start. | "disk" | 60 min | Restore the newest snapshot onto a new volume ([](RESTORE.md)). | None: the restore drill proves the way back. | | |
| 13 | | Snapshot store | Nothing now; the next restore has nothing to start from. | "snapshot" | 60 min | Fix the destination under Settings → Backups and take a snapshot. | None: the restore drill reads the store. | | |
| 14 | | Edge (tunnel and DNS) | The forge is unreachable from outside; inside, it is fine. | "unreachable", "530", "1033" or "502" | 10 min | Restart the tunnel; check DNS if the tunnel is up. | Stop the tunnel. | | |
| 15 | | Identity (OAuth origin, passkeys) | Sign-in through the origin; passkeys still work. | "origin" | 30 min | Sign in with a passkey; re-authorize the origin. | None: revoking sign-in is the harm. | | |
| 16 | | Model credential | The crew cannot start runs; the board and repositories are fine. | (nothing yet) | 15 min | Seal a fresh credential under Settings → Subscriptions. | None: health says nothing of a dead credential, so a drill could only be red. | | |
| 17 | | Runner | Checks queue and the gate slows; a fix can still be released. | "behind one lane" | 30 min | Bring the runner back; checks resume by themselves. | Stop the runner, then push something so a check is queued: the queue shows only once one has waited. | | |
| 18 | ||
| 19 | ## The drills | |
| 20 | ||
| 21 | Three domains are drilled: pod, edge, runner. Each is a standby | |
| 22 | script the operator runs, because the fault is the operator's to cause: | |
| 23 | ||
| 24 | sh | |
| 25 | FORGE_URL=https://… FORGE_TOKEN=<admin token> bun scripts/drills/run.ts compute | |
| 26 | ||
| 27 | ||
| 28 | It says what fault to cause, waits for Enter, then polls `/api/v1/health` and | |
| 29 | the board once a second, keeping the words each said, until the forge is | |
| 30 | reachable again (judged from the status and the rollout, never from `ok`; the | |
| 31 | runner drill is down while health carries a `queue:` cause). If the forge never goes down in an hour (an idle forge for the runner drill, or a fault not caused) the script says the fault was not seen and exits non-zero without posting. The time back is counted from Enter. It posts the result to `POST /api/v1/drills`; the forge keeps | |
| 32 | it and gives its verdict: **green** when the recorded words contain one of the | |
| 33 | phrases above and the forge was back within the time above (the runner's phrase is judged on the board alone, since its health always carries the queue cause), else **red** with | |
| 34 | the reason. Settings → Resilience shows each domain's last drill and verdict; so do | |
| 35 | `GET /api/v1/drills` (admin only: the map, each domain's `last` drill, and the | |
| 36 | `undrilled` list) and the MCP `drills` tool. | |
| 37 | A drilled domain with no drill in eight days is one quiet line on that page | |
| 38 | (only on a forge older than eight days); it is not a vitals need. |
docs/SNAPSHOT.md +3
| @@ -112,3 +112,6 @@ sealed variable and an app's SQLite is snapshotted, restored into an empty | ||
| 112 | 112 | directory with the passphrase and booted there as the same forge; restored |
| 113 | 113 | without it, the repositories come back and the sealed variable is reported by |
| 114 | 114 | name. It also checks that the raw key is in no file of the store. |
| 115 | ||
| 116 | The other drills — pod, tunnel, runner, credential — are in | |
| 117 | [](DOMAINS.md), and read on Settings → Resilience. |
scripts/drills/run.ts added +84
| @@ -0,0 +1,84 @@ | ||
| 1 | /** | |
| 2 | * The operator's standby drill: `FORGE_URL=… FORGE_TOKEN=<admin token> bun | |
| 3 | * scripts/drills/run.ts <domain>`. Says what fault to cause, waits for | |
| 4 | * Enter, then polls the health and the board once a second, keeping the | |
| 5 | * words each said, until the forge is reachable again (the runner drill: until the queue clears); posts the result | |
| 6 | * to /api/v1/drills, whose answer is the verdict. If the forge never went | |
| 7 | * down, nothing is posted and it exits 1; the time back counts from Enter. See docs/DOMAINS.md. | |
| 8 | */ | |
| 9 | import { DRILLED, domainOf } from "../../src/kernel/domains.ts"; | |
| 10 | import { SAID_MAX, heard as hear, isDown } from "../../src/kernel/drills.ts"; | |
| 11 | ||
| 12 | const [id] = process.argv.slice(2); | |
| 13 | const domain = domainOf(id ?? ""); | |
| 14 | const base = (process.env["FORGE_URL"] ?? "").replace(/\/$/, ""); | |
| 15 | const token = process.env["FORGE_TOKEN"] ?? ""; | |
| 16 | if (domain === undefined || domain.drill === null || base === "" || token === "") { | |
| 17 | console.error( | |
| 18 | `usage: FORGE_URL=… FORGE_TOKEN=… bun scripts/drills/run.ts <${DRILLED.map((d) => d.id).join("|")}>`, | |
| 19 | ); | |
| 20 | process.exit(2); | |
| 21 | } | |
| 22 | ||
| 23 | const words = (text: string): string => | |
| 24 | text.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim(); | |
| 25 | ||
| 26 | async function sample(): Promise<{ down: boolean; health: string; board: string }> { | |
| 27 | const get = async (path: string): Promise<{ status: number; text: string }> => { | |
| 28 | try { | |
| 29 | const r = await fetch(base + path, { | |
| 30 | headers: { authorization: `Bearer ${token}` }, | |
| 31 | signal: AbortSignal.timeout(5000), | |
| 32 | }); | |
| 33 | return { status: r.status, text: await r.text() }; | |
| 34 | } catch (error) { | |
| 35 | return { status: 0, text: `unreachable: ${String(error)}` }; | |
| 36 | } | |
| 37 | }; | |
| 38 | const [h, b] = await Promise.all([get("/api/v1/health"), get("/")]); | |
| 39 | return { | |
| 40 | down: isDown(domain!.id, h.status, h.text), | |
| 41 | health: hear(h.status, h.text), board: `${b.status} ${words(b.text)}`, | |
| 42 | }; | |
| 43 | } | |
| 44 | ||
| 45 | console.log(`Drill: ${domain.drill}\nCause it, then press Enter.`); | |
| 46 | for await (const _ of console) break; | |
| 47 | const started = Date.now(); | |
| 48 | const heard = { health: new Set<string>(), board: new Set<string>() }; | |
| 49 | let wentDown = false; | |
outdated
|
||
| 50 | for (;;) { | |
| 51 | const s = await sample(); | |
| 52 | if (s.down && !wentDown) { | |
| 53 | wentDown = true; | |
| 54 | } | |
| 55 | if (s.down) { | |
| 56 | heard.health.add(s.health.slice(0, 600)); | |
| 57 | heard.board.add(s.board.slice(0, 600)); | |
| 58 | } | |
| 59 | if (wentDown && !s.down) break; | |
| 60 | await Bun.sleep(1000); | |
| 61 | if (Date.now() - started > 3_600_000) break; | |
| 62 | } | |
| 63 | if (!wentDown) { | |
| 64 | console.error( | |
| 65 | "The fault was not seen: the forge never went down in an hour. Nothing was posted." + | |
| 66 | (domain.id === "runner" ? " The runner drill needs a check queued: push something while the runner is stopped." : ""), | |
| 67 | ); | |
| 68 | process.exit(1); | |
| 69 | } | |
| 70 | // From Enter, not from the first sight of the fault: the delay in noticing it is not free. | |
| 71 | const backMs = Date.now() - started; | |
| 72 | const cap = (set: Set<string>): string => [...set].join("\n").slice(0, SAID_MAX); | |
| 73 | const r = await fetch(`${base}/api/v1/drills`, { | |
| 74 | method: "POST", | |
| 75 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, | |
| 76 | body: JSON.stringify({ | |
| 77 | domain: domain.id, | |
| 78 | backMs, | |
| 79 | health: cap(heard.health), | |
| 80 | board: cap(heard.board), | |
| 81 | }), | |
| 82 | }); | |
| 83 | console.log(r.status, await r.text()); | |
| 84 | process.exit(r.ok ? 0 : 1); |
scripts/gate.ts +1
| @@ -157,6 +157,7 @@ export const GATE: readonly string[] = [ | ||
| 157 | 157 | "test/snapshot-drill.test.ts", |
| 158 | 158 | "test/drill-verdict.test.ts", |
| 159 | 159 | "test/snapshot-drill-page.test.ts", |
| 160 | "test/domains.test.ts", | |
| 160 | 161 | "test/snapshot-store.test.ts", |
| 161 | 162 | "test/migrate.test.ts", |
| 162 | 163 | "test/schema-additive.test.ts", |
src/core/schema.ts +14
| @@ -1787,6 +1787,20 @@ export const migrations: readonly string[] = [ | ||
| 1787 | 1787 | PRIMARY KEY (step, at, target) |
| 1788 | 1788 | ) WITHOUT ROWID; |
| 1789 | 1789 | `, |
| 1790 | // 89 — domain drills (#1195): what the forge said during a fault, judged | |
| 1791 | // against docs/DOMAINS.md. | |
| 1792 | ` | |
| 1793 | CREATE TABLE domain_drill ( | |
| 1794 | id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| 1795 | domain TEXT NOT NULL, | |
| 1796 | at TEXT NOT NULL, | |
| 1797 | back_ms INTEGER NOT NULL, | |
| 1798 | health TEXT NOT NULL, | |
| 1799 | board TEXT NOT NULL, | |
| 1800 | verdict TEXT NOT NULL CHECK (verdict IN ('green', 'red')), | |
| 1801 | reason TEXT | |
| 1802 | ); | |
| 1803 | `, | |
| 1790 | 1804 | ]; |
| 1791 | 1805 | |
| 1792 | 1806 | /** |
src/http/api.ts +21
| @@ -46,6 +46,7 @@ import { resendVerification } from "../actions/verify.ts"; | ||
| 46 | 46 | import { CAPPED_WORDS } from "../actions/mail.ts"; |
| 47 | 47 | import { emailVerified } from "../core/verify.ts"; |
| 48 | 48 | import { readHealth } from "../actions/health.ts"; |
| 49 | import { drillMap, recordDomainDrill } from "../kernel/drills.ts"; | |
| 49 | 50 | import { listChildren } from "../actions/spawn.ts"; |
| 50 | 51 | import { forgeState, PARENT_HEADER } from "../spawn/clients.ts"; |
| 51 | 52 | import { reissueDoor, spawnDoor } from "../spawn/door.ts"; |
| @@ -4096,6 +4097,26 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 4096 | 4097 | json(readHealth(ctx.app, ctx.auth.user)), |
| 4097 | 4098 | ); |
| 4098 | 4099 | |
| 4100 | // The map with each domain's last drill and verdict, and the overdue | |
| 4101 | // list: what Settings → Resilience shows, for an admin. | |
| 4102 | router.add("GET", "/api/v1/drills", (ctx) => { | |
| 4103 | if (!ctx.auth.user?.isAdmin) return forbidden(); | |
| 4104 | return json(drillMap(ctx.app.db)); | |
| 4105 | }); | |
| 4106 | ||
| 4107 | // A domain drill's result, from the operator's standby script | |
| 4108 | // (docs/DOMAINS.md): an admin's, kept, and judged against the map. | |
| 4109 | router.add("POST", "/api/v1/drills", async (ctx) => { | |
| 4110 | const input = await body(ctx.request); | |
| 4111 | const denied = requireScope(ctx, "admin"); | |
| 4112 | if (denied) return denied; | |
| 4113 | if (!ctx.auth.user?.isAdmin) return forbidden(); | |
| 4114 | const kept = recordDomainDrill(ctx.app.db, input); | |
| 4115 | return typeof kept === "string" | |
| 4116 | ? apiError("invalid", 422, kept) | |
| 4117 | : json(kept, 201); | |
| 4118 | }); | |
| 4119 | ||
| 4099 | 4120 | // Explore (#607): the rows /explore shows, for the same one line. |
| 4100 | 4121 | router.add("GET", "/api/v1/explore", async (ctx) => { |
| 4101 | 4122 | const query = parseExploreQuery(ctx.url.searchParams.get("q") ?? ""); |
src/http/mcp.ts +13
| @@ -141,6 +141,7 @@ import { | ||
| 141 | 141 | } from "../actions/explore.ts"; |
| 142 | 142 | import { frontInput, frontJson, setFront } from "../actions/front.ts"; |
| 143 | 143 | import { readHealth } from "../actions/health.ts"; |
| 144 | import { drillMap } from "../kernel/drills.ts"; | |
| 144 | 145 | import { running } from "../kernel/version.ts"; |
| 145 | 146 | import { parentForgeFor } from "../core/parent_releases.ts"; |
| 146 | 147 | import { COPIES_PER_DAY, makeItYours } from "../actions/make_it_yours.ts"; |
| @@ -791,6 +792,18 @@ const TOOLS: readonly Tool[] = [ | ||
| 791 | 792 | writes: false, |
| 792 | 793 | run: (ctx, user) => good(readHealth(ctx.app, user)), |
| 793 | 794 | }, |
| 795 | { | |
| 796 | name: "drills", | |
| 797 | description: | |
| 798 | "The forge's failure domains (docs/DOMAINS.md) with each one's last drill and its verdict (green or red, and why), and the drilled domains with no drill in eight days. An admin's.", | |
| 799 | inputSchema: { type: "object", properties: {} }, | |
| 800 | writes: false, | |
| 801 | run(ctx, user) { | |
| 802 | if (!user.isAdmin) | |
| 803 | return bad("forbidden", "only an admin of this forge sees its drills"); | |
| 804 | return good(drillMap(ctx.app.db)); | |
| 805 | }, | |
| 806 | }, | |
| 794 | 807 | { |
| 795 | 808 | name: "audit", |
| 796 | 809 | description: |
src/http/server.ts +2
| @@ -116,6 +116,7 @@ import { | ||
| 116 | 116 | backupsPage, |
| 117 | 117 | backupsTest, |
| 118 | 118 | } from "../web/pages/backups.ts"; |
| 119 | import { resiliencePage } from "../web/pages/resilience.ts"; | |
| 119 | 120 | import { |
| 120 | 121 | cloudAdd, |
| 121 | 122 | cloudAudit, |
| @@ -716,6 +717,7 @@ export function buildRouter(): Router<Handler> { | ||
| 716 | 717 | router.add("GET", "/admin/limits", limitsPage); |
| 717 | 718 | router.add("POST", "/admin/limits", limitsSet); |
| 718 | 719 | router.add("GET", "/settings/backups", backupsPage); |
| 720 | router.add("GET", "/settings/resilience", resiliencePage); | |
| 719 | 721 | router.add("POST", "/settings/backups/now", backupsNow); |
| 720 | 722 | router.add("POST", "/settings/backups/drill", backupsDrill); |
| 721 | 723 | router.add("POST", "/settings/backups/destination", backupsDestination); |
src/kernel/domains.ts added +97
| @@ -0,0 +1,97 @@ | ||
| 1 | /** | |
| 2 | * The forge's failure domains (docs/DOMAINS.md is the same map in prose; a | |
| 3 | * test keeps them in step). For each: what breaks, how the forge says so | |
| 4 | * (`says`: any one of these phrases, case-insensitive, must be in what the | |
| 5 | * forge said during a drill), how long until it is back, what the owner | |
| 6 | * does, and its drill — or why it has none. Plain data. | |
| 7 | */ | |
| 8 | ||
| 9 | export interface Domain { | |
| 10 | readonly id: string; | |
| 11 | readonly name: string; | |
| 12 | readonly breaks: string; | |
| 13 | readonly says: readonly string[]; | |
| 14 | readonly backMinutes: number; | |
| 15 | readonly owner: string; | |
| 16 | /** The drill's fault, for the operator; null when it cannot be drilled without harm. */ | |
| 17 | readonly drill: string | null; | |
| 18 | /** Why there is no drill. */ | |
| 19 | readonly undrilled?: string; | |
| 20 | } | |
| 21 | ||
| 22 | export const DOMAINS: readonly Domain[] = [ | |
| 23 | { | |
| 24 | id: "compute", | |
| 25 | name: "Compute (the pod)", | |
| 26 | breaks: "Every page and the API until the pod is replaced.", | |
| 27 | says: ["unreachable", "502", "503", "504"], | |
outdated
"the forge is restarting" appears only in the service worker's offline page ( |
||
| 28 | backMinutes: 5, | |
| 29 | owner: "Wait for the pod to be rescheduled; if it is not back, restart the deployment.", | |
| 30 | drill: "Delete the forge's pod.", | |
| 31 | }, | |
| 32 | { | |
| 33 | id: "state", | |
| 34 | name: "State (the volume)", | |
| 35 | breaks: "The database, repositories and keys; the forge cannot start.", | |
| 36 | says: ["disk"], | |
| 37 | backMinutes: 60, | |
| 38 | owner: "Restore the newest snapshot onto a new volume (docs/RESTORE.md).", | |
| 39 | drill: null, | |
| 40 | undrilled: "Losing the volume loses data; the restore drill on the Backups page proves the way back.", | |
| 41 | }, | |
| 42 | { | |
| 43 | id: "snapshots", | |
| 44 | name: "Snapshot store", | |
| 45 | breaks: "Nothing now; the next restore has nothing to start from.", | |
| 46 | says: ["snapshot"], | |
| 47 | backMinutes: 60, | |
| 48 | owner: "Fix the destination under Settings → Backups and take a snapshot.", | |
| 49 | drill: null, | |
| 50 | undrilled: "The restore drill reads the store every time it runs.", | |
| 51 | }, | |
| 52 | { | |
| 53 | id: "edge", | |
| 54 | name: "Edge (tunnel and DNS)", | |
| 55 | breaks: "The forge is unreachable from outside; inside, it is fine.", | |
| 56 | says: ["unreachable", "530", "1033", "502"], | |
| 57 | backMinutes: 10, | |
| 58 | owner: "Restart the tunnel; check DNS if the tunnel is up.", | |
| 59 | drill: "Stop the tunnel.", | |
| 60 | }, | |
| 61 | { | |
| 62 | id: "identity", | |
| 63 | name: "Identity (OAuth origin, passkeys)", | |
| 64 | breaks: "Sign-in through the origin; passkeys still work.", | |
| 65 | says: ["origin"], | |
| 66 | backMinutes: 30, | |
| 67 | owner: "Sign in with a passkey; re-authorize the origin.", | |
| 68 | drill: null, | |
| 69 | undrilled: "Revoking the owner's sign-in is the harm.", | |
| 70 | }, | |
| 71 | { | |
| 72 | id: "credential", | |
| 73 | name: "Model credential", | |
| 74 | breaks: "The crew cannot start runs; the board and the repositories are fine.", | |
| 75 | says: [], | |
| 76 | backMinutes: 15, | |
| 77 | owner: "Seal a fresh credential under Settings → Subscriptions.", | |
| 78 | drill: null, | |
| 79 | undrilled: "Health says nothing of a dead credential yet, so a drill could only be red.", | |
| 80 | }, | |
| 81 | { | |
| 82 | id: "runner", | |
| 83 | name: "Runner", | |
| 84 | breaks: "Checks queue and the gate slows; a fix can still be released.", | |
| 85 | says: ["behind one lane"], | |
| 86 | backMinutes: 30, | |
| 87 | owner: "Bring the runner back; checks resume by themselves.", | |
| 88 | drill: "Stop the runner, then push something so a check is queued: the queue shows only once one has waited.", | |
outdated
High: with only "Stop the runner.", the drill never sees the forge go down unless a check is queued and waits more than 10 min ( |
||
| 89 | }, | |
| 90 | ]; | |
| 91 | ||
| 92 | /** The domains with a drill. */ | |
| 93 | export const DRILLED: readonly Domain[] = DOMAINS.filter((d) => d.drill !== null); | |
| 94 | ||
| 95 | export function domainOf(id: string): Domain | undefined { | |
| 96 | return DOMAINS.find((d) => d.id === id); | |
| 97 | } |
src/kernel/drills.ts added +159
| @@ -0,0 +1,159 @@ | ||
| 1 | /** | |
| 2 | * Domain drills, kept: what the forge said during a fault and how long until | |
| 3 | * it was back, judged against the domain's map (`domains.ts`). Plain data in, | |
| 4 | * plain data out; the operator's standby script is the only writer. | |
| 5 | */ | |
| 6 | ||
| 7 | import type { Database } from "bun:sqlite"; | |
| 8 | import { DOMAINS, DRILLED, domainOf } from "./domains.ts"; | |
| 9 | ||
| 10 | /** A drilled domain with no drill in this long is a need. */ | |
| 11 | export const DRILL_STALE_MS = 8 * 24 * 3_600_000; | |
| 12 | /** The most words a drill keeps of what the forge said; the script caps with the same number. */ | |
| 13 | export const SAID_MAX = 4000; | |
| 14 | ||
| 15 | export interface DomainDrill { | |
| 16 | readonly domain: string; | |
| 17 | readonly at: string; | |
| 18 | readonly backMs: number; | |
| 19 | readonly health: string; | |
| 20 | readonly board: string; | |
| 21 | readonly verdict: "green" | "red"; | |
| 22 | readonly reason: string | null; | |
| 23 | } | |
| 24 | ||
| 25 | /** The verdict: the words must hold one of the domain's phrases, and it must be back in time. */ | |
| 26 | export function judge( | |
| 27 | domain: string, | |
| 28 | said: { health: string; board: string }, | |
| 29 | backMs: number, | |
| 30 | ): { verdict: "green" | "red"; reason: string | null } { | |
| 31 | const d = domainOf(domain); | |
| 32 | if (d === undefined) return { verdict: "red", reason: "unknown domain" }; | |
| 33 | // The runner is only "down" while health carries a queue cause, so health | |
| 34 | // proves nothing there: its phrase must be on the board. | |
| 35 | const words = (domain === "runner" ? said.board : `${said.health}\n${said.board}`).toLowerCase(); | |
| 36 | // A status code counts only as a status line (`heard()` starts with it); | |
| 37 | // a number elsewhere in a body says nothing. | |
| 38 | const said1 = (p: string): boolean => | |
| 39 | /^\d+$/.test(p) ? new RegExp(`(^|\\n)${p}( |$)`).test(words) : words.includes(p.toLowerCase()); | |
| 40 | if (!d.says.some(said1)) | |
| 41 | return { | |
| 42 | verdict: "red", | |
| 43 | reason: `the forge did not say ${d.says.map((p) => `"${p}"`).join(" or ")}`, | |
| 44 | }; | |
| 45 | if (backMs > d.backMinutes * 60_000) | |
| 46 | return { | |
| 47 | verdict: "red", | |
| 48 | reason: `back after ${Math.round(backMs / 60_000)} min; the map says ${d.backMinutes}`, | |
| 49 | }; | |
| 50 | return { verdict: "green", reason: null }; | |
| 51 | } | |
| 52 | ||
| 53 | /** Validate an operator's report at the boundary; an error sentence or the record kept. */ | |
| 54 | export function recordDomainDrill( | |
| 55 | db: Database, | |
| 56 | input: Record<string, unknown>, | |
| 57 | now: Date = new Date(), | |
| 58 | ): DomainDrill | string { | |
| 59 | const domain = typeof input["domain"] === "string" ? input["domain"] : ""; | |
| 60 | if (!DRILLED.some((d) => d.id === domain)) | |
| 61 | return `domain must be one of: ${DRILLED.map((d) => d.id).join(", ")}`; | |
| 62 | const backMs = input["backMs"]; | |
| 63 | if (typeof backMs !== "number" || !Number.isInteger(backMs) || backMs < 0 || backMs > 86_400_000) | |
| 64 | return "backMs must be a whole number of milliseconds, at most a day"; | |
| 65 | const said = (k: string): string | undefined => { | |
| 66 | const v = input[k]; | |
| 67 | return typeof v === "string" && v.length <= SAID_MAX ? v : undefined; | |
| 68 | }; | |
| 69 | const health = said("health"); | |
| 70 | const board = said("board"); | |
| 71 | if (health === undefined || board === undefined) | |
| 72 | return `health and board must be text of at most ${SAID_MAX} characters`; | |
| 73 | const { verdict, reason } = judge(domain, { health, board }, backMs); | |
| 74 | const drill: DomainDrill = { | |
| 75 | domain, | |
| 76 | at: now.toISOString(), | |
| 77 | backMs, | |
| 78 | health, | |
| 79 | board, | |
| 80 | verdict, | |
| 81 | reason, | |
| 82 | }; | |
| 83 | db.query( | |
| 84 | `INSERT INTO domain_drill (domain, at, back_ms, health, board, verdict, reason) | |
| 85 | VALUES (?, ?, ?, ?, ?, ?, ?)`, | |
| 86 | ).run(domain, drill.at, backMs, health, board, verdict, reason); | |
| 87 | return drill; | |
| 88 | } | |
| 89 | ||
| 90 | /** The newest drill of each domain that has one. */ | |
| 91 | export function lastDrills(db: Database): Map<string, DomainDrill> { | |
| 92 | const rows = db | |
| 93 | .query< | |
| 94 | { domain: string; at: string; back_ms: number; health: string; board: string; verdict: "green" | "red"; reason: string | null }, | |
| 95 | [] | |
| 96 | >( | |
| 97 | `SELECT * FROM domain_drill WHERE id IN (SELECT MAX(id) FROM domain_drill GROUP BY domain)`, | |
| 98 | ) | |
| 99 | .all(); | |
| 100 | return new Map( | |
| 101 | rows.map((r) => [ | |
| 102 | r.domain, | |
| 103 | { domain: r.domain, at: r.at, backMs: r.back_ms, health: r.health, board: r.board, verdict: r.verdict, reason: r.reason }, | |
| 104 | ]), | |
| 105 | ); | |
| 106 | } | |
| 107 | ||
| 108 | /** Drilled domains with no drill in eight days; none at all for a forge younger than that. */ | |
| 109 | export function undrilled(db: Database, now: number): { id: string; name: string; at: string }[] { | |
| 110 | const born = db | |
| 111 | .query<{ at: string | null }, []>("SELECT MIN(created_at) AS at FROM user") | |
| 112 | .get()?.at; | |
| 113 | if (born === null || born === undefined) return []; | |
| 114 | const bornMs = Date.parse(born); | |
| 115 | if (!(now - bornMs > DRILL_STALE_MS)) return []; | |
| 116 | const last = lastDrills(db); | |
| 117 | return DRILLED.flatMap((d) => { | |
| 118 | const at = last.get(d.id)?.at; | |
| 119 | return at !== undefined && now - Date.parse(at) <= DRILL_STALE_MS | |
| 120 | ? [] | |
| 121 | : [{ id: d.id, name: d.name, at: at ?? born }]; | |
| 122 | }); | |
| 123 | } | |
| 124 | ||
| 125 | /** | |
| 126 | * What one poll heard, as the words a drill keeps: the status and body of | |
| 127 | * the health, or `unreachable:` when nothing answered. The script and the | |
| 128 | * map's phrases share this one form. | |
| 129 | */ | |
| 130 | export function heard(status: number, text: string): string { | |
| 131 | return `${status} ${text}`; | |
| 132 | } | |
| 133 | ||
| 134 | /** | |
| 135 | * Is the forge down for this drill? From reachability and the rollout, never | |
| 136 | * from `ok`: the vitals' needs are the forge's other business. The runner | |
| 137 | * drill is the exception that proves it: nothing is unreachable, so it is | |
| 138 | * down while the health carries a `queue:` cause. | |
| 139 | */ | |
| 140 | export function isDown(domain: string, status: number, text: string): boolean { | |
| 141 | let h: { draining?: unknown; rollout?: { state?: unknown }; degraded?: { cause?: unknown }[] } = {}; | |
| 142 | try { | |
outdated
Nit: the domain's phrase is
outdated
Runner "down" is defined as health carrying |
||
| 143 | h = JSON.parse(text) as typeof h; | |
| 144 | } catch { | |
| 145 | return domain !== "runner"; | |
| 146 | } | |
| 147 | if (domain === "runner") | |
| 148 | return (h.degraded ?? []).some((d) => typeof d.cause === "string" && d.cause.startsWith("queue:")); | |
| 149 | return status !== 200 || h.draining === true || (h.rollout?.state !== undefined && h.rollout.state !== "ok"); | |
| 150 | } | |
| 151 | ||
| 152 | /** The whole map with each domain's last drill, and the domains overdue: one answer for the page's content, the API and MCP. */ | |
| 153 | export function drillMap(db: Database, now: number = Date.now()) { | |
| 154 | const last = lastDrills(db); | |
| 155 | return { | |
| 156 | domains: DOMAINS.map((d) => ({ ...d, last: last.get(d.id) ?? null })), | |
| 157 | undrilled: undrilled(db, now), | |
| 158 | }; | |
| 159 | } |
src/tui/forge.ts +9
| @@ -31,6 +31,7 @@ import { issueScreen } from "./screens/issue.ts"; | ||
| 31 | 31 | import { pullScreen } from "./screens/pull.ts"; |
| 32 | 32 | import { blobScreen } from "./screens/repo.ts"; |
| 33 | 33 | import { dashboardScreen } from "./screens/dashboard.ts"; |
| 34 | import { drillLines, drillsScreen } from "./screens/drills.ts"; | |
| 34 | 35 | import { flowLines, flowScreen } from "./screens/flow.ts"; |
| 35 | 36 | import { issuesScreen, newIssueScreen } from "./screens/issues.ts"; |
| 36 | 37 | import { limbsScreen } from "./screens/limbs.ts"; |
| @@ -192,6 +193,14 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] { | ||
| 192 | 193 | hint: "the pipeline's bottleneck and throughput", |
| 193 | 194 | run: () => ctx.push(flowScreen(ctx, flowLines(session.db))), |
| 194 | 195 | }); |
| 196 | // Resilience, as Settings → Resilience says it: a site admin's (#1195). | |
| 197 | if (session.user?.isAdmin === true) | |
| 198 | commands.push({ | |
| 199 | id: "drills", | |
| 200 | title: "Drills", | |
| 201 | hint: "each failure domain's last drill", | |
| 202 | run: () => ctx.push(drillsScreen(ctx, drillLines(session.db))), | |
| 203 | }); | |
| 195 | 204 | commands.push({ |
| 196 | 205 | id: "quit", |
| 197 | 206 | title: "Quit", |
src/tui/screens/drills.ts added +65
| @@ -0,0 +1,65 @@ | ||
| 1 | /** | |
| 2 | * The Drills command's dialog, a forge admin's (#1195): each failure domain | |
| 3 | * of docs/DOMAINS.md with its last drill's verdict, then the overdue line — | |
| 4 | * the `drillMap()` the Resilience page, the API and the MCP tool read. | |
| 5 | * Read-only; Enter, Esc or q closes it. | |
| 6 | */ | |
| 7 | ||
| 8 | import type { Database } from "bun:sqlite"; | |
| 9 | import { drillMap } from "../../kernel/drills.ts"; | |
| 10 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 11 | import { binding } from "../app/keys.ts"; | |
| 12 | import { wrap } from "../term/width.ts"; | |
| 13 | import { dialog } from "../ui/widgets.ts"; | |
| 14 | ||
| 15 | const WIDTH = 72; | |
| 16 | ||
| 17 | /** What the dialog says, line by line, wrapped to fit inside it. */ | |
| 18 | export function drillLines(db: Database, now = Date.now()): string[] { | |
| 19 | const map = drillMap(db, now); | |
| 20 | const inner = WIDTH - 6; | |
| 21 | const rows = map.domains.map((d) => { | |
| 22 | const last = d.last; | |
| 23 | const said = | |
| 24 | d.drill === null | |
| 25 | ? "no drill" | |
| 26 | : last === null | |
| 27 | ? "never drilled" | |
| 28 | : last.verdict === "green" | |
| 29 | ? `green ${last.at.slice(0, 16).replace("T", " ")}, back in ${Math.round(last.backMs / 1000)} s` | |
| 30 | : `red ${last.at.slice(0, 16).replace("T", " ")}: ${last.reason ?? ""}`; | |
| 31 | return wrap(`${d.name}: ${said}`, inner); | |
| 32 | }); | |
| 33 | const overdue = map.undrilled.map((d) => d.name); | |
| 34 | return [ | |
| 35 | ...rows.flat(), | |
| 36 | "", | |
| 37 | ...wrap( | |
| 38 | overdue.length === 0 | |
| 39 | ? "No drill is overdue." | |
| 40 | : `Overdue (none in eight days): ${overdue.join(", ")}.`, | |
| 41 | inner, | |
| 42 | ), | |
| 43 | ]; | |
| 44 | } | |
| 45 | ||
| 46 | export function drillsScreen(ctx: Ctx, lines: readonly string[]): Screen { | |
| 47 | return { | |
| 48 | title: "Drills", | |
| 49 | keys: [binding(["enter", "esc", "q"], "close")], | |
| 50 | render(area, s) { | |
| 51 | const buttons = dialog(s, area, ctx.theme.c, { | |
| 52 | title: "Drills", | |
| 53 | body: lines, | |
| 54 | actions: [{ label: "Close" }], | |
| 55 | selected: 0, | |
| 56 | width: WIDTH, | |
| 57 | }); | |
| 58 | buttons.forEach((rect) => ctx.hit(rect, () => ctx.pop())); | |
| 59 | }, | |
| 60 | key(e) { | |
| 61 | if (e.key === "enter" || e.key === "esc" || e.key === "q") ctx.pop(); | |
| 62 | return true; | |
| 63 | }, | |
| 64 | }; | |
| 65 | } |
src/web/pages/origins.ts +7
| @@ -79,6 +79,7 @@ export type AccountSection = | ||
| 79 | 79 | | "accounts" |
| 80 | 80 | | "subscriptions" |
| 81 | 81 | | "backups" |
| 82 | | "resilience" | |
| 82 | 83 | | "secrets" |
| 83 | 84 | | "capacity" |
| 84 | 85 | | "access" |
| @@ -152,6 +153,12 @@ export function accountSections( | ||
| 152 | 153 | icon: "download" as const, |
| 153 | 154 | current: current === "backups", |
| 154 | 155 | }, |
| 156 | { | |
| 157 | label: "Resilience", | |
| 158 | href: "/settings/resilience", | |
| 159 | icon: "activity" as const, | |
| 160 | current: current === "resilience", | |
| 161 | }, | |
| 155 | 162 | ] |
| 156 | 163 | : []), |
| 157 | 164 | { |
src/web/pages/resilience.ts added +69
| @@ -0,0 +1,69 @@ | ||
| 1 | /** | |
| 2 | * Resilience, for an admin: each failure domain of docs/DOMAINS.md with its | |
| 3 | * last drill and the verdict, red when what the forge said did not match | |
| 4 | * the map. The drills are the operator's standby scripts; this page only | |
| 5 | * reads what they recorded. | |
| 6 | */ | |
| 7 | ||
| 8 | import { drillMap } from "../../kernel/drills.ts"; | |
| 9 | import type { Ctx } from "../../http/context.ts"; | |
| 10 | import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts"; | |
| 11 | import { html } from "../html.ts"; | |
| 12 | import { page } from "../layout.ts"; | |
| 13 | import { card, icon, time } from "../ui.ts"; | |
| 14 | import { accountSections } from "./origins.ts"; | |
| 15 | ||
| 16 | export function resiliencePage(ctx: Ctx): Response { | |
| 17 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 18 | if (!ctx.auth.user.isAdmin) return notFoundPage(ctx); | |
| 19 | const map = drillMap(ctx.app.db); | |
| 20 | const overdue = map.undrilled.map((d) => d.name); | |
| 21 | const rows = map.domains.map((d) => { | |
| 22 | const drill = d.last ?? undefined; | |
| 23 | const status = | |
| 24 | d.drill === null | |
| 25 | ? html`<span class="muted">No drill: ${d.undrilled ?? ""}</span>` | |
| 26 | : drill === undefined | |
| 27 | ? html`<span class="backups-error">${icon("alert")} Never drilled.</span>` | |
| 28 | : drill.verdict === "green" | |
| 29 | ? html`${icon("check")} Green ${time(drill.at)}, back in | |
| 30 | ${Math.round(drill.backMs / 1000)} s.` | |
| 31 | : html`<span class="backups-error" | |
| 32 | >${icon("alert")} Red ${time(drill.at)}: ${drill.reason ?? ""}</span | |
| 33 | >`; | |
| 34 | return html`<li> | |
| 35 | <div class="row"> | |
| 36 | <span class="row-main"> | |
| 37 | <span class="row-title">${d.name}</span> | |
| 38 | <span class="row-meta">${d.breaks} The forge says | |
| 39 | ${d.says.length === 0 ? "nothing yet" : d.says.map((p) => `“${p}”`).join(" or ")}; back in | |
| 40 | ${d.backMinutes} min. ${d.owner}</span> | |
| 41 | <span class="row-meta">${status}</span> | |
| 42 | ${d.drill === null | |
| 43 | ? "" | |
| 44 | : html`<span class="row-meta muted">Drill: ${d.drill} Run | |
| 45 | <code>bun scripts/drills/run.ts ${d.id}</code></span>`} | |
| 46 | </span> | |
| 47 | </div> | |
| 48 | </li>`; | |
| 49 | }); | |
| 50 | return page({ | |
| 51 | ctx, | |
| 52 | title: "Resilience", | |
| 53 | body: html`<div class="page-head"><h1>Resilience</h1></div> | |
| 54 | ${settingsLayout( | |
| 55 | accountSections("resilience", { admin: true }), | |
| 56 | card(html`<ul class="list">${rows}</ul>`, { | |
| 57 | pad: false, | |
| 58 | head: html`${icon("activity")} | |
| 59 | <h2>Failure domains</h2>`, | |
| 60 | foot: html`<span class="muted small" | |
| 61 | >The map is docs/DOMAINS.md.${overdue.length === 0 | |
| 62 | ? "" | |
| 63 | : ` No drill in eight days: ${overdue.join(", ")}.`}</span | |
| 64 | >`, | |
| 65 | }), | |
| 66 | "Account settings", | |
| 67 | )}`, | |
| 68 | }); | |
| 69 | } |
test/domains.test.ts added +238
| @@ -0,0 +1,238 @@ | ||
| 1 | /** | |
| 2 | * The failure domains: the map in docs/DOMAINS.md and the data in | |
| 3 | * src/kernel/domains.ts agree; a drill's words are judged against the map; | |
| 4 | * Settings → Resilience shows the last drill and its verdict; an undrilled | |
| 5 | * domain on an old forge is a line on that page and never a vitals need; | |
| 6 | * the script judges up and down without `ok`; every phrase is something the | |
| 7 | * forge emits. | |
| 8 | */ | |
| 9 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 10 | import { mkdtempSync, readFileSync, rmSync } from "node:fs"; | |
| 11 | import { tmpdir } from "node:os"; | |
| 12 | import { join } from "node:path"; | |
| 13 | import { createApp, type App } from "../src/app.ts"; | |
| 14 | import { createUser } from "../src/core/users.ts"; | |
| 15 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 16 | import { DOMAINS, DRILLED } from "../src/kernel/domains.ts"; | |
| 17 | import { heard, isDown, judge, undrilled } from "../src/kernel/drills.ts"; | |
| 18 | import { drillLines } from "../src/tui/screens/drills.ts"; | |
| 19 | import { forgeCommands, Session } from "../src/tui/forge.ts"; | |
| 20 | import type { Ctx, Screen } from "../src/tui/app/app.ts"; | |
| 21 | import { recordDomainDrill } from "../src/kernel/drills.ts"; | |
| 22 | import { vitals } from "../src/kernel/vitals.ts"; | |
| 23 | import { quietLogs } from "./helpers/globals.ts"; | |
| 24 | ||
| 25 | quietLogs(); | |
| 26 | ||
| 27 | describe("the map", () => { | |
| 28 | const doc = readFileSync(join(import.meta.dir, "../docs/DOMAINS.md"), "utf8"); | |
| 29 | test("docs/DOMAINS.md names every domain, its phrases and its time", () => { | |
| 30 | for (const d of DOMAINS) { | |
| 31 | expect(doc).toContain(d.name); | |
| 32 | for (const p of d.says) expect(doc).toContain(`"${p}"`); | |
| 33 | expect(doc).toContain(`${d.backMinutes} min`); | |
| 34 | } | |
| 35 | }); | |
| 36 | test("the pod, the tunnel and the runner are drilled", () => { | |
| 37 | expect(DRILLED.map((d) => d.id).sort()).toEqual(["compute", "edge", "runner"]); | |
| 38 | }); | |
| 39 | }); | |
| 40 | ||
| 41 | describe("the verdict", () => { | |
| 42 | test("words that match and a timely return are green", () => { | |
| 43 | expect(judge("compute", { health: "503 Service Unavailable", board: "" }, 60_000).verdict).toBe("green"); | |
| 44 | }); | |
| 45 | test("words that do not match are red, naming the phrase", () => { | |
| 46 | const v = judge("compute", { health: "500 broken", board: "" }, 1000); | |
| 47 | expect(v.verdict).toBe("red"); | |
| 48 | expect(v.reason).toContain("unreachable"); | |
| 49 | }); | |
| 50 | test("the runner is judged on the board's words, not the health's", () => { | |
| 51 | const health = '200 {"degraded":[{"cause":"queue:check"}]}'; | |
| 52 | expect(judge("runner", { health, board: "all quiet" }, 1000).verdict).toBe("red"); | |
| 53 | expect(judge("runner", { health, board: "22 checks wait behind one lane" }, 1000).verdict).toBe("green"); | |
| 54 | }); | |
| 55 | test("a slow return is red", () => { | |
| 56 | const v = judge("compute", { health: "0 unreachable: x", board: "" }, 6 * 60_000); | |
| 57 | expect(v).toEqual({ verdict: "red", reason: "back after 6 min; the map says 5" }); | |
| 58 | }); | |
| 59 | }); | |
| 60 | ||
| 61 | describe("the drills kept", () => { | |
| 62 | let root = ""; | |
| 63 | let app: App; | |
| 64 | let servers: Servers; | |
| 65 | const login = async (username: string, password: string) => { | |
| 66 | const r = await fetch(`${servers.url}/signin`, { | |
| 67 | method: "POST", | |
| 68 | headers: { origin: servers.url }, | |
| 69 | body: new URLSearchParams({ username, password }), | |
| 70 | redirect: "manual", | |
| 71 | }); | |
| 72 | return (r.headers.get("set-cookie") ?? "").split(";")[0]!; | |
| 73 | }; | |
| 74 | const send = (cookie: string, payload: unknown, origin = servers.url) => | |
| 75 | fetch(`${servers.url}/api/v1/drills`, { | |
| 76 | method: "POST", | |
| 77 | headers: { cookie, origin, "content-type": "application/json" }, | |
| 78 | body: JSON.stringify(payload), | |
| 79 | }); | |
| 80 | ||
| 81 | beforeAll(async () => { | |
| 82 | root = mkdtempSync(join(tmpdir(), "forge-domains-")); | |
| 83 | app = createApp({ dataDir: root, port: 0 }); | |
| 84 | for (const [username, password, adminIfFirst] of [ | |
| 85 | ["alice", "a-good-passphrase", true], | |
| 86 | ["bob", "another-good-passphrase", false], | |
| 87 | ] as const) { | |
| 88 | const u = await createUser(app.db, { | |
| 89 | trusted: true, | |
| 90 | username, | |
| 91 | email: `${username}@forge.local`, | |
| 92 | password, | |
| 93 | adminIfFirst, | |
| 94 | }); | |
| 95 | if (!u.ok) throw new Error(u.error); | |
| 96 | } | |
| 97 | servers = await serve(app); | |
| 98 | }); | |
| 99 | afterAll(() => { | |
| 100 | servers.stop(); | |
| 101 | app.close(); | |
| 102 | rmSync(root, { recursive: true, force: true }); | |
| 103 | }); | |
| 104 | ||
| 105 | test("an admin's report is judged, kept, and shown on the page", async () => { | |
| 106 | const alice = await login("alice", "a-good-passphrase"); | |
| 107 | const page = () => | |
| 108 | fetch(`${servers.url}/settings/resilience`, { headers: { cookie: alice } }).then((r) => r.text()); | |
| 109 | expect(await page()).toContain("Never drilled"); | |
| 110 | const ok = await send(alice, { domain: "compute", backMs: 90_000, health: "0 unreachable: TypeError", board: "" }); | |
| 111 | expect(ok.status).toBe(201); | |
| 112 | expect(((await ok.json()) as { verdict: string }).verdict).toBe("green"); | |
| 113 | const red = await send(alice, { domain: "edge", backMs: 1000, health: "200 fine", board: "nothing" }); | |
| 114 | expect(((await red.json()) as { verdict: string }).verdict).toBe("red"); | |
| 115 | const html = await page(); | |
| 116 | expect(html).toContain("Green"); | |
| 117 | expect(html).toContain("Red"); | |
| 118 | expect(html).toContain("the forge did not say"); | |
| 119 | }); | |
| 120 | ||
| 121 | test("an admin reads the map with the green and red verdicts; others are refused", async () => { | |
| 122 | const alice = await login("alice", "a-good-passphrase"); | |
| 123 | const bob = await login("bob", "another-good-passphrase"); | |
| 124 | const read = (cookie?: string) => | |
| 125 | fetch(`${servers.url}/api/v1/drills`, { headers: cookie ? { cookie } : {} }); | |
| 126 | const r = await read(alice); | |
| 127 | expect(r.status).toBe(200); | |
| 128 | const map = (await r.json()) as { | |
| 129 | domains: { id: string; last: { verdict: string; reason: string | null; backMs: number } | null }[]; | |
| 130 | undrilled: unknown[]; | |
| 131 | }; | |
| 132 | expect(map.domains.map((d) => d.id)).toEqual(DOMAINS.map((d) => d.id)); | |
| 133 | const by = (id: string) => map.domains.find((d) => d.id === id)?.last; | |
| 134 | expect(by("compute")?.verdict).toBe("green"); | |
| 135 | expect(by("edge")?.verdict).toBe("red"); | |
| 136 | expect(by("edge")?.reason).toContain("the forge did not say"); | |
| 137 | expect(by("state")).toBeNull(); | |
| 138 | expect(map.undrilled).toEqual([]); | |
| 139 | expect((await read(bob)).status).toBe(403); | |
| 140 | expect((await read()).status).toBeGreaterThanOrEqual(401); | |
| 141 | }); | |
| 142 | ||
| 143 | test("bad input, other domains, strangers and other origins are refused", async () => { | |
| 144 | const alice = await login("alice", "a-good-passphrase"); | |
| 145 | const bob = await login("bob", "another-good-passphrase"); | |
| 146 | const good = { domain: "runner", backMs: 1, health: "queue:check", board: "" }; | |
| 147 | expect((await send(alice, { ...good, domain: "state" })).status).toBe(422); | |
| 148 | expect((await send(alice, { ...good, backMs: -1 })).status).toBe(422); | |
| 149 | expect((await send(alice, { ...good, health: 5 })).status).toBe(422); | |
| 150 | expect((await send(bob, good)).status).toBeGreaterThanOrEqual(400); | |
| 151 | expect((await send(alice, good, "https://evil.example")).status).toBeGreaterThanOrEqual(400); | |
| 152 | const page = await fetch(`${servers.url}/settings/resilience`, { headers: { cookie: bob } }); | |
| 153 | expect(page.status).toBe(404); | |
| 154 | }); | |
| 155 | ||
| 156 | test("no drill in eight days is a line, never a vitals need", async () => { | |
| 157 | const day = 24 * 3_600_000; | |
| 158 | expect(undrilled(app.db, Date.now())).toEqual([]); | |
| 159 | const later = Date.now() + 9 * day; | |
| 160 | expect(undrilled(app.db, later).map((d) => d.id)).toEqual(["compute", "edge", "runner"]); | |
| 161 | // A drill from two days before "later" is fresh. | |
| 162 | app.db.query("UPDATE domain_drill SET at = ? WHERE domain = 'compute'").run(new Date(later - 2 * day).toISOString()); | |
| 163 | expect(undrilled(app.db, later).map((d) => d.id)).toEqual(["edge", "runner"]); | |
| 164 | const v = vitals({ db: app.db, dataDir: root, now: later, signals: app.signals }); | |
| 165 | expect(v.needs.some((n) => n.startsWith("No drill"))).toBe(false); | |
| 166 | expect(v.ok).toBe(true); | |
| 167 | }); | |
| 168 | }); | |
| 169 | ||
| 170 | describe("the script's up and down", () => { | |
| 171 | const drillNeed = { ok: false, needs: ["No drill of Compute (the pod) in eight days."], draining: false, rollout: { state: "ok", reason: "" }, degraded: [] }; | |
| 172 | test("an admin health that is not ok for its own reasons is still up", () => { | |
| 173 | expect(isDown("compute", 200, JSON.stringify(drillNeed))).toBe(false); | |
| 174 | expect(isDown("edge", 200, JSON.stringify(drillNeed))).toBe(false); | |
| 175 | }); | |
| 176 | test("no answer, a gateway error or a draining forge is down", () => { | |
| 177 | expect(isDown("compute", 0, "unreachable: TypeError")).toBe(true); | |
| 178 | expect(isDown("compute", 502, "<html>bad gateway</html>")).toBe(true); | |
| 179 | expect(isDown("compute", 200, JSON.stringify({ ...drillNeed, draining: true }))).toBe(true); | |
| 180 | }); | |
| 181 | test("the runner is down while a queue cause is in health", () => { | |
| 182 | const q = { ...drillNeed, degraded: [{ cause: "queue:check" }] }; | |
| 183 | expect(isDown("runner", 200, JSON.stringify(q))).toBe(true); | |
| 184 | expect(isDown("runner", 200, JSON.stringify(drillNeed))).toBe(false); | |
| 185 | }); | |
| 186 | test("a status number elsewhere in a body is not a status line", () => { | |
| 187 | expect(judge("compute", { health: '200 {"port":502,"x":"503"}', board: "200 ok" }, 1000).verdict).toBe("red"); | |
| 188 | expect(judge("compute", { health: "200 ok\n502 Bad Gateway", board: "" }, 1000).verdict).toBe("green"); | |
| 189 | }); | |
| 190 | test("what an unanswered poll hears holds the compute and edge phrases", () => { | |
| 191 | const w = heard(0, "unreachable: TypeError: fetch failed"); | |
| 192 | expect(judge("compute", { health: w, board: "" }, 1000).verdict).toBe("green"); | |
| 193 | expect(judge("edge", { health: w, board: "" }, 1000).verdict).toBe("green"); | |
| 194 | }); | |
| 195 | }); | |
| 196 | ||
| 197 | describe("the terminal's drills", () => { | |
| 198 | const rootT = mkdtempSync(join(tmpdir(), "forge-domains-tty-")); | |
| 199 | const appT = createApp({ dataDir: rootT, port: 0 }); | |
| 200 | afterAll(() => { | |
| 201 | appT.close(); | |
| 202 | rmSync(rootT, { recursive: true, force: true }); | |
| 203 | }); | |
| 204 | const command = (user?: { username: string }) => { | |
| 205 | const pushed: Screen[] = []; | |
| 206 | const ctx = { push: (s: Screen) => pushed.push(s) } as unknown as Ctx; | |
| 207 | const session = new Session(appT, { | |
| 208 | sshUsername: user?.username ?? "git", | |
| 209 | remoteAddress: "127.0.0.1", | |
| 210 | fingerprint: "SHA256:test", | |
| 211 | user: user as never, | |
| 212 | }); | |
| 213 | return { found: forgeCommands(session)(ctx).find((c) => c.id === "drills"), pushed }; | |
| 214 | }; | |
| 215 | test("an admin reads the map with each last verdict and the overdue line; a guest is offered nothing", async () => { | |
| 216 | const make = async (username: string, adminIfFirst: boolean) => { | |
| 217 | const u = await createUser(appT.db, { trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst }); | |
| 218 | if (!u.ok) throw new Error(u.error); | |
| 219 | return u.value; | |
| 220 | }; | |
| 221 | const admin = await make("alice", true); | |
| 222 | const other = await make("bob", false); | |
| 223 | recordDomainDrill(appT.db, { domain: "compute", backMs: 1000, health: "503 x", board: "" }); | |
| 224 | recordDomainDrill(appT.db, { domain: "edge", backMs: 1000, health: "200 fine", board: "" }); | |
| 225 | const { found, pushed } = command(admin); | |
| 226 | expect(found?.title).toBe("Drills"); | |
| 227 | found!.run(); | |
| 228 | expect(pushed.map((s) => s.title)).toEqual(["Drills"]); | |
| 229 | const text = drillLines(appT.db).join("\n"); | |
| 230 | expect(text).toContain("Compute (the pod): green"); | |
| 231 | expect(text).toContain("Edge (tunnel and DNS): red"); | |
| 232 | expect(text).toContain("Runner: never drilled"); | |
| 233 | expect(text).toContain("No drill is overdue."); | |
| 234 | expect(drillLines(appT.db, Date.now() + 30 * 86_400_000).join("\n")).toContain("Overdue"); | |
| 235 | expect(command(other).found).toBeUndefined(); | |
| 236 | expect(command(undefined).found).toBeUndefined(); | |
| 237 | }); | |
| 238 | }); |
test/mcp.test.ts +9
| @@ -173,6 +173,7 @@ describe("the forge over MCP", () => { | ||
| 173 | 173 | "now", |
| 174 | 174 | "stop", |
| 175 | 175 | "health", |
| 176 | "drills", | |
| 176 | 177 | "audit", |
| 177 | 178 | "outsiders", |
| 178 | 179 | "decisions_by", |
| @@ -589,6 +590,14 @@ describe("the forge over MCP", () => { | ||
| 589 | 590 | }); |
| 590 | 591 | expect(res.status).toBe(401); |
| 591 | 592 | }); |
| 593 | test("drills: an admin reads the map with each last drill, anyone else is refused", async () => { | |
| 594 | const seen = await tool(rw, "drills"); | |
| 595 | expect(seen.value.domains.length).toBeGreaterThan(0); | |
| 596 | expect(seen.value.domains.every((d: { last: unknown }) => "last" in d)).toBe(true); | |
| 597 | expect(Array.isArray(seen.value.undrilled)).toBe(true); | |
| 598 | expect((await tool(bobRw, "drills")).error).toContain("forbidden"); | |
| 599 | }); | |
| 600 | ||
| 592 | 601 | test("limits: admins only, dry by default, an admin-scope token to change", async () => { |
| 593 | 602 | const key = "front.pinned_max"; |
| 594 | 603 | const admin = createToken(app.db, alice.id, "admin", "admin").token; |
test/vitals.test.ts +12
| @@ -6,6 +6,7 @@ import { tmpdir } from "node:os"; | ||
| 6 | 6 | import { join } from "node:path"; |
| 7 | 7 | import { createApp, type App } from "../src/app.ts"; |
| 8 | 8 | import { createRun } from "../src/core/runs.ts"; |
| 9 | import { isDown, judge } from "../src/kernel/drills.ts"; | |
| 9 | 10 | import { vitals } from "../src/kernel/vitals.ts"; |
| 10 | 11 | import { fetchInternal } from "../src/git/hook-address.ts"; |
| 11 | 12 | import { serve, type Servers } from "../src/http/server.ts"; |
| @@ -438,3 +439,14 @@ test("a lane older than its budget is degraded with its cause; a silent run is s | ||
| 438 | 439 | expect(stuck?.sentence).toBe(`Run ${live.id} is stuck: no heartbeat for 4 min (limit 3).`); |
| 439 | 440 | app.db.query("DELETE FROM run").run(); |
| 440 | 441 | }); |
| 442 | ||
| 443 | test("a stalled check queue says what the runner drill listens for", async () => { | |
| 444 | app.db.query("DELETE FROM run WHERE state = 'queued'").run(); | |
| 445 | const now = Date.now(); | |
| 446 | const r = createRun(app.db, { repoId, kind: "check" }); | |
| 447 | app.db.query("UPDATE run SET created_at=?2 WHERE id=?1").run(r.id, new Date(now - 3 * 3_600_000).toISOString()); | |
| 448 | const res = await fetch(servers.url + "/api/v1/health", { headers: { authorization: `Bearer ${admin}` } }); | |
| 449 | const text = await res.text(); | |
| 450 | expect(isDown("runner", res.status, text)).toBe(true); | |
| 451 | expect(judge("runner", { health: text, board: "" }, 60_000).verdict).toBe("green"); | |
| 452 | }); |
With an admin token,
okincludes the vitals, so thedrill:*needs this pull adds keep it false. The forge counts as "down" at the first sample and never comes back, the loop runs the full hour, and then it postsbackMsof about 3.6M, which is red. Judge up and down from reachability and the rollout, not the vitals'ok.