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

A weekly restore drill: the newest snapshot restored into an empty directory, opened and its sealed values read, the verdict on the Backups page #1189

Closed opened this
Closed without merging

scout/forge:scout/1182-a-weekly-restore-drill-the-newest-snapsh → main 2 commits fork 4 threads · 4 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
10 files changed +724 −3
docs/SNAPSHOT.md +21
@@ -96,3 +96,24 @@ sealed variable and an app's SQLite is snapshotted, restored into an empty
9696 directory with the passphrase and booted there as the same forge; restored
9797 without it, the repositories come back and the sealed variable is reported by
9898 name. It also checks that the raw key is in no file of the store.
99
100 ## The restore drill
101
102 A backup is real once a restore of it is proven. Every Sunday at 09:00 UTC
103 (an hour after the nightly), and on demand from **Settings → Backups → Run
104 restore drill**, the forge takes the newest snapshot, restores it into a
105 fresh directory under `$FORGE_APP_DATA/drill/`, opens the database, counts
106 repositories and issues, opens one sealed value with the restored key, and
107 deletes the directory. `src/snapshot/drill.ts`.
108
109 Each drill is a record (when, snapshot, duration, counts, verdict, and for a
110 red one the step and why) kept in `snapshot-drills.json` (the last twenty).
111 The Backups page shows the latest in one line.
112
113 A red verdict names its step: `fetch` (no snapshot, or the store will not
114 answer), `disk` (free space under twice the snapshot's size: the drill
115 refuses to start), `restore` (including a wrong passphrase), `open`,
116 `count`, `unseal` (the key did not come back, or a value would not open), or
117 `timeout` (15 minutes with no verdict; the restore is stopped and the
118 directory removed). A forge with no sealed values has nothing to read and is
119 still green.
src/actions/health.ts +12 −2
@@ -12,13 +12,21 @@ 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 { snapshotsOf } from "../snapshot/service.ts";
1516 import { forgeHealth, type ForgeHealth } from "../kernel/guard.ts";
1617 import { vitals, type Vitals } from "../kernel/vitals.ts";
1718
19 /** The last restore drill, as an admin sees it in health. */
20 export interface DrillHealth {
21 readonly at: string;
22 readonly ok: boolean;
23 readonly step: string | null;
24 }
25
1826 export function readHealth(
1927 app: App,
2028 actor: User | undefined,
21 ): ForgeHealth | (Vitals & ForgeHealth) {
29 ): ForgeHealth | (Vitals & ForgeHealth & { drill: DrillHealth | null }) {
2230 const forge = forgeHealth();
2331 if (!actor?.isAdmin) return forge;
2432 const runtime = appsRuntime(app);
@@ -26,5 +34,7 @@ export function readHealth(
2634 ? listApps(app.db).flatMap((record) => runtime.status(record))
2735 : [];
2836 const v = vitals({ db: app.db, dataDir: app.config.dataDir, envs });
29 return { ...v, ...forge, ok: forge.ok && v.ok };
37 const last = snapshotsOf(app)?.lastDrill();
38 const drill = last ? { at: last.at, ok: last.ok, step: last.step ?? null } : null;
39 return { ...v, ...forge, ok: forge.ok && v.ok, drill };
3040 }
src/http/mcp.ts +22
@@ -109,6 +109,7 @@ import {
109109 parseExploreQuery,
110110 } from "../actions/explore.ts";
111111 import { frontInput, frontJson, setFront } from "../actions/front.ts";
112 import { snapshotsOf } from "../snapshot/service.ts";
112113 import { readHealth } from "../actions/health.ts";
113114 import { running } from "../kernel/version.ts";
114115 import { COPIES_PER_DAY, makeItYours } from "../actions/make_it_yours.ts";
@@ -593,6 +594,27 @@ const TOOLS: readonly Tool[] = [
593594 writes: false,
594595 run: (ctx, user) => good(readHealth(ctx.app, user)),
595596 },
597 {
598 name: "restore_drill",
599 description:
600 "Start a restore drill (a site admin's): the newest snapshot is restored into a scratch directory, opened and read, then removed. It runs in the background; the verdict is `drill: {at, ok, step}` in `health`, and on the Backups page.",
601 inputSchema: { type: "object", properties: {} },
602 writes: true,
603 run(ctx, user) {
604 if (!user.isAdmin)
605 return bad("forbidden", "only an admin of this forge starts a restore drill");
606 const svc = snapshotsOf(ctx.app);
607 const started = svc?.startDrill() ?? "nowhere";
608 return started === "nowhere"
609 ? bad("unavailable", "this forge has nowhere to restore a snapshot from")
610 : good({
611 says:
612 started === "started"
613 ? "Restore drill started; read the verdict in health."
614 : "A restore drill is already running.",
615 });
616 },
617 },
596618 {
597619 name: "audit",
598620 description:
src/http/server.ts +2
@@ -87,6 +87,7 @@ import { secretDelete, secretSet, secretsPage } from "../web/pages/secrets.ts";
8787 import {
8888 backupsClear,
8989 backupsDestination,
90 backupsDrill,
9091 backupsNow,
9192 backupsPage,
9293 backupsTest,
@@ -650,6 +651,7 @@ export function buildRouter(): Router<Handler> {
650651 router.add("POST", "/settings/capacity", capacitySet);
651652 router.add("GET", "/settings/backups", backupsPage);
652653 router.add("POST", "/settings/backups/now", backupsNow);
654 router.add("POST", "/settings/backups/drill", backupsDrill);
653655 router.add("POST", "/settings/backups/destination", backupsDestination);
654656 router.add("POST", "/settings/backups/test", backupsTest);
655657 router.add("POST", "/settings/backups/clear", backupsClear);
src/snapshot/drill.ts added +252
@@ -0,0 +1,252 @@
1 /**
2 * The restore drill: a backup is real once a restore of it is proven. The
3 * newest snapshot is restored into a fresh directory, its database opened,
4 * repositories and issues counted, one sealed value read; then the
5 * directory goes. Every outcome is a record with a verdict, and a failure
6 * names the step it failed at. A hang ends as a red verdict at the
7 * timeout, never as a stuck job.
8 *
9 * Records are one JSON file under the data directory (the last few kept).
10 */
11
12 import {
13 existsSync,
14 mkdirSync,
15 readdirSync,
16 readFileSync,
17 rmSync,
18 statfsSync,
19 } from "node:fs";
20 import { join } from "node:path";
21 import { forgetKey, open } from "../kernel/secret.ts";
22 import { restoreSnapshot } from "./restore.ts";
23 import { listSnapshots } from "./snapshot.ts";
24 import type { Store } from "./store.ts";
25
26 export type DrillStep =
27 | "fetch"
28 | "disk"
29 | "restore"
30 | "open"
31 | "count"
32 | "unseal"
33 | "timeout";
34
35 export interface DrillRecord {
36 readonly at: string;
37 readonly snapshot: string | null;
38 readonly ms: number;
39 readonly repos: number;
40 readonly issues: number;
41 /** Sealed values read: 0 or 1 (a forge with none has nothing to read). */
42 readonly sealed: number;
43 readonly ok: boolean;
44 /** The step that failed, when the verdict is red. */
45 readonly step?: DrillStep;
46 readonly error?: string;
47 }
48
49 export const DRILL_TIMEOUT_MS = 15 * 60_000;
50 const KEEP_RECORDS = 20;
51 const FILE = "snapshot-drills.json";
52
53 export interface DrillInput {
54 readonly store: Store;
55 readonly dataDir: string;
56 readonly passphrase?: string | undefined;
57 readonly timeoutMs?: number;
58 /** Ends the drill early, as a red verdict at `timeout` (the forge is stopping). */
59 readonly signal?: AbortSignal;
60 /** Test seam: the free bytes on the disk the drill works on. */
61 readonly freeBytes?: () => number;
62 readonly now?: () => Date;
63 }
64
65 class StepError extends Error {
66 constructor(
67 readonly step: DrillStep,
68 message: string,
69 ) {
70 super(message);
71 }
72 }
73
74 const message = (e: unknown): string =>
75 (e instanceof Error ? e.message : String(e)).slice(0, 500);
76
77 /** Every drill on record, newest first. */
78 export function drillRecords(dataDir: string): DrillRecord[] {
79 try {
80 const all = JSON.parse(readFileSync(join(dataDir, FILE), "utf8"));
81 return Array.isArray(all) ? (all as DrillRecord[]) : [];
82 } catch {
83 return [];
84 }
85 }
86
87 async function remember(dataDir: string, record: DrillRecord): Promise<void> {
88 const all = [record, ...drillRecords(dataDir)].slice(0, KEEP_RECORDS);
89 await Bun.write(join(dataDir, FILE), JSON.stringify(all));
90 }
91
92 /** One sealed value, opened with the restored key; the count read (0 or 1). */
93 async function readOneSealed(dir: string): Promise<number> {
94 const { Database } = await import("bun:sqlite");
95 const db = new Database(join(dir, "forge.db"), { readonly: true });
96 try {
97 const secret = db
98 .query<{ name: string; scope: string; value_enc: string }, []>(
99 "SELECT name, scope, value_enc FROM secret LIMIT 1",
100 )
101 .get();
102 const env = db
103 .query<{ app_id: string; name: string; value_enc: string }, []>(
104 "SELECT app_id, name, value_enc FROM app_env LIMIT 1",
105 )
106 .get();
107 const [sealed, aad] = secret
108 ? [secret.value_enc, `secret:${secret.scope}:${secret.name}`]
109 : env
110 ? [env.value_enc, `${env.app_id}:${env.name}`]
111 : [undefined, ""];
112 if (sealed === undefined) return 0;
113 if (!existsSync(join(dir, "secret.key")))
114 throw new StepError(
115 "unseal",
116 "the key did not come back (no passphrase, or a snapshot taken without one), so sealed values cannot be read",
117 );
118 forgetKey(dir);
119 const opened = open(dir, sealed, aad);
120 forgetKey(dir);
121 if (!opened.ok)
122 throw new StepError("unseal", "a sealed value would not open with the restored key");
123 return 1;
124 } finally {
125 db.close();
126 }
127 }
128
129 export async function runDrill(input: DrillInput): Promise<DrillRecord> {
130 const now = input.now ?? (() => new Date());
131 const started = Date.now();
132 const at = now().toISOString();
133 const abort = new AbortController();
134 let snapshot: string | null = null;
135 let repos = 0;
136 let issues = 0;
137 let sealed = 0;
138 let dir: string | undefined;
139 let timer: ReturnType<typeof setTimeout> | undefined;
140
141 const work = async (): Promise<void> => {
142 let newest;
143 try {
144 newest = (await listSnapshots(input.store))[0];
145 } catch (e) {
146 throw new StepError("fetch", `the store could not be listed: ${message(e)}`);
147 }
148 if (newest === undefined)
149 throw new StepError("fetch", "the store holds no snapshot to restore");
150 snapshot = newest.name;
151 const root = join(input.dataDir, "drill");
152 mkdirSync(root, { recursive: true });
153 // A drill that timed out may have left a tree a late write recreated.
154 for (const old of readdirSync(root))
155 rmSync(join(root, old), { recursive: true, force: true });
156 const free =
157 input.freeBytes?.() ??
158 (() => {
159 const s = statfsSync(root);
160 return s.bavail * s.bsize;
161 })();
162 if (free < 2 * newest.bytes)
163 throw new StepError(
164 "disk",
165 `refused to start: ${free} bytes free, under twice the snapshot's ${newest.bytes}`,
166 );
167 dir = join(root, `${newest.name}-${crypto.randomUUID().slice(0, 8)}`);
168 try {
169 await restoreSnapshot(input.store, newest.name, dir, {
170 passphrase: input.passphrase,
171 signal: abort.signal,
172 });
173 } catch (e) {
174 throw new StepError("restore", message(e));
175 }
176 const { Database } = await import("bun:sqlite");
177 let db: InstanceType<typeof Database>;
178 try {
179 db = new Database(join(dir, "forge.db"), { readonly: true });
180 db.query("SELECT count(*) FROM sqlite_master").get();
181 } catch (e) {
182 throw new StepError("open", message(e));
183 }
184 try {
185 repos = db.query<{ n: number }, []>("SELECT count(*) AS n FROM repo").get()!.n;
186 issues = db.query<{ n: number }, []>("SELECT count(*) AS n FROM issue").get()!.n;
187 } catch (e) {
188 throw new StepError("count", message(e));
189 } finally {
190 db.close();
191 }
192 try {
193 sealed = await readOneSealed(dir);
194 } catch (e) {
195 throw e instanceof StepError ? e : new StepError("unseal", message(e));
196 }
197 };
198
199 let failure: StepError | undefined;
200 const stopping = (): void => abort.abort();
201 input.signal?.addEventListener("abort", stopping, { once: true });
202 const job = work();
203 // If the timeout wins, the job may still settle later; its error is moot.
204 job.catch(() => {});
205 try {
206 await Promise.race([
207 job,
208 new Promise<never>((_, reject) => {
209 const stop = (): void =>
210 reject(new StepError("timeout", "stopped: the forge is shutting down"));
211 if (input.signal?.aborted) stop();
212 else input.signal?.addEventListener("abort", stop, { once: true });
213 }),
214 new Promise<never>((_, reject) => {
215 timer = setTimeout(
outdated

On timeout this runs while the aborted restore may still be in the middle of a Bun.write, and that call recreates parent directories. Sweep drill/ of old entries when a drill starts, so a leftover from a timed-out run cannot pile up.

216 () => reject(new StepError("timeout", "")),
217 input.timeoutMs ?? DRILL_TIMEOUT_MS,
218 );
219 }),
220 ]);
221 } catch (e) {
222 failure =
223 e instanceof StepError
224 ? e
225 : new StepError("restore", message(e));
226 if (failure.step === "timeout") {
227 abort.abort();
228 failure = new StepError(
229 "timeout",
230 input.signal?.aborted
231 ? `stopped (the forge is shutting down) while ${snapshot === null ? "fetching the newest snapshot" : `restoring ${snapshot}`}`
232 : `no verdict in ${Math.round((input.timeoutMs ?? DRILL_TIMEOUT_MS) / 1000)}s; stopped while ${snapshot === null ? "fetching the newest snapshot" : `restoring ${snapshot}`}`,
233 );
234 }
235 } finally {
236 clearTimeout(timer);
237 input.signal?.removeEventListener("abort", stopping);
238 if (dir !== undefined) rmSync(dir, { recursive: true, force: true });
239 }
240 const record: DrillRecord = {
241 at,
242 snapshot,
243 ms: Date.now() - started,
244 repos,
245 issues,
246 sealed,
247 ok: failure === undefined,
248 ...(failure === undefined ? {} : { step: failure.step, error: failure.message }),
249 };
250 await remember(input.dataDir, record);
251 return record;
252 }
src/snapshot/restore.ts +7 −1
@@ -68,7 +68,11 @@ export async function restoreSnapshot(
6868 store: Store,
6969 name: string,
7070 dataDir: string,
71 options: { readonly passphrase?: string | undefined } = {},
71 options: {
72 readonly passphrase?: string | undefined;
73 /** Stops the restore between files (the drill's timeout). */
74 readonly signal?: AbortSignal | undefined;
75 } = {},
7276 ): Promise<Restored> {
7377 if (!/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}-[0-9]{2}-[0-9]{2}Z$/.test(name))
7478 throw new Error(`not a snapshot name: ${name}`);
@@ -100,7 +104,9 @@ export async function restoreSnapshot(
100104 let repos = 0;
101105 const bundles: { owner: string; name: string; file: string }[] = [];
102106 for (const entry of manifest.files) {
107 options.signal?.throwIfAborted();
103108 const body = await store.get(prefix + entry.path);
109 options.signal?.throwIfAborted();
104110 if (body === undefined)
105111 throw new Error(`snapshot ${name} is missing ${entry.path}`);
106112 if (body.byteLength !== entry.bytes)
src/snapshot/service.ts +78
@@ -17,10 +17,15 @@ import {
1717 takeSnapshot,
1818 type Manifest,
1919 } from "./snapshot.ts";
20 import { drillRecords, runDrill, type DrillRecord } from "./drill.ts";
2021 import type { Store } from "./store.ts";
2122
2223 const log = createLog("snapshots");
2324
25 /** The weekly restore drill: Sundays, an hour after the nightly snapshot. */
26 const DRILL_DAY_UTC = 0;
27 const DRILL_HOUR_UTC = 9;
28
2429 /** When the nightly snapshot is taken, in UTC: before the probe round. */
2530 const NIGHTLY_HOUR_UTC = 8;
2631
@@ -33,6 +38,14 @@ export interface SnapshotsHandle {
3338 readonly now: () => Promise<Manifest>;
3439 /** The newest first, from the store. */
3540 readonly list: () => Promise<Manifest[]>;
41 /** Restore the newest snapshot into a scratch directory and say what came of it. */
42 readonly drill: () => Promise<DrillRecord>;

#1182 asks for this through MCP too: health carries drill: {at, verdict, step}, and an admin can start a drill from MCP. Neither is wired into src/http/mcp.ts.

43 /** Start one in the background: it ran at once, one was already running, or there is no store. */
44 readonly startDrill: () => "started" | "running" | "nowhere";
45 /** When the drill in flight began, if one is. */
46 readonly drillingSince: () => string | undefined;
47 /** The last drill, from the record on disk. */
48 readonly lastDrill: () => DrillRecord | undefined;
3649 /** The last one taken by this process, and what it said. */
3750 readonly last: () => { manifest?: Manifest; error?: string; at?: string };
3851 /** Forget the resolved store; the next use resolves again (a new destination was saved). */
@@ -51,6 +64,16 @@ export function untilNightly(now = Date.now()): number {
5164 return next.getTime() - now;
5265 }
5366
67 export function untilDrill(now = Date.now()): number {
68 const next = new Date(now);
69 next.setUTCHours(DRILL_HOUR_UTC, 0, 0, 0);
70 next.setUTCDate(
71 next.getUTCDate() + ((DRILL_DAY_UTC - next.getUTCDay() + 7) % 7),
72 );
73 if (next.getTime() <= now) next.setUTCDate(next.getUTCDate() + 7);
74 return next.getTime() - now;
75 }
76
5477 export function startSnapshots(
5578 app: App,
5679 destination: Store | (() => Store | undefined),
@@ -58,6 +81,7 @@ export function startSnapshots(
5881 readonly version: string;
5982 readonly nightly?: boolean;
6083 readonly passphrase?: string | undefined;
84 readonly drillTimeoutMs?: number;
6185 } = {
6286 version: "0",
6387 },
@@ -119,6 +143,53 @@ export function startSnapshots(
119143 };
120144 schedule();
121145
146 let drilling: Promise<DrillRecord> | undefined;
147 let drillSince: string | undefined;
148 const drillAbort = new AbortController();
149 const drill = (): Promise<DrillRecord> => {
150 if (drilling === undefined) drillSince = new Date().toISOString();
151 drilling ??= (async () => {
152 const store = current();
153 if (store === undefined)
154 throw new Error("this forge has nowhere to restore a snapshot from");
155 const record = await runDrill({
156 store,
157 dataDir: app.config.dataDir,
158 passphrase: options.passphrase,
159 signal: drillAbort.signal,
160 ...(options.drillTimeoutMs === undefined
161 ? {}
162 : { timeoutMs: options.drillTimeoutMs }),
163 });
164 if (!record.ok)
165 log.error("restore drill failed", {
166 step: record.step,
167 error: record.error,
168 });
169 return record;
170 })().finally(() => {
171 drilling = undefined;
172 drillSince = undefined;
173 });
174 return drilling;
175 };
176 const startDrill = (): "started" | "running" | "nowhere" => {
177 if (drilling !== undefined) return "running";
178 if (current() === undefined) return "nowhere";
179 drill().catch(() => {});
180 return "started";
181 };
182 let drillTimer: ReturnType<typeof setTimeout> | undefined;
183 const scheduleDrill = (): void => {
184 if (options.nightly === false || stopped) return;
185 drillTimer = setTimeout(() => {
186 drill()
187 .catch(() => {})
188 .finally(scheduleDrill);
189 }, untilDrill());
190 };
191 scheduleDrill();
192
122193 const handle: SnapshotsHandle = {
123194 get store() {
124195 return current();
@@ -129,6 +200,10 @@ export function startSnapshots(
129200 const store = current();
130201 return store === undefined ? [] : listSnapshots(store);
131202 },
203 drill,
204 startDrill,
205 drillingSince: () => drillSince,
206 lastDrill: () => drillRecords(app.config.dataDir)[0],
132207 last: () => last,
133208 forget: () => {
134209 resolved = undefined;
@@ -136,6 +211,9 @@ export function startSnapshots(
136211 stop: async () => {
137212 stopped = true;
138213 if (timer !== undefined) clearTimeout(timer);
214 if (drillTimer !== undefined) clearTimeout(drillTimer);
215 drillAbort.abort();
216 if (drilling !== undefined) await drilling.catch(() => {});
139217 if (inFlight !== undefined) await inFlight.catch(() => {});
140218 if (handles.get(app) === handle) handles.delete(app);
141219 },
src/web/pages/backups.ts +55
@@ -16,6 +16,7 @@ import {
1616 } from "../../actions/destination.ts";
1717 import { resolveDestination, sealedSet } from "../../snapshot/destination.ts";
1818 import { keyOf } from "../../snapshot/snapshot.ts";
19 import type { DrillRecord } from "../../snapshot/drill.ts";
1920 import { snapshotsOf } from "../../snapshot/service.ts";
2021 import type { Ctx } from "../../http/context.ts";
2122 import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts";
@@ -84,6 +85,32 @@ function keyNote(
8485 </p>`;
8586 }
8687
88 /** The last restore drill in one line: green with its counts, red with the step. */
89 function drillLine(d: DrillRecord | undefined, since?: string): Html {
90 if (since !== undefined)
91 return html`<p class="muted">
92 ${icon("clock")} Restore drill running since ${time(since)}; reload for
93 the verdict.
94 </p>`;
95 if (d === undefined)
96 return html`<p class="muted">
97 ${icon("clock")} No restore drill yet; one runs every Sunday, or press the
98 button.
99 </p>`;
100 const secs = (d.ms / 1000).toFixed(1);
101 return d.ok
102 ? html`<p>
103 ${icon("check")} Restore drill ${time(d.at)}: ${d.snapshot} restored and
104 opened in ${secs}s — ${d.repos} repositories, ${d.issues} issues,
105 ${d.sealed === 1 ? "a sealed value read" : "no sealed values to read"}.
106 </p>`
107 : html`<p class="backups-error">
108 ${icon("alert")} Restore drill ${time(d.at)} failed at
109 <strong>${d.step}</strong>${d.snapshot ? html` (${d.snapshot})` : ""}
110 after ${secs}s: ${d.error}
111 </p>`;
112 }
113
87114 export async function backupsPage(ctx: Ctx): Promise<Response> {
88115 const denied = requireAdmin(ctx);
89116 if (denied) return denied;
@@ -137,12 +164,16 @@ bun run src/snapshot/restore.ts ${snapshots[0].name} /path/to/empty/data</pre>`
137164 ${icon("alert")} The store could not be listed just now: ${error}
138165 </p>`,
139166 )}
167 ${drillLine(svc.lastDrill(), svc.drillingSince())}
140168 <form method="post" action="/settings/backups/now" class="backups-now">
141169 ${btn("Snapshot now", {
142170 type: "submit",
143171 variant: "primary",
144172 icon: "download",
145173 })}
174 <button class="btn" type="submit" formaction="/settings/backups/drill">
175 Run restore drill
176 </button>
146177 </form>`,
147178 {
148179 head: html`${icon("download")}
@@ -356,3 +387,27 @@ export async function backupsNow(ctx: Ctx): Promise<Response> {
356387 });
357388 }
358389 }
390
391 /** POST /settings/backups/drill — restore the newest snapshot as a proof, and say what came of it. */
392 export async function backupsDrill(ctx: Ctx): Promise<Response> {
393 const denied = requireAdmin(ctx);
394 if (denied) return denied;
395 const form = await readForm(ctx, "admin");
396 if (form instanceof Response) return form;
397 const svc = snapshotsOf(ctx.app);
398 if (svc === undefined)
399 return flashTo(ctx, "/settings/backups", {
outdated

This awaits the full drill inside the request, which can take up to DRILL_TIMEOUT_MS (15 min). Start it in the background (void svc.drill()), redirect at once with "drill started", and show the running state on the page.

400 tone: "danger",
401 message: "This forge has no snapshots to restore.",
402 });
403 const started = svc.startDrill();
404 return flashTo(ctx, "/settings/backups", {
405 tone: started === "nowhere" ? "danger" : "success",
406 message:
407 started === "started"
408 ? "Restore drill started; the verdict appears here when it is done."
409 : started === "running"
410 ? "A restore drill is already running."
411 : "This forge has nowhere to restore a snapshot from.",
412 });
413 }
test/snapshot-drill.test.ts added +157
@@ -0,0 +1,157 @@
1 /**
2 * The restore drill: green over a real snapshot, and red — naming the step —
3 * for a wrong passphrase, a missing snapshot, a hang and a full disk. The
4 * scratch directory is gone in every case.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { existsSync, mkdirSync, mkdtempSync, readdirSync } from "node:fs";
8 import { rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createRepo } from "../src/actions/repos.ts";
12 import { setAppEnvVar, enableApp } from "../src/actions/apps.ts";
13 import { createApp, type App } from "../src/app.ts";
14 import { createUser } from "../src/core/users.ts";
15 import { drillRecords, runDrill } from "../src/snapshot/drill.ts";
16 import { untilDrill } from "../src/snapshot/service.ts";
17 import { takeSnapshot } from "../src/snapshot/snapshot.ts";
18 import { dirStore, type Store } from "../src/snapshot/store.ts";
19
20 const PASS = "correct horse battery staple";
21
22 describe("the restore drill", () => {
23 let root: string;
24 let app: App;
25 let work: string;
26 const store = () => dirStore(join(root, "store"));
27
28 beforeAll(async () => {
29 root = mkdtempSync(join(tmpdir(), "forge-drill-"));
30 work = join(root, "work");
31 app = createApp({ dataDir: join(root, "live"), port: 0 });
32 const a = await createUser(app.db, {
33 trusted: true,
34 username: "alice",
35 email: "[email protected]",
36 password: "a-good-passphrase",
37 adminIfFirst: true,
38 });
39 if (!a.ok) throw new Error(a.error);
40 const repo = await createRepo(app, a.value, { name: "notes", visibility: "private" });
41 if (!repo.ok) throw new Error(String(repo.error));
42 const enabled = enableApp(app, a.value, repo.value);
43 if (!enabled.ok) throw new Error(String(enabled.error));
44 const set = await setAppEnvVar(app, a.value, repo.value, "WORD", "swordfish", "all");
45 if (!set.ok) throw new Error(String(set.error));
46 await takeSnapshot(
47 {
48 db: app.db,
49 dataDir: app.config.dataDir,
50 reposRoot: app.reposRoot,
51 version: "t",
52 passphrase: PASS,
53 },
54 store(),
55 new Date("2026-09-22T08:00:00Z"),
56 );
57 });
58
59 afterAll(async () => {
60 app.close();
61 await rm(root, { recursive: true, force: true });
62 });
63
64 const scratchEmpty = () =>
65 !existsSync(join(work, "drill")) || readdirSync(join(work, "drill")).length === 0;
66
67 test("green over a test snapshot, recorded, and the directory is gone", async () => {
68 const d = await runDrill({ store: store(), dataDir: work, passphrase: PASS });
69 expect(d.ok).toBe(true);
70 expect(d.snapshot).toBe("2026-09-22T08-00-00Z");
71 expect(d.repos).toBe(1);
72 expect(d.sealed).toBe(1);
73 expect(d.step).toBeUndefined();
74 expect(scratchEmpty()).toBe(true);
75 expect(drillRecords(work)[0]).toEqual(d);
76 });
77
78 test("a wrong passphrase is red at restore", async () => {
79 const d = await runDrill({ store: store(), dataDir: work, passphrase: "wrong" });
80 expect(d.ok).toBe(false);
81 expect(d.step).toBe("restore");
82 expect(d.error).toContain("passphrase");
83 expect(scratchEmpty()).toBe(true);
84 });
85
86 test("no passphrase leaves the key out: red at unseal", async () => {
87 const d = await runDrill({ store: store(), dataDir: work });
88 expect(d.ok).toBe(false);
89 expect(d.step).toBe("unseal");
90 expect(scratchEmpty()).toBe(true);
91 });
92
93 test("a store with no snapshot is red at fetch", async () => {
94 const d = await runDrill({
95 store: dirStore(join(root, "nothing")),
96 dataDir: work,
97 passphrase: PASS,
98 });
99 expect(d.ok).toBe(false);
100 expect(d.step).toBe("fetch");
101 expect(d.snapshot).toBeNull();
102 });
103
104 test("a hang ends as a red verdict at the timeout", async () => {
105 const real = store();
106 const hung: Store = {
107 ...real,
108 get: (key) =>
109 key.endsWith("manifest.json") ? real.get(key) : new Promise(() => {}),
110 };
111 const t = Date.now();
112 const d = await runDrill({ store: hung, dataDir: work, passphrase: PASS, timeoutMs: 200 });
113 expect(Date.now() - t).toBeLessThan(5000);
114 expect(d.ok).toBe(false);
115 expect(d.step).toBe("timeout");
116 expect(d.error).toContain("2026-09-22T08-00-00Z");
117 expect(scratchEmpty()).toBe(true);
118 });
119
120 test("an abort ends the drill red at timeout, and old scratch trees are swept at the next start", async () => {
121 const real = store();
122 const hung: Store = {
123 ...real,
124 get: (key) =>
125 key.endsWith("manifest.json") ? real.get(key) : new Promise(() => {}),
126 };
127 const stop = new AbortController();
128 setTimeout(() => stop.abort(), 100);
129 const t = Date.now();
130 const d = await runDrill({ store: hung, dataDir: work, passphrase: PASS, signal: stop.signal });
131 expect(Date.now() - t).toBeLessThan(5000);
132 expect(d.step).toBe("timeout");
133 expect(d.error).toContain("shutting down");
134 mkdirSync(join(work, "drill", "leftover", "deep"), { recursive: true });
135 const green = await runDrill({ store: real, dataDir: work, passphrase: PASS });
136 expect(green.ok).toBe(true);
137 expect(scratchEmpty()).toBe(true);
138 });
139
140 test("too little free disk refuses to start", async () => {
141 const d = await runDrill({
142 store: store(),
143 dataDir: work,
144 passphrase: PASS,
145 freeBytes: () => 10,
146 });
147 expect(d.ok).toBe(false);
148 expect(d.step).toBe("disk");
149 expect(d.error).toContain("twice");
150 });
151
152 test("the weekly clock lands on a Sunday after the nightly", () => {
153 const now = Date.parse("2026-10-13T12:00:00Z");
154 const when = new Date(now + untilDrill(now));
155 expect([when.getUTCDay(), when.getUTCHours()]).toEqual([0, 9]);
156 });
157 });
test/snapshot.test.ts +118
@@ -25,6 +25,7 @@ import { envDataDir } from "../src/apps/data.ts";
2525 import { getAppByRepo } from "../src/core/apps.ts";
2626 import { resolveAppEnv } from "../src/core/app_env.ts";
2727 import { getRepo } from "../src/core/repos.ts";
28 import { createToken } from "../src/core/tokens.ts";
2829 import { createUser, getUserByName, type User } from "../src/core/users.ts";
2930 import { commitLog } from "../src/git/read.ts";
3031 import { repoDir } from "../src/git/repos.ts";
@@ -407,4 +408,121 @@ describe("a forge back from a snapshot", () => {
407408 servers.stop();
408409 }
409410 });
411
412 test("the drill: page line, admin-only route, same-origin, health and MCP", async () => {
413 const bob = await createUser(app.db, {
414 trusted: true,
415 username: "bob",
416 email: "[email protected]",
417 password: "a-good-passphrase",
418 });
419 if (!bob.ok) throw new Error(bob.error);
420 const servers: Servers = await serve(app);
421 const login = async (username: string) => {
422 const r = await fetch(`${servers.url}/signin`, {
423 method: "POST",
424 headers: { origin: servers.url },
425 body: new URLSearchParams({ username, password: "a-good-passphrase" }),
426 redirect: "manual",
427 });
428 return (r.headers.get("set-cookie") ?? "").split(";")[0]!;
429 };
430 const mcp = async (token: string, name: string) => {
431 const res = await fetch(`${servers.url}/mcp`, {
432 method: "POST",
433 headers: {
434 "content-type": "application/json",
435 accept: "application/json, text/event-stream",
436 authorization: `Bearer ${token}`,
437 },
438 body: JSON.stringify({
439 jsonrpc: "2.0",
440 id: 1,
441 method: "tools/call",
442 params: { name, arguments: {} },
443 }),
444 });
445 const body = (await res.json()) as any;
446 const text: string = body.result.content[0].text;
447 return { isError: body.result.isError === true, text };
448 };
449 const svc = startSnapshots(app, dirStore(join(root, "store3")), {
450 version: "t",
451 nightly: false,
452 passphrase: PASS,
453 });
454 try {
455 const adminCookie = await login("alice");
456 const bobCookie = await login("bob");
457 const page = () =>
458 fetch(`${servers.url}/settings/backups`, {
459 headers: { cookie: adminCookie },
460 }).then((r) => r.text());
461 expect(await page()).toContain("No restore drill yet");
462 const post = (cookie: string, origin?: string) =>
463 fetch(`${servers.url}/settings/backups/drill`, {
464 method: "POST",
465 headers: { cookie, ...(origin ? { origin } : {}) },
466 redirect: "manual",
467 });
468 // Refused: not an admin, and a cross-origin post.
469 expect((await post(bobCookie, servers.url)).status).toBe(404);
470 expect(svc.drillingSince()).toBeUndefined();
471 const cross = await post(adminCookie, "https://evil.example");
472 expect(cross.status).toBeGreaterThanOrEqual(400);
473 expect(svc.drillingSince()).toBeUndefined();
474 expect(svc.lastDrill()).toBeUndefined();
475
476 // Red first: no snapshot in the store yet.
477 const started = await post(adminCookie, servers.url);
478 expect(started.status).toBe(303);
479 expect(decodeURIComponent(started.headers.get("set-cookie") ?? "")).toContain(
480 "Restore drill started",
481 );
482 for (let i = 0; i < 100 && svc.lastDrill() === undefined; i++)
483 await Bun.sleep(50);
484 expect(await page()).toContain("failed at");
485 expect(await page()).toContain("fetch");
486
487 // Green over a real snapshot; the running state shows while in flight.
488 await svc.now();
489 expect(svc.startDrill()).toBe("started");
490 expect(svc.startDrill()).toBe("running");
491 expect(svc.drillingSince()).toBeDefined();
492 expect(await page()).toContain("running since");
493 await svc.drill();
494 expect(svc.drillingSince()).toBeUndefined();
495 const green = (await page()).replace(/\s+/g, " ");
496 expect(green).toContain("restored and opened");
497 expect(green).toContain("1 repositories");
498
499 // Health: an admin sees the drill, nobody else does.
500 const adminToken = createToken(app.db, alice.id, "admin", "admin").token;
501 const bobToken = createToken(app.db, bob.value.id, "rw", "rw").token;
502 const health = async (token?: string) =>
503 (await (
504 await fetch(`${servers.url}/api/v1/health`, {
505 headers: token ? { authorization: `Bearer ${token}` } : {},
506 })
507 ).json()) as any;
508 const seen = await health(adminToken);
509 expect(seen.drill.ok).toBe(true);
510 expect(seen.drill.at).toBe(svc.lastDrill()!.at);
511 expect(seen.drill.step).toBeNull();
512 expect((await health(bobToken)).drill).toBeUndefined();
513 expect((await health()).drill).toBeUndefined();
514
515 // MCP: refused for a non-admin, started for an admin.
516 const refused = await mcp(bobToken, "restore_drill");
517 expect(refused.isError).toBe(true);
518 expect(svc.drillingSince()).toBeUndefined();
519 const ok = await mcp(adminToken, "restore_drill");
520 expect(ok.isError).toBe(false);
521 expect(svc.drillingSince()).toBeDefined();
522 await svc.drill();
523 } finally {
524 await svc.stop();
525 servers.stop();
526 }
527 });
410528 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs