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 #1718

Closed opened this
Closed without merging

scout/forge:scout/1183-a-red-restore-drill-or-none-in-eight-day → main 4 commits fork 3 threads · 3 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
13 files changed +401 −4
README.md +8
@@ -462,6 +462,14 @@ into scratch, opens it, counts what is there and unseals a value; the page
462462 waits for it, up to 10 minutes, and the last drill shows there as one line.
463463 Only one runs at a time. See `docs/SNAPSHOT.md`.
464464
465 A red drill, or none in eight days on a forge that has a snapshot store, is
466 one line for the forge admin, naming the step that failed: on the board's
467 forge strip, in the asks (`GET /api/v1/asks`, MCP `asks`), in `health`
468 (`degraded`/`needs`, MCP and API) and in the terminal dashboard, which reads
469 the same vitals. It clears on the next green drill. The admin's phone
470 (`notify_url`) hears it once per cause; a push that fails to arrive is tried
471 again at the next wake. The nightly runs a drill when the last is over six days old.
472
465473 `docs/EXTRACT.md` is the forge on a machine of its own, and the platform it
466474 grew up in switched off: what a host owes it, the moves in order, and what is
467475 given up.
scripts/gate.ts +1
@@ -227,6 +227,7 @@ export const GATE: readonly string[] = [
227227 "test/mcp.test.ts",
228228 "test/name-marks.test.ts",
229229 "test/new-forge.test.ts",
230 "test/drill-notice.test.ts",
230231 "test/notify.test.ts",
231232 "test/onboarding.test.ts",
232233 "test/org-owners.test.ts",
src/actions/health.ts +2
@@ -10,6 +10,7 @@
1010
1111 import type { App } from "../app.ts";
1212 import { appsRuntime } from "../apps/runtime.ts";
13 import { drillsOn } from "../snapshot/service.ts";
1314 import { listApps } from "../core/apps.ts";
1415 import type { User } from "../core/users.ts";
1516 import { forgeHealth, rolloutLine, type ForgeHealth } from "../kernel/guard.ts";
@@ -30,6 +31,7 @@ export function readHealth(
3031 dataDir: app.config.dataDir,
3132 envs,
3233 signals: app.signals,
34 drillsOn: drillsOn(app),
3335 });
3436 return { ...v, ...forge, ok: forge.ok && v.ok };
3537 }
src/core/schema.ts +10
@@ -1670,6 +1670,16 @@ export const migrations: readonly string[] = [
16701670 reason TEXT
16711671 );
16721672 `,
1673 // 81 — the pushes already sent about a restore drill (#1183). The primary key
1674 // is the claim: two processes inserting the same one, only one changes a row.
1675 `
1676 CREATE TABLE drill_notice (
1677 user_id TEXT NOT NULL,
1678 cause TEXT NOT NULL,
1679 at TEXT NOT NULL,
1680 PRIMARY KEY (user_id, cause)
1681 );
1682 `,
16731683 ];
16741684
16751685 /**
src/crew/notify.ts +28 −1
@@ -6,7 +6,8 @@
66 * the forge's admin a person who just joined — one
77 * short line and a link to the asks screen is posted there. A milestone
88 * 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`).
1011 *
1112 * What asks a person is read the way the asks panel reads it
1213 * (`askLinesFor`), as that person, so nothing private leaves for someone who
@@ -30,6 +31,8 @@ import { getUserSetting, setUserSetting } from "../core/settings.ts";
3031 import { getUserById } from "../core/users.ts";
3132 import { landedLines } from "../core/watches.ts";
3233 import { err, ok, type Result } from "../kernel/result.ts";
34 import { drillsOn } from "../snapshot/service.ts";
35 import { claimNotice, drillNeed, releaseNotice } from "../snapshot/drill_log.ts";
3336 import { askLinesFor } from "../web/studio/asks.ts";
3437
3538 const KEY = "notify_url";
@@ -53,6 +56,7 @@ const WAKES = new Set([
5356 "account.notify_set",
5457 "user.created",
5558 "mail.ceiling",
59 "drill.checked",
5660 ]);
5761
5862 export type NotifyUrlError =
@@ -161,6 +165,19 @@ export interface NotifyOptions {
161165 now?: () => number;
162166 }
163167
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
164181 const oneLine = (s: string): string =>
165182 // eslint-disable-next-line no-control-regex
166183 s.replace(/[\u0000-\u001f\u007f]+/g, " ").slice(0, 160);
@@ -200,6 +217,7 @@ export function startNotifier(app: App, options: NotifyOptions): Notifier {
200217 ...newAccountLines(app.db, user, now()),
201218 ...landedLines(app.db, user, now()),
202219 ...mailCeilingLines(app, user, now()),
220 ...drillLines(app, user, now()),
203221 ];
204222 const before = seen.get(userId);
205223 // 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 {
214232 sent.set(userId, recent);
215233 if (recent.length >= HOURLY) return;
216234 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.
outdated

The claim is taken before delivery. A failed send burns the one push for this cause. Release the claim on failure.

237 if (ask.items[0]?.startsWith("drill:") && !claimNotice(app.db, userId, ask.items[0], t))
238 continue;
217239 recent.push(t);
218240 let delivered = false;
219241 try {
@@ -229,6 +251,11 @@ export function startNotifier(app: App, options: NotifyOptions): Notifier {
229251 delivered = false;
230252 }
231253 if (!delivered) {
254 // A push that did not arrive was not told: give the claim back.
255 if (ask.items[0]?.startsWith("drill:")) {
256 releaseNotice(app.db, userId, ask.items[0]);
257 seen.get(userId)?.delete(ask.items[0]); // so the next wake tries it again
258 }
232259 const next = Math.min(
233260 pause.get(userId)?.next ?? BACKOFF_FIRST_MS,
234261 BACKOFF_MAX_MS,
src/kernel/vitals.ts +7
@@ -20,6 +20,7 @@ import {
2020 queueDepth,
2121 } from "../core/runs.ts";
2222 import { STALE_AFTER_MS } from "../runs/lease.ts";
23 import { drillNeed } from "../snapshot/drill_log.ts";
2324
2425 /** Free disk under this share of the volume is something to say. */
2526 export const DISK_FREE_MIN = 0.1;
@@ -91,6 +92,8 @@ export interface VitalsInput {
9192 /** Every environment the runtime holds, when one is up. */
9293 readonly envs?: readonly EnvCount[];
9394 readonly now?: number;
95 /** Whether the forge has a snapshot store: without one, no drill is late (`snapshot/service.ts`). */
96 readonly drillsOn?: boolean;
9497 /** The free-disk share below which the disk is a need; `DISK_FREE_MIN` unless a test says. */
9598 readonly diskFreeMin?: number;
9699 /** One forge's own signals (`App.signals`). */
@@ -297,6 +300,10 @@ export function vitals(input: VitalsInput): Vitals {
297300 "/settings/capacity#internal",
298301 );
299302
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
300307 for (const cause of firstSeen.keys())
301308 if (!degraded.some((d) => d.cause === cause)) firstSeen.delete(cause);
302309
src/main.ts +2 −1
@@ -20,7 +20,7 @@ import { resolveAppDomain } from "./apps/host.ts";
2020 import { requeueAbandonedChecks, startChecks } from "./checks/service.ts";
2121 import { startLooks } from "./looks/service.ts";
2222 import { startProbes } from "./contract/probes.ts";
23 import { startSnapshots } from "./snapshot/service.ts";
23 import { drillsOn, startSnapshots } from "./snapshot/service.ts";
2424 import { resolveDestination } from "./snapshot/destination.ts";
2525 import { releaseOrphans } from "./core/run_secret.ts";
2626 import { failAbandonedRuns } from "./core/runs.ts";
@@ -339,6 +339,7 @@ const tickAsks = async (): Promise<void> => {
339339 db: app.db,
340340 dataDir: app.config.dataDir,
341341 signals: app.signals,
342 drillsOn: drillsOn(app),
342343 }).degraded,
343344 Date.now(),
344345 app.log,
src/snapshot/drill_log.ts added +103
@@ -0,0 +1,103 @@
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 /** A green drill ends the story: a later red is a new cause that tells again. */
28 export function forgetNotices(db: Database): void {
29 db.query("DELETE FROM drill_notice").run();
30 }
31
32 /** The newest drill's time, or null when none ran. */
33 export function lastDrillAt(db: Database): string | null {
34 return (
35 db.query<{ at: string }, []>("SELECT at FROM drill ORDER BY id DESC LIMIT 1").get()?.at ?? null
36 );
37 }
38
39 /**
40 * Why the drill is a need now, or null when it is not. A forge with no
41 * snapshot store (`drillsOn`) has no drill to be late, so only a red one
42 * speaks for it. One read of four small subselects over indexed-by-id rows.
43 */
44 export function drillNeed(
45 db: Database,
46 now: number = Date.now(),
47 storeOn = true,
48 ): DrillNeed | null {
49 // One read however many drills there are: the newest, and the forge's age.
50 const row = db
51 .query<
52 { at: string | null; verdict: string | null; failed_step: string | null; born: string | null },
53 []
54 >(
55 `SELECT (SELECT at FROM drill ORDER BY id DESC LIMIT 1) AS at,
56 (SELECT verdict FROM drill ORDER BY id DESC LIMIT 1) AS verdict,
57 (SELECT failed_step FROM drill ORDER BY id DESC LIMIT 1) AS failed_step,
58 (SELECT MIN(created_at) FROM event) AS born`,
59 )
60 .get();
61 const last = row?.at != null ? { at: row.at, verdict: row.verdict, failed_step: row.failed_step } : null;
62 if (last?.verdict === "red")
63 return {
64 cause: `drill:red:${last.at}`,
65 sentence: `The last restore drill failed at the ${last.failed_step ?? "unknown"} step.`,
66 since: last.at,
67 };
outdated

With no snapshot store configured, this fires after 8 days and nothing can clear it. Gate it on a store existing.

68 if (!storeOn) return null;
69 // Without a drill on record, the forge's own age is the evidence.
70 const from = last?.at ?? row?.born ?? null;
71 if (from === null) return null;
72 const ran = Date.parse(from);
73 if (!Number.isFinite(ran) || now - ran <= STALE_AFTER_MS) return null;
74 return {
75 cause: `drill:stale:${last?.at ?? "none"}`,
76 sentence:
77 last === null
78 ? "No restore drill has run in 8 days."
79 : `No restore drill has run in 8 days; the last was ${last.at.slice(0, 10)}.`,
80 since: new Date(ran + STALE_AFTER_MS).toISOString(),
81 };
82 }
83
84 /** Take the claim back: the push did not arrive, so the next look may try again. */
85 export function releaseNotice(db: Database, userId: string, cause: string): void {
86 db.query("DELETE FROM drill_notice WHERE user_id = ?1 AND cause = ?2").run(userId, cause);
87 }
88
89 /** True once per person and cause, across processes. */
90 export function claimNotice(
91 db: Database,
92 userId: string,
93 cause: string,
94 now: number = Date.now(),
95 ): boolean {
96 return (
97 db
98 .query(
99 "INSERT OR IGNORE INTO drill_notice (user_id, cause, at) VALUES (?1, ?2, ?3)",
100 )
101 .run(userId, cause, new Date(now).toISOString()).changes === 1
102 );
103 }
src/snapshot/service.ts +24
@@ -20,12 +20,15 @@ import {
2020 } from "./snapshot.ts";
2121 import { runDrill, type DrillDeps, type DrillResult } from "./drill.ts";
2222 import { recordDrill } from "./drills.ts";
23 import { forgetNotices, lastDrillAt } from "./drill_log.ts";
2324 import type { Store } from "./store.ts";
2425
2526 const log = createLog("snapshots");
2627
2728 /** When the nightly snapshot is taken, in UTC: before the probe round. */
2829 const NIGHTLY_HOUR_UTC = 8;
30 /** A drill is due when the last is older than this: weekly, inside the eight days the board allows. */
31 const DRILL_EVERY_MS = 6 * 24 * 3_600_000;
2932
3033 export interface SnapshotsHandle {
3134 /** The store in effect now; undefined when the forge has been given none. */
@@ -42,6 +45,8 @@ export interface SnapshotsHandle {
4245 readonly last: () => { manifest?: Manifest; error?: string; at?: string };
4346 /** Drill the newest snapshot now and keep the result; waits for any snapshot in flight. */
4447 readonly drill: () => Promise<DrillResult>;
48 /** Drill unless one ran inside the last six days; what the nightly does after its snapshot. */
49 readonly drillIfDue: () => Promise<void>;
4550 /** Forget the resolved store; the next use resolves again (a new destination was saved). */
4651 readonly forget: () => void;
4752 readonly stop: () => Promise<void>;
@@ -51,6 +56,9 @@ const handles = new WeakMap<App, SnapshotsHandle>();
5156 export const snapshotsOf = (app: App): SnapshotsHandle | undefined =>
5257 handles.get(app);
5358
59 /** Whether this forge has somewhere to snapshot to, and so a drill to run. */
60 export const drillsOn = (app: App): boolean => snapshotsOf(app)?.store !== undefined;
61
5462 export function untilNightly(now = Date.now()): number {
5563 const next = new Date(now);
5664 next.setUTCHours(NIGHTLY_HOUR_UTC, 0, 0, 0);
@@ -139,6 +147,10 @@ export function startSnapshots(
139147 passphrase: options.passphrase,
140148 });
141149 recordDrill(app.db, result);
150 if (result.verdict === "green") forgetNotices(app.db);
151 else log.error("restore drill failed", { step: result.failedStep ?? "" });
152 // The need may have changed: let the notifier look.
153 app.bus.append({ kind: "drill.checked", payload: {} });
142154 return result;
143155 })().finally(() => {
144156 drilling = undefined;
@@ -146,12 +158,23 @@ export function startSnapshots(
146158 return drilling;
147159 };
148160
161 /** After the nightly: a drill when none ran in the last week; a failed one is already recorded. */
162 const drillIfDue = async (): Promise<void> => {
163 if (stopped) return;
164 const at = lastDrillAt(app.db);
165 if (at !== null && Date.now() - Date.parse(at) <= DRILL_EVERY_MS) return;
166 await drill().catch((error) =>
167 log.error("restore drill could not run", { error: String(error) }),
168 );
169 };
170
149171 let timer: ReturnType<typeof setTimeout> | undefined;
150172 const schedule = (): void => {
151173 if (options.nightly === false || stopped) return;
152174 timer = setTimeout(() => {
153175 take()
154176 .catch(() => {})
177 .then(drillIfDue)
155178 .finally(schedule);
156179 }, untilNightly());
157180 };
@@ -164,6 +187,7 @@ export function startSnapshots(
164187 wraps: !!options.passphrase,
165188 now: take,
166189 drill,
190 drillIfDue,
167191 list: async () => {
168192 const store = current();
169193 return store === undefined ? [] : listSnapshots(store);
src/web/pages/board.ts +2
@@ -14,6 +14,7 @@
1414 * pointer. The old big view (`/big`, every address it had) lands here.
1515 */
1616
17 import { drillsOn } from "../../snapshot/service.ts";
1718 import { sentinelNotice } from "../../crew/sentinel.ts";
1819 import { appsForRepos, type AppRecord } from "../../core/apps.ts";
1920 import { askMeasure } from "../../core/ask_ledger.ts";
@@ -329,6 +330,7 @@ function forgeStrip(ctx: Ctx): Html | null {
329330 db: app.db,
330331 dataDir: app.config.dataDir,
331332 signals: app.signals,
333 drillsOn: drillsOn(app),
332334 envs: runtime
333335 ? listApps(app.db).flatMap((record) => runtime.status(record))
334336 : [],
src/web/studio/asks.ts +2
@@ -7,6 +7,7 @@
77 * to the route a person could have posted to by hand (`actions.ts`).
88 */
99
10 import { drillsOn } from "../../snapshot/service.ts";
1011 import type { Database } from "bun:sqlite";
1112 import { needLine } from "../../actions/health.ts";
1213 import type { Degraded } from "../../kernel/vitals.ts";
@@ -965,6 +966,7 @@ export function forgeNeedsFor(ctx: Ctx, user: User | undefined): Degraded[] {
965966 db: ctx.app.db,
966967 dataDir: ctx.app.config.dataDir,
967968 signals: ctx.app.signals,
969 drillsOn: drillsOn(ctx.app),
968970 envs,
969971 }).degraded;
970972 }
test/drill-notice.test.ts added +210
@@ -0,0 +1,210 @@
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";
outdated

This wrapper re-implements the service. Remove it and test the real path (see point 1).

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 reason: failedStep === null ? null : "boom",
32 });
33
34 describe("the restore drill as a need", () => {
35 let dataDir: string;
36 let app: App;
37 let admin: User;
38 let notifiers: Notifier[] = [];
39 let svc: SnapshotsHandle;
40 let next: DrillResult;
41 let ran = 0;
42 let healthy = true;
43 let clock = Date.now();
44 /** A drill, the way the service takes one: run, kept, notices forgotten on green, the notifier woken. */
45 const recordDrill = async (_db: App["db"], r: DrillResult): Promise<void> => {
46 next = r;
47 await svc.drill();
48 for (const n of notifiers) await n.settled();
49 };
50 const posts: string[] = [];
51 const send = async (_url: string, body: string) => {
52 posts.push(body);
53 return healthy;
54 };
55 const lines = () =>
56 (readHealth(app, admin) as Vitals).degraded.filter((d) => d.cause.startsWith("drill:"));
57 const wake = async () => {
58 app.bus.append({ kind: "drill.checked", payload: {} });
59 for (const n of notifiers) await n.settled();
60 };
61
62 beforeAll(async () => {
63 dataDir = await mkdtemp(join(tmpdir(), "forge-drill-"));
64 app = createApp({ dataDir, port: 0 });
65 const made = await createUser(app.db, {
66 trusted: true,
67 username: "keeper",
68 email: "[email protected]",
69 password: "a-good-passphrase",
70 adminIfFirst: true,
71 });
72 if (!made.ok) throw new Error(made.error);
73 admin = made.value;
74 svc = startSnapshots(app, dirStore(join(dataDir, "store")), {
75 version: "t",
76 nightly: false,
77 drill: async () => {
78 ran++;
79 return next;
80 },
81 });
82 setNotifyUrl(app.db, admin.id, "https://ntfy.example.test/owner-topic");
83 // Two processes looking at one database.
84 for (let i = 0; i < 2; i++) {
85 const n = startNotifier(app, { forgeUrl: "https://forge.example.test", send, now: () => clock });
86 await n.settled();
87 notifiers.push(n);
88 }
89 });
90 // Each test stands alone, whatever order they run in.
91 beforeEach(() => {
92 app.db.query("DELETE FROM drill").run();
93 app.db.query("DELETE FROM drill_notice").run();
94 posts.length = 0;
95 ran = 0;
96 healthy = true;
97 });
98 afterAll(async () => {
99 await svc.stop();
100 for (const n of notifiers) n.stop();
101 await rm(dataDir, { recursive: true, force: true });
102 });
103
104 test("a fresh forge with no drill yet says nothing", () => {
105 expect(lines()).toHaveLength(0);
106 });
107
108 test("a red drill is one line naming the step, and one push across two processes and many ticks", async () => {
109 await recordDrill(app.db, drill(new Date().toISOString(), "unseal"));
110 const found = lines();
111 expect(found).toHaveLength(1);
112 expect(found[0]!.sentence).toContain("unseal");
113 expect(found[0]!.href).toBe("/settings/backups");
114 await wake();
115 await wake();
116 await wake();
117 expect(posts).toHaveLength(1);
118 expect(posts[0]).toContain("unseal");
119 });
120
121 test("the line is in the asks and in the health answer", async () => {
122 await recordDrill(app.db, drill(new Date().toISOString(), "unseal"));
123 const ctx = { app } as unknown as Ctx;
124 expect(forgeNeedsFor(ctx, admin).some((d) => d.sentence.includes("unseal"))).toBe(true);
125 expect(asksAnswer(ctx, admin).forge.some((l) => l.includes("restore drill"))).toBe(true);
126 expect((readHealth(app, admin) as Vitals).needs.some((l) => l.includes("restore drill"))).toBe(true);
127 });
128
129 test("a green drill clears the line, and a later red tells again", async () => {
130 await recordDrill(app.db, drill(new Date().toISOString(), "unseal"));
131 await wake();
132 expect(posts).toHaveLength(1);
133 await recordDrill(app.db, drill(new Date(Date.now() + 1000).toISOString()));
134 expect(lines()).toHaveLength(0);
135 await wake();
136 expect(posts).toHaveLength(1);
137 await recordDrill(app.db, drill(new Date(Date.now() + 2000).toISOString(), "restore"));
138 await wake();
139 expect(posts).toHaveLength(2);
140 expect(posts[1]).toContain("restore");
141 });
142
143 test("eight days with none is a line, once; before that it is not", async () => {
144 const db = app.db;
145 // The forge's age is its oldest event.
146 app.bus.append({ kind: "drill.checked", payload: {} });
147 const born = (db.query("SELECT MIN(created_at) AS at FROM event").get() as { at: string }).at;
148 const t = Date.parse(born);
149 expect(drillNeed(db, t + STALE_AFTER_MS - 1000)).toBeNull();
150 const need = drillNeed(db, t + STALE_AFTER_MS + 1000);
151 expect(need?.sentence).toContain("8 days");
152 // The same cause keeps one key however late it is asked.
153 expect(drillNeed(db, t + STALE_AFTER_MS * 2)?.cause).toBe(need!.cause);
154 // A green drill inside the window clears it.
155 await recordDrill(db, drill(new Date(t + STALE_AFTER_MS).toISOString()));
156 expect(drillNeed(db, t + STALE_AFTER_MS + 1000)).toBeNull();
157 expect(drillNeed(db, t + STALE_AFTER_MS * 3)?.cause).toContain("stale:");
158 });
159
160 test("a notice is claimed once per person and cause", () => {
161 expect(claimNotice(app.db, admin.id, "drill:x")).toBe(true);
162 expect(claimNotice(app.db, admin.id, "drill:x")).toBe(false);
163 });
164
165 test("the service forgets the notices on green and wakes the notifier, through the real drill()", async () => {
166 expect(claimNotice(app.db, admin.id, "drill:old")).toBe(true);
167 const before = listEvents(app.db, { limit: 1000 }).filter((e) => e.kind === "drill.checked").length;
168 await recordDrill(app.db, drill(new Date().toISOString()));
169 expect(claimNotice(app.db, admin.id, "drill:old")).toBe(true); // forgotten, so claimable again
170 const after = listEvents(app.db, { limit: 1000 }).filter((e) => e.kind === "drill.checked").length;
171 expect(after).toBe(before + 1);
172 });
173
174 test("a push that does not arrive gives its claim back and is tried again", async () => {
175 healthy = false;
176 await recordDrill(app.db, drill(new Date().toISOString(), "open"));
177 expect(posts).toHaveLength(1); // tried once (the other process found the claim taken or the pause)
178 expect(claimNotice(app.db, admin.id, drillNeed(app.db)!.cause)).toBe(true);
179 app.db.query("DELETE FROM drill_notice").run();
180 healthy = true;
181 clock += 2 * 3_600_000; // past the endpoint's pause
182 await wake();
183 expect(posts.length).toBeGreaterThanOrEqual(2);
184 expect(posts.at(-1)).toContain("open");
185 });
186
187 test("the nightly drills only when the last is older than six days", async () => {
188 keep(app.db, drill(new Date(Date.now() - 2 * 86_400_000).toISOString()));
189 next = drill(new Date().toISOString());
190 await svc.drillIfDue();
191 expect(ran).toBe(0);
192 keep(app.db, drill(new Date(Date.now() - 7 * 86_400_000).toISOString()));
193 await svc.drillIfDue();
194 expect(ran).toBe(1);
195 });
196
197 test("a forge with no snapshot store is never late, but a red drill still speaks", () => {
198 const db = app.db;
199 app.bus.append({ kind: "drill.checked", payload: {} });
200 expect(drillNeed(db, Date.now() + 30 * 86_400_000, false)).toBeNull();
201 expect(drillNeed(db, Date.now() + 30 * 86_400_000, true)).not.toBeNull();
202 keep(db, drill(new Date().toISOString(), "fetch"));
203 expect(drillNeed(db, Date.now(), false)?.sentence).toContain("fetch");
204 });
205
206 test("the terminal's dashboard reads the same line", async () => {
207 await recordDrill(app.db, drill(new Date().toISOString(), "count"));
208 expect(forgeNeeds(app, admin)?.some((l) => l.includes("restore drill") && l.includes("count"))).toBe(true);
209 });
210 });
test/vitals.test.ts +2 −2
@@ -153,8 +153,8 @@ test("the number of queries does not grow with runs", () => {
153153 if (i % 2) app.db.query("UPDATE run SET state='running' WHERE id=?1").run(r.id);
154154 }
155155 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);
158158 });
159159
160160 test("errors are counted, bounded, redacted, and a burst is said", async () => {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs