Public: anyone can read this; the crew can change it.
A red restore drill, or none in eight days, is one line on the board and a push to the owner's phone #1721
scout/forge:scout/1183-a-red-restore-drill-or-none-in-eight-day → main 7 commits fork
13 files
changed +393
−11
README.md +8
| @@ -467,6 +467,14 @@ into scratch, opens it, counts what is there and unseals a value; the page | ||
| 467 | 467 | waits for it, up to 10 minutes, and the last drill shows there as one line. |
| 468 | 468 | Only one runs at a time. See `docs/SNAPSHOT.md`. |
| 469 | 469 | |
| 470 | A red drill, or none in eight days on a forge that has a snapshot store, is | |
| 471 | one line for the forge admin, naming the step that failed: on the board's | |
| 472 | forge strip, in the asks (`GET /api/v1/asks`, MCP `asks`), in `health` | |
| 473 | (`degraded`/`needs`, MCP and API) and in the terminal dashboard, which reads | |
| 474 | the same vitals. It clears on the next green drill. The admin's phone | |
| 475 | (`notify_url`) hears it once per cause; a push that fails to arrive is tried | |
| 476 | again at the next wake. The nightly runs a drill when the last is over six days old. | |
| 477 | ||
| 470 | 478 | `docs/EXTRACT.md` is the forge on a machine of its own, and the platform it |
| 471 | 479 | grew up in switched off: what a host owes it, the moves in order, and what is |
| 472 | 480 | given up. |
scripts/gate.ts +1
| @@ -230,6 +230,7 @@ export const GATE: readonly string[] = [ | ||
| 230 | 230 | "test/mcp.test.ts", |
| 231 | 231 | "test/name-marks.test.ts", |
| 232 | 232 | "test/new-forge.test.ts", |
| 233 | "test/drill-notice.test.ts", | |
| 233 | 234 | "test/notify.test.ts", |
| 234 | 235 | "test/onboarding.test.ts", |
| 235 | 236 | "test/org-owners.test.ts", |
src/actions/health.ts +2
| @@ -14,6 +14,7 @@ import { listApps } from "../core/apps.ts"; | ||
| 14 | 14 | import type { User } from "../core/users.ts"; |
| 15 | 15 | import { forgeHealth, rolloutLine, type ForgeHealth } from "../kernel/guard.ts"; |
| 16 | 16 | import { laneLine, sinceWords, vitals, type Degraded, type Vitals } from "../kernel/vitals.ts"; |
| 17 | import { drillsOn } from "../snapshot/service.ts"; | |
| 17 | 18 | |
| 18 | 19 | export function readHealth( |
| 19 | 20 | app: App, |
| @@ -30,6 +31,7 @@ export function readHealth( | ||
| 30 | 31 | dataDir: app.config.dataDir, |
| 31 | 32 | envs, |
| 32 | 33 | signals: app.signals, |
| 34 | drillsOn: drillsOn(app), | |
| 33 | 35 | }); |
| 34 | 36 | return { ...v, ...forge, ok: forge.ok && v.ok }; |
| 35 | 37 | } |
src/core/schema.ts +10
| @@ -1688,6 +1688,16 @@ export const migrations: readonly string[] = [ | ||
| 1688 | 1688 | CREATE TRIGGER thought_no_delete BEFORE DELETE ON thought |
| 1689 | 1689 | BEGIN SELECT RAISE(ABORT, 'a thought is never deleted'); END; |
| 1690 | 1690 | `, |
| 1691 | // 82 — the pushes already sent about a restore drill (#1183). The primary key | |
| 1692 | // is the claim: two processes inserting the same one, only one changes a row. | |
| 1693 | ` | |
| 1694 | CREATE TABLE drill_notice ( | |
| 1695 | user_id TEXT NOT NULL, | |
| 1696 | cause TEXT NOT NULL, | |
| 1697 | at TEXT NOT NULL, | |
| 1698 | PRIMARY KEY (user_id, cause) | |
| 1699 | ); | |
| 1700 | `, | |
| 1691 | 1701 | ]; |
| 1692 | 1702 | |
| 1693 | 1703 | /** |
src/crew/notify.ts +28 −1
| @@ -6,7 +6,8 @@ | ||
| 6 | 6 | * the forge's admin a person who just joined — one |
| 7 | 7 | * short line and a link to the asks screen is posted there. A milestone |
| 8 | 8 | * the person watches says one line too, once, when it lands, with a link to |
| 9 | * the milestone; its progress never does. | |
| 9 | * the milestone; its progress never does. A red restore drill, or none in | |
| 10 | * eight days, tells the admin once per cause (`snapshot/drill_log.ts`). | |
| 10 | 11 | * |
| 11 | 12 | * What asks a person is read the way the asks panel reads it |
| 12 | 13 | * (`askLinesFor`), as that person, so nothing private leaves for someone who |
| @@ -30,6 +31,8 @@ import { getUserSetting, setUserSetting } from "../core/settings.ts"; | ||
| 30 | 31 | import { getUserById } from "../core/users.ts"; |
| 31 | 32 | import { landedLines } from "../core/watches.ts"; |
| 32 | 33 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 34 | import { drillsOn } from "../snapshot/service.ts"; | |
| 35 | import { claimNotice, drillNeed, isDrillCause, releaseNotice } from "../snapshot/drill_log.ts"; | |
| 33 | 36 | import { askLinesFor } from "../web/studio/asks.ts"; |
| 34 | 37 | |
| 35 | 38 | const KEY = "notify_url"; |
| @@ -53,6 +56,7 @@ const WAKES = new Set([ | ||
| 53 | 56 | "account.notify_set", |
| 54 | 57 | "user.created", |
| 55 | 58 | "mail.ceiling", |
| 59 | "drill.checked", | |
| 56 | 60 | ]); |
| 57 | 61 | |
| 58 | 62 | export type NotifyUrlError = |
| @@ -161,6 +165,19 @@ export interface NotifyOptions { | ||
| 161 | 165 | now?: () => number; |
| 162 | 166 | } |
| 163 | 167 | |
| 168 | /** The restore drill, red or overdue, as the owner's phone hears it (admins only). */ | |
| 169 | function drillLines( | |
| 170 | app: App, | |
| 171 | user: { isAdmin: boolean; kind: string }, | |
| 172 | now: number, | |
| 173 | ): { line: string; items: readonly string[]; link: string }[] { | |
| 174 | if (!user.isAdmin || user.kind !== "user") return []; | |
| 175 | const need = drillNeed(app.db, now, drillsOn(app)); | |
| 176 | return need === null | |
| 177 | ? [] | |
| 178 | : [{ line: need.sentence, items: [need.cause], link: "/settings/backups" }]; | |
| 179 | } | |
| 180 | ||
| 164 | 181 | const oneLine = (s: string): string => |
| 165 | 182 | // eslint-disable-next-line no-control-regex |
| 166 | 183 | s.replace(/[\u0000-\u001f\u007f]+/g, " ").slice(0, 160); |
| @@ -200,6 +217,7 @@ export function startNotifier(app: App, options: NotifyOptions): Notifier { | ||
| 200 | 217 | ...newAccountLines(app.db, user, now()), |
| 201 | 218 | ...landedLines(app.db, user, now()), |
| 202 | 219 | ...mailCeilingLines(app, user, now()), |
| 220 | ...drillLines(app, user, now()), | |
| 203 | 221 | ]; |
| 204 | 222 | const before = seen.get(userId); |
| 205 | 223 | // What is gone may ask again later, and then it is new again. Seen by |
| @@ -214,6 +232,10 @@ export function startNotifier(app: App, options: NotifyOptions): Notifier { | ||
| 214 | 232 | sent.set(userId, recent); |
| 215 | 233 | if (recent.length >= HOURLY) return; |
| 216 | 234 | if (t < (pause.get(userId)?.until ?? 0)) return; |
| 235 | // One push per person and cause, claimed in the database so a roll | |
| 236 | // (two processes) cannot send it twice. | |
| 237 | if (isDrillCause(ask.items[0]) && !claimNotice(app.db, userId, ask.items[0], t)) | |
| 238 | continue; | |
| 217 | 239 | recent.push(t); |
| 218 | 240 | let delivered = false; |
| 219 | 241 | try { |
| @@ -229,6 +251,11 @@ export function startNotifier(app: App, options: NotifyOptions): Notifier { | ||
| 229 | 251 | delivered = false; |
| 230 | 252 | } |
| 231 | 253 | if (!delivered) { |
| 254 | // A push that did not arrive was not told: give the claim back. | |
| 255 | if (isDrillCause(ask.items[0])) { | |
| 256 | releaseNotice(app.db, userId, ask.items[0]); | |
| 257 | seen.get(userId)?.delete(ask.items[0]); // so the next wake tries it again | |
| 258 | } | |
| 232 | 259 | const next = Math.min( |
| 233 | 260 | pause.get(userId)?.next ?? BACKOFF_FIRST_MS, |
| 234 | 261 | BACKOFF_MAX_MS, |
src/kernel/vitals.ts +7 −7
| @@ -20,7 +20,7 @@ import { | ||
| 20 | 20 | queueDepth, |
| 21 | 21 | } from "../core/runs.ts"; |
| 22 | 22 | import { STALE_AFTER_MS } from "../runs/lease.ts"; |
| 23 | import { failedSentence, lastVerdict } from "../snapshot/verdict.ts"; | |
| 23 | import { drillNeed } from "../snapshot/drill_log.ts"; | |
| 24 | 24 | |
| 25 | 25 | /** Free disk under this share of the volume is something to say. */ |
| 26 | 26 | export const DISK_FREE_MIN = 0.1; |
| @@ -92,6 +92,8 @@ export interface VitalsInput { | ||
| 92 | 92 | /** Every environment the runtime holds, when one is up. */ |
| 93 | 93 | readonly envs?: readonly EnvCount[]; |
| 94 | 94 | readonly now?: number; |
| 95 | /** Whether the forge has a snapshot store: without one, no drill is late (`snapshot/service.ts`). */ | |
| 96 | readonly drillsOn?: boolean; | |
| 95 | 97 | /** The free-disk share below which the disk is a need; `DISK_FREE_MIN` unless a test says. */ |
| 96 | 98 | readonly diskFreeMin?: number; |
| 97 | 99 | /** One forge's own signals (`App.signals`). */ |
| @@ -273,12 +275,6 @@ export function vitals(input: VitalsInput): Vitals { | ||
| 273 | 275 | "/settings/capacity", |
| 274 | 276 | ); |
| 275 | 277 | |
| 276 | // A failed restore drill is a card until a drill passes. | |
| 277 | const drill = lastVerdict(input.dataDir); | |
| 278 | const failed = failedSentence(drill); | |
| 279 | if (failed !== undefined) | |
| 280 | need("drill", failed, drill?.at, "/settings/backups"); | |
| 281 | ||
| 282 | 278 | const apps = { serving: 0, asleep: 0, previews: 0 }; |
| 283 | 279 | for (const e of input.envs ?? []) { |
| 284 | 280 | if (e.env !== "production") apps.previews++; |
| @@ -304,6 +300,10 @@ export function vitals(input: VitalsInput): Vitals { | ||
| 304 | 300 | "/settings/capacity#internal", |
| 305 | 301 | ); |
| 306 | 302 | |
| 303 | // A red restore drill, or none in eight days: the backups are a hope. | |
| 304 | const drill = drillNeed(input.db, now, input.drillsOn ?? false); | |
| 305 | if (drill !== null) need(drill.cause, drill.sentence, drill.since, "/settings/backups"); | |
| 306 | ||
| 307 | 307 | for (const cause of firstSeen.keys()) |
| 308 | 308 | if (!degraded.some((d) => d.cause === cause)) firstSeen.delete(cause); |
| 309 | 309 |
src/main.ts +2 −1
| @@ -20,7 +20,7 @@ import { resolveAppDomain } from "./apps/host.ts"; | ||
| 20 | 20 | import { requeueAbandonedChecks, startChecks } from "./checks/service.ts"; |
| 21 | 21 | import { startLooks } from "./looks/service.ts"; |
| 22 | 22 | import { startProbes } from "./contract/probes.ts"; |
| 23 | import { startSnapshots } from "./snapshot/service.ts"; | |
| 23 | import { drillsOn, startSnapshots } from "./snapshot/service.ts"; | |
| 24 | 24 | import { resolveDestination } from "./snapshot/destination.ts"; |
| 25 | 25 | import { releaseOrphans } from "./core/run_secret.ts"; |
| 26 | 26 | import { failAbandonedRuns } from "./core/runs.ts"; |
| @@ -350,6 +350,7 @@ const tickAsks = async (): Promise<void> => { | ||
| 350 | 350 | db: app.db, |
| 351 | 351 | dataDir: app.config.dataDir, |
| 352 | 352 | signals: app.signals, |
| 353 | drillsOn: drillsOn(app), | |
| 353 | 354 | }).degraded, |
| 354 | 355 | Date.now(), |
| 355 | 356 | app.log, |
src/snapshot/drill_log.ts added +108
| @@ -0,0 +1,108 @@ | ||
| 1 | /** | |
| 2 | * What the restore drills said, kept, and what the forge's owner is told of | |
| 3 | * it: a drill nobody hears about is not a drill (#1183). | |
| 4 | * | |
| 5 | * The need is one cause at a time. The newest drill red names the step that | |
| 6 | * failed; the newest drill older than `STALE_AFTER_MS` (or none at all, in a | |
| 7 | * forge that old) says the drill has not run. A green drill inside the | |
| 8 | * window clears both. The cause key names the evidence (`red:<when>`, | |
| 9 | * `stale:<newest drill>`), so the same cause is the same key on every tick | |
| 10 | * and in every process. | |
| 11 | * | |
| 12 | * The push is claimed in the database (`claimNotice`): the claim is one | |
| 13 | * INSERT, so two processes rolling past each other send it once. | |
| 14 | */ | |
| 15 | ||
| 16 | import type { Database } from "bun:sqlite"; | |
| 17 | ||
| 18 | export const STALE_AFTER_MS = 8 * 24 * 3_600_000; | |
| 19 | ||
| 20 | export interface DrillNeed { | |
| 21 | readonly cause: string; | |
| 22 | readonly sentence: string; | |
| 23 | /** When it began: the red drill's time, or when the window ran out. */ | |
| 24 | readonly since: string; | |
| 25 | } | |
| 26 | ||
| 27 | /** True for a cause key this module made. */ | |
| 28 | export function isDrillCause(cause: string | undefined): cause is string { | |
| 29 | return cause !== undefined && cause.startsWith("drill:"); | |
| 30 | } | |
| 31 | ||
| 32 | /** A green drill ends the story: a later red is a new cause that tells again. */ | |
| 33 | export function forgetNotices(db: Database): void { | |
| 34 | db.query("DELETE FROM drill_notice").run(); | |
| 35 | } | |
| 36 | ||
| 37 | /** The newest drill's time, or null when none ran. */ | |
| 38 | export function lastDrillAt(db: Database): string | null { | |
| 39 | return ( | |
| 40 | db.query<{ at: string }, []>("SELECT at FROM drill ORDER BY id DESC LIMIT 1").get()?.at ?? null | |
| 41 | ); | |
| 42 | } | |
| 43 | ||
| 44 | /** | |
| 45 | * Why the drill is a need now, or null when it is not. A forge with no | |
| 46 | * snapshot store (`drillsOn`) has no drill to be late, so only a red one | |
| 47 | * speaks for it. One read of four small subselects, each a key lookup (drill by id, event by seq). | |
| 48 | */ | |
| 49 | export function drillNeed( | |
| 50 | db: Database, | |
| 51 | now: number = Date.now(), | |
| 52 | storeOn = true, | |
| 53 | ): DrillNeed | null { | |
| 54 | // One read however many drills there are: the newest, and the forge's age. | |
| 55 | const row = db | |
| 56 | .query< | |
| 57 | { at: string | null; verdict: string | null; failed_step: string | null; born: string | null }, | |
| 58 | [] | |
| 59 | >( | |
| 60 | `SELECT (SELECT at FROM drill ORDER BY id DESC LIMIT 1) AS at, | |
| 61 | (SELECT verdict FROM drill ORDER BY id DESC LIMIT 1) AS verdict, | |
| 62 | (SELECT failed_step FROM drill ORDER BY id DESC LIMIT 1) AS failed_step, | |
| 63 | (SELECT created_at FROM event WHERE seq IS NOT NULL ORDER BY seq LIMIT 1) AS born`, | |
| 64 | ) | |
| 65 | .get(); | |
| 66 | const last = row?.at != null ? { at: row.at, verdict: row.verdict, failed_step: row.failed_step } : null; | |
| 67 | if (last?.verdict === "red") | |
| 68 | return { | |
| 69 | cause: `drill:red:${last.at}`, | |
| 70 | sentence: `The last restore drill failed at the ${last.failed_step ?? "unknown"} step.`, | |
| 71 | since: last.at, | |
| 72 | }; | |
| 73 | if (!storeOn) return null; | |
| 74 | // Without a drill on record, the forge's own age is the evidence. | |
| 75 | const from = last?.at ?? row?.born ?? null; | |
| 76 | if (from === null) return null; | |
| 77 | const ran = Date.parse(from); | |
| 78 | if (!Number.isFinite(ran) || now - ran <= STALE_AFTER_MS) return null; | |
| 79 | return { | |
| 80 | cause: `drill:stale:${last?.at ?? "none"}`, | |
| 81 | sentence: | |
| 82 | last === null | |
| 83 | ? "No restore drill has run in 8 days." | |
| 84 | : `No restore drill has run in 8 days; the last was ${last.at.slice(0, 10)}.`, | |
| 85 | since: new Date(ran + STALE_AFTER_MS).toISOString(), | |
| 86 | }; | |
| 87 | } | |
| 88 | ||
| 89 | /** Take the claim back: the push did not arrive, so the next look may try again. */ | |
| 90 | export function releaseNotice(db: Database, userId: string, cause: string): void { | |
| 91 | db.query("DELETE FROM drill_notice WHERE user_id = ?1 AND cause = ?2").run(userId, cause); | |
| 92 | } | |
| 93 | ||
| 94 | /** True once per person and cause, across processes. */ | |
| 95 | export function claimNotice( | |
| 96 | db: Database, | |
| 97 | userId: string, | |
| 98 | cause: string, | |
| 99 | now: number = Date.now(), | |
| 100 | ): boolean { | |
| 101 | return ( | |
| 102 | db | |
| 103 | .query( | |
| 104 | "INSERT OR IGNORE INTO drill_notice (user_id, cause, at) VALUES (?1, ?2, ?3)", | |
| 105 | ) | |
| 106 | .run(userId, cause, new Date(now).toISOString()).changes === 1 | |
| 107 | ); | |
| 108 | } |
src/snapshot/service.ts +8
| @@ -21,6 +21,7 @@ import { | ||
| 21 | 21 | } from "./snapshot.ts"; |
| 22 | 22 | import { runDrill, type DrillDeps, type DrillResult } from "./drill.ts"; |
| 23 | 23 | import { recordDrill } from "./drills.ts"; |
| 24 | import { forgetNotices } from "./drill_log.ts"; | |
| 24 | 25 | import type { Store } from "./store.ts"; |
| 25 | 26 | |
| 26 | 27 | const log = createLog("snapshots"); |
| @@ -52,6 +53,9 @@ const handles = new WeakMap<App, SnapshotsHandle>(); | ||
| 52 | 53 | export const snapshotsOf = (app: App): SnapshotsHandle | undefined => |
| 53 | 54 | handles.get(app); |
| 54 | 55 | |
| 56 | /** Whether this forge has somewhere to snapshot to, and so a drill to run. */ | |
| 57 | export const drillsOn = (app: App): boolean => snapshotsOf(app)?.store !== undefined; | |
| 58 | ||
| 55 | 59 | /** The weekly restore drill: Sunday, an hour after the nightly snapshot. */ |
| 56 | 60 | const DRILL_DAY_UTC = 0; |
| 57 | 61 | const DRILL_HOUR_UTC = 9; |
| @@ -152,6 +156,10 @@ export function startSnapshots( | ||
| 152 | 156 | passphrase: options.passphrase, |
| 153 | 157 | }); |
| 154 | 158 | recordDrill(app.db, result); |
| 159 | if (result.verdict === "green") forgetNotices(app.db); | |
| 160 | else log.error("restore drill failed", { step: result.failedStep ?? "" }); | |
| 161 | // The need may have changed: let the notifier look. | |
| 162 | app.bus.append({ kind: "drill.checked", payload: {} }); | |
| 155 | 163 | // The card and the recovery issue hear of every drill, whoever asked. |
| 156 | 164 | const posted = await reportVerdict(app.config.dataDir, result); |
| 157 | 165 | log.info("restore drill", { verdict: result.verdict, step: result.failedStep ?? "none", posted }); |
src/web/pages/board.ts +2
| @@ -14,6 +14,7 @@ | ||
| 14 | 14 | * pointer. The old big view (`/big`, every address it had) lands here. |
| 15 | 15 | */ |
| 16 | 16 | |
| 17 | import { drillsOn } from "../../snapshot/service.ts"; | |
| 17 | 18 | import { sentinelNotice } from "../../crew/sentinel.ts"; |
| 18 | 19 | import { appsForRepos, type AppRecord } from "../../core/apps.ts"; |
| 19 | 20 | import { askMeasure } from "../../core/ask_ledger.ts"; |
| @@ -329,6 +330,7 @@ function forgeStrip(ctx: Ctx): Html | null { | ||
| 329 | 330 | db: app.db, |
| 330 | 331 | dataDir: app.config.dataDir, |
| 331 | 332 | signals: app.signals, |
| 333 | drillsOn: drillsOn(app), | |
| 332 | 334 | envs: runtime |
| 333 | 335 | ? listApps(app.db).flatMap((record) => runtime.status(record)) |
| 334 | 336 | : [], |
src/web/studio/asks.ts +2
| @@ -55,6 +55,7 @@ import { isStalePull, mergesAgainSince } from "../../crew/stale_asks.ts"; | ||
| 55 | 55 | import { waitsForPerson, type ReviewWait } from "../../crew/review.ts"; |
| 56 | 56 | import type { Ctx } from "../../http/context.ts"; |
| 57 | 57 | import { vitals } from "../../kernel/vitals.ts"; |
| 58 | import { drillsOn } from "../../snapshot/service.ts"; | |
| 58 | 59 | import { repoBase } from "../chrome.ts"; |
| 59 | 60 | import { html, type Html } from "../html.ts"; |
| 60 | 61 | import { btn, card, icon, row } from "../ui.ts"; |
| @@ -1004,6 +1005,7 @@ export function forgeNeedsFor(ctx: Ctx, user: User | undefined): Degraded[] { | ||
| 1004 | 1005 | db: ctx.app.db, |
| 1005 | 1006 | dataDir: ctx.app.config.dataDir, |
| 1006 | 1007 | signals: ctx.app.signals, |
| 1008 | drillsOn: drillsOn(ctx.app), | |
| 1007 | 1009 | envs, |
| 1008 | 1010 | }).degraded; |
| 1009 | 1011 | } |
test/drill-notice.test.ts added +213
| @@ -0,0 +1,213 @@ | ||
| 1 | /** | |
| 2 | * A red restore drill, or none in eight days, is one line for the owner (the | |
| 3 | * board's strip, the asks, `health`) and one push, however many ticks or | |
| 4 | * processes look at it; a green drill clears it (#1183). | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, 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 { readHealth, forgeNeeds } from "../src/actions/health.ts"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { startNotifier, setNotifyUrl, type Notifier } from "../src/crew/notify.ts"; | |
| 13 | import { createUser, type User } from "../src/core/users.ts"; | |
| 14 | import { listEvents } from "../src/core/events.ts"; | |
| 15 | import type { DrillResult } from "../src/snapshot/drill.ts"; | |
| 16 | import { recordDrill as keep } from "../src/snapshot/drills.ts"; | |
| 17 | import { startSnapshots, type SnapshotsHandle } from "../src/snapshot/service.ts"; | |
| 18 | import { dirStore } from "../src/snapshot/store.ts"; | |
| 19 | import { claimNotice, drillNeed, STALE_AFTER_MS } from "../src/snapshot/drill_log.ts"; | |
| 20 | import type { Vitals } from "../src/kernel/vitals.ts"; | |
| 21 | import { forgeNeedsFor, asksAnswer } from "../src/web/studio/asks.ts"; | |
| 22 | import type { Ctx } from "../src/http/context.ts"; | |
| 23 | ||
| 24 | const drill = (at: string, failedStep: DrillResult["failedStep"] = null): DrillResult => ({ | |
| 25 | at, | |
| 26 | snapshotId: "snap-1", | |
| 27 | ms: 5, | |
| 28 | counts: { repositories: 1, issues: 2 }, | |
| 29 | verdict: failedStep === null ? "green" : "red", | |
| 30 | failedStep, | |
| 31 | health: failedStep === null ? "ok" : "unreached", | |
| 32 | reason: failedStep === null ? null : "boom", | |
| 33 | }); | |
| 34 | ||
| 35 | describe("the restore drill as a need", () => { | |
| 36 | let dataDir: string; | |
| 37 | let app: App; | |
| 38 | let admin: User; | |
| 39 | let notifiers: Notifier[] = []; | |
| 40 | let svc: SnapshotsHandle; | |
| 41 | let next: DrillResult; | |
| 42 | let ran = 0; | |
| 43 | let healthy = true; | |
| 44 | let clock = Date.now(); | |
| 45 | /** A drill, the way the service takes one: run, kept, notices forgotten on green, the notifier woken. */ | |
| 46 | const recordDrill = async (_db: App["db"], r: DrillResult): Promise<void> => { | |
| 47 | next = r; | |
| 48 | await svc.drill(); | |
| 49 | for (const n of notifiers) await n.settled(); | |
| 50 | }; | |
| 51 | const posts: string[] = []; | |
| 52 | const send = async (_url: string, body: string) => { | |
| 53 | posts.push(body); | |
| 54 | return healthy; | |
| 55 | }; | |
| 56 | const lines = () => | |
| 57 | (readHealth(app, admin) as Vitals).degraded.filter((d) => d.cause.startsWith("drill:")); | |
| 58 | const wake = async () => { | |
| 59 | app.bus.append({ kind: "drill.checked", payload: {} }); | |
| 60 | for (const n of notifiers) await n.settled(); | |
| 61 | }; | |
| 62 | ||
| 63 | beforeAll(async () => { | |
| 64 | dataDir = await mkdtemp(join(tmpdir(), "forge-drill-")); | |
| 65 | app = createApp({ dataDir, port: 0 }); | |
| 66 | const made = await createUser(app.db, { | |
| 67 | trusted: true, | |
| 68 | username: "keeper", | |
| 69 | email: "[email protected]", | |
| 70 | password: "a-good-passphrase", | |
| 71 | adminIfFirst: true, | |
| 72 | }); | |
| 73 | if (!made.ok) throw new Error(made.error); | |
| 74 | admin = made.value; | |
| 75 | svc = startSnapshots(app, dirStore(join(dataDir, "store")), { | |
| 76 | version: "t", | |
| 77 | nightly: false, | |
| 78 | drill: async () => { | |
| 79 | ran++; | |
| 80 | return next; | |
| 81 | }, | |
| 82 | }); | |
| 83 | setNotifyUrl(app.db, admin.id, "https://ntfy.example.test/owner-topic"); | |
| 84 | // Two processes looking at one database. | |
| 85 | for (let i = 0; i < 2; i++) { | |
| 86 | const n = startNotifier(app, { forgeUrl: "https://forge.example.test", send, now: () => clock }); | |
| 87 | await n.settled(); | |
| 88 | notifiers.push(n); | |
| 89 | } | |
| 90 | }); | |
| 91 | // Each test stands alone, whatever order they run in. | |
| 92 | beforeEach(() => { | |
| 93 | app.db.query("DELETE FROM drill").run(); | |
| 94 | app.db.query("DELETE FROM drill_notice").run(); | |
| 95 | posts.length = 0; | |
| 96 | ran = 0; | |
| 97 | healthy = true; | |
| 98 | }); | |
| 99 | afterAll(async () => { | |
| 100 | await svc.stop(); | |
| 101 | for (const n of notifiers) n.stop(); | |
| 102 | await rm(dataDir, { recursive: true, force: true }); | |
| 103 | }); | |
| 104 | ||
| 105 | test("a fresh forge with no drill yet says nothing", () => { | |
| 106 | expect(lines()).toHaveLength(0); | |
| 107 | }); | |
| 108 | ||
| 109 | test("a red drill is one line naming the step, and one push across two processes and many ticks", async () => { | |
| 110 | await recordDrill(app.db, drill(new Date().toISOString(), "unseal")); | |
| 111 | const found = lines(); | |
| 112 | expect(found).toHaveLength(1); | |
| 113 | expect(found[0]!.sentence).toContain("unseal"); | |
| 114 | expect(found[0]!.href).toBe("/settings/backups"); | |
| 115 | await wake(); | |
| 116 | await wake(); | |
| 117 | await wake(); | |
| 118 | expect(posts).toHaveLength(1); | |
| 119 | expect(posts[0]).toContain("unseal"); | |
| 120 | }); | |
| 121 | ||
| 122 | test("the line is in the asks and in the health answer", async () => { | |
| 123 | await recordDrill(app.db, drill(new Date().toISOString(), "unseal")); | |
| 124 | const ctx = { app } as unknown as Ctx; | |
| 125 | expect(forgeNeedsFor(ctx, admin).some((d) => d.sentence.includes("unseal"))).toBe(true); | |
| 126 | expect(asksAnswer(ctx, admin).forge.some((l) => l.includes("restore drill"))).toBe(true); | |
| 127 | expect((readHealth(app, admin) as Vitals).needs.some((l) => l.includes("restore drill"))).toBe(true); | |
| 128 | }); | |
| 129 | ||
| 130 | test("a green drill clears the line, and a later red tells again", async () => { | |
| 131 | await recordDrill(app.db, drill(new Date().toISOString(), "unseal")); | |
| 132 | await wake(); | |
| 133 | expect(posts).toHaveLength(1); | |
| 134 | await recordDrill(app.db, drill(new Date(Date.now() + 1000).toISOString())); | |
| 135 | expect(lines()).toHaveLength(0); | |
| 136 | await wake(); | |
| 137 | expect(posts).toHaveLength(1); | |
| 138 | await recordDrill(app.db, drill(new Date(Date.now() + 2000).toISOString(), "restore")); | |
| 139 | await wake(); | |
| 140 | expect(posts).toHaveLength(2); | |
| 141 | expect(posts[1]).toContain("restore"); | |
| 142 | }); | |
| 143 | ||
| 144 | test("eight days with none is a line, once; before that it is not", async () => { | |
| 145 | const db = app.db; | |
| 146 | // The forge's age is its oldest event. | |
| 147 | app.bus.append({ kind: "drill.checked", payload: {} }); | |
| 148 | const born = (db.query("SELECT MIN(created_at) AS at FROM event").get() as { at: string }).at; | |
| 149 | const t = Date.parse(born); | |
| 150 | expect(drillNeed(db, t + STALE_AFTER_MS - 1000)).toBeNull(); | |
| 151 | const need = drillNeed(db, t + STALE_AFTER_MS + 1000); | |
| 152 | expect(need?.sentence).toContain("8 days"); | |
| 153 | // The same cause keeps one key however late it is asked. | |
| 154 | expect(drillNeed(db, t + STALE_AFTER_MS * 2)?.cause).toBe(need!.cause); | |
| 155 | // A green drill inside the window clears it. | |
| 156 | await recordDrill(db, drill(new Date(t + STALE_AFTER_MS).toISOString())); | |
| 157 | expect(drillNeed(db, t + STALE_AFTER_MS + 1000)).toBeNull(); | |
| 158 | expect(drillNeed(db, t + STALE_AFTER_MS * 3)?.cause).toContain("stale:"); | |
| 159 | }); | |
| 160 | ||
| 161 | test("a notice is claimed once per person and cause", () => { | |
| 162 | expect(claimNotice(app.db, admin.id, "drill:x")).toBe(true); | |
| 163 | expect(claimNotice(app.db, admin.id, "drill:x")).toBe(false); | |
| 164 | }); | |
| 165 | ||
| 166 | test("the service forgets the notices on green and wakes the notifier, through the real drill()", async () => { | |
| 167 | expect(claimNotice(app.db, admin.id, "drill:old")).toBe(true); | |
| 168 | const before = listEvents(app.db, { limit: 1000 }).filter((e) => e.kind === "drill.checked").length; | |
| 169 | await recordDrill(app.db, drill(new Date().toISOString())); | |
| 170 | expect(claimNotice(app.db, admin.id, "drill:old")).toBe(true); // forgotten, so claimable again | |
| 171 | const after = listEvents(app.db, { limit: 1000 }).filter((e) => e.kind === "drill.checked").length; | |
| 172 | expect(after).toBe(before + 1); | |
| 173 | }); | |
| 174 | ||
| 175 | test("a push that does not arrive gives its claim back and is tried again", async () => { | |
| 176 | healthy = false; | |
| 177 | await recordDrill(app.db, drill(new Date().toISOString(), "open")); | |
| 178 | expect(posts).toHaveLength(1); // tried once (the other process found the claim taken or the pause) | |
| 179 | expect(claimNotice(app.db, admin.id, drillNeed(app.db)!.cause)).toBe(true); | |
| 180 | app.db.query("DELETE FROM drill_notice").run(); | |
| 181 | healthy = true; | |
| 182 | clock += 2 * 3_600_000; // past the endpoint's pause | |
| 183 | await wake(); | |
| 184 | expect(posts.length).toBeGreaterThanOrEqual(2); | |
| 185 | expect(posts.at(-1)).toContain("open"); | |
| 186 | }); | |
| 187 | ||
| 188 | test("a forge with no snapshot store is never late, but a red drill still speaks", () => { | |
| 189 | const db = app.db; | |
| 190 | app.bus.append({ kind: "drill.checked", payload: {} }); | |
| 191 | expect(drillNeed(db, Date.now() + 30 * 86_400_000, false)).toBeNull(); | |
| 192 | expect(drillNeed(db, Date.now() + 30 * 86_400_000, true)).not.toBeNull(); | |
| 193 | keep(db, drill(new Date().toISOString(), "fetch")); | |
| 194 | expect(drillNeed(db, Date.now(), false)?.sentence).toContain("fetch"); | |
| 195 | }); | |
| 196 | ||
| 197 | test("the terminal's dashboard reads the same line", async () => { | |
| 198 | await recordDrill(app.db, drill(new Date().toISOString(), "count")); | |
| 199 | expect(forgeNeeds(app, admin)?.some((l) => l.includes("restore drill") && l.includes("count"))).toBe(true); | |
| 200 | }); | |
| 201 | ||
| 202 | test("the forge's age is read by key, never by scanning the events", () => { | |
| 203 | const plan = app.db | |
| 204 | .query<{ detail: string }, []>( | |
| 205 | "EXPLAIN QUERY PLAN SELECT created_at FROM event WHERE seq IS NOT NULL ORDER BY seq LIMIT 1", | |
| 206 | ) | |
| 207 | .all() | |
| 208 | .map((r) => r.detail) | |
| 209 | .join(" "); | |
| 210 | expect(plan).toContain("event_seq"); | |
| 211 | expect(plan).not.toMatch(/SCAN event(?! USING)/); | |
| 212 | }); | |
| 213 | }); |
test/vitals.test.ts +2 −2
| @@ -153,8 +153,8 @@ test("the number of queries does not grow with runs", () => { | ||
| 153 | 153 | if (i % 2) app.db.query("UPDATE run SET state='running' WHERE id=?1").run(r.id); |
| 154 | 154 | } |
| 155 | 155 | expect(count()).toBe(before); |
| 156 | // The queue, the running runs, the runs killed twice for their budget, and the lane's depth and finished checks. | |
| 157 | expect(before).toBe(5); | |
| 156 | // The queue, the running runs, the runs killed twice for their budget, and the lane's depth and finished checks, and the restore drill. | |
| 157 | expect(before).toBe(6); | |
| 158 | 158 | }); |
| 159 | 159 | |
| 160 | 160 | test("errors are counted, bounded, redacted, and a burst is said", async () => { |
new above
offline