Public: anyone can read this; the crew can change it.
The forge pages the phone once when it has been draining for five minutes, and once when the drain ends #2497
scout/forge:scout/2491-the-forge-pages-the-phone-once-when-it-h → main 1 commit fork
5 files
changed +270
−2
src/crew/incidents.ts added +44
| @@ -0,0 +1,44 @@ | ||
| 1 | /** | |
| 2 | * What is wrong with the forge itself that is worth a page. Pure: the | |
| 3 | * drain's start and the clock in, plain data out. Only a drain that has | |
| 4 | * outlived a release is paged; the vitals and `forge-guard`'s `held`, | |
| 5 | * `stuck` and `oom:*` already have their own place on the board. | |
| 6 | */ | |
| 7 | ||
| 8 | import { DRAIN_LIMIT_MS } from "../kernel/guard_verdict.ts"; | |
| 9 | ||
| 10 | export interface Incident { | |
| 11 | /** Stable for one drain, so a repeat tick is not news. */ | |
| 12 | readonly key: string; | |
| 13 | readonly line: string; | |
| 14 | } | |
| 15 | ||
| 16 | /** The drain as one incident once it has lasted more than five minutes. */ | |
| 17 | export function drainIncident( | |
| 18 | drainingSince: number | null | undefined, | |
| 19 | now: number, | |
| 20 | ): Incident | undefined { | |
| 21 | if (typeof drainingSince !== "number" || now - drainingSince <= DRAIN_LIMIT_MS) | |
| 22 | return undefined; | |
| 23 | return { | |
| 24 | key: `drain:${drainingSince}`, | |
| 25 | line: `forge has been draining for ${Math.floor((now - drainingSince) / 60_000)} minutes`, | |
| 26 | }; | |
| 27 | } | |
| 28 | ||
| 29 | export const RECOVERED = "Recovered: the forge is no longer draining"; | |
| 30 | ||
| 31 | /** | |
| 32 | * What to say, given the incident now and the key last paged: a page for an | |
| 33 | * incident not yet paged, "Recovered" for a paged one that ended, else nothing. | |
| 34 | */ | |
| 35 | export function nextPage( | |
| 36 | current: Incident | undefined, | |
| 37 | paged: string | undefined, | |
| 38 | ): { line: string; paged: string | undefined } | undefined { | |
| 39 | if (current !== undefined && current.key !== paged) | |
| 40 | return { line: current.line, paged: current.key }; | |
| 41 | if (current === undefined && paged !== undefined) | |
| 42 | return { line: RECOVERED, paged: undefined }; | |
| 43 | return undefined; | |
| 44 | } |
src/crew/notify.ts +83 −1
| @@ -32,6 +32,8 @@ import { landedLines } from "../core/watches.ts"; | ||
| 32 | 32 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 33 | 33 | import { lastMirror, mirrorNeed } from "../snapshot/mirror.ts"; |
| 34 | 34 | import { drillNeed, firstSeen, lastVerdict } from "../snapshot/verdict.ts"; |
| 35 | import { health } from "../http/health.ts"; | |
| 36 | import { drainIncident, nextPage } from "./incidents.ts"; | |
| 35 | 37 | import { askLinesFor } from "../web/studio/asks.ts"; |
| 36 | 38 | |
| 37 | 39 | const KEY = "notify_url"; |
| @@ -39,6 +41,7 @@ export const MAX_URL = 200; | ||
| 39 | 41 | const HOURLY = 10; |
| 40 | 42 | const HOUR_MS = 3_600_000; |
| 41 | 43 | const CLOCK_MS = 10 * 60_000; |
| 44 | const PAGE_MS = 60_000; | |
| 42 | 45 | const SEND_TIMEOUT_MS = 5_000; |
| 43 | 46 | const BACKOFF_FIRST_MS = 60_000; |
| 44 | 47 | const BACKOFF_MAX_MS = HOUR_MS; |
| @@ -184,6 +187,8 @@ export function mirrorLines( | ||
| 184 | 187 | export interface Notifier { |
| 185 | 188 | /** Resolves when the work queued so far is done. For tests and shutdown. */ |
| 186 | 189 | settled(): Promise<void>; |
| 190 | /** Looks at the forge's own health now, as the minute's clock does. */ | |
| 191 | tick(): Promise<void>; | |
| 187 | 192 | stop(): void; |
| 188 | 193 | } |
| 189 | 194 | |
| @@ -194,6 +199,8 @@ export interface NotifyOptions { | ||
| 194 | 199 | now?: () => number; |
| 195 | 200 | /** How often the clock wakes the notifier; ten minutes unless a test says. */ |
| 196 | 201 | clockMs?: number; |
| 202 | /** When this process began draining; the live health unless a test says. */ | |
| 203 | drainingSince?: () => number | null; | |
| 197 | 204 | } |
| 198 | 205 | |
| 199 | 206 | const oneLine = (s: string): string => |
| @@ -208,6 +215,8 @@ export function startNotifier(app: App, options: NotifyOptions): Notifier { | ||
| 208 | 215 | const seen = new Map<string, Set<string>>(); |
| 209 | 216 | const sent = new Map<string, number[]>(); |
| 210 | 217 | const pause = new Map<string, { until: number; next: number }>(); |
| 218 | /** Per admin: the drain last paged and not yet recovered, set only after delivery. */ | |
| 219 | const paged = new Map<string, string | undefined>(); | |
| 211 | 220 | let queue: Promise<void> = Promise.resolve(); |
| 212 | 221 | let stopped = false; |
| 213 | 222 | |
| @@ -220,6 +229,60 @@ export function startNotifier(app: App, options: NotifyOptions): Notifier { | ||
| 220 | 229 | .all(KEY) |
| 221 | 230 | .map((r) => r.user_id); |
| 222 | 231 | |
| 232 | const drainStart = (): number | null => | |
| 233 | options.drainingSince | |
| 234 | ? options.drainingSince() | |
| 235 | : health.draining | |
| 236 | ? health.drainingSince | |
| 237 | : null; | |
| 238 | ||
| 239 | /** | |
| 240 | * The admin is paged once for a drain past five minutes and once when it | |
| 241 | * ends. The key is recorded after delivery only, so a page the cap or the | |
| 242 | * backoff held back is tried again next tick and its Recovered is kept. | |
| 243 | */ | |
| 244 | async function page(userId: string, baseline: boolean): Promise<void> { | |
| 245 | const user = getUserById(app.db, userId); | |
| 246 | const url = notifyUrlOf(app.db, userId); | |
| 247 | if (user === undefined || url === undefined || !user.isAdmin || user.kind !== "user") { | |
| 248 | paged.delete(userId); | |
| 249 | return; | |
| 250 | } | |
| 251 | const current = drainIncident(drainStart(), now()); | |
| 252 | if (baseline || !paged.has(userId)) { | |
| 253 | // A restart has paged what it paged: start from what is true now. | |
| 254 | paged.set(userId, current?.key); | |
| 255 | return; | |
| 256 | } | |
| 257 | const next = nextPage(current, paged.get(userId)); | |
| 258 | if (next === undefined) return; | |
| 259 | const t = now(); | |
| 260 | const recent = (sent.get(userId) ?? []).filter((s) => t - s < HOUR_MS); | |
| 261 | sent.set(userId, recent); | |
| 262 | if (recent.length >= HOURLY || t < (pause.get(userId)?.until ?? 0)) return; | |
| 263 | recent.push(t); | |
| 264 | let delivered = false; | |
| 265 | try { | |
| 266 | delivered = await send(url, `${oneLine(next.line)}\n${link}`, { | |
| 267 | click: link, | |
| 268 | title: "forge", | |
| 269 | }); | |
| 270 | } catch { | |
| 271 | delivered = false; | |
| 272 | } | |
| 273 | if (delivered) { | |
| 274 | paged.set(userId, next.paged); | |
| 275 | pause.delete(userId); | |
| 276 | return; | |
| 277 | } | |
| 278 | const wait = Math.min(pause.get(userId)?.next ?? BACKOFF_FIRST_MS, BACKOFF_MAX_MS); | |
| 279 | pause.set(userId, { until: now() + wait, next: wait * 2 }); | |
| 280 | app.log.warn("notify endpoint failed; pausing", { | |
| 281 | host: notifyHost(url) ?? "", | |
| 282 | pauseMs: wait, | |
| 283 | }); | |
| 284 | } | |
| 285 | ||
| 223 | 286 | async function tell(userId: string, baseline: boolean): Promise<void> { |
| 224 | 287 | const user = getUserById(app.db, userId); |
| 225 | 288 | const url = notifyUrlOf(app.db, userId); |
| @@ -300,7 +363,10 @@ export function startNotifier(app: App, options: NotifyOptions): Notifier { | ||
| 300 | 363 | |
| 301 | 364 | // A forge that was down has told what it told: start from what asks now. |
| 302 | 365 | queue = queue.then(async () => { |
| 303 | for (const id of people()) await tell(id, true).catch(() => undefined); | |
| 366 | for (const id of people()) { | |
| 367 | await tell(id, true).catch(() => undefined); | |
| 368 | await page(id, true).catch(() => undefined); | |
| 369 | } | |
| 304 | 370 | }); |
| 305 | 371 | |
| 306 | 372 | // Eight days of silence is no event: the clock wakes the notifier too. |
| @@ -315,11 +381,27 @@ export function startNotifier(app: App, options: NotifyOptions): Notifier { | ||
| 315 | 381 | }, options.clockMs ?? CLOCK_MS); |
| 316 | 382 | clock.unref(); |
| 317 | 383 | |
| 384 | // A drain is paged within a minute of its fifth, not within ten. | |
| 385 | const pageAll = (): Promise<void> => { | |
| 386 | queue = queue.then(async () => { | |
| 387 | try { | |
| 388 | for (const id of people()) await page(id, false); | |
| 389 | } catch (error) { | |
| 390 | app.log.error("notify failed", { error: String(error) }); | |
| 391 | } | |
| 392 | }); | |
| 393 | return queue; | |
| 394 | }; | |
| 395 | const pager = setInterval(() => void pageAll(), Math.min(options.clockMs ?? CLOCK_MS, PAGE_MS)); | |
| 396 | pager.unref(); | |
| 397 | ||
| 318 | 398 | return { |
| 319 | 399 | settled: () => queue, |
| 400 | tick: pageAll, | |
| 320 | 401 | stop() { |
| 321 | 402 | stopped = true; |
| 322 | 403 | clearInterval(clock); |
| 404 | clearInterval(pager); | |
| 323 | 405 | unsubscribe(); |
| 324 | 406 | }, |
| 325 | 407 | }; |
src/http/health.ts +5 −1
| @@ -16,7 +16,10 @@ | ||
| 16 | 16 | |
| 17 | 17 | import type { Log } from "../kernel/log.ts"; |
| 18 | 18 | |
| 19 | export const health = { draining: false }; | |
| 19 | export const health: { draining: boolean; drainingSince: number | null } = { | |
| 20 | draining: false, | |
| 21 | drainingSince: null, | |
| 22 | }; | |
| 20 | 23 | |
| 21 | 24 | /** Whether the last liveness answer was a 503, so the log says so once. */ |
| 22 | 25 | let databaseDown = false; |
| @@ -28,6 +31,7 @@ let databaseDown = false; | ||
| 28 | 31 | export function startDraining(log: Log, why: string, fields: Record<string, number> = {}): void { |
| 29 | 32 | if (health.draining) return; |
| 30 | 33 | health.draining = true; |
| 34 | health.drainingSince = Date.now(); | |
| 31 | 35 | log.info("forge draining: /readyz answers 503 from now", { why, ...fields }); |
| 32 | 36 | } |
| 33 | 37 |
src/kernel/guard.ts +3
| @@ -38,6 +38,8 @@ export interface ForgeHealth { | ||
| 38 | 38 | readonly version: string; |
| 39 | 39 | readonly commit: string | null; |
| 40 | 40 | readonly draining: boolean; |
| 41 | /** When this process began draining (epoch ms), if it has. */ | |
| 42 | readonly drainingSince: number | null; | |
| 41 | 43 | readonly rollout: Rollout; |
| 42 | 44 | readonly incidents: Incident[]; |
| 43 | 45 | readonly stale: boolean; |
| @@ -120,6 +122,7 @@ export function forgeHealth( | ||
| 120 | 122 | version, |
| 121 | 123 | commit, |
| 122 | 124 | draining: health.draining, |
| 125 | drainingSince: health.draining ? health.drainingSince : null, | |
| 123 | 126 | rollout, |
| 124 | 127 | incidents: guard.incidents, |
| 125 | 128 | stale, |
test/notify-drain.test.ts added +135
| @@ -0,0 +1,135 @@ | ||
| 1 | /** | |
| 2 | * A drain past five minutes pages the admin once, its end says Recovered | |
| 3 | * once; a page the cap or the backoff held back is sent later; what the | |
| 4 | * guard already shows (`stuck`, `drill`) is not paged here. | |
| 5 | */ | |
| 6 | import { afterEach, beforeEach, 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 } from "../src/core/users.ts"; | |
| 12 | import { drainIncident, nextPage } from "../src/crew/incidents.ts"; | |
| 13 | import { setNotifyUrl, startNotifier, type Notifier } from "../src/crew/notify.ts"; | |
| 14 | ||
| 15 | const MIN = 60_000; | |
| 16 | ||
| 17 | describe("incidents (pure)", () => { | |
| 18 | test("only a drain past five minutes is an incident, keyed by its start", () => { | |
| 19 | expect(drainIncident(null, 10 * MIN)).toBeUndefined(); | |
| 20 | expect(drainIncident(0, 5 * MIN)).toBeUndefined(); | |
| 21 | expect(drainIncident(0, 6 * MIN)?.key).toBe("drain:0"); | |
| 22 | }); | |
| 23 | test("a page, then nothing, then Recovered", () => { | |
| 24 | const inc = drainIncident(0, 6 * MIN); | |
| 25 | const page = nextPage(inc, undefined)!; | |
| 26 | expect(page.paged).toBe("drain:0"); | |
| 27 | expect(nextPage(inc, page.paged)).toBeUndefined(); | |
| 28 | expect(nextPage(undefined, page.paged)?.line).toContain("Recovered"); | |
| 29 | expect(nextPage(undefined, undefined)).toBeUndefined(); | |
| 30 | }); | |
| 31 | }); | |
| 32 | ||
| 33 | describe("the drain page", () => { | |
| 34 | let dataDir: string; | |
| 35 | let app: App; | |
| 36 | let notifier: Notifier; | |
| 37 | let clock = 1_000_000; | |
| 38 | let since: number | null = null; | |
| 39 | let accept = true; | |
| 40 | const posts: string[] = []; | |
| 41 | ||
| 42 | async function boot(): Promise<void> { | |
| 43 | notifier = startNotifier(app, { | |
| 44 | forgeUrl: "https://forge.example.test", | |
| 45 | now: () => clock, | |
| 46 | drainingSince: () => since, | |
| 47 | send: async (_u, body) => { | |
| 48 | posts.push(body); | |
| 49 | return accept; | |
| 50 | }, | |
| 51 | }); | |
| 52 | await notifier.settled(); | |
| 53 | } | |
| 54 | ||
| 55 | beforeEach(async () => { | |
| 56 | dataDir = await mkdtemp(join(tmpdir(), "forge-drain-")); | |
| 57 | app = createApp({ dataDir, port: 0 }); | |
| 58 | const made = await createUser(app.db, { | |
| 59 | trusted: true, | |
| 60 | username: "alice", | |
| 61 | email: "[email protected]", | |
| 62 | password: "a-good-passphrase", | |
| 63 | adminIfFirst: true, | |
| 64 | }); | |
| 65 | if (!made.ok) throw new Error(made.error); | |
| 66 | setNotifyUrl(app.db, made.value.id, "https://ntfy.example.test/root-topic"); | |
| 67 | posts.length = 0; | |
| 68 | clock = 1_000_000; | |
| 69 | since = null; | |
| 70 | accept = true; | |
| 71 | await boot(); | |
| 72 | }); | |
| 73 | afterEach(async () => { | |
| 74 | notifier.stop(); | |
| 75 | await rm(dataDir, { recursive: true, force: true }); | |
| 76 | }); | |
| 77 | ||
| 78 | test("six minutes of draining sends one page, its end one Recovered", async () => { | |
| 79 | since = clock; | |
| 80 | clock += 4 * MIN; | |
| 81 | await notifier.tick(); | |
| 82 | expect(posts).toHaveLength(0); | |
| 83 | clock += 2 * MIN; | |
| 84 | await notifier.tick(); | |
| 85 | await notifier.tick(); | |
| 86 | expect(posts).toHaveLength(1); | |
| 87 | expect(posts[0]).toContain("draining for 6 minutes"); | |
| 88 | since = null; | |
| 89 | await notifier.tick(); | |
| 90 | await notifier.tick(); | |
| 91 | expect(posts).toHaveLength(2); | |
| 92 | expect(posts[1]).toContain("Recovered"); | |
| 93 | }); | |
| 94 | ||
| 95 | test("a page the endpoint refused is sent on a later tick, and Recovered is not lost", async () => { | |
| 96 | since = clock; | |
| 97 | clock += 6 * MIN; | |
| 98 | accept = false; | |
| 99 | await notifier.tick(); | |
| 100 | expect(posts).toHaveLength(1); | |
| 101 | // Backed off: nothing is tried at once. | |
| 102 | await notifier.tick(); | |
| 103 | expect(posts).toHaveLength(1); | |
| 104 | accept = true; | |
| 105 | clock += 2 * MIN; | |
| 106 | await notifier.tick(); | |
| 107 | expect(posts).toHaveLength(2); | |
| 108 | since = null; | |
| 109 | await notifier.tick(); | |
| 110 | expect(posts).toHaveLength(3); | |
| 111 | expect(posts[2]).toContain("Recovered"); | |
| 112 | }); | |
| 113 | ||
| 114 | test("a restart in a paged drain does not page again", async () => { | |
| 115 | since = clock; | |
| 116 | clock += 6 * MIN; | |
| 117 | notifier.stop(); | |
| 118 | await boot(); | |
| 119 | await notifier.tick(); | |
| 120 | expect(posts).toHaveLength(0); | |
| 121 | }); | |
| 122 | ||
| 123 | test("a stuck or drill cause in the guard, however old, sends no page", async () => { | |
| 124 | process.env["FORGE_GUARD_DIR"] = dataDir; | |
| 125 | await Bun.write( | |
| 126 | join(dataDir, "status.json"), | |
| 127 | JSON.stringify({ incidents: { "stuck:r1": "x", drill: "y" } }), | |
| 128 | ); | |
| 129 | await Bun.write(join(dataDir, "checkedAt"), new Date(clock).toISOString()); | |
| 130 | clock += 10 * MIN; | |
| 131 | await notifier.tick(); | |
| 132 | delete process.env["FORGE_GUARD_DIR"]; | |
| 133 | expect(posts).toHaveLength(0); | |
| 134 | }); | |
| 135 | }); |
new above
offline