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

When the forge itself is degraded, the board's 'all fine / needs you' line pages the phone #2291

Parked opened this in answer to
Closed without merging

scout/forge:scout/477-when-the-forge-itself-is-degraded-the-bo → main 2 commits fork 3 threads · 3 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
7 files changed +252 −21
README.md +10
@@ -284,6 +284,16 @@ the hour) or else the first time the forge saw it, and holds until the cause
284284 clears; `href` is the page to look at. The board's forge strip links each
285285 entry, and the terminal dashboard prints each with its start.
286286
287 The forge's own state reads the same on the board, in the terminal and in the
288 API's `needs`: each platform incident (`held`, `stuck`, `oom:*`, `down`, `edge`),
289 a drain longer than five minutes, and a platform view older than ten minutes
290 each print as `needs you: forge <what is wrong and the fix>`. A site admin with
291 a notify URL is paged once for a drain or a stale view (what the forge finds
292 itself) and once more, "Forge recovered", when it clears; incidents from
293 `forge-guard` are shown but not paged, because the droplet's watchdog has paged
294 them. A recovered page the hourly cap or a dead endpoint held back is sent on
295 a later tick.
296
287297 ## Origins
288298
289299 Your forge is the index of everything you work on, wherever it actually lives.
src/actions/health.ts +7 −9
@@ -12,7 +12,7 @@ import type { App } from "../app.ts";
1212 import { appsRuntime } from "../apps/runtime.ts";
1313 import { listApps } from "../core/apps.ts";
1414 import type { User } from "../core/users.ts";
15 import { forgeHealth, rolloutLine, type ForgeHealth } from "../kernel/guard.ts";
15 import { forgeCauses, forgeHealth, forgeLine, type ForgeHealth } from "../kernel/guard.ts";
1616 import {
1717 laneLine,
1818 sinceWords,
@@ -61,6 +61,11 @@ export function readHealth(
6161 return { ...v, ...forge, ok: forge.ok && v.ok };
6262 }
6363
64 /** The platform's and the forge's own causes, as lines: what the board, the terminal and the API all print first. */
65 export function causeLines(h: ForgeHealth): string[] {
66 return forgeCauses(h).map(forgeLine);
67 }
68
6469 /**
6570 * The forge's causes for concern as one sentence each, for a site admin: the
6671 * rollout, each platform incident, then the vitals' needs, in the order the
@@ -70,14 +75,7 @@ export function readHealth(
7075 export function forgeNeeds(app: App, actor: User | undefined): string[] | undefined {
7176 if (!actor?.isAdmin) return undefined;
7277 const h = readHealth(app, actor) as Vitals & ForgeHealth;
73 const rollout = rolloutLine(h);
74 return [
75 ...(rollout === null ? [] : [rollout]),
76 ...h.incidents
77 .filter((i) => i.key !== "stuck" && i.key !== "held")
78 .map((i) => `${i.key}: ${i.message}`),
79 ...h.degraded.map(needLine),
80 ];
78 return [...causeLines(h), ...h.degraded.map(needLine)];
8179 }
8280
8381 export { sinceWords };
src/crew/notify.ts +37 −2
@@ -29,6 +29,7 @@ import { isPrivateHost } from "../actions/migrate.ts";
2929 import { getUserSetting, setUserSetting } from "../core/settings.ts";
3030 import { getUserById, type User } from "../core/users.ts";
3131 import { landedLines } from "../core/watches.ts";
32 import { forgeCauses, forgeHealth } from "../kernel/guard.ts";
3233 import { err, ok, type Result } from "../kernel/result.ts";
3334 import { lastMirror, mirrorNeed } from "../snapshot/mirror.ts";
3435 import { drillNeed, firstSeen, lastVerdict } from "../snapshot/verdict.ts";
@@ -181,6 +182,24 @@ export function mirrorLines(
181182 return [{ id, line: need.sentence, items: [id] }];
182183 }
183184
185 /**
186 * The admin hears of what the forge finds wrong with itself, once per cause.
187 * Incidents the droplet's watchdog already paged are shown on the board,
188 * never paged here. The id is the cause's key, so a repeat tick is not news.
189 */
190 export function forgeLines(
191 user: User,
192 now = Date.now(),
193 ): { id: string; line: string; items: readonly string[] }[] {
194 if (!user.isAdmin || user.kind !== "user") return [];
195 return forgeCauses(forgeHealth(undefined, now), undefined, now)
outdated

Low: if this tick's send is capped (HOURLY) or paused, the recovered line is dropped for good, because seen no longer has the forge: id.

196 .filter((n) => n.own)
197 .map((n) => {
198 const id = `forge:${n.key}`;
199 return { id, line: `Forge: ${n.message}`, items: [id] };
200 });
201 }
202
184203 export interface Notifier {
185204 /** Resolves when the work queued so far is done. For tests and shutdown. */
186205 settled(): Promise<void>;
@@ -207,6 +226,7 @@ export function startNotifier(app: App, options: NotifyOptions): Notifier {
207226 /** Per person: the asks last seen, and so already told or deliberately skipped. */
208227 const seen = new Map<string, Set<string>>();
209228 const sent = new Map<string, number[]>();
229 const owed = new Map<string, Set<string>>();
210230 const pause = new Map<string, { until: number; next: number }>();
211231 let queue: Promise<void> = Promise.resolve();
212232 let stopped = false;
@@ -237,15 +257,29 @@ export function startNotifier(app: App, options: NotifyOptions): Notifier {
237257 ...mailCeilingLines(app, user, now()),
238258 ...drillLines(app, user, now()),
239259 ...mirrorLines(app, user, now()),
260 ...forgeLines(user, now()),
240261 ];
241262 const before = seen.get(userId);
263 const nowIds = new Set(asks.flatMap((a) => a.items));
264 // A forge cause that cleared is told once, as recovered; one whose page
265 // was capped or paused stays owed until it goes out.
266 const owing = owed.get(userId) ?? new Set<string>();
267 for (const id of before ?? []) if (id.startsWith("forge:") && !nowIds.has(id)) owing.add(id);
268 for (const id of nowIds) owing.delete(id);
269 owed.set(userId, owing);
242270 // What is gone may ask again later, and then it is new again. Seen by
243271 // the asks a row holds, so a new one under a collapsed row is still news.
244272 seen.set(userId, new Set(asks.flatMap((a) => a.items)));
245273 if (before === undefined && !baseline) baseline = true;
246274 if (baseline) return;
247 for (const ask of asks) {
248 if (ask.items.every((id) => before!.has(id))) continue;
275 const cleared: { line: string; items: readonly string[]; link?: string; owes: string }[] = [...owing].map((id) => ({
276 line: `Forge recovered: ${id.slice(6)} is clear.`,
277 items: [`recovered:${id}`],
278 owes: id,
279 }));
280 const lines: { line: string; items: readonly string[]; link?: string; owes?: string }[] = [...asks, ...cleared];
281 for (const ask of lines) {
282 if (ask.owes === undefined && ask.items.every((id) => before!.has(id))) continue;
249283 const t = now();
250284 const recent = (sent.get(userId) ?? []).filter((s) => t - s < HOUR_MS);
251285 sent.set(userId, recent);
@@ -279,6 +313,7 @@ export function startNotifier(app: App, options: NotifyOptions): Notifier {
279313 return;
280314 }
281315 pause.delete(userId);
316 if (ask.owes !== undefined) owing.delete(ask.owes);
282317 }
283318 }
284319
src/http/health.ts +3 −1
@@ -16,7 +16,8 @@
1616
1717 import type { Log } from "../kernel/log.ts";
1818
19 export const health = { draining: false };
19 /** `since` is when the drain began (ms), for the board and the phone to say it has lasted. */
20 export const health: { draining: boolean; since: number | null } = { draining: false, since: null };
2021
2122 /** Whether the last liveness answer was a 503, so the log says so once. */
2223 let databaseDown = false;
@@ -28,6 +29,7 @@ let databaseDown = false;
2829 export function startDraining(log: Log, why: string, fields: Record<string, number> = {}): void {
2930 if (health.draining) return;
3031 health.draining = true;
32 health.since = Date.now();
3133 log.info("forge draining: /readyz answers 503 from now", { why, ...fields });
3234 }
3335
src/kernel/guard.ts +54
@@ -133,3 +133,57 @@ export function rolloutLine(h: ForgeHealth): string | null {
133133 if (h.rollout.state === "held") return `rollout held: ${h.rollout.reason}`;
134134 return h.stale ? h.rollout.reason : null;
135135 }
136
137 /** A drain longer than this is the forge's own trouble: a release that never finished. */
138 export const DRAIN_PAGE_MS = 5 * 60_000;
139
140 export interface ForgeNeed {
141 /** Stable while the cause lasts, so a page is told once. */
142 readonly key: string;
143 /** What is wrong and the fix, in a sentence or two. */
144 readonly message: string;
145 /** Detected by the forge itself; the rest the droplet's watchdog has already paged. */
146 readonly own: boolean;
147 }
148
149 /**
150 * Every way the forge is degraded, as plain data: each platform incident
151 * (shown, not paged, for the watchdog has paged it), a drain past five
152 * minutes, and a stale platform view (both the forge's own to page).
153 */
154 export function forgeCauses(
outdated

There is already a forgeNeeds in src/actions/health.ts, and the terminal dashboard and resilience.ts read from that one. This new one feeds only the board and the notifier, so the terminal and the API never show the 5-minute drain or the "needs you: forge" line. Rename this one, and make actions/health.forgeNeeds the single list that every door uses, built on top of it.

155 h: ForgeHealth,
156 drainingSince: number | null = health.since,
157 now: number = Date.now(),
158 ): ForgeNeed[] {
159 const needs: ForgeNeed[] = h.incidents.map((i) => ({
160 key: i.key,
161 message:
162 i.key === "stuck"
163 ? `rollout blocked: ${i.message}`
164 : i.key === "held"
165 ? `rollout held: ${i.message}`
166 : i.message,
167 own: false,
168 }));
169 if (h.draining && drainingSince !== null && now - drainingSince > DRAIN_PAGE_MS)
170 needs.push({
171 key: "draining",
172 message:
173 `draining for ${Math.round((now - drainingSince) / 60_000)} minutes: a release did not finish. ` +
174 "Check that the new version is ready, or restart the forge.",
175 own: true,
176 });
177 if (h.stale)
178 needs.push({
179 key: "stale",
180 message: `${h.rollout.reason}. Check that forge-watchdog is running on the droplet.`,
181 own: true,
182 });
183 return needs;
184 }
185
186 /** One cause as the line every door prints: the board, the terminal, the API. */
187 export function forgeLine(need: ForgeNeed): string {
188 return `needs you: forge ${need.message}`;
189 }
src/web/pages/board.ts +5 −9
@@ -19,7 +19,7 @@ import { appsForRepos, type AppRecord } from "../../core/apps.ts";
1919 import { askMeasure } from "../../core/ask_ledger.ts";
2020 import { reviewersOf, waitsForPerson } from "../../crew/review.ts";
2121 import { tokenReturns } from "../../core/returns.ts";
22 import { forgeVitals, needLine } from "../../actions/health.ts";
22 import { causeLines, forgeVitals, needLine } from "../../actions/health.ts";
2323 import { returnsRepos } from "../../actions/returns.ts";
2424 import {
2525 deciderCounts,
@@ -43,7 +43,7 @@ import {
4343 import { readSpend } from "../../actions/spend.ts";
4444 import { spendView } from "./spend.ts";
4545 import type { HandContext } from "../../crew/handover.ts";
46 import { forgeHealth, rolloutLine } from "../../kernel/guard.ts";
46 import { forgeHealth } from "../../kernel/guard.ts";
4747 import { laneLine, type Vitals } from "../../kernel/vitals.ts";
4848 import { getIssue, getIssuesByIds, type Issue } from "../../core/issues.ts";
4949 import { looksForApps } from "../../core/looks.ts";
@@ -328,11 +328,8 @@ function forgeStrip(ctx: Ctx): Html | null {
328328 if (!ctx.auth.user?.isAdmin) return null;
329329 const v = forgeVitals(ctx.app);
330330 const fh = forgeHealth();
331 const rollout = rolloutLine(fh);
332 const others = fh.incidents.filter(
333 (i) => i.key !== "stuck" && i.key !== "held",
334 );
335 const ok = v.ok && fh.ok;
331 const needs = causeLines(fh);
outdated

The board now builds its own list, separate from actions/health.forgeNeeds, whose doc promises the strip's order. Use the shared list here so the page, the terminal and the API stay identical.

332 const ok = v.ok && fh.ok && needs.length === 0;
336333 const lane = laneLine(v.lane);
337334 return html`<div
338335 class="board-forge"
@@ -343,8 +340,7 @@ function forgeStrip(ctx: Ctx): Html | null {
343340 role="status"
344341 >
345342 ${sentinelSpan(ctx.app)}
346 ${rollout === null ? "" : html`<span class="board-forge-need">${rollout}</span>`}
347 ${others.map((i) => html`<span class="board-forge-need">${i.key}: ${i.message}</span>`)}
343 ${needs.map((n) => html`<span class="board-forge-need">${n}</span>`)}
348344 ${lane === null ? "" : html`<span class="board-forge-lane">Lane: ${lane}</span>`}
349345 ${
350346 ok
test/forge-degraded.test.ts added +136
@@ -0,0 +1,136 @@
1 /**
2 * The forge's own trouble: the board's line says "needs you: forge …", the
3 * phone is told once per cause the forge finds itself and once when it
4 * clears, and never for what the droplet's watchdog already paged.
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 { createUser, getUserByName } from "../src/core/users.ts";
12 import { setNotifyUrl, startNotifier, type Notifier, type Sender } from "../src/crew/notify.ts";
13 import { health } from "../src/http/health.ts";
14 import { forgeNeeds } from "../src/actions/health.ts";
15 import { DRAIN_PAGE_MS, forgeHealth, forgeLine, forgeCauses, parseGuard } from "../src/kernel/guard.ts";
16
17 const at = new Date(1_000_000_000_000).toISOString();
18
19 describe("forge needs", () => {
20 const view = (incidents: object, checkedAt = at) =>
21 forgeHealth(parseGuard(JSON.stringify({ incidents }), checkedAt), Date.parse(checkedAt));
22
23 test("a held rollout is shown, with the incident's own words, and is not ours to page", () => {
24 const needs = forgeCauses(view({ held: "5Gi refused by LimitRange 4Gi" }), null);
25 expect(needs).toEqual([
26 { key: "held", message: "rollout held: 5Gi refused by LimitRange 4Gi", own: false },
27 ]);
28 expect(forgeLine(needs[0]!)).toBe("needs you: forge rollout held: 5Gi refused by LimitRange 4Gi");
29 });
30
31 test("an oom incident is shown; a healthy forge says nothing", () => {
32 expect(forgeCauses(view({ "oom:forge": "killed at 3Gi" }), null)[0]!.message).toBe("killed at 3Gi");
33 expect(forgeCauses(view({}), null)).toEqual([]);
34 });
35
36 test("draining past five minutes is ours; before that it is nothing", () => {
37 const h = { ...view({}), draining: true };
38 const t0 = 5_000;
39 expect(forgeCauses(h, t0, t0 + DRAIN_PAGE_MS)).toEqual([]);
40 const late = forgeCauses(h, t0, t0 + 6 * 60_000);
41 expect(late.map((n) => [n.key, n.own])).toEqual([["draining", true]]);
42 });
43
44 test("a stale platform view is ours", () => {
45 const h = forgeHealth(parseGuard("{}", at), Date.parse(at) + 11 * 60_000);
46 expect(forgeCauses(h, null).map((n) => [n.key, n.own])).toEqual([["stale", true]]);
47 });
48 });
49
50 describe("forge pages", () => {
51 let dataDir: string;
52 let app: App;
53 let notifier: Notifier;
54 const posts: string[] = [];
55 let failing = false;
56 let clock = 2_000_000_000_000;
57 const send: Sender = async (_url, body) => {
58 posts.push(body);
59 return !failing;
60 };
61
62 beforeAll(async () => {
63 dataDir = await mkdtemp(join(tmpdir(), "forge-degraded-"));
64 app = createApp({ dataDir, port: 0 });
65 const made = await createUser(app.db, {
66 trusted: true,
67 username: "alice",
68 email: "[email protected]",
69 password: "a-good-passphrase",
70 adminIfFirst: true,
71 });
72 if (!made.ok) throw new Error(made.error);
73 setNotifyUrl(app.db, made.value.id, "https://ntfy.example.test/root-topic");
74 notifier = startNotifier(app, { forgeUrl: "https://forge.example.test", send, now: () => clock });
75 await notifier.settled();
76 });
77 afterAll(async () => {
78 notifier.stop();
79 health.draining = false;
80 health.since = null;
81 await rm(dataDir, { recursive: true, force: true });
82 });
83
84 const tick = async () => {
85 // Any event the notifier wakes on stands for a poll or a viewer.
86 app.bus.append({ kind: "issue.closed" });
87 await notifier.settled();
88 };
89
90 test("a drain past five minutes is in the list the terminal and the API read", async () => {
91 const made = getUserByName(app.db, "alice")!;
92 health.draining = true;
93 health.since = Date.now() - 6 * 60_000;
94 try {
95 expect(forgeNeeds(app, made)!.some((l) => l.startsWith("needs you: forge draining for 6 minutes"))).toBe(true);
96 } finally {
97 health.draining = false;
98 health.since = null;
99 }
100 });
101
102 test("one page when draining passes five minutes, none per poll, one on recovery", async () => {
103 health.draining = true;
104 health.since = clock;
105 clock += 4 * 60_000;
106 await tick();
107 expect(posts).toHaveLength(0);
108 clock += 2 * 60_000;
109 await tick();
110 await tick();
111 await tick();
112 expect(posts).toHaveLength(1);
113 expect(posts[0]).toContain("draining");
114 health.draining = false;
115 await tick();
116 await tick();
117 expect(posts).toHaveLength(2);
118 expect(posts[1]).toContain("recovered");
119 });
120
121 test("a recovered page that was capped is sent on a later tick", async () => {
122 const before = posts.length;
123 health.draining = true;
124 health.since = clock - 6 * 60_000;
125 await tick();
126 expect(posts).toHaveLength(before + 1);
127 health.draining = false;
128 failing = true;
129 await tick();
130 expect(posts).toHaveLength(before + 2);
131 clock += 2 * 60_000; // past the pause
132 failing = false;
133 await tick();
134 expect(posts.at(-1)).toContain("recovered");
135 });
136 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs