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

Recovery, part 2: snapshots are mirrored off the box within the hour, and a stale mirror is a board line and a push #1992

Parked opened this
Closed without merging

scout/forge:scout/1987-recovery-part-2-snapshots-are-mirrored-o → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
12 files changed +787 −3
docs/SNAPSHOT.md +18
@@ -67,6 +67,24 @@ Delete the old ones from the bucket if the bucket is not trusted.
6767 - Given neither, no snapshots are taken, and the Backups page says so
6868 instead of showing an empty list that looks like a clean bill.
6969
70 ## The off-box mirror
71
72 A second S3-compatible bucket (Backblaze B2, say) that every snapshot is
73 copied to, so the snapshots do not die with the machine. Seal it on the
74 Backups page (`SNAPSHOT_MIRROR_S3_*`, write-only like the destination) or
75 give `FORGE_MIRROR_S3_ENDPOINT`, `_BUCKET`, `_ACCESS_KEY`, `_SECRET_KEY` and
76 optionally `_REGION`. A pass runs right after each snapshot, thirty seconds
77 after boot and every hour: it copies the newest fourteen snapshots the mirror
78 lacks (manifest last, so a half copy is never listed; objects already there
79 are skipped), then prunes the mirror to fourteen. What it found is kept in
80 `mirror/state.json` under the data directory. The Backups page shows the
81 mirror's reachability, its newest snapshot and when it was last confirmed
82 level. A pass that fails (store unreachable, or a snapshot that did not land)
83 or a mirror not confirmed level for a day is one card on the board
84 (`mirror`) and one push to the admin, the path the drill uses. Not done: the
85 mirror is copied from the primary store, not written in parallel, so a snapshot
86 that never landed on the primary is not seen by it.
87
7088 The store is `Bun.S3Client` or a directory behind one small interface
7189 (`src/snapshot/store.ts`): put, get, list, delete. Nothing else.
7290
scripts/gate.ts +1
@@ -187,6 +187,7 @@ export const GATE: readonly string[] = [
187187 "test/drill-board-line.test.ts",
188188 "test/snapshot-drill-page.test.ts",
189189 "test/snapshot-store.test.ts",
190 "test/snapshot-mirror.test.ts",
190191 "test/migrate.test.ts",
191192 "test/schema-additive.test.ts",
192193 "test/schema-migrations.test.ts",
src/actions/mirror.ts added +76
@@ -0,0 +1,76 @@
1 /**
2 * The off-box mirror, as an admin sets it. The same fields as the
3 * destination (`actions/destination.ts`), validated the same way and sealed
4 * as forge-level secrets under their own names; nothing is read back to a
5 * person except which are set. A blank field keeps what was sealed.
6 */
7
8 import type { App } from "../app.ts";
9 import { putSecret } from "./secrets.ts";
10 import { invalidField, type DestinationInput } from "./destination.ts";
11 import {
12 clearMirrorSealed,
13 mirrorSealedSet,
14 MIRROR_SEALED,
15 } from "../snapshot/mirror.ts";
16 import { snapshotsOf } from "../snapshot/service.ts";
17 import type { User } from "../core/users.ts";
18 import { err, ok, type Result } from "../kernel/result.ts";
19
20 const isAdmin = (actor: User | undefined): boolean => actor?.isAdmin === true;
21
22 /** Seal what was given (an error is `not_found` or a sentence for the page); says what is still missing. */
23 export function saveMirror(
24 app: App,
25 actor: User | undefined,
26 input: DestinationInput,
27 ): Result<string, string> {
28 if (!isAdmin(actor)) return err("not_found");
29 const bad = invalidField(input);
30 if (bad) return err(bad);
31 const fields: [string, string][] = [
32 [MIRROR_SEALED.endpoint, input.endpoint],
33 [MIRROR_SEALED.bucket, input.bucket],
34 [MIRROR_SEALED.region, input.region],
35 [MIRROR_SEALED.accessKey, input.accessKey],
36 [MIRROR_SEALED.secretKey, input.secretKey],
37 ];
38 for (const [name, value] of fields) {
39 if (value === "") continue;
40 if (!putSecret(app, actor, "forge", "", name, value).ok)
41 return err("That could not be sealed.");
42 }
43 snapshotsOf(app)?.forget();
44 const have = mirrorSealedSet(app.db);
45 const missing = [
46 [MIRROR_SEALED.endpoint, "endpoint"],
47 [MIRROR_SEALED.bucket, "bucket"],
48 [MIRROR_SEALED.accessKey, "access key"],
49 [MIRROR_SEALED.secretKey, "secret key"],
50 ]
51 .filter(([n]) => !have.includes(n!))
52 .map(([, label]) => label);
53 return ok(
54 missing.length === 0
55 ? "Mirror sealed; it is brought level within the hour."
56 : `Sealed, but not in effect until the ${missing.join(", ")} ${missing.length === 1 ? "is" : "are"} set.`,
57 );
58 }
59
60 export function forgetMirror(
61 app: App,
62 actor: User | undefined,
63 ): Result<void, "not_found"> {
64 if (!isAdmin(actor)) return err("not_found");
65 clearMirrorSealed(app.db);
66 app.bus.append({
67 kind: "secret.deleted",
68 actorId: actor!.id,
69 payload: { name: "SNAPSHOT_MIRROR_S3_*", scope: "forge" },
70 });
71 const svc = snapshotsOf(app);
72 svc?.forget();
73 // Clears the state the board reads: no mirror, no line.
74 void svc?.mirrorNow().catch(() => {});
75 return ok();
76 }
src/crew/notify.ts +15
@@ -30,6 +30,7 @@ import { getUserSetting, setUserSetting } from "../core/settings.ts";
3030 import { getUserById, type User } from "../core/users.ts";
3131 import { landedLines } from "../core/watches.ts";
3232 import { err, ok, type Result } from "../kernel/result.ts";
33 import { lastMirror, mirrorNeed } from "../snapshot/mirror.ts";
3334 import { drillNeed, firstSeen, lastVerdict } from "../snapshot/verdict.ts";
3435 import { askLinesFor } from "../web/studio/asks.ts";
3536
@@ -167,6 +168,19 @@ export function drillLines(
167168 return [{ id, line: need.sentence, items: [id] }];
168169 }
169170
171 /** The admin hears of a snapshot that did not land off the box, or a stale mirror, once per cause. */
172 export function mirrorLines(
173 app: App,
174 user: User,
175 now = Date.now(),
176 ): { id: string; line: string; items: readonly string[] }[] {
177 if (!user.isAdmin || user.kind !== "user") return [];
178 const need = mirrorNeed(lastMirror(app.config.dataDir), now);
179 if (need === undefined) return [];
180 const id = `mirror:${need.key}`;
181 return [{ id, line: need.sentence, items: [id] }];
182 }
183
170184 export interface Notifier {
171185 /** Resolves when the work queued so far is done. For tests and shutdown. */
172186 settled(): Promise<void>;
@@ -222,6 +236,7 @@ export function startNotifier(app: App, options: NotifyOptions): Notifier {
222236 ...landedLines(app.db, user, now()),
223237 ...mailCeilingLines(app, user, now()),
224238 ...drillLines(app, user, now()),
239 ...mirrorLines(app, user, now()),
225240 ];
226241 const before = seen.get(userId);
227242 // What is gone may ask again later, and then it is new again. Seen by
src/http/server.ts +6
@@ -112,6 +112,9 @@ import {
112112 backupsClear,
113113 backupsDestination,
114114 backupsDrill,
115 backupsMirror,
116 backupsMirrorClear,
117 backupsMirrorNow,
115118 backupsNow,
116119 backupsPage,
117120 backupsTest,
@@ -723,6 +726,9 @@ export function buildRouter(): Router<Handler> {
723726 router.add("POST", "/settings/backups/destination", backupsDestination);
724727 router.add("POST", "/settings/backups/test", backupsTest);
725728 router.add("POST", "/settings/backups/clear", backupsClear);
729 router.add("POST", "/settings/backups/mirror", backupsMirror);
730 router.add("POST", "/settings/backups/mirror/clear", backupsMirrorClear);
731 router.add("POST", "/settings/backups/mirror/now", backupsMirrorNow);
726732 router.add("GET", "/settings/accounts", accountsPage);
727733 router.add("GET", "/settings/accounts/:username", personSignInsPage);
728734 router.add(
src/kernel/vitals.ts +5
@@ -21,6 +21,7 @@ import {
2121 } from "../core/runs.ts";
2222 import { STALE_AFTER_MS } from "../runs/lease.ts";
2323 import { BUDGETS } from "./budgets.ts";
24 import { lastMirror, mirrorNeed } from "../snapshot/mirror.ts";
2425 import { drillNeed, firstSeen as drillFirstSeen, lastVerdict } from "../snapshot/verdict.ts";
2526 import { heldChecks, redSentence } from "../checks/red_main.ts";
2627
@@ -318,6 +319,10 @@ export function vitals(input: VitalsInput): Vitals {
318319 if (owed !== undefined)
319320 need("drill", owed.sentence, owed.since, "/settings/backups");
320321
322 // A snapshot that did not land off the box, or a mirror a day behind, is a card until it does.
323 const behind = mirrorNeed(lastMirror(input.dataDir), now);
324 if (behind !== undefined) need("mirror", behind.sentence, behind.since, "/settings/backups");
325
321326 const apps = { serving: 0, asleep: 0, previews: 0 };
322327 for (const e of input.envs ?? []) {
323328 if (e.env !== "production") apps.previews++;
src/main.ts +3
@@ -31,6 +31,7 @@ import { startLooks } from "./looks/service.ts";
3131 import { startProbes } from "./contract/probes.ts";
3232 import { startSnapshots } from "./snapshot/service.ts";
3333 import { resolveDestination } from "./snapshot/destination.ts";
34 import { resolveMirror } from "./snapshot/mirror.ts";
3435 import { releaseOrphans } from "./core/run_secret.ts";
3536 import { failAbandonedRuns } from "./core/runs.ts";
3637 import { DRAIN_LINGER_MAX_S, drainLingerMs, startDraining } from "./http/health.ts";
@@ -325,6 +326,8 @@ const snapshots = startSnapshots(
325326 })?.store,
326327 {
327328 version: running().version,
329 mirror: () =>
330 resolveMirror({ db: app.db, dataDir: app.config.dataDir, bus: app.bus })?.store,
328331 passphrase: process.env["FORGE_SNAPSHOT_PASSPHRASE"] || undefined,
329332 },
330333 );
src/snapshot/mirror.ts added +246
@@ -0,0 +1,246 @@
1 /**
2 * The off-box mirror: a second S3-compatible bucket (Backblaze B2, say) that
3 * every snapshot is copied to, so losing the machine does not lose the
4 * snapshots with it. Its keys are sealed in the forge like the Backups
5 * destination (`SNAPSHOT_MIRROR_S3_*`), or given as `FORGE_MIRROR_S3_*`.
6 *
7 * A pass copies each of the newest snapshots the mirror lacks, the manifest
8 * last, so a half-copied snapshot is never listed; objects already there are
9 * skipped, so a pass that died resumes. What the last pass found is kept in
10 * one small file under the data directory (`mirror/state.json`), so the
11 * board and the push read it without touching the network. Plain data in,
12 * plain data out.
13 */
14
15 import type { Database } from "bun:sqlite";
16 import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
17 import { join } from "node:path";
18 import type { EventBus } from "../core/events.ts";
19 import { deleteSecret, resolveSecrets } from "../core/secret_store.ts";
20 import { KEEP, listSnapshots, pruneSnapshots, SNAPSHOT_PREFIX } from "./snapshot.ts";
21 import { s3Store, type S3Target, type Store } from "./store.ts";
22
23 /** The sealed names, one per field of the form. */
24 export const MIRROR_SEALED = {
25 endpoint: "SNAPSHOT_MIRROR_S3_ENDPOINT",
26 bucket: "SNAPSHOT_MIRROR_S3_BUCKET",
27 region: "SNAPSHOT_MIRROR_S3_REGION",
28 accessKey: "SNAPSHOT_MIRROR_S3_ACCESS_KEY",
29 secretKey: "SNAPSHOT_MIRROR_S3_SECRET_KEY",
30 } as const;
31 export const MIRROR_NAMES: readonly string[] = Object.values(MIRROR_SEALED);
32
33 /** A mirror not confirmed in sync for this long is one line on the board. */
34 export const MIRROR_STALE_MS = 24 * 3_600_000;
35 /** How often the forge looks for snapshots the mirror lacks. */
36 export const MIRROR_EVERY_MS = 3_600_000;
37 /** Objects copied at once: each is held in memory while it moves. */
38 const COPY_AT_ONCE = 4;
39
40 export interface MirrorSources {
41 readonly db?: Database | undefined;
42 readonly dataDir?: string | undefined;
43 readonly bus?: EventBus | undefined;
44 readonly env?: Record<string, string | undefined>;
45 }
46
47 export interface Mirror {
48 readonly source: "sealed" | "env";
49 readonly store: Store;
50 }
51
52 /** The mirror's target: sealed in this forge, else `FORGE_MIRROR_S3_*`; undefined when neither is whole. */
53 export function mirrorTarget(s: MirrorSources = {}): { source: Mirror["source"]; target: S3Target } | undefined {
54 if (s.db && s.dataDir !== undefined && s.bus) {
55 const v = resolveSecrets(s.db, s.dataDir, s.bus, MIRROR_NAMES, {});
56 const endpoint = v[MIRROR_SEALED.endpoint];
57 const bucket = v[MIRROR_SEALED.bucket];
58 const accessKeyId = v[MIRROR_SEALED.accessKey];
59 const secretAccessKey = v[MIRROR_SEALED.secretKey];
60 if (endpoint && bucket && accessKeyId && secretAccessKey)
61 return {
62 source: "sealed",
63 target: { endpoint, bucket, accessKeyId, secretAccessKey, region: v[MIRROR_SEALED.region] },
64 };
65 }
66 const env = s.env ?? process.env;
67 const endpoint = env["FORGE_MIRROR_S3_ENDPOINT"]?.trim();
68 const bucket = env["FORGE_MIRROR_S3_BUCKET"]?.trim();
69 const accessKeyId = env["FORGE_MIRROR_S3_ACCESS_KEY"]?.trim();
70 const secretAccessKey = env["FORGE_MIRROR_S3_SECRET_KEY"]?.trim();
71 if (!endpoint || !bucket || !accessKeyId || !secretAccessKey) return undefined;
72 return {
73 source: "env",
74 target: { endpoint, bucket, accessKeyId, secretAccessKey, region: env["FORGE_MIRROR_S3_REGION"]?.trim() || undefined },
75 };
76 }
77
78 export function resolveMirror(s: MirrorSources = {}): Mirror | undefined {
79 const t = mirrorTarget(s);
80 return t === undefined ? undefined : { source: t.source, store: s3Store(t.target) };
81 }
82
83 /** Which of the sealed mirror names are set, without opening any. */
84 export function mirrorSealedSet(db: Database): string[] {
85 return db
86 .query<{ name: string }, []>(
87 `SELECT name FROM secret WHERE scope = 'forge' AND scope_id = ''
88 AND name LIKE 'SNAPSHOT\\_MIRROR\\_S3\\_%' ESCAPE '\\'`,
89 )
90 .all()
91 .map((r) => r.name);
92 }
93
94 export function clearMirrorSealed(db: Database): void {
95 for (const name of MIRROR_NAMES) deleteSecret(db, "forge", "", name);
96 }
97
98 export interface MirrorState {
99 readonly where: string;
100 /** When the last pass began. */
101 readonly attemptAt: string;
102 /** Whether the last pass could list the mirror. */
103 readonly reachable: boolean;
104 /** The last time the mirror was confirmed to hold the newest snapshot. */
105 readonly syncedAt?: string;
106 /** The newest snapshot the mirror holds, and when it finished. */
107 readonly newest?: string;
108 readonly newestAt?: string;
109 /** Set while passes are failing: since when, which snapshot, and why. */
110 readonly failingSince?: string;
111 readonly failed?: string;
112 readonly error?: string;
113 }
114
115 const stateFile = (dataDir: string): string => join(dataDir, "mirror", "state.json");
116
117 export function recordMirror(dataDir: string, state: MirrorState | undefined): void {
118 if (state === undefined) {
119 rmSync(stateFile(dataDir), { force: true });
120 return;
121 }
122 mkdirSync(join(dataDir, "mirror"), { recursive: true });
123 const tmp = `${stateFile(dataDir)}.tmp`;
124 writeFileSync(tmp, JSON.stringify(state));
125 renameSync(tmp, stateFile(dataDir));
126 }
127
128 /** What the last pass found; undefined when no mirror has been tried or the file is not one. */
129 export function lastMirror(dataDir: string): MirrorState | undefined {
130 try {
131 const s = JSON.parse(readFileSync(stateFile(dataDir), "utf8")) as MirrorState;
132 if (typeof s.where !== "string" || typeof s.attemptAt !== "string" || typeof s.reachable !== "boolean")
133 return undefined;
134 return s;
135 } catch {
136 return undefined;
137 }
138 }
139
140 async function copyOne(src: Store, dst: Store, name: string): Promise<void> {
141 const prefix = `${SNAPSHOT_PREFIX}${name}/`;
142 const manifest = `${prefix}manifest.json`;
143 const have = new Set(await dst.list(prefix));
144 const todo = (await src.list(prefix)).filter((k) => k !== manifest && !have.has(k));
145 for (let i = 0; i < todo.length; i += COPY_AT_ONCE)
146 await Promise.all(
147 todo.slice(i, i + COPY_AT_ONCE).map(async (key) => {
148 const body = await src.get(key);
149 if (body === undefined) throw new Error(`${key} vanished from the source`);
150 await dst.put(key, body);
151 }),
152 );
153 const body = await src.get(manifest);
154 if (body === undefined) throw new Error(`${manifest} vanished from the source`);
155 await dst.put(manifest, body);
156 }
157
158 /**
159 * One pass: bring the mirror level with the source, prune it to `keep`, and
160 * keep what came of it. Never throws; a failure is the returned state.
161 */
162 export async function mirrorPass(
163 dataDir: string,
164 src: Store,
165 dst: Store,
166 options: { now?: number; keep?: number } = {},
167 ): Promise<MirrorState> {
168 const now = options.now ?? Date.now();
169 const keep = options.keep ?? KEEP;
170 const at = new Date(now).toISOString();
171 const prev = lastMirror(dataDir);
172 let reachable = false;
173 let failed: string | undefined;
174 let state: MirrorState;
175 try {
176 const names = new Set(await dst.names(SNAPSHOT_PREFIX));
177 reachable = true;
178 const wanted = (await listSnapshots(src)).slice(0, keep);
179 for (const m of [...wanted].reverse()) {
180 if (names.has(m.name) && (await dst.get(`${SNAPSHOT_PREFIX}${m.name}/manifest.json`)) !== undefined)
181 continue;
182 failed = m.name;
183 await copyOne(src, dst, m.name);
184 failed = undefined;
185 }
186 await pruneSnapshots(dst, keep);
187 const newest = wanted[0];
188 state = {
189 where: dst.where,
190 attemptAt: at,
191 reachable: true,
192 syncedAt: at,
193 ...(newest === undefined ? {} : { newest: newest.name, newestAt: newest.finishedAt }),
194 };
195 } catch (error) {
196 const reason = error instanceof Error ? error.message : String(error);
197 state = {
198 where: dst.where,
199 attemptAt: at,
200 reachable,
201 ...(prev?.syncedAt === undefined ? {} : { syncedAt: prev.syncedAt }),
202 ...(prev?.newest === undefined ? {} : { newest: prev.newest }),
203 ...(prev?.newestAt === undefined ? {} : { newestAt: prev.newestAt }),
204 failingSince: prev?.failingSince ?? at,
205 ...(failed === undefined ? {} : { failed }),
206 error: reason.slice(0, 200),
207 };
208 }
209 try {
210 recordMirror(dataDir, state);
211 } catch {
212 // A disk that will not take the file must not turn a copied snapshot into a failure.
213 }
214 return state;
215 }
216
217 export interface MirrorNeed {
218 /** Holds as long as the same cause does: a new failure or a new silence is a new key. */
219 readonly key: string;
220 readonly sentence: string;
221 readonly since: string;
222 }
223
224 /**
225 * The one line the mirror owes the board: a pass that failed (the store
226 * unreachable, or a snapshot that did not land), or a mirror not confirmed
227 * in sync for a day. A mirror in sync: none.
228 */
229 export function mirrorNeed(s: MirrorState | undefined, now: number): MirrorNeed | undefined {
230 if (s === undefined) return undefined;
231 if (s.failingSince !== undefined)
232 return {
233 key: `fail:${s.failingSince}`,
234 sentence: s.reachable
235 ? `Snapshot ${s.failed ?? "(unknown)"} did not land on the off-box mirror ${s.where}: ${s.error ?? "unknown reason"}.`
236 : `The off-box mirror ${s.where} is unreachable: ${s.error ?? "unknown reason"}.`,
237 since: s.failingSince,
238 };
239 const at = Date.parse(s.syncedAt ?? "");
240 if (Number.isFinite(at) && now - at <= MIRROR_STALE_MS) return undefined;
241 return {
242 key: `stale:${s.syncedAt ?? s.attemptAt}`,
243 sentence: `The off-box mirror ${s.where} has not been confirmed in sync for over a day${s.syncedAt ? `; last on ${s.syncedAt.slice(0, 10)}` : ""}.`,
244 since: s.syncedAt ? new Date(at + MIRROR_STALE_MS).toISOString() : s.attemptAt,
245 };
246 }
src/snapshot/service.ts +67
@@ -21,6 +21,7 @@ import {
2121 } from "./snapshot.ts";
2222 import { runDrill, type DrillDeps, type DrillResult } from "./drill.ts";
2323 import { recordDrill } from "./drills.ts";
24 import { lastMirror, mirrorPass, MIRROR_EVERY_MS, recordMirror, type MirrorState } from "./mirror.ts";
2425 import type { Store } from "./store.ts";
2526
2627 const log = createLog("snapshots");
@@ -43,6 +44,12 @@ export interface SnapshotsHandle {
4344 readonly last: () => { manifest?: Manifest; error?: string; at?: string };
4445 /** Drill the newest snapshot now and keep the result; waits for any snapshot in flight. */
4546 readonly drill: () => Promise<DrillResult>;
47 /** The off-box mirror's store; undefined when the forge has none. */
48 readonly mirror: Store | undefined;
49 /** Bring the mirror level now; waits for any snapshot in flight. Undefined when there is no mirror. */
50 readonly mirrorNow: () => Promise<MirrorState | undefined>;
51 /** What the last mirror pass found. */
52 readonly mirrored: () => MirrorState | undefined;
4653 /** Forget the resolved store; the next use resolves again (a new destination was saved). */
4754 readonly forget: () => void;
4855 readonly stop: () => Promise<void>;
@@ -76,6 +83,10 @@ export function startSnapshots(
7683 destination: Store | (() => Store | undefined),
7784 options: {
7885 readonly version: string;
86 /** The off-box mirror, resolved like the destination. */
87 readonly mirror?: Store | (() => Store | undefined) | undefined;
88 /** Test seam: how often the mirror is looked at. */
89 readonly mirrorEveryMs?: number | undefined;
7990 readonly nightly?: boolean;
8091 readonly passphrase?: string | undefined;
8192 /** Test seam: the drill itself. */
@@ -92,6 +103,13 @@ export function startSnapshots(
92103 resolved ??= { store: destination() };
93104 return resolved.store;
94105 };
106 let resolvedMirror: { store: Store | undefined } | undefined;
107 const currentMirror = (): Store | undefined => {
108 const m = options.mirror;
109 if (typeof m !== "function") return m;
110 resolvedMirror ??= { store: m() };
111 return resolvedMirror.store;
112 };
95113 let stopped = false;
96114 let inFlight: Promise<Manifest> | undefined;
97115 let running: Progress | undefined;
@@ -123,6 +141,9 @@ export function startSnapshots(
123141 await pruneSnapshots(store, KEEP);
124142 return manifest;
125143 });
144 // The mirror hears of every snapshot at once; a failure there is its own
145 // line on the board and never the snapshot's.
146 run.then(() => mirrorNow()).catch(() => {});
126147 inFlight = run.then(
127148 (m) => {
128149 last = { manifest: m, at: m.finishedAt };
@@ -137,6 +158,31 @@ export function startSnapshots(
137158 return inFlight;
138159 };
139160
161 // Single-flight: two passes at once would copy the same objects twice.
162 let mirroring: Promise<MirrorState | undefined> | undefined;
163 const mirrorNow = (): Promise<MirrorState | undefined> => {
164 mirroring ??= (async () => {
165 await (inFlight ?? Promise.resolve()).catch(() => {});
166 const dst = currentMirror();
167 const src = current();
168 if (dst === undefined || src === undefined) {
169 try {
170 recordMirror(app.config.dataDir, undefined);
171 } catch (error) {
172 log.warn("mirror: state not cleared", { error: String(error) });
173 }
174 return undefined;
175 }
176 const state = await mirrorPass(app.config.dataDir, src, dst);
177 if (state.failingSince === undefined) log.info("mirror level", { where: state.where, newest: state.newest ?? "none" });
178 else log.error("mirror failed", { where: state.where, reachable: state.reachable, error: state.error ?? "" });
179 return state;
180 })().finally(() => {
181 mirroring = undefined;
182 });
183 return mirroring;
184 };
185
140186 // Single-flight: a restore of every repository is heavy, so a second call
141187 // while one runs joins it instead of filling the disk with another.
142188 let drilling: Promise<DrillResult> | undefined;
@@ -192,6 +238,19 @@ export function startSnapshots(
192238 };
193239 scheduleDrill();
194240
241 // Within the hour: look for snapshots the mirror lacks, soon after boot and then hourly.
242 let mirrorTimer: ReturnType<typeof setTimeout> | undefined;
243 const everyMs = options.mirrorEveryMs ?? MIRROR_EVERY_MS;
244 const scheduleMirror = (first: boolean): void => {
245 if (options.nightly === false || stopped) return;
246 mirrorTimer = setTimeout(() => {
247 mirrorNow()
248 .catch(() => {})
249 .finally(() => scheduleMirror(false));
250 }, first ? Math.min(30_000, everyMs) : everyMs);
251 };
252 scheduleMirror(true);
253
195254 const handle: SnapshotsHandle = {
196255 get store() {
197256 return current();
@@ -205,13 +264,21 @@ export function startSnapshots(
205264 },
206265 last: () => last,
207266 progress: () => running,
267 get mirror() {
268 return currentMirror();
269 },
270 mirrorNow,
271 mirrored: () => lastMirror(app.config.dataDir),
208272 forget: () => {
209273 resolved = undefined;
274 resolvedMirror = undefined;
210275 },
211276 stop: async () => {
212277 stopped = true;
213278 if (timer !== undefined) clearTimeout(timer);
214279 if (drillTimer !== undefined) clearTimeout(drillTimer);
280 if (mirrorTimer !== undefined) clearTimeout(mirrorTimer);
281 if (mirroring !== undefined) await mirroring.catch(() => {});
215282 if (inFlight !== undefined) await inFlight.catch(() => {});
216283 if (handles.get(app) === handle) handles.delete(app);
217284 },
src/snapshot/store.ts +5 −2
@@ -112,8 +112,11 @@ function answered<T>(attempt: Promise<T>, ms: number): Promise<T> {
112112 return Promise.race([attempt, deadline]).finally(() => clearTimeout(timer));
113113 }
114114
115 export function s3Store(target: S3Target): Store {
116 return withRetries(rawS3Store(target));
115 export function s3Store(
116 target: S3Target,
117 retries?: Parameters<typeof withRetries>[1],
118 ): Store {
119 return withRetries(rawS3Store(target), retries);
117120 }
118121
119122 function rawS3Store(target: S3Target): Store {
src/web/pages/backups.ts +100 −1
@@ -14,6 +14,8 @@ import {
1414 testDestination,
1515 type DestinationInput,
1616 } from "../../actions/destination.ts";
17 import { forgetMirror, saveMirror } from "../../actions/mirror.ts";
18 import { mirrorSealedSet, mirrorNeed } from "../../snapshot/mirror.ts";
1719 import { resolveDestination, sealedSet } from "../../snapshot/destination.ts";
1820 import { keyOf } from "../../snapshot/snapshot.ts";
1921 import { lastDrill } from "../../snapshot/drills.ts";
@@ -115,7 +117,7 @@ export async function backupsPage(ctx: Ctx): Promise<Response> {
115117 const denied = requireAdmin(ctx);
116118 if (denied) return denied;
117119 const svc = snapshotsOf(ctx.app);
118 const form = destinationCard(ctx);
120 const form = html`${destinationCard(ctx)}${mirrorCard(ctx)}`;
119121 if (svc === undefined || svc.store === undefined)
120122 return shell(
121123 ctx,
@@ -314,6 +316,61 @@ function destinationCard(ctx: Ctx): Html {
314316 );
315317 }
316318
319 /** The mirror: its age and reachability from the last pass, and the write-only form that seals it. */
320 function mirrorCard(ctx: Ctx): Html {
321 const svc = snapshotsOf(ctx.app);
322 const state = svc?.mirrored();
323 const configured = svc?.mirror !== undefined;
324 const need = mirrorNeed(state, Date.now());
325 const set = mirrorSealedSet(ctx.app.db);
326 const field_ = (name: string, label: string, sealed: string, type = "text"): Html =>
327 html`<label class="field"
328 ><span>${label}</span
329 ><input
330 name="${name}"
331 type="${type}"
332 autocomplete="off"
333 spellcheck="false"
334 placeholder="${set.includes(sealed) ? "set — leave blank to keep" : ""}"
335 /></label>`;
336 const status = !configured
337 ? html`<p>No off-box mirror: snapshots live only where the destination is.
338 Seal a second bucket below (or set <code>FORGE_MIRROR_S3_*</code>) and
339 every snapshot is copied there within the hour.</p>`
340 : state === undefined
341 ? html`<p>Mirroring to <code>${svc!.mirror!.where}</code>; the first pass has not run yet.</p>`
342 : html`<p class="${need ? "backups-error" : ""}">
343 ${icon(need ? "alert" : "check")} <code>${state.where}</code> is
344 ${state.reachable ? "reachable" : "unreachable"} (checked
345 ${time(state.attemptAt)}).
346 ${state.newest
347 ? html`It holds <code>${state.newest}</code>, taken
348 ${time(state.newestAt ?? "")}; confirmed level ${time(state.syncedAt ?? "")}.`
349 : html`It holds no snapshot yet.`}
350 ${need ? html`<br />${need.sentence}` : ""}
351 </p>`;
352 return card(
353 html`${status}
354 <form method="post" action="/settings/backups/mirror" class="stack">
355 ${field_("endpoint", "Endpoint", "SNAPSHOT_MIRROR_S3_ENDPOINT")}
356 ${field_("bucket", "Bucket", "SNAPSHOT_MIRROR_S3_BUCKET")}
357 ${field_("region", "Region (optional)", "SNAPSHOT_MIRROR_S3_REGION")}
358 ${field_("access_key", "Access key", "SNAPSHOT_MIRROR_S3_ACCESS_KEY")}
359 ${field_("secret_key", "Secret key", "SNAPSHOT_MIRROR_S3_SECRET_KEY", "password")}
360 <div class="row-actions">
361 ${btn("Seal mirror", { type: "submit", variant: "primary", icon: "lock" })}
362 <button class="btn" type="submit" formaction="/settings/backups/mirror/now" formnovalidate>
363 Mirror now
364 </button>
365 <button class="btn" type="submit" formaction="/settings/backups/mirror/clear" formnovalidate>
366 Clear sealed mirror
367 </button>
368 </div>
369 </form>`,
370 { head: html`${icon("download")}<h2>Off-box mirror</h2>` },
371 );
372 }
373
317374 function destinationInput(form: Form): DestinationInput {
318375 return {
319376 endpoint: field(form, "endpoint").trim(),
@@ -427,3 +484,45 @@ export async function backupsDrill(ctx: Ctx): Promise<Response> {
427484 });
428485 }
429486 }
487
488 /** POST /settings/backups/mirror — seal the mirror. */
489 export async function backupsMirror(ctx: Ctx): Promise<Response> {
490 const denied = requireAdmin(ctx);
491 if (denied) return denied;
492 const form = await readForm(ctx, "admin");
493 if (form instanceof Response) return form;
494 const saved = saveMirror(ctx.app, ctx.auth.user, destinationInput(form));
495 return flashTo(
496 ctx,
497 "/settings/backups",
498 saved.ok ? { message: saved.value } : { tone: "danger", message: saved.error },
499 );
500 }
501
502 /** POST /settings/backups/mirror/clear — forget the sealed mirror. */
503 export async function backupsMirrorClear(ctx: Ctx): Promise<Response> {
504 const denied = requireAdmin(ctx);
505 if (denied) return denied;
506 const form = await readForm(ctx, "admin");
507 if (form instanceof Response) return form;
508 forgetMirror(ctx.app, ctx.auth.user);
509 return flashTo(ctx, "/settings/backups", { message: "The sealed mirror is cleared." });
510 }
511
512 /** POST /settings/backups/mirror/now — bring the mirror level, and say what came of it. */
513 export async function backupsMirrorNow(ctx: Ctx): Promise<Response> {
514 const denied = requireAdmin(ctx);
515 if (denied) return denied;
516 const form = await readForm(ctx, "admin");
517 if (form instanceof Response) return form;
518 const state = await snapshotsOf(ctx.app)?.mirrorNow();
519 if (state === undefined)
520 return flashTo(ctx, "/settings/backups", { tone: "danger", message: "This forge has no mirror to bring level." });
521 return flashTo(
522 ctx,
523 "/settings/backups",
524 state.failingSince === undefined
525 ? { message: `The mirror is level${state.newest ? ` at ${state.newest}` : ""}.` }
526 : { tone: "danger", message: `The mirror is not level: ${state.error ?? "unknown reason"}` },
527 );
528 }
test/snapshot-mirror.test.ts added +245
@@ -0,0 +1,245 @@
1 /**
2 * The off-box mirror, against a stand-in S3 on a loopback port: a snapshot
3 * lands in both buckets; a mirror that cannot be reached is one line on the
4 * board and one push; so is a mirror a day out of date; and a mirror
5 * brought back catches up, resumes, and clears the line.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtempSync } from "node:fs";
9 import { rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createApp, type App } from "../src/app.ts";
13 import { createUser } from "../src/core/users.ts";
14 import { setNotifyUrl, startNotifier } from "../src/crew/notify.ts";
15 import { vitals } from "../src/kernel/vitals.ts";
16 import { listSnapshots, SNAPSHOT_PREFIX } from "../src/snapshot/snapshot.ts";
17 import {
18 lastMirror,
19 MIRROR_STALE_MS,
20 mirrorNeed,
21 mirrorPass,
22 recordMirror,
23 resolveMirror,
24 } from "../src/snapshot/mirror.ts";
25 import { startSnapshots } from "../src/snapshot/service.ts";
26 import { dirStore, s3Store, type S3Target } from "../src/snapshot/store.ts";
27
28 /** A just-enough S3: path-style get, put, head, delete and list-v2 over a Map. */
29 function standIn(): { url: string; objects: Map<string, Uint8Array>; stop: () => void; down: boolean } {
30 const objects = new Map<string, Uint8Array>();
31 const me = { url: "", objects, stop: () => {}, down: false };
32 const xml = (s: string) => new Response(s, { headers: { "content-type": "application/xml" } });
33 const server = Bun.serve({
34 port: 0,
35 hostname: "127.0.0.1",
36 async fetch(req) {
37 if (me.down) return new Response("down", { status: 503 });
38 const u = new URL(req.url);
39 const [, bucket, ...rest] = u.pathname.split("/");
40 const key = decodeURIComponent(rest.join("/"));
41 const k = `${bucket}/${key}`;
42 if (req.method === "PUT") {
43 objects.set(k, new Uint8Array(await req.arrayBuffer()));
44 return new Response("", { status: 200, headers: { etag: '"x"' } });
45 }
46 if (req.method === "DELETE") {
47 objects.delete(k);
48 return new Response(null, { status: 204 });
49 }
50 if (req.method === "GET" && u.searchParams.get("list-type") === "2") {
51 const prefix = u.searchParams.get("prefix") ?? "";
52 const delimiter = u.searchParams.get("delimiter");
53 const keys = [...objects.keys()]
54 .filter((x) => x.startsWith(`${bucket}/`))
55 .map((x) => x.slice(bucket!.length + 1))
56 .filter((x) => x.startsWith(prefix))
57 .sort();
58 const contents: string[] = [];
59 const prefixes = new Set<string>();
60 for (const x of keys) {
61 const cut = delimiter ? x.indexOf(delimiter, prefix.length) : -1;
62 if (cut >= 0) prefixes.add(x.slice(0, cut + 1));
63 else contents.push(`<Contents><Key>${x}</Key><Size>${objects.get(`${bucket}/${x}`)!.length}</Size></Contents>`);
64 }
65 return xml(
66 `<?xml version="1.0"?><ListBucketResult><Name>${bucket}</Name><Prefix>${prefix}</Prefix><KeyCount>${keys.length}</KeyCount><IsTruncated>false</IsTruncated>${contents.join("")}${[...prefixes].map((p) => `<CommonPrefixes><Prefix>${p}</Prefix></CommonPrefixes>`).join("")}</ListBucketResult>`,
67 );
68 }
69 const body = objects.get(k);
70 if (body === undefined) return new Response("<Error><Code>NoSuchKey</Code></Error>", { status: 404 });
71 return new Response(req.method === "HEAD" ? null : body, {
72 headers: { "content-length": String(body.length) },
73 });
74 },
75 });
76 me.url = `http://127.0.0.1:${server.port}`;
77 me.stop = () => void server.stop(true);
78 return me;
79 }
80
81 const target = (url: string, bucket: string): S3Target => ({
82 endpoint: url,
83 bucket,
84 accessKeyId: "AKTEST",
85 secretAccessKey: "secret-test",
86 region: "us-east-1",
87 });
88 const FAST = { attempts: 1, baseMs: 1, deadlineMs: 3000 };
89
90 const T0 = Date.parse("2026-10-01T00:00:00Z");
91
92 describe("the off-box mirror", () => {
93 let root: string;
94 let app: App;
95 let admin: { id: string };
96 const primary = standIn();
97 const offbox = standIn();
98 const src = () => s3Store(target(primary.url, "forge-snapshots"), FAST);
99 const dst = () => s3Store(target(offbox.url, "offbox"), FAST);
100 const board = (now: number) =>
101 vitals({ db: app.db, dataDir: app.config.dataDir, signals: app.signals, now }).degraded.filter(
102 (d) => d.cause === "mirror",
103 );
104
105 beforeAll(async () => {
106 root = mkdtempSync(join(tmpdir(), "forge-mirror-"));
107 app = createApp({ dataDir: root, port: 0 });
108 const u = await createUser(app.db, {
109 trusted: true,
110 username: "alice",
111 email: "[email protected]",
112 password: "a-good-passphrase",
113 adminIfFirst: true,
114 });
115 if (!u.ok) throw new Error(u.error);
116 admin = u.value;
117 });
118 afterAll(async () => {
119 primary.stop();
120 offbox.stop();
121 await rm(root, { recursive: true, force: true });
122 });
123
124 test("a snapshot lands in both buckets, and the page's facts say so", async () => {
125 const svc = startSnapshots(app, src(), { version: "t", nightly: false, mirror: dst() });
126 const m = await svc.now();
127 const state = await svc.mirrorNow();
128 expect(state?.reachable).toBe(true);
129 expect(state?.failingSince).toBeUndefined();
130 const there = await listSnapshots(dst());
131 expect(there.map((x) => x.name)).toEqual([m.name]);
132 // Every file the manifest names is in the off-box bucket, byte for byte.
133 for (const f of m.files) {
134 const a = await src().get(`${SNAPSHOT_PREFIX}${m.name}/${f.path}`);
135 const b = await dst().get(`${SNAPSHOT_PREFIX}${m.name}/${f.path}`);
136 expect(a).toBeDefined();
137 expect(Buffer.from(b!).equals(Buffer.from(a!))).toBe(true);
138 }
139 expect(svc.mirrored()?.newest).toBe(m.name);
140 expect(board(Date.now())).toHaveLength(0);
141 await svc.stop();
142 });
143
144 test("an unreachable mirror is one line on the board and one push", async () => {
145 const sent: string[] = [];
146 setNotifyUrl(app.db, admin.id, "https://ntfy.example.com/topic");
147 let clock = Date.now();
148 // The notifier's first look is its baseline: it starts on a healthy mirror.
149 recordMirror(root, { where: "x", attemptAt: new Date(clock).toISOString(), reachable: true, syncedAt: new Date(clock).toISOString() });
150 const n = startNotifier(app, {
151 forgeUrl: "https://forge.example.com",
152 now: () => clock,
153 send: async (_u, body) => (sent.push(body), true),
154 clockMs: 20,
155 });
156 await n.settled();
157 offbox.down = true;
158 const svc = startSnapshots(app, src(), { version: "t", nightly: false, mirror: dst() });
159 await svc.now();
160 const state = await svc.mirrorNow();
161 expect(state?.reachable).toBe(false);
162 const line = board(Date.now());
163 expect(line).toHaveLength(1);
164 expect(line[0]!.sentence).toContain("unreachable");
165 expect(line[0]!.href).toBe("/settings/backups");
166 // A second failing pass is the same cause, not a second line.
167 const first = lastMirror(root)!.failingSince;
168 await svc.mirrorNow();
169 expect(lastMirror(root)!.failingSince).toBe(first);
170 expect(board(Date.now())).toHaveLength(1);
171
172 // The clock wakes the notifier a few times: one push, however many ticks.
173 for (let i = 0; i < 4; i++) {
174 clock += 60_000;
175 await Bun.sleep(40);
176 await n.settled();
177 }
178 n.stop();
179 expect(sent).toHaveLength(1);
180 expect(sent[0]).toContain("off-box mirror");
181 expect(sent[0]).toContain("unreachable");
182 await svc.stop();
183 });
184
185 test("a mirror that comes back catches up and the line goes", async () => {
186 offbox.down = false;
187 const svc = startSnapshots(app, src(), { version: "t", nightly: false, mirror: dst() });
188 const state = await svc.mirrorNow();
189 expect(state?.failingSince).toBeUndefined();
190 expect((await listSnapshots(dst())).length).toBe((await listSnapshots(src())).length);
191 expect(board(Date.now())).toHaveLength(0);
192 await svc.stop();
193 });
194
195 test("a snapshot that did not land says which, and a half-copied one is never listed", async () => {
196 const s = src();
197 const m = (await listSnapshots(s))[0]!;
198 const broken = dirStore(join(root, "dst-dir"));
199 let puts = 0;
200 const flaky = {
201 ...broken,
202 put: async (k: string, b: Uint8Array | string) => {
203 if (++puts > 1) throw new Error("quota exceeded");
204 await broken.put(k, b);
205 },
206 };
207 const state = await mirrorPass(root, s, flaky, { now: Date.now() });
208 expect(state.reachable).toBe(true);
209 expect(state.failed).toBeDefined();
210 expect(mirrorNeed(state, Date.now())?.sentence).toContain("did not land");
211 expect(await listSnapshots(broken)).toEqual([]);
212 expect(await broken.get(`${SNAPSHOT_PREFIX}${m.name}/manifest.json`)).toBeUndefined();
213 // Reset to the good mirror for what follows.
214 await mirrorPass(root, s, dst());
215 });
216
217 test("a mirror not confirmed level for a day is a line, once, until it is level again", () => {
218 const synced = new Date(T0).toISOString();
219 const state = { where: "b2/offbox", attemptAt: synced, reachable: true, syncedAt: synced, newest: "n" };
220 expect(mirrorNeed(state, T0 + MIRROR_STALE_MS)).toBeUndefined();
221 const stale = mirrorNeed(state, T0 + MIRROR_STALE_MS + 1);
222 expect(stale?.sentence).toContain("over a day");
223 expect(stale?.key).toBe(`stale:${synced}`);
224 recordMirror(root, state);
225 expect(board(T0 + MIRROR_STALE_MS + 1)).toHaveLength(1);
226 expect(board(T0 + 1000)).toHaveLength(0);
227 recordMirror(root, undefined);
228 expect(board(T0 + 5 * MIRROR_STALE_MS)).toHaveLength(0);
229 });
230
231 test("the mirror comes from the environment when nothing is sealed, and from nowhere otherwise", () => {
232 expect(resolveMirror({ env: {} })).toBeUndefined();
233 expect(resolveMirror({ env: { FORGE_MIRROR_S3_ENDPOINT: "http://x", FORGE_MIRROR_S3_BUCKET: "b" } })).toBeUndefined();
234 const m = resolveMirror({
235 env: {
236 FORGE_MIRROR_S3_ENDPOINT: "https://s3.b2.example.com",
237 FORGE_MIRROR_S3_BUCKET: "offbox",
238 FORGE_MIRROR_S3_ACCESS_KEY: "a",
239 FORGE_MIRROR_S3_SECRET_KEY: "s",
240 },
241 });
242 expect(m?.source).toBe("env");
243 expect(m?.store.where).toBe("s3.b2.example.com/offbox");
244 });
245 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs