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 #1222
mason/forge:mason/1219-recovery-on-one-page-docs-recovery-md-wi → main 6 commits fork
9 files
changed +751
−6
.forgejo/workflows/restore-drill.yml added +54
| @@ -0,0 +1,54 @@ | ||
| 1 | name: restore-drill | |
| 2 | # The weekly restore drill (docs/RESTORE.md): the newest snapshot restored | |
| 3 | # into a scratch directory, a forge booted on it on a side port, health and | |
| 4 | # counts read, the result a comment on the recovery issue. A failed drill | |
| 5 | # also opens an issue assigned to DRILL_OWNER — their inbox. | |
| 6 | # | |
| 7 | # Secrets this needs, in the repository's Actions secrets: the five S3_* | |
| 8 | # the forge runs under, FORGE_SNAPSHOT_PASSPHRASE, and DRILL_FORGE_TOKEN (a | |
| 9 | # token that may comment and open issues on DRILL_REPO). | |
| 10 | on: | |
| 11 | schedule: | |
| 12 | - cron: "0 3 * * 0" | |
| 13 | workflow_dispatch: {} | |
| 14 | ||
| 15 | jobs: | |
| 16 | drill: | |
| 17 | runs-on: isolated | |
| 18 | timeout-minutes: 180 | |
| 19 | env: | |
| 20 | REGISTRY: forgejo-http.forgejo.svc.cluster.local:3000 | |
| 21 | steps: | |
| 22 | - name: clone source at this ref | |
| 23 | env: | |
| 24 | TOKEN: ${{ github.token }} | |
| 25 | run: | | |
| 26 | set -eu | |
| 27 | git clone "http://x-access-token:$TOKEN@$REGISTRY/$GITHUB_REPOSITORY.git" src | |
| 28 | cd src | |
| 29 | git checkout -q "$GITHUB_SHA" | |
| 30 | ||
| 31 | - name: install dependencies | |
| 32 | working-directory: src | |
| 33 | run: bun install --frozen-lockfile | |
| 34 | ||
| 35 | - name: restore, boot, read, post | |
| 36 | working-directory: src | |
| 37 | env: | |
| 38 | S3_ENDPOINT: ${{ secrets.S3_ENDPOINT }} | |
| 39 | S3_BUCKET: ${{ secrets.S3_BUCKET }} | |
| 40 | S3_REGION: ${{ secrets.S3_REGION }} | |
| 41 | S3_ACCESS_KEY: ${{ secrets.S3_ACCESS_KEY }} | |
| 42 | S3_SECRET_KEY: ${{ secrets.S3_SECRET_KEY }} | |
| 43 | FORGE_SNAPSHOT_PASSPHRASE: ${{ secrets.FORGE_SNAPSHOT_PASSPHRASE }} | |
| 44 | DRILL_FORGE_URL: https://forge.open-platform.sh | |
| 45 | DRILL_FORGE_TOKEN: ${{ secrets.DRILL_FORGE_TOKEN }} | |
| 46 | DRILL_REPO: trevato/forge | |
| 47 | # #1147, "Recovery you can print on a notecard": the drill's history. | |
| 48 | DRILL_ISSUE: "1147" | |
| 49 | DRILL_OWNER: trevato | |
| 50 | run: | | |
| 51 | set -eu | |
| 52 | scratch="$(mktemp -d /tmp/drill.XXXXXX)" | |
| 53 | trap 'rm -rf "$scratch"' EXIT | |
| 54 | bun run src/snapshot/drill.ts "$scratch" |
README.md +3
| @@ -360,6 +360,9 @@ it answers by default: `.well-known`, feeds, cards, the manifest. | ||
| 360 | 360 | |
| 361 | 361 | `docs/SNAPSHOT.md` is a forge back from a copy: what a nightly snapshot |
| 362 | 362 | holds, where it goes, and the one command that restores it. |
| 363 | `docs/RESTORE.md` is the printable card: the restore lines, a look on a | |
| 364 | side port, the manual tarball route, and the weekly drill | |
| 365 | (`src/snapshot/drill.ts`) that proves it. | |
| 363 | 366 | |
| 364 | 367 | `docs/EXTRACT.md` is the forge on a machine of its own, and the platform it |
| 365 | 368 | grew up in switched off: what a host owes it, the moves in order, and what is |
docs/RESTORE.md +35 −5
| @@ -4,14 +4,17 @@ Print this. Keep it somewhere that is not the forge. | ||
| 4 | 4 | |
| 5 | 5 | ## Have ready |
| 6 | 6 | |
| 7 | - The **passphrase** (`FORGE_SNAPSHOT_PASSPHRASE`). Without it every sealed | |
| 8 | value is lost and set again by hand; the rest restores. | |
| 7 | - The **passphrase** (`FORGE_SNAPSHOT_PASSPHRASE`, in the owner's safe). | |
| 8 | Without it every sealed value is lost and set again by hand; the rest restores. | |
| 9 | 9 | - The **store address**: the directory (`FORGE_SNAPSHOT_DIR`) or the bucket |
| 10 | 10 | (`S3_ENDPOINT`, `S3_BUCKET`, `S3_ACCESS_KEY`, `S3_SECRET_KEY`, |
| 11 | `S3_REGION`; export them in place of line 3). | |
| 11 | `S3_REGION`, from the platform's secrets; export them in place of line 3). | |
| 12 | Snapshots sit under `snapshots/<name>/`, the newest fourteen kept. | |
| 12 | 13 | - The **keys**: access to the forge's git remote and the store's credentials. |
| 13 | 14 | The forge's own host key and secret key come out of the snapshot. |
| 14 | 15 | - A machine with `git`, `bun` and an empty data directory. |
| 16 | - Not in any snapshot: the forge's environment (`S3_*`, model keys, the | |
| 17 | passphrase); the crew's clones, checks and previews, which a boot rebuilds. | |
| 15 | 18 | |
| 16 | 19 | ## The lines |
| 17 | 20 | |
| @@ -31,5 +34,32 @@ snapshot, so this card cannot drift from the command. | ||
| 31 | 34 | The restore prints what it brought back. A wrong passphrase refuses before |
| 32 | 35 | writing anything; a missing one restores without the key and lists the |
| 33 | 36 | sealed values to set again. To pick an older snapshot, put its name |
| 34 | (`2026-09-22T08-00-00Z`) where line 5 says `latest`. Details: | |
| 35 | [](SNAPSHOT.md). | |
| 37 | (`2026-09-22T08-00-00Z`) where line 5 says `latest`. From the bucket it is | |
| 38 | slow: 350 MiB and 110 repositories took 81 minutes on 2026-10-13. | |
| 39 | ||
| 40 | ## Before line 7, look on a side port | |
| 41 | ||
| 42 | `bun run src/snapshot/look.ts <data-dir> 18080` | |
| 43 | ||
| 44 | The drill's boot, on 127.0.0.1: no crew, checks, apps, webhooks, origin | |
| 45 | sync or snapshots (`src/main.ts` starts them all). Look: `/api/v1/health` | |
| 46 | ok; the home, signed in as the owner; one repository's issues. Then Ctrl-C, | |
| 47 | stop the old forge, run line 7 with the real `PORT` and URL (or move DNS). | |
| 48 | ||
| 49 | ## The manual tarball, when restore.ts cannot | |
| 50 | ||
| 51 | Nothing in the forge writes these: an operator places tarballs by hand | |
| 52 | under `manual/<stamp>/` in the bucket, sealed with the same passphrase. If | |
| 53 | any are there, put the passphrase in a file, then for each, and look as above: | |
| 54 | ||
| 55 | openssl enc -d -aes-256-cbc -pbkdf2 -pass file:<passphrase-file> -in <file> | tar -x -C <data-dir> | |
| 56 | ||
| 57 | It is a raw copy: `secret.key` travels inside, so the passphrase is all | |
| 58 | that protects it. Use it when restore.ts refuses a snapshot or none is newer. | |
| 59 | ||
| 60 | ## The weekly drill | |
| 61 | ||
| 62 | Sundays, `.forgejo/workflows/restore-drill.yml` runs | |
| 63 | `bun run src/snapshot/drill.ts <empty scratch dir>`: the newest snapshot | |
| 64 | booted as the look above, health and counts a comment on #1147 (the | |
| 65 | recovery issue); a failure opens one for the owner. Why: [](SNAPSHOT.md). |
scripts/gate.ts +2
| @@ -104,6 +104,8 @@ export const GATE: readonly string[] = [ | ||
| 104 | 104 | "test/helpers.test.ts", |
| 105 | 105 | "test/shards.test.ts", |
| 106 | 106 | "test/snapshot-store.test.ts", |
| 107 | "test/recovery-doc.test.ts", | |
| 108 | "test/recovery-drill.test.ts", | |
| 107 | 109 | "test/migrate.test.ts", |
| 108 | 110 | "test/schema-additive.test.ts", |
| 109 | 111 | "test/schema-migrations.test.ts", |
src/snapshot/drill.ts added +287
| @@ -0,0 +1,287 @@ | ||
| 1 | /** | |
| 2 | * The restore drill: the newest snapshot brought back into a scratch | |
| 3 | * directory, a forge booted on it on a side port, and what it answers | |
| 4 | * read back — health, the home page, and the counts a person would check | |
| 5 | * (repositories, users, issues, pulls, apps). `docs/RESTORE.md` is the | |
| 6 | * card a person follows; this is the same restore and boot, on a clock. | |
| 7 | * | |
| 8 | * The boot is the side-port look's (`look.ts`): the forge's own and | |
| 9 | * nothing more, so a drill leaves no mark outside its scratch directory. | |
| 10 | * | |
| 11 | * bun run src/snapshot/drill.ts <empty scratch dir> | |
| 12 | * | |
| 13 | * with the same `S3_*` and `FORGE_SNAPSHOT_PASSPHRASE` a restore needs. | |
| 14 | * Given `DRILL_FORGE_URL` and `DRILL_FORGE_TOKEN`, the result is posted as | |
| 15 | * a comment on `DRILL_REPO` issue `DRILL_ISSUE`; a failed drill also opens | |
| 16 | * an issue assigned to `DRILL_OWNER`, which is their inbox. Exit 1 when | |
| 17 | * the drill failed, whether or not the post went through. | |
| 18 | */ | |
| 19 | ||
| 20 | import { join } from "node:path"; | |
| 21 | import { resolveDestination } from "./destination.ts"; | |
| 22 | import { bootQuiet } from "./look.ts"; | |
| 23 | import { restoreSnapshot } from "./restore.ts"; | |
| 24 | import { keyOf, listSnapshots } from "./snapshot.ts"; | |
| 25 | import type { Store } from "./store.ts"; | |
| 26 | ||
| 27 | export interface DrillCounts { | |
| 28 | readonly repos: number; | |
| 29 | readonly users: number; | |
| 30 | readonly issues: number; | |
| 31 | readonly pulls: number; | |
| 32 | readonly apps: number; | |
| 33 | } | |
| 34 | ||
| 35 | export interface DrillResult { | |
| 36 | readonly ok: boolean; | |
| 37 | /** The snapshot drilled; undefined when the store held none. */ | |
| 38 | readonly snapshot?: string; | |
| 39 | readonly version?: string; | |
| 40 | readonly startedAt: string; | |
| 41 | readonly seconds: number; | |
| 42 | /** Repositories the snapshot says it bundled, and how many came back. */ | |
| 43 | readonly bundled?: number; | |
| 44 | readonly restored?: number; | |
| 45 | readonly key?: "restored" | "raw" | "missing"; | |
| 46 | /** HTTP status of `/api/v1/health` and `/` on the booted copy. */ | |
| 47 | readonly health?: number; | |
| 48 | readonly home?: number; | |
| 49 | readonly counts?: DrillCounts; | |
| 50 | /** Everything that went wrong, in words; empty when `ok`. */ | |
| 51 | readonly problems: readonly string[]; | |
| 52 | } | |
| 53 | ||
| 54 | function countsOf(db: import("bun:sqlite").Database): DrillCounts { | |
| 55 | const n = (sql: string): number => | |
| 56 | db.query<{ n: number }, []>(sql).get()?.n ?? 0; | |
| 57 | return { | |
| 58 | repos: n("SELECT count(*) AS n FROM repo"), | |
| 59 | users: n("SELECT count(*) AS n FROM user WHERE kind = 'user'"), | |
| 60 | issues: n("SELECT count(*) AS n FROM issue WHERE kind = 'issue'"), | |
| 61 | pulls: n("SELECT count(*) AS n FROM issue WHERE kind = 'pull'"), | |
| 62 | apps: n("SELECT count(*) AS n FROM app"), | |
| 63 | }; | |
| 64 | } | |
| 65 | ||
| 66 | export async function runDrill( | |
| 67 | store: Store, | |
| 68 | scratch: string, | |
| 69 | options: { | |
| 70 | readonly passphrase?: string | undefined; | |
| 71 | readonly now?: () => number; | |
| 72 | } = {}, | |
| 73 | ): Promise<DrillResult> { | |
| 74 | const now = options.now ?? Date.now; | |
| 75 | const began = now(); | |
| 76 | const startedAt = new Date(began).toISOString(); | |
| 77 | const seconds = (): number => Math.round((now() - began) / 1000); | |
| 78 | const problems: string[] = []; | |
| 79 | ||
| 80 | const newest = (await listSnapshots(store))[0]; | |
| 81 | if (newest === undefined) | |
| 82 | return { | |
| 83 | ok: false, | |
| 84 | startedAt, | |
| 85 | seconds: seconds(), | |
| 86 | problems: [`no snapshot in ${store.where}`], | |
| 87 | }; | |
| 88 | const base = { snapshot: newest.name, version: newest.version, startedAt }; | |
| 89 | ||
| 90 | const dataDir = join(scratch, "data"); | |
| 91 | let done; | |
| 92 | try { | |
| 93 | done = await restoreSnapshot(store, newest.name, dataDir, { | |
| 94 | passphrase: options.passphrase, | |
| 95 | }); | |
| 96 | } catch (error) { | |
| 97 | return { | |
| 98 | ...base, | |
| 99 | ok: false, | |
| 100 | seconds: seconds(), | |
| 101 | problems: [`restore failed: ${error instanceof Error ? error.message : String(error)}`], | |
| 102 | }; | |
| 103 | } | |
| 104 | if (done.repos !== newest.repos) | |
| 105 | problems.push( | |
| 106 | `${done.repos} repositories came back of ${newest.repos} bundled`, | |
| 107 | ); | |
| 108 | if (keyOf(newest) === "wrapped" && done.key !== "restored") | |
| 109 | problems.push( | |
| 110 | options.passphrase | |
| 111 | ? "the key did not come back" | |
| 112 | : "no FORGE_SNAPSHOT_PASSPHRASE: the key was not tried", | |
| 113 | ); | |
| 114 | ||
| 115 | let health: number | undefined; | |
| 116 | let home: number | undefined; | |
| 117 | let counts: DrillCounts | undefined; | |
| 118 | try { | |
| 119 | const look = await bootQuiet(dataDir); | |
| 120 | try { | |
| 121 | health = (await fetch(`${look.servers.url}/api/v1/health`)).status; | |
| 122 | home = (await fetch(`${look.servers.url}/`, { redirect: "manual" })).status; | |
| 123 | counts = countsOf(look.app.db); | |
| 124 | } finally { | |
| 125 | look.stop(); | |
| 126 | } | |
| 127 | } catch (error) { | |
| 128 | problems.push( | |
| 129 | `boot failed: ${error instanceof Error ? error.message : String(error)}`, | |
| 130 | ); | |
| 131 | } | |
| 132 | if (health !== undefined && health !== 200) | |
| 133 | problems.push(`/api/v1/health answered ${health}`); | |
| 134 | // The home answers a stranger with the page or a way in; never a fault. | |
| 135 | if (home !== undefined && home >= 500) problems.push(`/ answered ${home}`); | |
| 136 | if (counts !== undefined && counts.repos < done.repos) | |
| 137 | problems.push( | |
| 138 | `${counts.repos} repositories indexed of ${done.repos} restored`, | |
| 139 | ); | |
| 140 | ||
| 141 | return { | |
| 142 | ...base, | |
| 143 | ok: problems.length === 0, | |
| 144 | seconds: seconds(), | |
| 145 | bundled: newest.repos, | |
| 146 | restored: done.repos, | |
| 147 | key: done.key, | |
| 148 | ...(health === undefined ? {} : { health }), | |
| 149 | ...(home === undefined ? {} : { home }), | |
| 150 | ...(counts === undefined ? {} : { counts }), | |
| 151 | problems, | |
| 152 | }; | |
| 153 | } | |
| 154 | ||
| 155 | const minutes = (s: number): string => | |
| 156 | s < 60 ? `${s} s` : `${Math.floor(s / 60)} min ${s % 60} s`; | |
| 157 | ||
| 158 | /** The drill as one comment: a verdict line, then the facts. */ | |
| 159 | export function drillReport(r: DrillResult): string { | |
| 160 | const day = r.startedAt.slice(0, 10); | |
| 161 | const head = r.ok | |
| 162 | ? `Restore drill, ${day}: passed in ${minutes(r.seconds)}.` | |
| 163 | : `Restore drill, ${day}: **failed** after ${minutes(r.seconds)}.`; | |
| 164 | const lines = [head, ""]; | |
| 165 | if (r.snapshot !== undefined) | |
| 166 | lines.push( | |
| 167 | `- snapshot \`${r.snapshot}\` (forge ${r.version ?? "?"}), key ${r.key ?? "not reached"}`, | |
| 168 | ); | |
| 169 | if (r.restored !== undefined) | |
| 170 | lines.push(`- repositories restored: ${r.restored} of ${r.bundled ?? "?"} bundled`); | |
| 171 | if (r.health !== undefined) | |
| 172 | lines.push(`- \`/api/v1/health\` ${r.health}, \`/\` ${r.home ?? "?"}`); | |
| 173 | if (r.counts !== undefined) | |
| 174 | lines.push( | |
| 175 | `- counts: ${r.counts.repos} repositories, ${r.counts.users} users, ${r.counts.issues} issues, ${r.counts.pulls} pulls, ${r.counts.apps} apps`, | |
| 176 | ); | |
| 177 | for (const p of r.problems) lines.push(`- problem: ${p}`); | |
| 178 | return lines.join("\n"); | |
| 179 | } | |
| 180 | ||
| 181 | export interface ReportTarget { | |
| 182 | /** The forge's base URL, without a trailing slash. */ | |
| 183 | readonly url: string; | |
| 184 | readonly token: string; | |
| 185 | /** `owner/name`. */ | |
| 186 | readonly repo: string; | |
| 187 | readonly issue: number; | |
| 188 | /** Who a failed drill is assigned to; unset leaves it unassigned. */ | |
| 189 | readonly owner?: string | undefined; | |
| 190 | } | |
| 191 | ||
| 192 | /** | |
| 193 | * Post the drill: a comment on the recovery issue, and for a failure an | |
| 194 | * issue of its own assigned to the owner. Returns what did not go through, | |
| 195 | * in words; empty when everything landed. | |
| 196 | */ | |
| 197 | export async function postDrill( | |
| 198 | r: DrillResult, | |
| 199 | to: ReportTarget, | |
| 200 | send: typeof fetch = fetch, | |
| 201 | ): Promise<string[]> { | |
| 202 | const failed: string[] = []; | |
| 203 | const api = `${to.url}/api/v1/repos/${to.repo}`; | |
| 204 | const call = async ( | |
| 205 | method: string, | |
| 206 | path: string, | |
| 207 | payload: unknown, | |
| 208 | ): Promise<Response | undefined> => { | |
| 209 | try { | |
| 210 | const res = await send(`${api}${path}`, { | |
| 211 | method, | |
| 212 | headers: { | |
| 213 | authorization: `Bearer ${to.token}`, | |
| 214 | "content-type": "application/json", | |
| 215 | }, | |
| 216 | body: JSON.stringify(payload), | |
| 217 | }); | |
| 218 | if (!res.ok) failed.push(`${method} ${path}: ${res.status}`); | |
| 219 | return res.ok ? res : undefined; | |
| 220 | } catch (error) { | |
| 221 | failed.push(`${method} ${path}: ${String(error)}`); | |
| 222 | return undefined; | |
| 223 | } | |
| 224 | }; | |
| 225 | const body = drillReport(r); | |
| 226 | await call("POST", `/issues/${to.issue}/comments`, { body }); | |
| 227 | if (!r.ok) { | |
| 228 | const opened = await call("POST", "/issues", { | |
| 229 | title: `Restore drill failed ${r.startedAt.slice(0, 10)}`, | |
| 230 | body: `${body}\n\nThe runbook is docs/RESTORE.md; the drill's history is on #${to.issue}.`, | |
| 231 | }); | |
| 232 | const number = opened | |
| 233 | ? ((await opened.json()) as { number?: unknown }).number | |
| 234 | : undefined; | |
| 235 | if (to.owner && typeof number === "number") | |
| 236 | await call("PUT", `/issues/${number}/assignee`, { assignee: to.owner }); | |
| 237 | } | |
| 238 | return failed; | |
| 239 | } | |
| 240 | ||
| 241 | /** The report target from the environment; undefined posts nothing. */ | |
| 242 | export function reportTargetFromEnv( | |
| 243 | env: Record<string, string | undefined> = process.env, | |
| 244 | ): ReportTarget | undefined { | |
| 245 | const url = env["DRILL_FORGE_URL"]?.trim().replace(/\/+$/, ""); | |
| 246 | const token = env["DRILL_FORGE_TOKEN"]?.trim(); | |
| 247 | const repo = env["DRILL_REPO"]?.trim() || "trevato/forge"; | |
| 248 | // #1147 is the recovery issue ("Recovery you can print on a notecard"). | |
| 249 | const issue = Number(env["DRILL_ISSUE"] ?? 1147); | |
| 250 | if (!url || !token) return undefined; | |
| 251 | if (!/^https?:\/\//.test(url)) throw new Error(`DRILL_FORGE_URL: ${url} is not a URL`); | |
| 252 | if (!/^[A-Za-z0-9_][A-Za-z0-9._-]*\/[A-Za-z0-9_][A-Za-z0-9._-]*$/.test(repo)) | |
| 253 | throw new Error(`DRILL_REPO: ${repo} is not owner/name`); | |
| 254 | if (!Number.isInteger(issue) || issue < 1) | |
| 255 | throw new Error(`DRILL_ISSUE: ${env["DRILL_ISSUE"]} is not an issue number`); | |
| 256 | const owner = env["DRILL_OWNER"]?.trim(); | |
| 257 | if (owner && !/^[A-Za-z0-9_][A-Za-z0-9._-]*$/.test(owner)) | |
| 258 | throw new Error(`DRILL_OWNER: ${owner} is not a username`); | |
| 259 | return { url, token, repo, issue, owner: owner || undefined }; | |
| 260 | } | |
| 261 | ||
| 262 | if (import.meta.main) { | |
| 263 | const [scratch] = process.argv.slice(2); | |
| 264 | if (!scratch) { | |
| 265 | // CLI usage on stderr for the person at the terminal. | |
| 266 | console.error("usage: bun run src/snapshot/drill.ts <empty scratch dir>"); | |
| 267 | process.exit(2); | |
| 268 | } | |
| 269 | const target = reportTargetFromEnv(); | |
| 270 | const store = resolveDestination()?.store; | |
| 271 | if (store === undefined) { | |
| 272 | // CLI message on stderr for the person at the terminal. | |
| 273 | console.error("no store: set S3_* as the forge has them, or FORGE_SNAPSHOT_DIR"); | |
| 274 | process.exit(2); | |
| 275 | } | |
| 276 | const result = await runDrill(store, scratch, { | |
| 277 | passphrase: process.env["FORGE_SNAPSHOT_PASSPHRASE"] || undefined, | |
| 278 | }); | |
| 279 | console.log(drillReport(result)); | |
| 280 | if (target !== undefined) { | |
| 281 | const failed = await postDrill(result, target); | |
| 282 | // CLI message on stderr: the drill ran, the post did not land. | |
| 283 | for (const f of failed) console.error(`post failed: ${f}`); | |
| 284 | if (failed.length > 0) process.exit(1); | |
| 285 | } | |
| 286 | process.exit(result.ok ? 0 : 1); | |
| 287 | } |
src/snapshot/look.ts added +66
| @@ -0,0 +1,66 @@ | ||
| 1 | /** | |
| 2 | * The side-port look: a restored data directory booted quiet, for a person | |
| 3 | * (or the drill) to read before the real forge starts on it. The boot is | |
| 4 | * the forge's own (`createApp`, `reconcile`, `serve`) and nothing more: no | |
| 5 | * webhook delivery, no origin sync, no notifier, no apps, no crew, no | |
| 6 | * checks, no nightly snapshot. A restored copy that delivered a queued | |
| 7 | * webhook, pushed to an origin or wrote a snapshot to the live store would | |
| 8 | * be a second forge acting as the first. | |
| 9 | * | |
| 10 | * bun run src/snapshot/look.ts <data-dir> <port> | |
| 11 | * | |
| 12 | * listens on 127.0.0.1 only and runs until stopped (Ctrl-C). | |
| 13 | */ | |
| 14 | ||
| 15 | import { createApp, type App } from "../app.ts"; | |
| 16 | import { reconcile } from "../core/reconcile.ts"; | |
| 17 | import { serve, type Servers } from "../http/server.ts"; | |
| 18 | ||
| 19 | export interface Look { | |
| 20 | readonly app: App; | |
| 21 | readonly servers: Servers; | |
| 22 | /** Stop the listener and close the database. */ | |
| 23 | stop(): void; | |
| 24 | } | |
| 25 | ||
| 26 | /** Boot `dataDir` quiet on 127.0.0.1; port 0 picks a free one. */ | |
| 27 | export async function bootQuiet(dataDir: string, port = 0): Promise<Look> { | |
| 28 | const app = createApp({ | |
| 29 | dataDir, | |
| 30 | port, | |
| 31 | host: "127.0.0.1", | |
| 32 | ...(port === 0 ? {} : { url: `http://127.0.0.1:${port}` }), | |
| 33 | }); | |
| 34 | try { | |
| 35 | await reconcile(app); | |
| 36 | const servers = await serve(app); | |
| 37 | return { | |
| 38 | app, | |
| 39 | servers, | |
| 40 | stop() { | |
| 41 | servers.stop(); | |
| 42 | app.close(); | |
| 43 | }, | |
| 44 | }; | |
| 45 | } catch (error) { | |
| 46 | app.close(); | |
| 47 | throw error; | |
| 48 | } | |
| 49 | } | |
| 50 | ||
| 51 | if (import.meta.main) { | |
| 52 | const [dataDir, portText] = process.argv.slice(2); | |
| 53 | const port = Number(portText); | |
| 54 | if (!dataDir || !Number.isInteger(port) || port < 1 || port > 65_535) { | |
| 55 | // CLI usage on stderr for the person at the terminal. | |
| 56 | console.error("usage: bun run src/snapshot/look.ts <data-dir> <port>"); | |
| 57 | process.exit(2); | |
| 58 | } | |
| 59 | const look = await bootQuiet(dataDir, port); | |
| 60 | // CLI message for the person at the terminal. | |
| 61 | console.log(`quiet forge on ${look.servers.url} (no crew, checks, apps, webhooks, sync or snapshots); Ctrl-C stops it`); | |
| 62 | process.on("SIGINT", () => { | |
| 63 | look.stop(); | |
| 64 | process.exit(0); | |
| 65 | }); | |
| 66 | } |
test/recovery-doc.test.ts added +90
| @@ -0,0 +1,90 @@ | ||
| 1 | /** | |
| 2 | * The card cannot drift from the code: `docs/RESTORE.md` names every | |
| 3 | * variable the bucket store reads, the passphrase the restore reads, the | |
| 4 | * side-port look as `look.ts` boots it, the manual tarball's openssl line | |
| 5 | * (run here on a tarball sealed the same way), and the drill command | |
| 6 | * exactly as `drill.ts` prints it. Its numbered restore lines and the look | |
| 7 | * are run by `test/restore-card.test.ts`. | |
| 8 | */ | |
| 9 | import { describe, expect, test } from "bun:test"; | |
| 10 | import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; | |
| 11 | import { tmpdir } from "node:os"; | |
| 12 | import { join } from "node:path"; | |
| 13 | ||
| 14 | const root = join(import.meta.dir, ".."); | |
| 15 | const read = (p: string) => readFileSync(join(root, p), "utf8"); | |
| 16 | const doc = read("docs/RESTORE.md"); | |
| 17 | ||
| 18 | describe("docs/RESTORE.md", () => { | |
| 19 | test("names every environment variable the store and the restore read", () => { | |
| 20 | const store = read("src/snapshot/store.ts"); | |
| 21 | const names = [...store.matchAll(/env\["([A-Z0-9_]+)"\]/g)].map((m) => m[1]!); | |
| 22 | expect(new Set(names)).toEqual( | |
| 23 | new Set(["S3_ENDPOINT", "S3_BUCKET", "S3_REGION", "S3_ACCESS_KEY", "S3_SECRET_KEY"]), | |
| 24 | ); | |
| 25 | for (const n of names) expect(doc).toContain(n); | |
| 26 | expect(read("src/snapshot/restore.ts")).toContain('process.env["FORGE_SNAPSHOT_PASSPHRASE"]'); | |
| 27 | expect(doc).toContain("FORGE_SNAPSHOT_PASSPHRASE"); | |
| 28 | }); | |
| 29 | ||
| 30 | test("carries the drill command as its usage line prints it", () => { | |
| 31 | const m = /"usage: (bun run [^"]+)"/.exec(read("src/snapshot/drill.ts")); | |
| 32 | if (!m) throw new Error("drill.ts prints no usage line"); | |
| 33 | expect(doc).toContain(`\`${m[1]!}\``); | |
| 34 | }); | |
| 35 | ||
| 36 | test("the side-port look is look.ts's own boot, which starts nothing but the forge", () => { | |
| 37 | expect(read("src/snapshot/look.ts")).toContain( | |
| 38 | '"usage: bun run src/snapshot/look.ts <data-dir> <port>"', | |
| 39 | ); | |
| 40 | expect(doc).toMatch(/^`bun run src\/snapshot\/look\.ts <data-dir> \d+`$/m); | |
| 41 | // main.ts is booted once, by line 7, and never on a side port: its | |
| 42 | // workers (crew, checks, delivery, sync, snapshots) are what the look | |
| 43 | // must not start. look.ts reaches only the forge's own boot. | |
| 44 | expect(doc.match(/bun run src\/main\.ts/g)).toHaveLength(1); | |
| 45 | const imports = [...read("src/snapshot/look.ts").matchAll(/^import .* from "([^"]+)";$/gm)] | |
| 46 | .map((i) => i[1]!) | |
| 47 | .sort(); | |
| 48 | expect(imports).toEqual(["../app.ts", "../core/reconcile.ts", "../http/server.ts"]); | |
| 49 | expect(read("src/snapshot/drill.ts")).toContain('import { bootQuiet } from "./look.ts";'); | |
| 50 | }); | |
| 51 | ||
| 52 | test("the drill workflow exists and runs weekly", () => { | |
| 53 | const workflow = read(".forgejo/workflows/restore-drill.yml"); | |
| 54 | expect(workflow).toContain("bun run src/snapshot/drill.ts"); | |
| 55 | expect(workflow).toContain("schedule:"); | |
| 56 | }); | |
| 57 | ||
| 58 | test("says the manual tarballs are placed by hand, and its openssl line opens one", () => { | |
| 59 | expect(doc).toContain("Nothing in the forge writes these"); | |
| 60 | const m = /^ {4}(openssl enc -d .+)$/m.exec(doc); | |
| 61 | if (!m) throw new Error("the card has no openssl line"); | |
| 62 | const dir = mkdtempSync(join(tmpdir(), "forge-manual-")); | |
| 63 | try { | |
| 64 | mkdirSync(join(dir, "src")); | |
| 65 | mkdirSync(join(dir, "data")); | |
| 66 | writeFileSync(join(dir, "src", "secret.key"), "k"); | |
| 67 | writeFileSync(join(dir, "pass"), "correct horse battery staple\n"); | |
| 68 | const line = m[1]! | |
| 69 | .replaceAll("<passphrase-file>", join(dir, "pass")) | |
| 70 | .replaceAll("<file>", join(dir, "data.tar.enc")) | |
| 71 | .replaceAll("<data-dir>", join(dir, "data")); | |
| 72 | // Sealed the way the card says a person seals one: the same cipher | |
| 73 | // and key derivation, the passphrase from a file. | |
| 74 | const seal = `tar -c -C "${dir}/src" . | openssl enc -aes-256-cbc -pbkdf2 -salt -pass file:"${dir}/pass" -out "${dir}/data.tar.enc"`; | |
| 75 | const run = Bun.spawnSync(["sh", "-ec", `${seal}\n${line}`], { | |
| 76 | stdout: "pipe", | |
| 77 | stderr: "pipe", | |
| 78 | }); | |
| 79 | expect(run.stderr.toString()).toBe(""); | |
| 80 | expect(run.exitCode).toBe(0); | |
| 81 | expect(readFileSync(join(dir, "data", "secret.key"), "utf8")).toBe("k"); | |
| 82 | } finally { | |
| 83 | rmSync(dir, { recursive: true, force: true }); | |
| 84 | } | |
| 85 | }); | |
| 86 | ||
| 87 | test("fits on one printed side", () => { | |
| 88 | expect(doc.split("\n").length).toBeLessThanOrEqual(66); | |
| 89 | }); | |
| 90 | }); |
test/recovery-drill.test.ts added +141
| @@ -0,0 +1,141 @@ | ||
| 1 | /** | |
| 2 | * The weekly restore drill. A forge with a person, a repository and an | |
| 3 | * issue is snapshotted; the drill restores the newest snapshot into a | |
| 4 | * scratch directory, boots it, and reports health and counts. An empty | |
| 5 | * store, a wrong passphrase and a missing one each fail it in words. The | |
| 6 | * report goes to the recovery issue; a failure also opens an issue | |
| 7 | * assigned to the owner. | |
| 8 | */ | |
| 9 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 10 | import { mkdtempSync } from "node:fs"; | |
| 11 | import { rm } from "node:fs/promises"; | |
| 12 | import { tmpdir } from "node:os"; | |
| 13 | import { join } from "node:path"; | |
| 14 | import { openIssue } from "../src/actions/issues.ts"; | |
| 15 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 16 | import { createApp, type App } from "../src/app.ts"; | |
| 17 | import { createUser } from "../src/core/users.ts"; | |
| 18 | import { loadKey } from "../src/kernel/secret.ts"; | |
| 19 | import { | |
| 20 | drillReport, | |
| 21 | postDrill, | |
| 22 | reportTargetFromEnv, | |
| 23 | runDrill, | |
| 24 | type DrillResult, | |
| 25 | } from "../src/snapshot/drill.ts"; | |
| 26 | import { takeSnapshot } from "../src/snapshot/snapshot.ts"; | |
| 27 | import { dirStore } from "../src/snapshot/store.ts"; | |
| 28 | ||
| 29 | const PASS = "correct horse battery staple"; | |
| 30 | ||
| 31 | describe("the restore drill", () => { | |
| 32 | let root: string; | |
| 33 | let app: App; | |
| 34 | const store = () => dirStore(join(root, "store")); | |
| 35 | const scratch = (n: string) => join(root, "scratch", n); | |
| 36 | ||
| 37 | beforeAll(async () => { | |
| 38 | root = mkdtempSync(join(tmpdir(), "forge-drill-")); | |
| 39 | app = createApp({ dataDir: join(root, "live"), port: 0 }); | |
| 40 | const a = await createUser(app.db, { | |
| 41 | trusted: true, | |
| 42 | username: "alice", | |
| 43 | email: "[email protected]", | |
| 44 | password: "a-good-passphrase", | |
| 45 | adminIfFirst: true, | |
| 46 | }); | |
| 47 | if (!a.ok) throw new Error(a.error); | |
| 48 | const repo = await createRepo(app, a.value, { name: "notes", visibility: "public" }); | |
| 49 | if (!repo.ok) throw new Error(String(repo.error)); | |
| 50 | const c = await commitToBranch(app, a.value, repo.value, { | |
| 51 | message: "first", | |
| 52 | files: [{ path: "README.md", content: "# notes\n" }], | |
| 53 | }); | |
| 54 | if (!c.ok) throw new Error(JSON.stringify(c.error)); | |
| 55 | const issue = await openIssue(app, a.value, repo.value, { title: "one", body: "" }); | |
| 56 | if (!issue.ok) throw new Error(JSON.stringify(issue.error)); | |
| 57 | // The key a sealed value would make; the snapshot carries it wrapped. | |
| 58 | loadKey(app.config.dataDir); | |
| 59 | await takeSnapshot( | |
| 60 | { | |
| 61 | db: app.db, | |
| 62 | dataDir: app.config.dataDir, | |
| 63 | reposRoot: app.reposRoot, | |
| 64 | version: "t", | |
| 65 | passphrase: PASS, | |
| 66 | }, | |
| 67 | store(), | |
| 68 | new Date("2026-10-13T00:45:35Z"), | |
| 69 | ); | |
| 70 | }, 60_000); | |
| 71 | ||
| 72 | afterAll(async () => { | |
| 73 | app.close(); | |
| 74 | await rm(root, { recursive: true, force: true }); | |
| 75 | }); | |
| 76 | ||
| 77 | test("the newest snapshot restores, boots, and its counts come back", async () => { | |
| 78 | const r = await runDrill(store(), scratch("pass"), { passphrase: PASS }); | |
| 79 | expect(r.problems).toEqual([]); | |
| 80 | expect(r.ok).toBe(true); | |
| 81 | expect(r.snapshot).toBe("2026-10-13T00-45-35Z"); | |
| 82 | expect(r.key).toBe("restored"); | |
| 83 | expect(r.restored).toBe(1); | |
| 84 | expect(r.health).toBe(200); | |
| 85 | expect(r.home).toBeLessThan(500); | |
| 86 | expect(r.counts).toEqual({ repos: 1, users: 1, issues: 1, pulls: 0, apps: 0 }); | |
| 87 | expect(drillReport(r)).toContain("passed"); | |
| 88 | expect(drillReport(r)).toContain("1 repositories, 1 users, 1 issues"); | |
| 89 | }); | |
| 90 | ||
| 91 | test("an empty store, a wrong passphrase and none each fail in words", async () => { | |
| 92 | const empty = await runDrill(dirStore(join(root, "nothing")), scratch("empty")); | |
| 93 | expect(empty.ok).toBe(false); | |
| 94 | expect(empty.problems[0]).toContain("no snapshot"); | |
| 95 | ||
| 96 | const wrong = await runDrill(store(), scratch("wrong"), { passphrase: "nope" }); | |
| 97 | expect(wrong.ok).toBe(false); | |
| 98 | expect(wrong.problems[0]).toContain("restore failed"); | |
| 99 | ||
| 100 | const none = await runDrill(store(), scratch("none")); | |
| 101 | expect(none.ok).toBe(false); | |
| 102 | expect(none.problems).toContain("no FORGE_SNAPSHOT_PASSPHRASE: the key was not tried"); | |
| 103 | expect(drillReport(none)).toContain("**failed**"); | |
| 104 | }); | |
| 105 | ||
| 106 | test("a pass is one comment; a failure also opens an issue assigned to the owner", async () => { | |
| 107 | const calls: { method: string; url: string; body: unknown }[] = []; | |
| 108 | const send = (async (url: string, init: RequestInit) => { | |
| 109 | calls.push({ method: init.method!, url, body: JSON.parse(String(init.body)) }); | |
| 110 | return Response.json({ number: 7 }, { status: 201 }); | |
| 111 | }) as unknown as typeof fetch; | |
| 112 | const to = { url: "https://forge.example", token: "t", repo: "o/forge", issue: 1147, owner: "alice" }; | |
| 113 | const passed: DrillResult = { ok: true, startedAt: "2026-10-19T03:00:00Z", seconds: 252, problems: [] }; | |
| 114 | expect(await postDrill(passed, to, send)).toEqual([]); | |
| 115 | expect(calls.map((c) => `${c.method} ${c.url}`)).toEqual([ | |
| 116 | "POST https://forge.example/api/v1/repos/o/forge/issues/1147/comments", | |
| 117 | ]); | |
| 118 | calls.length = 0; | |
| 119 | const failed: DrillResult = { ...passed, ok: false, problems: ["restore failed: x"] }; | |
| 120 | expect(await postDrill(failed, to, send)).toEqual([]); | |
| 121 | expect(calls.map((c) => `${c.method} ${c.url}`)).toEqual([ | |
| 122 | "POST https://forge.example/api/v1/repos/o/forge/issues/1147/comments", | |
| 123 | "POST https://forge.example/api/v1/repos/o/forge/issues", | |
| 124 | "PUT https://forge.example/api/v1/repos/o/forge/issues/7/assignee", | |
| 125 | ]); | |
| 126 | expect(calls[2]!.body).toEqual({ assignee: "alice" }); | |
| 127 | }); | |
| 128 | ||
| 129 | test("the report target is read at the boundary and refuses what is not one", () => { | |
| 130 | expect(reportTargetFromEnv({})).toBeUndefined(); | |
| 131 | expect( | |
| 132 | reportTargetFromEnv({ DRILL_FORGE_URL: "https://f.example/", DRILL_FORGE_TOKEN: "t" }), | |
| 133 | ).toEqual({ url: "https://f.example", token: "t", repo: "trevato/forge", issue: 1147, owner: undefined }); | |
| 134 | expect(() => | |
| 135 | reportTargetFromEnv({ DRILL_FORGE_URL: "https://f", DRILL_FORGE_TOKEN: "t", DRILL_REPO: "../x" }), | |
| 136 | ).toThrow("DRILL_REPO"); | |
| 137 | expect(() => | |
| 138 | reportTargetFromEnv({ DRILL_FORGE_URL: "https://f", DRILL_FORGE_TOKEN: "t", DRILL_ISSUE: "x" }), | |
| 139 | ).toThrow("DRILL_ISSUE"); | |
| 140 | }); | |
| 141 | }); |
test/restore-card.test.ts +73 −1
| @@ -4,8 +4,11 @@ | ||
| 4 | 4 | * taken here into a temporary directory; a card that drifts from the |
| 5 | 5 | * command goes red. Only the lines marked `# network` (clone, install) and |
| 6 | 6 | * `# boot` (start the forge) are skipped, and the test names them so a line |
| 7 | * cannot dodge the run by being marked. | |
| 7 | * cannot dodge the run by being marked. The side-port look is run too, on | |
| 8 | * the copy just restored: it answers health and leaves a queued webhook | |
| 9 | * queued, so the look is quiet in fact and not just in words. | |
| 8 | 10 | */ |
| 11 | import { Database } from "bun:sqlite"; | |
| 9 | 12 | import { afterAll, beforeAll, expect, test } from "bun:test"; |
| 10 | 13 | import { existsSync, mkdtempSync, readFileSync } from "node:fs"; |
| 11 | 14 | import { rm } from "node:fs/promises"; |
| @@ -14,6 +17,7 @@ import { join } from "node:path"; | ||
| 14 | 17 | import { createApp, type App } from "../src/app.ts"; |
| 15 | 18 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; |
| 16 | 19 | import { createUser } from "../src/core/users.ts"; |
| 20 | import { createWebhook } from "../src/core/webhooks.ts"; | |
| 17 | 21 | import { dirStore } from "../src/snapshot/store.ts"; |
| 18 | 22 | import { takeSnapshot } from "../src/snapshot/snapshot.ts"; |
| 19 | 23 | |
| @@ -26,6 +30,17 @@ const lines = [...card.matchAll(/^(\d+)\. `(.+)`$/gm)].map((m) => ({ | ||
| 26 | 30 | |
| 27 | 31 | let root: string; |
| 28 | 32 | let app: App; |
| 33 | // Where the fixture's webhook points: a restored copy that delivered it | |
| 34 | // would be a second forge acting as the first. | |
| 35 | let hooked = 0; | |
| 36 | const receiver = Bun.serve({ | |
| 37 | port: 0, | |
| 38 | hostname: "127.0.0.1", | |
| 39 | fetch() { | |
| 40 | hooked++; | |
| 41 | return new Response("ok"); | |
| 42 | }, | |
| 43 | }); | |
| 29 | 44 | |
| 30 | 45 | beforeAll(async () => { |
| 31 | 46 | root = mkdtempSync(join(tmpdir(), "forge-restore-card-")); |
| @@ -40,6 +55,11 @@ beforeAll(async () => { | ||
| 40 | 55 | if (!u.ok) throw new Error(u.error); |
| 41 | 56 | const repo = await createRepo(app, u.value, { name: "notes", visibility: "private" }); |
| 42 | 57 | if (!repo.ok) throw new Error(String(repo.error)); |
| 58 | const hook = createWebhook(app.db, { | |
| 59 | repoId: repo.value.id, | |
| 60 | url: `http://127.0.0.1:${receiver.port}/hook`, | |
| 61 | }); | |
| 62 | if (!hook.ok) throw new Error(hook.error); | |
| 43 | 63 | const c = await commitToBranch(app, u.value, repo.value, { |
| 44 | 64 | message: "first", |
| 45 | 65 | files: [{ path: "README.md", content: "# notes\n" }], |
| @@ -59,6 +79,7 @@ beforeAll(async () => { | ||
| 59 | 79 | }); |
| 60 | 80 | |
| 61 | 81 | afterAll(async () => { |
| 82 | receiver.stop(true); | |
| 62 | 83 | app.close(); |
| 63 | 84 | await rm(root, { recursive: true, force: true }); |
| 64 | 85 | }); |
| @@ -102,3 +123,54 @@ test("the card's own lines restore the snapshot into an empty directory", async | ||
| 102 | 123 | expect(existsSync(join(data, "forge.db"))).toBe(true); |
| 103 | 124 | expect(existsSync(join(data, "repos"))).toBe(true); |
| 104 | 125 | }); |
| 126 | ||
| 127 | test("the side-port look boots the restored copy quiet", async () => { | |
| 128 | const data = join(root, "restored"); | |
| 129 | expect(existsSync(join(data, "forge.db"))).toBe(true); | |
| 130 | const m = /^`(bun run src\/snapshot\/look\.ts <data-dir> \d+)`$/m.exec(card); | |
| 131 | if (!m) throw new Error("the card has no look line"); | |
| 132 | const free = Bun.serve({ port: 0, fetch: () => new Response() }); | |
| 133 | const port = free.port; | |
| 134 | free.stop(true); | |
| 135 | const argv = m[1]! | |
| 136 | .replace("<data-dir>", data) | |
| 137 | .replace(/ \d+$/, ` ${port}`) | |
| 138 | .split(" "); | |
| 139 | const pending = (): number => { | |
| 140 | const db = new Database(join(data, "forge.db"), { readonly: true }); | |
| 141 | try { | |
| 142 | return db | |
| 143 | .query<{ n: number }, []>( | |
| 144 | "SELECT count(*) AS n FROM webhook_delivery WHERE state = 'pending'", | |
| 145 | ) | |
| 146 | .get()!.n; | |
| 147 | } finally { | |
| 148 | db.close(); | |
| 149 | } | |
| 150 | }; | |
| 151 | const queued = pending(); | |
| 152 | expect(queued).toBeGreaterThan(0); | |
| 153 | const look = Bun.spawn(argv, { | |
| 154 | cwd: join(import.meta.dir, ".."), | |
| 155 | env: { PATH: process.env["PATH"] ?? "", HOME: process.env["HOME"] ?? root }, | |
| 156 | stdout: "pipe", | |
| 157 | stderr: "pipe", | |
| 158 | }); | |
| 159 | try { | |
| 160 | let health = 0; | |
| 161 | for (let i = 0; i < 100 && health !== 200; i++) { | |
| 162 | health = await fetch(`http://127.0.0.1:${port}/api/v1/health`) | |
| 163 | .then((r) => r.status) | |
| 164 | .catch(() => 0); | |
| 165 | if (health !== 200) await Bun.sleep(100); | |
| 166 | } | |
| 167 | expect(health).toBe(200); | |
| 168 | // main.ts sweeps the outbox the moment it boots; the look must not. | |
| 169 | await Bun.sleep(500); | |
| 170 | expect(hooked).toBe(0); | |
| 171 | expect(pending()).toBe(queued); | |
| 172 | } finally { | |
| 173 | look.kill("SIGINT"); | |
| 174 | await look.exited; | |
| 175 | } | |
| 176 | }, 20_000); |
new above
offline