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

Recovery on one page: docs/RECOVERY.md with the restore command, the boot on a side port, the manual tarball route, and a weekly drill that posts its result #1425

Closed opened this in answer to
Closed without merging

scout/forge:scout/1219-recovery-on-one-page-docs-recovery-md-wi → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
5 files changed +244 −0
.forgejo/workflows/recovery-drill.yml added +36
@@ -0,0 +1,36 @@
1 name: recovery-drill
2 # Weekly proof that the newest snapshot restores and boots (docs/RECOVERY.md):
3 # restore into a scratch directory, boot on a side port, read health, and
4 # post the result on the recovery issue. A failed drill mentions the owner
5 # there and turns this run red.
6 on:
7 workflow_dispatch: {}
8 schedule:
9 - cron: "17 5 * * 1"
10
11 jobs:
12 drill:
13 runs-on: isolated
14 timeout-minutes: 120
15 steps:
16 - name: clone source at this ref
17 env:
18 TOKEN: ${{ github.token }}
19 run: |
20 set -eu
21 git clone "http://x-access-token:[email protected]:3000/${GITHUB_REPOSITORY}.git" src
22 cd src
23 git checkout -q "$GITHUB_SHA"
24 bun install --frozen-lockfile
25 - name: restore, boot, report
26 working-directory: src
27 env:
28 S3_ENDPOINT: ${{ secrets.S3_ENDPOINT }}
29 S3_BUCKET: ${{ secrets.S3_BUCKET }}
30 S3_REGION: ${{ secrets.S3_REGION }}
31 S3_ACCESS_KEY: ${{ secrets.S3_ACCESS_KEY }}
32 S3_SECRET_KEY: ${{ secrets.S3_SECRET_KEY }}
33 FORGE_SNAPSHOT_PASSPHRASE: ${{ secrets.FORGE_SNAPSHOT_PASSPHRASE }}
34 FORGE_URL: ${{ github.server_url }}
35 FORGE_TOKEN: ${{ github.token }}
36 run: bun scripts/recovery-drill.ts
docs/RECOVERY.md added +61
@@ -0,0 +1,61 @@
1 # Recovery — the forge back from the bucket
2
3 Print this. Keep it somewhere that is not the forge. Longer reading:
4 [SNAPSHOT.md](SNAPSHOT.md), [RESTORE.md](RESTORE.md) (fresh machine).
5
6 ## Where the snapshots are
7
8 The platform's Backblaze bucket (`S3_BUCKET`, at `S3_ENDPOINT`, region
9 `S3_REGION`), under `snapshots/<stamp>/` (for example
10 `2026-10-13T00-45-35Z`). Hand-made tarballs live under `manual/<stamp>/`.
11 The Backups page of the forge shows the bucket; the owner's safe holds the
12 rest.
13
14 ## What a restore needs
15
16 Export `S3_ENDPOINT S3_BUCKET S3_REGION S3_ACCESS_KEY S3_SECRET_KEY`, and
17 `FORGE_SNAPSHOT_PASSPHRASE` from the owner's safe. Without the passphrase the
18 restore still works and lists the sealed values to set again.
19
20 ## The command
21
22 `bun run src/snapshot/restore.ts <snapshot-name|latest> <data-dir>`
23
24 The data directory must be empty. `latest` is the newest snapshot. A wrong
25 passphrase refuses before it writes anything.
26
27 ## Boot it on a side port
28
29 `FORGE_DATA=<data-dir> PORT=3999 FORGE_SSH_PORT=0 bun run src/main.ts`
30
31 Look at, in this order:
32
33 1. `curl localhost:3999/api/v1/health`: `ok` is true.
34 2. The home page, signed in as the owner.
35 3. One repository's issues: the list and a thread open.
36
37 Then point traffic at it, or copy the directory to where the forge lives.
38
39 ## What is not in a snapshot
40
41 - Sealed values (secrets, app variables) when the passphrase is missing: set
42 them again by hand; the restore names them.
43 - App variables are sealed; the apps redeploy on boot but need them set.
44 - The crew's clones: they are working copies, made again on the next run.
45
46 ## The second route: the tarball
47
48 If the snapshot is unreadable or the restore command will not run, take the
49 newest `manual/<stamp>/` from the same bucket, download the encrypted archive in it, then:
50
51 `openssl enc -d -aes-256-cbc -pbkdf2 -pass file:<passphrase> -in <archive> | tar -x -C <empty-dir>`
52
53 Prefer it when the forge's code is broken or gone, since it needs only
54 `openssl` and `tar`; it is a whole data directory, not per repository.
55
56 ## The weekly drill
57
58 `.forgejo/workflows/recovery-drill.yml` runs `scripts/recovery-drill.ts` on
59 Mondays: it restores the latest snapshot into a scratch directory, boots it
60 on a side port, reads health, and posts the result on issue #1219. A failed
61 drill mentions the owner there and the run goes red.
scripts/gate.ts +2
@@ -44,6 +44,8 @@ export const GATE: readonly string[] = [
4444 "test/event-order.test.ts",
4545 "test/refresh-meta.test.ts",
4646 "test/restore-card.test.ts",
47 "test/recovery-doc.test.ts",
48 "test/review-from-check.test.ts",
4749 "test/returns.test.ts",
4850 "test/review-route.test.ts",
4951 "test/review-lines.test.ts",
scripts/recovery-drill.ts added +106
@@ -0,0 +1,106 @@
1 /**
2 * The weekly restore drill (docs/RECOVERY.md): restore the newest snapshot
3 * into a scratch directory, boot the forge on it on a side port, read its
4 * health, and say what came back as a comment on the recovery issue. A
5 * failed drill says so on the same issue, naming the owner, and exits 1 so
6 * the scheduled run is red.
7 *
8 * bun scripts/recovery-drill.ts
9 *
10 * Reads the restore's own environment (`S3_*`, `FORGE_SNAPSHOT_PASSPHRASE`)
11 * and, to post, `FORGE_URL`, `FORGE_TOKEN`; `RECOVERY_ISSUE` (default 1219)
12 * and `RECOVERY_REPO` (default trevato/forge). Without a token the report
13 * is printed only.
14 */
15
16 import { mkdtempSync, rmSync } from "node:fs";
17 import { tmpdir } from "node:os";
18 import { join } from "node:path";
19
20 export interface Drill {
21 readonly ok: boolean;
22 readonly snapshot: string;
23 readonly restored: string;
24 readonly health: string;
25 readonly seconds: number;
26 }
27
28 /** The comment a drill posts: plain text, one line per fact. */
29 export function report(d: Drill, owner = "trevato"): string {
30 const head = d.ok
31 ? `Restore drill passed: ${d.snapshot}, ${d.seconds}s.`
32 : `@${owner} Restore drill FAILED: ${d.snapshot || "no snapshot"}, ${d.seconds}s.`;
33 return [head, "", `restore: ${d.restored}`, `health: ${d.health}`].join("\n");
34 }
35
36 async function run(cmd: string[], env: Record<string, string | undefined>) {
37 const p = Bun.spawn(cmd, { env, stdout: "pipe", stderr: "pipe" });
38 const [out, err] = await Promise.all([
39 new Response(p.stdout).text(),
40 new Response(p.stderr).text(),
41 ]);
42 return { code: await p.exited, out: out.trim(), err: err.trim() };
43 }
44
45 export async function drill(env = process.env): Promise<Drill> {
46 const started = Date.now();
47 const seconds = () => Math.round((Date.now() - started) / 1000);
48 const scratch = mkdtempSync(join(tmpdir(), "forge-drill-"));
49 const data = join(scratch, "data");
50 let snapshot = "";
51 let restored = "not run";
52 let health = "not read";
53 let server: ReturnType<typeof Bun.spawn> | undefined;
54 try {
55 const restore = await run(
56 ["bun", "run", "src/snapshot/restore.ts", "latest", data],
57 env,
58 );
59 restored = (restore.code === 0 ? restore.out : restore.err || restore.out).slice(0, 800);
60 snapshot = restore.out.match(/^restored (\S+)/)?.[1] ?? "";
61 if (restore.code !== 0) return { ok: false, snapshot, restored, health, seconds: seconds() };
62 const port = 20000 + Math.floor(Math.random() * 20000);
63 server = Bun.spawn(["bun", "run", "src/main.ts"], {
64 env: { ...env, FORGE_DATA: data, PORT: String(port), FORGE_SSH_PORT: "0" },
65 stdout: "ignore",
66 stderr: "ignore",
67 });
68 for (let i = 0; i < 60; i++) {
69 try {
70 const r = await fetch(`http://127.0.0.1:${port}/api/v1/health`);
71 const body = (await r.json()) as { ok?: boolean };
72 health = `HTTP ${r.status} ${JSON.stringify(body).slice(0, 400)}`;
73 return { ok: r.ok && body.ok !== false, snapshot, restored, health, seconds: seconds() };
74 } catch {
75 await Bun.sleep(1000);
76 }
77 }
78 health = "the restored forge did not answer in 60s";
79 return { ok: false, snapshot, restored, health, seconds: seconds() };
80 } catch (e) {
81 return { ok: false, snapshot, restored, health: String(e), seconds: seconds() };
82 } finally {
83 server?.kill();
84 rmSync(scratch, { recursive: true, force: true });
85 }
86 }
87
88 if (import.meta.main) {
89 const env = process.env;
90 const result = await drill(env);
91 const text = report(result);
92 console.log(text);
93 const url = env["FORGE_URL"];
94 const token = env["FORGE_TOKEN"];
95 if (url && token) {
96 const repo = env["RECOVERY_REPO"] ?? "trevato/forge";
97 const issue = env["RECOVERY_ISSUE"] ?? "1219";
98 const res = await fetch(`${url}/api/v1/repos/${repo}/issues/${issue}/comments`, {
99 method: "POST",
100 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
101 body: JSON.stringify({ body: text }),
102 });
103 if (!res.ok) console.error(`could not post the report: HTTP ${res.status}`);
104 }
105 process.exit(result.ok ? 0 : 1);
106 }
test/recovery-doc.test.ts added +39
@@ -0,0 +1,39 @@
1 /**
2 * docs/RECOVERY.md cannot drift from the code: it names every variable the
3 * snapshot store reads and the restore command as restore.ts prints it, and
4 * the drill's report says what failed.
5 */
6 import { expect, test } from "bun:test";
7 import { readFileSync } from "node:fs";
8 import { join } from "node:path";
9 import { report } from "../scripts/recovery-drill.ts";
10
11 const root = join(import.meta.dir, "..");
12 const doc = readFileSync(join(root, "docs/RECOVERY.md"), "utf8");
13
14 test("the document names every environment variable store.ts reads", () => {
15 const source = readFileSync(join(root, "src/snapshot/store.ts"), "utf8");
16 const names = new Set([...source.matchAll(/env\["([A-Z0-9_]+)"\]/g)].map((m) => m[1]!));
17 expect(names.size).toBeGreaterThanOrEqual(5);
18 for (const name of names) expect(doc).toContain(name);
19 expect(doc).toContain("FORGE_SNAPSHOT_PASSPHRASE");
20 });
21
22 test("the document carries the restore command exactly as restore.ts prints it", () => {
23 const source = readFileSync(join(root, "src/snapshot/restore.ts"), "utf8");
24 const usage = source.match(/"usage: (bun run src\/snapshot\/restore\.ts [^"]+)"/)?.[1];
25 expect(usage).toBeDefined();
26 expect(doc).toContain(`\`${usage}\``);
27 });
28
29 test("the document gives the manual route and the health look", () => {
30 expect(doc).toContain("manual/<stamp>/");
31 expect(doc).toContain("openssl enc -d -aes-256-cbc -pbkdf2 -pass file:<passphrase>");
32 expect(doc).toContain("/api/v1/health");
33 });
34
35 test("a failed drill mentions the owner; a passing one does not", () => {
36 const d = { ok: false, snapshot: "s", restored: "r", health: "h", seconds: 3 };
37 expect(report(d)).toStartWith("@trevato Restore drill FAILED");
38 expect(report({ ...d, ok: true })).toStartWith("Restore drill passed");
39 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs