Public: anyone can read this; the crew can change it.
Each hosted forge's state is written as one file to the parent's backup destination by the nightly, so one forge can be restored alone #13837
scout/forge:scout/13832-each-hosted-forge-s-state-is-written-as → main 10 commits fork 4 threads · 4 unresolved
12 files
changed +592
−83
- docs/features/README.md
- docs/features/forge-nightly-copy.md
- src/http/mcp/tools/forges.ts
- src/snapshot/service.ts
- src/spawn/archive.ts
- src/spawn/nightly_copy.ts
- src/tui/screens/forges.ts
- src/web/pages/backups.ts
- src/web/pages/forges.ts
- test/snapshot-children.test.ts
- test/spawn-sites.test.ts
- test/take-expect.test.ts
docs/features/README.md +1
docs/features/forge-nightly-copy.md added +26
| @@ -0,0 +1,26 @@ | ||
| 1 | # Nightly copy of each hosted forge | |
| 2 | ||
| 3 | After the forge's own nightly snapshot, every hosted forge is written as one file of its own to the same backup destination, so one lost forge can be brought back alone, without restoring the whole host. Code: `src/spawn/nightly_copy.ts` (the night), `src/spawn/archive.ts` (`archiveForge` with `keepRunning`, and Restore). | |
| 4 | ||
| 5 | ## What is copied | |
| 6 | ||
| 7 | The same file an archive is (see `forge-archive.md`): the forge's ledger (`<data>/spawn/<name>.json`) and its whole data directory (`<data>/children/<bodyId>/`), as one `.tar.gz`. Unlike an archive nothing is stopped or removed. The running forge's database is copied consistently with `VACUUM INTO`, off the serving thread. The other files are read as they stand. A file that changes while tar reads it (tar's exit 1) is taken as it is, and the next night copies it again. Any other tar failure fails that forge's copy, and nothing is stored for it. | |
| 8 | ||
| 9 | A forge whose files (sizes and times) and ledger have not changed since its last copy is not sent again, as long as the store still holds that copy. A store that has lost the file gets it again. | |
| 10 | ||
| 11 | ## Where the key lives | |
| 12 | ||
| 13 | One key per forge, replaced each night: `forge-snapshots/<name>.tar.gz` in the backup destination set on the Backups page. Snapshot retention only sweeps `snapshots/` and `chunks/`, so these copies are never pruned. This host also keeps a record of each forge's last copy at `<data>/archive/nightly/<name>.json`, and what the last night came to at `<data>/archive/nightly-outcome.json`. | |
| 14 | ||
| 15 | ## Size cap | |
| 16 | ||
| 17 | One file holds at most 256 MiB compressed (`ARCHIVE_MAX_BYTES`), the same as an archive. A forge over the cap is not copied, and it is named with its size: | |
| 18 | ||
| 19 | - **Backups page:** the "Hosted forges" block says what the last night came to, and names under "Not copied" every forge that was skipped or failed. | |
| 20 | - **Log:** a `snapshots` warning with the same words. | |
| 21 | ||
| 22 | ## Restoring one forge | |
| 23 | ||
| 24 | A forge that is not here now and has a nightly copy is listed under "Archived" on `/forges` ("not here now; nightly copy of …") with a **Restore** button. In the terminal, press `r` on the Forges screen and pick it. Both bring it back under the same name, and every other forge keeps running. MCP restores by name too: `forges` with `restore: "<name>"`, and its dry run lists the same forges. | |
| 25 | ||
| 26 | If this host's own disk was lost, its records went with it. Restore by name still works: it reads `forge-snapshots/<name>.tar.gz` from the destination and finds the forge's data directory from the file itself. A listing of names is not available then, because a sealed destination hides its keys, so name the forge: MCP `forges` with `restore: "<name>"`. |
src/http/mcp/tools/forges.ts +3 −3
| @@ -5,7 +5,7 @@ import { publicOrigin } from "../../../core/public_origin.ts"; | ||
| 5 | 5 | import { scopeAllows } from "../../../core/tokens.ts"; |
| 6 | 6 | import { clientLines } from "../../../spawn/client_words.ts"; |
| 7 | 7 | import { clientRows, listed } from "../../../spawn/clients.ts"; |
| 8 | import { archiveForge, archivedForges, restoreForge } from "../../../spawn/archive.ts"; | |
| 8 | import { archiveForge, restorableForges, restoreForge } from "../../../spawn/archive.ts"; | |
| 9 | 9 | import { CHILD_NAME } from "../../../spawn/placement.ts"; |
| 10 | 10 | import { checkMove } from "../../../spawn/move_check.ts"; |
| 11 | 11 | import { moveToCell } from "../../../spawn/move_cell.ts"; |
| @@ -16,7 +16,7 @@ const sentSays = (n: number) => (n === 0 ? "This forge has sent no forges yet." | ||
| 16 | 16 | |
| 17 | 17 | export const tool: Tool = { |
| 18 | 18 | name: "forges", |
| 19 | doc: "an admin's list of the forges sent from here: name, address, whom for, apps, claimed, stage (sent/opened/signed in/last tell; resend true when unopened 3 days: claim_link), last activity (a person or the crew, never a heartbeat), who claimed it and when, keep cost, archive reason, reachable, size, use, madeFrom; `{ forge, plan?, dryRun? }` reads a forge's plan (small|medium|large) or, with `plan`, grants it by hand; `size` workshop raises a forge; `{ forge, sandbox: true }` reads what moving a forge out of this forge's own process into a sandbox would meet (hooks, command-running keys, size) and with `dryRun: false` moves it, proven and put back on any failure (`acknowledge: true` when it was held for what its repositories hold); each forge carries `placement` and `where`; gift codes: `codes` true lists, `code` {plan, uses?, note?, expires?} makes (shown once), `revoke` id; planned unless `dryRun` is false; `archive` a name or names stops each, writes its data and ledger as one file to the backup destination, then removes it; `restore` a name brings an archived one back; `kind` refused lists the last 20 refused first asks; `kind` clients lists each client in the page's words", | |
| 19 | doc: "an admin's list of the forges sent from here: name, address, whom for, apps, claimed, stage (sent/opened/signed in/last tell; resend true when unopened 3 days: claim_link), last activity (a person or the crew, never a heartbeat), who claimed it and when, keep cost, archive reason, reachable, size, use, madeFrom; `{ forge, plan?, dryRun? }` reads a forge's plan (small|medium|large) or, with `plan`, grants it by hand; `size` workshop raises a forge; `{ forge, sandbox: true }` reads what moving a forge out of this forge's own process into a sandbox would meet (hooks, command-running keys, size) and with `dryRun: false` moves it, proven and put back on any failure (`acknowledge: true` when it was held for what its repositories hold); each forge carries `placement` and `where`; gift codes: `codes` true lists, `code` {plan, uses?, note?, expires?} makes (shown once), `revoke` id; planned unless `dryRun` is false; `archive` a name or names stops each, writes its data and ledger as one file to the backup destination, then removes it; `restore` a name brings an archived one back, or a lost one from its nightly copy; `kind` refused lists the last 20 refused first asks; `kind` clients lists each client in the page's words", | |
| 20 | 20 | description: |
| 21 | 21 | "Forges sent from here (admin), clients, a forge's plan or size.", |
| 22 | 22 | inputSchema: { type: "object", properties: { kind: { type: "string", enum: ["refused", "clients"] }, forge: { type: "string" }, plan: { type: "string" }, codes: { type: "boolean" }, code: { type: "object" }, revoke: { type: "string" }, archive: { type: ["string", "array"], items: { type: "string" } }, restore: { type: "string" }, sandbox: { type: "boolean" }, size: { type: "string" }, acknowledge: { type: "boolean" }, dryRun: { type: "boolean" } } }, |
| @@ -63,7 +63,7 @@ export const tool: Tool = { | ||
| 63 | 63 | if (args["restore"] !== undefined) { |
| 64 | 64 | const name = String(args["restore"]); |
| 65 | 65 | if (!CHILD_NAME.test(name)) return bad("invalid", "restore names an archived forge"); |
| 66 | if (!live) return good({ says: `This would restore ${name} from its archive under the same name; nothing changed. Send dryRun: false to do it.`, archived: archivedForges(ctx.app) }); | |
| 66 | if (!live) return good({ says: `This would restore ${name} from its archive under the same name; nothing changed. Send dryRun: false to do it.`, archived: await restorableForges(ctx.app) }); | |
| 67 | 67 | const done = await restoreForge(ctx.app, name, { actorId: user.id }); |
| 68 | 68 | return done.ok ? good({ says: done.says }) : bad(done.says.startsWith("no forge named") ? "not_found" : "invalid", done.says); |
| 69 | 69 | } |
src/snapshot/service.ts +9
| @@ -37,6 +37,7 @@ import { failureCause } from "./cause.ts"; | ||
| 37 | 37 | import { noteOffBox, recordSnapshotOutcome, SNAPSHOT_RETRY_MS } from "./outcome.ts"; |
| 38 | 38 | import { remakeOf, s3FromEnv, type Store } from "./store.ts"; |
| 39 | 39 | import { verifySnapshot } from "./verify.ts"; |
| 40 | import { copyForges, nightlyWords } from "../spawn/nightly_copy.ts"; | |
| 40 | 41 | import { during } from "../perf/jobs.ts"; |
| 41 | 42 | |
| 42 | 43 | const log = createLog("snapshots"); |
| @@ -291,6 +292,14 @@ export function startSnapshots( | ||
| 291 | 292 | // Retention has swept the store: the snapshot just announced is still whole there, or this |
| 292 | 293 | // run failed and says so. |
| 293 | 294 | await verifySnapshot(store, manifest.name); |
| 295 | // Then each hosted forge as one file of its own, to the same store, so one can come back | |
| 296 | // alone (#13832). Its outcome is said, never the parent snapshot's failure. | |
| 297 | const copies = await copyForges(app, store); | |
| 298 | if (copies.written.length + copies.unchanged.length + copies.skipped.length + copies.failed.length > 0) { | |
| 299 | const says = nightlyWords(copies); | |
| 300 | if (copies.skipped.length + copies.failed.length > 0) log.warn("hosted forges copied, some not", { says }); | |
| 301 | else log.info("hosted forges copied", { says }); | |
| 302 | } | |
| 294 | 303 | // A snapshot in a format the last drill did not prove is drilled on its own (#12592). |
| 295 | 304 | const proved = lastDrill(app.db)?.format; |
| 296 | 305 | if (options.nightly !== false && !stopped && proved !== undefined && proved !== (manifest.format ?? 1)) { |
src/spawn/archive.ts +207 −61
| @@ -10,14 +10,15 @@ | ||
| 10 | 10 | * copy until verified, `notices.json` when each claimant was told. |
| 11 | 11 | */ |
| 12 | 12 | |
| 13 | import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs"; | |
| 13 | import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, utimesSync, writeFileSync } from "node:fs"; | |
| 14 | 14 | import { rm } from "node:fs/promises"; |
| 15 | import { join } from "node:path"; | |
| 15 | import { dirname, join } from "node:path"; | |
| 16 | 16 | import type { App } from "../app.ts"; |
| 17 | 17 | import { mailerOf } from "../actions/verify.ts"; |
| 18 | 18 | import { childDirOf, listChildren } from "../actions/spawn.ts"; |
| 19 | 19 | import { sha256 } from "../kernel/hash.ts"; |
| 20 | 20 | import { resolveDestination, type Destination } from "../snapshot/destination.ts"; |
| 21 | import { vacuumFile } from "../snapshot/vacuum.ts"; | |
| 21 | 22 | import { childPerson } from "./child_db.ts"; |
| 22 | 23 | import { dropServed, type ClientRow } from "./clients.ts"; |
| 23 | 24 | import { needsNotice } from "./archive_proposal.ts"; |
| @@ -38,6 +39,15 @@ export interface ArchiveRecord { | ||
| 38 | 39 | readonly apps: readonly string[]; |
| 39 | 40 | } |
| 40 | 41 | |
| 42 | /** | |
| 43 | * A hosted forge's last nightly copy (nightly_copy.ts): an archive's shape, of a forge still | |
| 44 | * running. | |
| 45 | */ | |
| 46 | export interface NightlyRecord extends ArchiveRecord { | |
| 47 | /** What the files were when copied: sizes and times, so an unchanged forge is not sent again. */ | |
| 48 | readonly fingerprint: string; | |
| 49 | } | |
| 50 | ||
| 41 | 51 | /** Tests swap where the copy goes. */ |
| 42 | 52 | export interface ArchiveOptions { |
| 43 | 53 | readonly destination?: Destination | undefined; |
| @@ -45,8 +55,21 @@ export interface ArchiveOptions { | ||
| 45 | 55 | readonly actorId?: string | undefined; |
| 46 | 56 | /** Tests lower the cap. */ |
| 47 | 57 | readonly maxBytes?: number; |
| 58 | /** | |
| 59 | * The nightly copy (#13832): the same one file, of a forge left running. Nothing is stopped or | |
| 60 | * removed, its database is copied consistently (VACUUM INTO), the key is replaced each night, | |
| 61 | * and the record kept under `nightly/` carries what its files were. | |
| 62 | */ | |
| 63 | readonly keepRunning?: { readonly fingerprint: string } | undefined; | |
| 48 | 64 | } |
| 49 | 65 | |
| 66 | /** What archiving said; `tooLarge` the size a copy came to when over the cap. */ | |
| 67 | export type Archived = Managed & { readonly tooLarge?: number }; | |
| 68 | ||
| 69 | /** Where a forge's nightly copy is kept, one key per forge. */ | |
| 70 | export const NIGHTLY_PREFIX = "forge-snapshots/"; | |
| 71 | export const nightlyKey = (name: string): string => `${NIGHTLY_PREFIX}${name}.tar.gz`; | |
| 72 | ||
| 50 | 73 | /** The largest archive written or restored: it is read into memory whole (twice, to verify it). */ |
| 51 | 74 | export const ARCHIVE_MAX_BYTES = 256 * 1_048_576; |
| 52 | 75 | |
| @@ -54,9 +77,21 @@ export const ARCHIVE_MAX_BYTES = 256 * 1_048_576; | ||
| 54 | 77 | const busy = new Set<string>(); |
| 55 | 78 | |
| 56 | 79 | const root = (app: App): string => join(app.config.dataDir, "archive"); |
| 57 | const recordPath = (app: App, name: string): string => join(root(app), `${name}.json`); | |
| 80 | /** An archive's record, or (`nightly`) the record of a forge's last nightly copy. */ | |
| 81 | const recordPath = (app: App, name: string, nightly = false): string => join(root(app), ...(nightly ? ["nightly"] : []), `${name}.json`); | |
| 58 | 82 | const BODY_ID = /^[A-Za-z0-9_-]{1,64}$/; |
| 59 | 83 | |
| 84 | /** The record of a forge's last nightly copy, when there is one. */ | |
| 85 | export function nightlyRecord(app: App, name: string): NightlyRecord | undefined { | |
| 86 | if (!CHILD_NAME.test(name)) return undefined; | |
| 87 | try { | |
| 88 | const r = JSON.parse(readFileSync(recordPath(app, name, true), "utf8")) as NightlyRecord; | |
| 89 | return r.name === name && BODY_ID.test(r.bodyId) && typeof r.key === "string" ? r : undefined; | |
| 90 | } catch { | |
| 91 | return undefined; | |
| 92 | } | |
| 93 | } | |
| 94 | ||
| 60 | 95 | /** The archived forges, newest first: one line each on /forges. */ |
| 61 | 96 | export function archivedForges(app: App): ArchiveRecord[] { |
| 62 | 97 | let files: string[]; |
| @@ -75,10 +110,11 @@ export function archivedForges(app: App): ArchiveRecord[] { | ||
| 75 | 110 | return out.sort((a, b) => b.archivedAt.localeCompare(a.archivedAt)); |
| 76 | 111 | } |
| 77 | 112 | |
| 78 | async function tar(args: readonly string[]): Promise<{ ok: boolean; out: string; err: string }> { | |
| 113 | async function tar(args: readonly string[]): Promise<{ ok: boolean; code: number; out: string; err: string }> { | |
| 79 | 114 | const p = Bun.spawn(["tar", ...args], { stdout: "pipe", stderr: "pipe" }); |
| 80 | 115 | const [out, err] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text()]); |
| 81 | return { ok: (await p.exited) === 0, out, err: err.trim().slice(0, 200) }; | |
| 116 | const code = await p.exited; | |
| 117 | return { ok: code === 0, code, out, err: err.trim().slice(0, 200) }; | |
| 82 | 118 | } |
| 83 | 119 | |
| 84 | 120 | /** Where an archive would be written, in words: the store, or that there is none. */ |
| @@ -87,7 +123,7 @@ export function destinationWords(app: App): string { | ||
| 87 | 123 | return d === undefined ? "a backup destination (none is set)" : d.store.where; |
| 88 | 124 | } |
| 89 | 125 | |
| 90 | export async function archiveForge(app: App, name: string, options: ArchiveOptions = {}): Promise<Managed> { | |
| 126 | export async function archiveForge(app: App, name: string, options: ArchiveOptions = {}): Promise<Archived> { | |
| 91 | 127 | if (!CHILD_NAME.test(name)) return { ok: false, says: `no forge named ${name}` }; |
| 92 | 128 | if (busy.has(name)) return { ok: false, says: `${name} is being archived or restored already` }; |
| 93 | 129 | busy.add(name); |
| @@ -100,71 +136,123 @@ export async function archiveForge(app: App, name: string, options: ArchiveOptio | ||
| 100 | 136 | |
| 101 | 137 | const STOPPED_SAFE = "it is stopped, wakes on its next request, and its data is untouched"; |
| 102 | 138 | |
| 103 | async function archiveOne(app: App, name: string, options: ArchiveOptions): Promise<Managed> { | |
| 139 | async function archiveOne(app: App, name: string, options: ArchiveOptions): Promise<Archived> { | |
| 140 | const kept = options.keepRunning; | |
| 141 | const not = kept === undefined ? "was not archived" : "was not copied"; | |
| 104 | 142 | const child = (await listChildren(app)).find((c) => c.name === name); |
| 105 | 143 | if (child === undefined) return { ok: false, says: `no forge named ${name}` }; |
| 106 | 144 | if (!child.done) return { ok: false, says: `${name} is still being made` }; |
| 107 | 145 | if (!BODY_ID.test(child.bodyId)) return { ok: false, says: `${name} has no data directory to archive` }; |
| 108 | 146 | const destination = options.destination ?? resolveDestination({ db: app.db, dataDir: app.config.dataDir, bus: app.bus }); |
| 109 | 147 | if (destination === undefined) |
| 110 | return { ok: false, says: `${name} was not archived: this forge has no backup destination to write the copy to (set one on the Backups page)` }; | |
| 148 | return { ok: false, says: `${name} ${not}: this forge has no backup destination to write the copy to (set one on the Backups page)` }; | |
| 111 | 149 | const now = options.now ?? Date.now(); |
| 112 | 150 | // The destination answers before anything is stopped: a forge is not put to sleep for a copy that |
| 113 | // cannot be kept. | |
| 114 | try { | |
| 115 | const probe = `forge-archives/.probe-${name}`; | |
| 116 | await destination.store.put(probe, "ok"); | |
| 117 | const back = await destination.store.get(probe); | |
| 118 | await destination.store.delete(probe).catch(() => {}); | |
| 119 | if (back === undefined) throw new Error("the probe did not read back"); | |
| 120 | } catch (error) { | |
| 121 | return { ok: false, says: `${name} was not archived: ${destination.store.where} did not take a test write (${String(error).slice(0, 160)}); ${name} is running as before` }; | |
| 151 | // cannot be kept. A running forge's copy is read back after it is written all the same. | |
| 152 | if (kept === undefined) { | |
| 153 | try { | |
| 154 | const probe = `forge-archives/.probe-${name}`; | |
| 155 | await destination.store.put(probe, "ok"); | |
| 156 | const back = await destination.store.get(probe); | |
| 157 | await destination.store.delete(probe).catch(() => {}); | |
| 158 | if (back === undefined) throw new Error("the probe did not read back"); | |
| 159 | } catch (error) { | |
| 160 | return { ok: false, says: `${name} was not archived: ${destination.store.where} did not take a test write (${String(error).slice(0, 160)}); ${name} is running as before` }; | |
| 161 | } | |
| 122 | 162 | } |
| 163 | const safe = kept === undefined ? STOPPED_SAFE : "it is running as before"; | |
| 123 | 164 | const stamp = new Date(now).toISOString().replace(/[-:.]/g, "").slice(0, 15); |
| 124 | mkdirSync(join(root(app), "files"), { recursive: true }); | |
| 125 | const local = join(root(app), "files", `${name}-${stamp}.tar.gz`); | |
| 126 | // Stopped first, so nothing writes while it is read. | |
| 127 | await sleepChild(app, name); | |
| 128 | const made = await tar(["-czf", local, "-C", join(app.config.dataDir, "spawn"), `${name}.json`, "-C", join(app.config.dataDir, "children"), child.bodyId]); | |
| 129 | if (!made.ok) { | |
| 130 | await rm(local, { force: true }); | |
| 131 | return { ok: false, says: `${name} was not archived: the copy could not be written (${made.err}); ${STOPPED_SAFE}` }; | |
| 132 | } | |
| 133 | const size = statSync(local).size; | |
| 134 | const cap = options.maxBytes ?? ARCHIVE_MAX_BYTES; | |
| 135 | if (size > cap) { | |
| 136 | await rm(local, { force: true }); | |
| 137 | return { ok: false, says: `${name} was not archived: its data is ${mib(size)}, over the ${mib(cap)} one archive can hold; ${STOPPED_SAFE}` }; | |
| 138 | } | |
| 139 | const body = new Uint8Array(await Bun.file(local).arrayBuffer()); | |
| 140 | const digest = sha256(body); | |
| 141 | const key = `forge-archives/${name}/${stamp}.tar.gz`; | |
| 165 | const stage = kept === undefined ? join(root(app), "files") : join(root(app), "nightly", `stage-${name}`); | |
| 166 | if (kept !== undefined) await rm(stage, { recursive: true, force: true }); | |
| 167 | mkdirSync(stage, { recursive: true }); | |
| 168 | const local = join(stage, `${name}-${stamp}.tar.gz`); | |
| 142 | 169 | try { |
| 143 | await destination.store.put(key, body); | |
| 144 | const back = await destination.store.get(key); | |
| 145 | if (back === undefined || back.length !== body.length || sha256(back) !== digest) | |
| 146 | return { ok: false, says: `${name} was not archived: the copy at ${destination.store.where} did not read back the same; ${STOPPED_SAFE}, and the local copy is kept at ${local}` }; | |
| 147 | } catch (error) { | |
| 148 | return { ok: false, says: `${name} was not archived: the upload to ${destination.store.where} failed (${String(error).slice(0, 160)}); ${STOPPED_SAFE}, and the local copy is kept at ${local}` }; | |
| 170 | // Stopped first, so nothing writes while it is read; a running one is read as it stands. | |
| 171 | if (kept === undefined) await sleepChild(app, name); | |
| 172 | const made = await packForge(app, name, child.bodyId, local, kept !== undefined); | |
| 173 | if (made !== undefined) { | |
| 174 | await rm(local, { force: true }); | |
| 175 | return { ok: false, says: `${name} ${not}: the copy could not be written (${made}); ${safe}` }; | |
| 176 | } | |
| 177 | const size = statSync(local).size; | |
| 178 | const cap = options.maxBytes ?? ARCHIVE_MAX_BYTES; | |
| 179 | if (size > cap) { | |
| 180 | await rm(local, { force: true }); | |
| 181 | return { ok: false, tooLarge: size, says: `${name} ${not}: its data is ${mib(size)}, over the ${mib(cap)} one archive can hold; ${safe}` }; | |
| 182 | } | |
| 183 | const body = new Uint8Array(await Bun.file(local).arrayBuffer()); | |
| 184 | const digest = sha256(body); | |
| 185 | const key = kept === undefined ? `forge-archives/${name}/${stamp}.tar.gz` : nightlyKey(name); | |
| 186 | const keptAt = kept === undefined ? `, and the local copy is kept at ${local}` : ""; | |
| 187 | try { | |
| 188 | await destination.store.put(key, body); | |
| 189 | const back = await destination.store.get(key); | |
| 190 | if (back === undefined || back.length !== body.length || sha256(back) !== digest) | |
| 191 | return { ok: false, says: `${name} ${not}: the copy at ${destination.store.where} did not read back the same; ${safe}${keptAt}` }; | |
| 192 | } catch (error) { | |
| 193 | return { ok: false, says: `${name} ${not}: the upload to ${destination.store.where} failed (${String(error).slice(0, 160)}); ${safe}${keptAt}` }; | |
| 194 | } | |
| 195 | const record: ArchiveRecord | NightlyRecord = { | |
| 196 | name, | |
| 197 | bodyId: child.bodyId, | |
| 198 | archivedAt: new Date(now).toISOString(), | |
| 199 | where: destination.store.where, | |
| 200 | key, | |
| 201 | bytes: body.length, | |
| 202 | sha256: digest, | |
| 203 | for: child.for, | |
| 204 | apps: child.apps, | |
| 205 | ...(kept === undefined ? {} : { fingerprint: kept.fingerprint }), | |
| 206 | }; | |
| 207 | writeFileSync(recordPath(app, name, kept !== undefined), JSON.stringify(record)); | |
| 208 | if (kept !== undefined) return { ok: true, says: `${name} is copied: ${mib(record.bytes)} written to ${record.where} (${key})` }; | |
| 209 | await removeForge(app, name); | |
| 210 | await rm(local, { force: true }); | |
| 211 | forgetNotice(app, name); | |
| 212 | dropServed(app); | |
| 213 | app.bus.append({ kind: "forge.archived", ...(options.actorId === undefined ? {} : { actorId: options.actorId }), payload: { name, where: record.where, key, bytes: record.bytes } }); | |
| 214 | return { ok: true, says: `${name} is archived: ${mib(record.bytes)} written to ${record.where} (${key}), then removed here` }; | |
| 215 | } finally { | |
| 216 | if (kept !== undefined) await rm(stage, { recursive: true, force: true }); | |
| 149 | 217 | } |
| 150 | const record: ArchiveRecord = { | |
| 151 | name, | |
| 152 | bodyId: child.bodyId, | |
| 153 | archivedAt: new Date(now).toISOString(), | |
| 154 | where: destination.store.where, | |
| 155 | key, | |
| 156 | bytes: body.length, | |
| 157 | sha256: digest, | |
| 158 | for: child.for, | |
| 159 | apps: child.apps, | |
| 160 | }; | |
| 161 | writeFileSync(recordPath(app, name), JSON.stringify(record)); | |
| 162 | await removeForge(app, name); | |
| 163 | await rm(local, { force: true }); | |
| 164 | forgetNotice(app, name); | |
| 165 | dropServed(app); | |
| 166 | app.bus.append({ kind: "forge.archived", ...(options.actorId === undefined ? {} : { actorId: options.actorId }), payload: { name, where: record.where, key, bytes: record.bytes } }); | |
| 167 | return { ok: true, says: `${name} is archived: ${mib(record.bytes)} written to ${record.where} (${key}), then removed here` }; | |
| 218 | } | |
| 219 | ||
| 220 | const DB_FILES = ["forge.db", "forge.db-wal", "forge.db-shm"]; | |
| 221 | ||
| 222 | /** | |
| 223 | * Write a forge's ledger and data directory to `file` as one gzip'd tar; undefined when written, | |
| 224 | * else why not. A stopped forge is read whole. A running one (`live`) has its database copied | |
| 225 | * consistently first, off the serving thread (VACUUM INTO froze every request on it, #8742), the | |
| 226 | * live database's files left out of the read and the copy appended under the same name. Tar's exit | |
| 227 | * 1 (a file changed while read) is the next night's; any other failure fails the copy. | |
| 228 | */ | |
| 229 | async function packForge(app: App, name: string, bodyId: string, file: string, live: boolean): Promise<string | undefined> { | |
| 230 | const sources = ["-C", join(app.config.dataDir, "spawn"), `${name}.json`, "-C", join(app.config.dataDir, "children"), bodyId]; | |
| 231 | if (!live) { | |
| 232 | const made = await tar(["-czf", file, ...sources]); | |
| 233 | return made.ok ? undefined : made.err; | |
| 234 | } | |
| 235 | const stage = dirname(file); | |
| 236 | const db = join(app.config.dataDir, "children", bodyId, "forge.db"); | |
| 237 | const plain = file.replace(/\.gz$/, ""); | |
| 238 | const made = await tar([ | |
| 239 | "-cf", plain, | |
| 240 | ...DB_FILES.map((f) => `--exclude=${bodyId}/${f}`), | |
| 241 | "--warning=no-file-changed", "--warning=no-file-removed", "--warning=no-file-ignored", | |
| 242 | ...sources, | |
| 243 | ]); | |
| 244 | if (!made.ok && made.code !== 1) return made.err || `tar exited ${made.code}`; | |
| 245 | if (existsSync(db)) { | |
| 246 | mkdirSync(join(stage, bodyId), { recursive: true }); | |
| 247 | const copy = join(stage, bodyId, "forge.db"); | |
| 248 | await vacuumFile(db, copy); | |
| 249 | const t = statSync(db).mtime; | |
| 250 | utimesSync(copy, t, t); | |
| 251 | const added = await tar(["-rf", plain, "-C", stage, `${bodyId}/forge.db`]); | |
| 252 | if (!added.ok) return `the database copy could not be added (${added.err})`; | |
| 253 | } | |
| 254 | const zipped = Bun.spawn(["gzip", "-n", "-f", plain], { stdout: "ignore", stderr: "ignore" }); | |
| 255 | return (await zipped.exited) === 0 && existsSync(file) ? undefined : "it could not be compressed"; | |
| 168 | 256 | } |
| 169 | 257 | |
| 170 | 258 | const mib = (n: number): string => `${(n / 1_048_576).toFixed(1)} MiB`; |
| @@ -182,7 +270,66 @@ export async function restoreForge(app: App, name: string, options: ArchiveOptio | ||
| 182 | 270 | |
| 183 | 271 | async function restoreOne(app: App, name: string, options: ArchiveOptions): Promise<Managed> { |
| 184 | 272 | const record = archivedForges(app).find((r) => r.name === name); |
| 185 | if (record === undefined) return { ok: false, says: `no archived forge named ${name}` }; | |
| 273 | if (record !== undefined) { | |
| 274 | const done = await restoreRecord(app, record, options); | |
| 275 | if (done.ok) await rm(recordPath(app, name), { force: true }); | |
| 276 | return done; | |
| 277 | } | |
| 278 | // A forge lost with no archive comes back from its last nightly copy (#13832), which is kept; | |
| 279 | // with this host's record of it lost too, from the copy the store holds under its name. | |
| 280 | const nightly = nightlyRecord(app, name) ?? (await nightlyFromStore(app, name, options)); | |
| 281 | return nightly === undefined ? { ok: false, says: `no archived forge named ${name}, and no nightly copy of it` } : await restoreRecord(app, nightly, options); | |
| 282 | } | |
| 283 | ||
| 284 | /** | |
| 285 | * A record for the nightly copy the store holds of `name`, read from the copy itself: for a host | |
| 286 | * whose own disk, and so its records, was what was lost. | |
| 287 | */ | |
| 288 | async function nightlyFromStore(app: App, name: string, options: ArchiveOptions): Promise<ArchiveRecord | undefined> { | |
| 289 | const destination = options.destination ?? resolveDestination({ db: app.db, dataDir: app.config.dataDir, bus: app.bus }); | |
| 290 | if (destination === undefined) return undefined; | |
| 291 | const key = nightlyKey(name); | |
| 292 | const body = await destination.store.get(key).catch(() => undefined); | |
| 293 | if (body === undefined || body.length > ARCHIVE_MAX_BYTES) return undefined; | |
| 294 | const stage = join(root(app), `finding-${name}`); | |
| 295 | await rm(stage, { recursive: true, force: true }); | |
| 296 | mkdirSync(stage, { recursive: true }); | |
| 297 | try { | |
| 298 | const file = join(stage, "copy.tar.gz"); | |
| 299 | await Bun.write(file, body); | |
| 300 | const listed = await tar(["-tzf", file]); | |
| 301 | if (!listed.ok) return undefined; | |
| 302 | const tops = new Set(listed.out.split("\n").filter((l) => l !== "" && l !== `${name}.json`).map((l) => l.split("/")[0] ?? "")); | |
| 303 | const bodyId = tops.size === 1 ? [...tops][0]! : ""; | |
| 304 | if (!BODY_ID.test(bodyId)) return undefined; | |
| 305 | return { name, bodyId, archivedAt: "", where: destination.store.where, key, bytes: body.length, sha256: sha256(body), for: null, apps: [] }; | |
| 306 | } finally { | |
| 307 | await rm(stage, { recursive: true, force: true }); | |
| 308 | } | |
| 309 | } | |
| 310 | ||
| 311 | /** What can be brought back by Restore: archives, and the nightly copies of forges not here now. */ | |
| 312 | export async function restorableForges(app: App): Promise<(ArchiveRecord & { readonly nightly: boolean })[]> { | |
| 313 | const here = new Set((await listChildren(app)).map((c) => c.name)); | |
| 314 | const archived = archivedForges(app); | |
| 315 | const out: (ArchiveRecord & { nightly: boolean })[] = archived.map((r) => ({ ...r, nightly: false })); | |
| 316 | let files: string[] = []; | |
| 317 | try { | |
| 318 | files = readdirSync(join(root(app), "nightly")); | |
| 319 | } catch {} | |
| 320 | for (const f of files.filter((f) => f.endsWith(".json")).sort()) { | |
| 321 | const r = nightlyRecord(app, f.slice(0, -5)); | |
| 322 | if (r !== undefined && !here.has(r.name) && !archived.some((a) => a.name === r.name)) out.push({ ...r, nightly: true }); | |
| 323 | } | |
| 324 | return out; | |
| 325 | } | |
| 326 | ||
| 327 | /** | |
| 328 | * Bring a forge back from one copy at the destination: an archive's, or the nightly's. The record | |
| 329 | * is the caller's to keep or drop. | |
| 330 | */ | |
| 331 | async function restoreRecord(app: App, record: ArchiveRecord, options: ArchiveOptions): Promise<Managed> { | |
| 332 | const name = record.name; | |
| 186 | 333 | if ((await listChildren(app)).some((c) => c.name === name)) |
| 187 | 334 | return { ok: false, says: `${name} was not restored: a forge of that name exists now` }; |
| 188 | 335 | const dir = childDirOf(app, record.bodyId); |
| @@ -224,7 +371,6 @@ async function restoreOne(app: App, name: string, options: ArchiveOptions): Prom | ||
| 224 | 371 | else mkdirSync(dir, { recursive: true }); |
| 225 | 372 | renameSync(join(extracted, `${name}.json`), join(app.config.dataDir, "spawn", `${name}.json`)); |
| 226 | 373 | await rm(stage, { recursive: true, force: true }); |
| 227 | await rm(recordPath(app, name), { force: true }); | |
| 228 | 374 | dropServed(app); |
| 229 | 375 | app.bus.append({ kind: "forge.restored", ...(options.actorId === undefined ? {} : { actorId: options.actorId }), payload: { name, from: record.where, key: record.key } }); |
| 230 | 376 | return { ok: true, says: `${name} is back under the same name, restored from ${record.where}` }; |
src/spawn/nightly_copy.ts added +139
| @@ -0,0 +1,139 @@ | ||
| 1 | /** | |
| 2 | * The nightly copy of each hosted forge (#13832): after the host's own snapshot, every hosted forge | |
| 3 | * is archived to the same destination with `keepRunning` (archive.ts): one file each, nothing | |
| 4 | * stopped or removed, one key per forge replaced each night. A forge whose files have not changed | |
| 5 | * since its last copy, and whose copy the store still holds, is not sent again. A forge over | |
| 6 | * ARCHIVE_MAX_BYTES is named as skipped with its size, never silently left out. | |
| 7 | * | |
| 8 | * Kept under `<data>/archive/`: `nightly/<name>.json` the record of a forge's last copy (written | |
| 9 | * by archive.ts), `nightly-outcome.json` what the last night came to, for the Backups page. | |
| 10 | */ | |
| 11 | ||
| 12 | import { readdirSync, readFileSync, statSync, writeFileSync, mkdirSync } from "node:fs"; | |
| 13 | import { join, relative } from "node:path"; | |
| 14 | import type { App } from "../app.ts"; | |
| 15 | import { childDirOf, listChildren, type Child } from "../actions/spawn.ts"; | |
| 16 | import { sha256 } from "../kernel/hash.ts"; | |
| 17 | import type { Store } from "../snapshot/store.ts"; | |
| 18 | import { archiveForge, ARCHIVE_MAX_BYTES, nightlyKey, nightlyRecord } from "./archive.ts"; | |
| 19 | import { CHILD_NAME } from "./placement.ts"; | |
| 20 | ||
| 21 | export interface NightlyOutcome { | |
| 22 | readonly at: string; | |
| 23 | readonly written: readonly string[]; | |
| 24 | readonly unchanged: readonly string[]; | |
| 25 | /** Too large for one file: named with the size it came to. */ | |
| 26 | readonly skipped: readonly { readonly name: string; readonly bytes: number }[]; | |
| 27 | readonly failed: readonly { readonly name: string; readonly why: string }[]; | |
| 28 | } | |
| 29 | ||
| 30 | export interface NightlyOptions { | |
| 31 | readonly now?: number; | |
| 32 | /** Tests lower the cap. */ | |
| 33 | readonly maxBytes?: number; | |
| 34 | } | |
| 35 | ||
| 36 | const outcomePath = (app: App): string => join(app.config.dataDir, "archive", "nightly-outcome.json"); | |
| 37 | ||
| 38 | /** Every file under `dir` with its size and time, in order: what "changed" means here. */ | |
| 39 | function fingerprintOf(dir: string, ledger: string): string { | |
| 40 | const lines: string[] = []; | |
| 41 | const walk = (d: string): void => { | |
| 42 | let names: string[]; | |
| 43 | try { | |
| 44 | names = readdirSync(d).sort(); | |
| 45 | } catch { | |
| 46 | return; | |
| 47 | } | |
| 48 | for (const n of names) { | |
| 49 | const p = join(d, n); | |
| 50 | try { | |
| 51 | const s = statSync(p); | |
| 52 | if (s.isDirectory()) walk(p); | |
| 53 | else if (s.isFile()) lines.push(`${relative(dir, p)}\t${s.size}\t${s.mtimeMs}`); | |
| 54 | } catch {} | |
| 55 | } | |
| 56 | }; | |
| 57 | walk(dir); | |
| 58 | try { | |
| 59 | const s = statSync(ledger); | |
| 60 | lines.push(`ledger\t${s.size}\t${s.mtimeMs}`); | |
| 61 | } catch {} | |
| 62 | return sha256(new TextEncoder().encode(lines.join("\n"))); | |
| 63 | } | |
| 64 | ||
| 65 | /** True when `store` still holds `key`: a store wiped of a copy is sent it again. */ | |
| 66 | async function holds(store: Store, key: string): Promise<boolean> { | |
| 67 | try { | |
| 68 | // A sealed store hides its keys from a listing by prefix: there the copy is read. | |
| 69 | if (store.storedKey !== undefined) return (await store.get(key)) !== undefined; | |
| 70 | return (await store.list(key)).includes(key); | |
| 71 | } catch { | |
| 72 | return false; | |
| 73 | } | |
| 74 | } | |
| 75 | ||
| 76 | /** | |
| 77 | * Copy every hosted forge to `store`, one file each, and keep what the night came to. Never throws: | |
| 78 | * each forge's outcome is said. | |
| 79 | */ | |
| 80 | export async function copyForges(app: App, store: Store, options: NightlyOptions = {}): Promise<NightlyOutcome> { | |
| 81 | const now = options.now ?? Date.now(); | |
| 82 | const written: string[] = []; | |
| 83 | const unchanged: string[] = []; | |
| 84 | const skipped: { name: string; bytes: number }[] = []; | |
| 85 | const failed: { name: string; why: string }[] = []; | |
| 86 | let children: Child[] = []; | |
| 87 | try { | |
| 88 | children = await listChildren(app); | |
| 89 | } catch (error) { | |
| 90 | failed.push({ name: "*", why: `the hosted forges could not be listed (${String(error).slice(0, 160)})` }); | |
| 91 | } | |
| 92 | for (const child of children) { | |
| 93 | if (!child.done || !CHILD_NAME.test(child.name)) continue; | |
| 94 | const name = child.name; | |
| 95 | const fingerprint = fingerprintOf(childDirOf(app, child.bodyId), join(app.config.dataDir, "spawn", `${name}.json`)); | |
| 96 | const before = nightlyRecord(app, name); | |
| 97 | if (before?.fingerprint === fingerprint && before.bodyId === child.bodyId && before.where === store.where && (await holds(store, nightlyKey(name)))) { | |
| 98 | unchanged.push(name); | |
| 99 | continue; | |
| 100 | } | |
| 101 | const said = await archiveForge(app, name, { | |
| 102 | destination: { source: "dir", store }, | |
| 103 | now, | |
| 104 | keepRunning: { fingerprint }, | |
| 105 | ...(options.maxBytes === undefined ? {} : { maxBytes: options.maxBytes }), | |
| 106 | }); | |
| 107 | if (said.ok) written.push(name); | |
| 108 | else if (said.tooLarge !== undefined) skipped.push({ name, bytes: said.tooLarge }); | |
| 109 | else failed.push({ name, why: said.says }); | |
| 110 | } | |
| 111 | const outcome: NightlyOutcome = { at: new Date(now).toISOString(), written, unchanged, skipped, failed }; | |
| 112 | if (children.length + failed.length > 0) { | |
| 113 | try { | |
| 114 | mkdirSync(join(app.config.dataDir, "archive"), { recursive: true }); | |
| 115 | writeFileSync(outcomePath(app), JSON.stringify(outcome)); | |
| 116 | } catch {} | |
| 117 | } | |
| 118 | return outcome; | |
| 119 | } | |
| 120 | ||
| 121 | /** What the last night's copies came to, when one ran. */ | |
| 122 | export function lastNightly(app: App): NightlyOutcome | undefined { | |
| 123 | try { | |
| 124 | const o = JSON.parse(readFileSync(outcomePath(app), "utf8")) as NightlyOutcome; | |
| 125 | return typeof o.at === "string" && Array.isArray(o.written) && Array.isArray(o.skipped) && Array.isArray(o.failed) && Array.isArray(o.unchanged) ? o : undefined; | |
| 126 | } catch { | |
| 127 | return undefined; | |
| 128 | } | |
| 129 | } | |
| 130 | ||
| 131 | const mib = (n: number): string => `${(n / 1_048_576).toFixed(1)} MiB`; | |
| 132 | ||
| 133 | /** One line for the log and the Backups page: what the night's copies came to. */ | |
| 134 | export function nightlyWords(o: NightlyOutcome): string { | |
| 135 | const parts = [`${o.written.length} hosted forge${o.written.length === 1 ? "" : "s"} copied`, `${o.unchanged.length} unchanged`]; | |
| 136 | for (const s of o.skipped) parts.push(`${s.name} skipped: ${mib(s.bytes)}, over the ${mib(ARCHIVE_MAX_BYTES)} one file holds`); | |
| 137 | for (const f of o.failed) parts.push(`${f.name} not copied: ${f.why}`); | |
| 138 | return parts.join("; "); | |
| 139 | } |
src/tui/screens/forges.ts +14 −12
| @@ -14,7 +14,7 @@ import { drawFacts, runAsync } from "./common.ts"; | ||
| 14 | 14 | import type { PaletteEntry } from "./entries.ts"; |
| 15 | 15 | import { clientRows } from "../../spawn/clients.ts"; |
| 16 | 16 | import { diskWords } from "../../spawn/disk_mount.ts"; |
| 17 | import { archiveForge, archivedForges, destinationWords, restoreForge } from "../../spawn/archive.ts"; | |
| 17 | import { archiveForge, destinationWords, restorableForges, restoreForge } from "../../spawn/archive.ts"; | |
| 18 | 18 | import { claimedWords, keepWords } from "../../spawn/keep_words.ts"; |
| 19 | 19 | import { changeLink, ownCode, removeForge, resizeForge, stopForge } from "../../spawn/manage.ts"; |
| 20 | 20 | import { moveToCell } from "../../spawn/move_cell.ts"; |
| @@ -238,17 +238,19 @@ export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Ses | ||
| 238 | 238 | ); |
| 239 | 239 | else if (e.key === "r" && session !== undefined && session.user?.isAdmin === true) { |
| 240 | 240 | const user = session.user; |
| 241 | const items = archivedForges(session.app).map((r) => ({ id: r.name, label: r.name, hint: `archived ${r.archivedAt.slice(0, 10)}, ${(r.bytes / 1_048_576).toFixed(1)} MiB at ${r.where}` })); | |
| 242 | if (items.length === 0) { ctx.toast("No forge is archived"); return true; } | |
| 243 | ctx.push( | |
| 244 | pickerScreen(ctx, screen, { | |
| 245 | title: "Restore which forge?", | |
| 246 | items, | |
| 247 | onPick: (ids) => { | |
| 248 | if (ids[0] !== undefined) void restoreForge(session.app, ids[0], { actorId: user.id }).then((done) => ctx.toast(done.says, done.ok ? "success" : "danger")); | |
| 249 | }, | |
| 250 | }), | |
| 251 | ); | |
| 241 | void restorableForges(session.app).then((all) => { | |
| 242 | const items = all.map((r) => ({ id: r.name, label: r.name, hint: `${r.nightly ? "nightly copy" : "archived"} ${r.archivedAt.slice(0, 10)}, ${(r.bytes / 1_048_576).toFixed(1)} MiB at ${r.where}` })); | |
| 243 | if (items.length === 0) { ctx.toast("No forge is archived, and no lost forge has a nightly copy"); return; } | |
| 244 | ctx.push( | |
| 245 | pickerScreen(ctx, screen, { | |
| 246 | title: "Restore which forge?", | |
| 247 | items, | |
| 248 | onPick: (ids) => { | |
| 249 | if (ids[0] !== undefined) void restoreForge(session.app, ids[0], { actorId: user.id }).then((done) => ctx.toast(done.says, done.ok ? "success" : "danger")); | |
| 250 | }, | |
| 251 | }), | |
| 252 | ); | |
| 253 | }); | |
| 252 | 254 | } else if (e.key === "m") sandboxOne(); |
| 253 | 255 | else if (e.key === "w") raiseOne(); |
| 254 | 256 | else if (e.key === "x" && session !== undefined) |
src/web/pages/backups.ts +17 −1
| @@ -33,6 +33,7 @@ import { bodiesOf, type Store } from "../../snapshot/store.ts"; | ||
| 33 | 33 | import { snapshotsOf, type SnapshotsHandle } from "../../snapshot/service.ts"; |
| 34 | 34 | import { drillStatus, mirrorNow, snapshotNow, startDrillNow } from "../../actions/backups_now.ts"; |
| 35 | 35 | import { lastSnapshotOutcome } from "../../snapshot/outcome.ts"; |
| 36 | import { lastNightly, nightlyWords } from "../../spawn/nightly_copy.ts"; | |
| 36 | 37 | import type { Ctx } from "../../http/context.ts"; |
| 37 | 38 | import { |
| 38 | 39 | notePhase, |
| @@ -349,7 +350,7 @@ async function movingPart( | ||
| 349 | 350 | const restore = snapshots[0] |
| 350 | 351 | ? html`<pre class="restore-command" tabindex="0" aria-label="Restore command">bun run src/snapshot/restore.ts ${snapshots[0].name} /path/to/empty/data</pre>` |
| 351 | 352 | : null; |
| 352 | return html`<div id="backups-live" data-live="backup.*" data-live-src="/settings/backups/live">${recovery}${lanesCard(ctx)}<section class="settings-block"> | |
| 353 | return html`<div id="backups-live" data-live="backup.*" data-live-src="/settings/backups/live">${recovery}${lanesCard(ctx)}${forgeCopiesCard(ctx)}<section class="settings-block"> | |
| 353 | 354 | <h2>Where and when</h2> |
| 354 | 355 | <p> |
| 355 | 356 | Every night at 08:00 UTC the forge writes what cannot be rebuilt — its |
| @@ -630,6 +631,21 @@ export async function backupsNow(ctx: Ctx): Promise<Response> { | ||
| 630 | 631 | ); |
| 631 | 632 | } |
| 632 | 633 | |
| 634 | /** | |
| 635 | * What the last night's copies of the hosted forges came to (#13832): a forge skipped for its size | |
| 636 | * or not copied is named here, with why, not only in the log. | |
| 637 | */ | |
| 638 | export function forgeCopiesCard(ctx: Ctx): Html | "" { | |
| 639 | const o = lastNightly(ctx.app); | |
| 640 | if (o === undefined) return ""; | |
| 641 | const missed = [...o.skipped.map((s) => s.name), ...o.failed.map((f) => f.name)]; | |
| 642 | return html`<section class="settings-block" id="forge-copies" data-forge-copies> | |
| 643 | <h2>Hosted forges</h2> | |
| 644 | <p>Each hosted forge is copied as one file after the nightly snapshot. ${time(o.at)}: ${nightlyWords(o)}.</p> | |
| 645 | ${missed.length === 0 ? null : html`<p role="status" data-forge-copies-missed>${badge("Not copied", { tone: "danger" })} ${missed.join(", ")}</p>`} | |
| 646 | </section>`; | |
| 647 | } | |
| 648 | ||
| 633 | 649 | /** |
| 634 | 650 | * Each lane beside its newest object and its line (#9067); a lane without a |
| 635 | 651 | * line says so, as information. Nothing when no lane has been read. The |
src/web/pages/forges.ts +8 −5
| @@ -32,7 +32,7 @@ import { claimLinkBody } from "./new-forge.ts"; | ||
| 32 | 32 | import { appLinkSummary, appLinkWords } from "../../spawn/app_links.ts"; |
| 33 | 33 | import { REACH_SETTINGS, reachByForge, type ForgeReach } from "../../actions/child_reach.ts"; |
| 34 | 34 | import { forgeReachRows } from "./hosted-forges.ts"; |
| 35 | import { archiveForge, archivedForges, restoreForge, type ArchiveRecord } from "../../spawn/archive.ts"; | |
| 35 | import { archiveForge, restorableForges, restoreForge, type ArchiveRecord } from "../../spawn/archive.ts"; | |
| 36 | 36 | import { claimedWords, isForgeSort, keepWords, SORT_WORDS, sortForges, type ForgeSort } from "../../spawn/keep_words.ts"; |
| 37 | 37 | import { CHILD_NAME } from "../../spawn/placement.ts"; |
| 38 | 38 | import { forgesMemory, memoryOverLine } from "../../spawn/memory_fit.ts"; |
| @@ -234,7 +234,7 @@ export async function forgesPage(ctx: Ctx): Promise<Response> { | ||
| 234 | 234 | const asked = ctx.url.searchParams.get("sort"); |
| 235 | 235 | const sort: ForgeSort = isForgeSort(asked) ? asked : "attention"; |
| 236 | 236 | const rows = sortForges(await timePhaseAsync(ctx.request, "clients", () => servedRows(ctx.app)), sort); |
| 237 | const archived = archivedForges(ctx.app); | |
| 237 | const archived = await restorableForges(ctx.app); | |
| 238 | 238 | const full = timePhase(ctx.request, "room", () => noRoom(ctx.app)); |
| 239 | 239 | // Two small tables, by name: the rows themselves come from memory, and this reads no ledger. |
| 240 | 240 | const reachOf = timePhase(ctx.request, "reach", () => reachByForge(ctx.app, user)); |
| @@ -314,8 +314,11 @@ export async function forgeLinkForm(ctx: Ctx): Promise<Response> { | ||
| 314 | 314 | return response; |
| 315 | 315 | } |
| 316 | 316 | |
| 317 | /** One line each for what was archived: where the copy is, and the way back. */ | |
| 318 | function archivedSection(ctx: Ctx, archived: readonly ArchiveRecord[]): Html | null { | |
| 317 | /** | |
| 318 | * One line each for what was archived, and for a forge lost with a nightly copy (#13832): where the | |
| 319 | * copy is, and the way back. | |
| 320 | */ | |
| 321 | function archivedSection(ctx: Ctx, archived: readonly (ArchiveRecord & { readonly nightly: boolean })[]): Html | null { | |
| 319 | 322 | const said = ctx.url.searchParams.get("archive"); |
| 320 | 323 | const note = said === null ? null : html`<p role="status" class="muted" data-receipt>${said.slice(0, 300)}</p>`; |
| 321 | 324 | if (archived.length === 0) return note === null ? null : html`<section class="settings-block" id="archived"><h2>Archived</h2>${note}</section>`; |
| @@ -326,7 +329,7 @@ function archivedSection(ctx: Ctx, archived: readonly ArchiveRecord[]): Html | n | ||
| 326 | 329 | ${archived.map((a) => |
| 327 | 330 | row({ |
| 328 | 331 | title: html`${a.name}`, |
| 329 | meta: html`archived ${time(a.archivedAt)} · copy at ${a.where} (${a.key}) · ${a.for === null ? "no one named" : `for ${a.for}`}`, | |
| 332 | meta: html`${a.nightly ? "not here now; nightly copy of" : "archived"} ${time(a.archivedAt)} · copy at ${a.where} (${a.key}) · ${a.for === null ? "no one named" : `for ${a.for}`}`, | |
| 330 | 333 | id: `archived-${a.name}`, |
| 331 | 334 | data: { archived: a.name }, |
| 332 | 335 | trail: html`<form method="post" action="/forges/${a.name}/restore" class="inline">${btn("Restore", { size: "sm", title: "Brings it back under the same name" })}</form>`, |
test/snapshot-children.test.ts added +164
| @@ -0,0 +1,164 @@ | ||
| 1 | /** | |
| 2 | * #13832: the nightly snapshot writes each hosted forge as one file to the same destination, so | |
| 3 | * one forge can be restored alone; a forge too large is named as skipped with its size. | |
| 4 | */ | |
| 5 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 6 | import { chmodSync, existsSync, writeFileSync } from "node:fs"; | |
| 7 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { childDirOf, childNamed, listChildren } from "../src/actions/spawn.ts"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { createUser } from "../src/core/users.ts"; | |
| 13 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 14 | import { startSnapshots } from "../src/snapshot/service.ts"; | |
| 15 | import { dirStore } from "../src/snapshot/store.ts"; | |
| 16 | import { useChildFetch } from "../src/spawn/clients.ts"; | |
| 17 | import { useProbe } from "../src/spawn/door.ts"; | |
| 18 | import { firstBoot } from "../src/spawn/first-boot.ts"; | |
| 19 | import { NIGHTLY_PREFIX, nightlyRecord, restorableForges, restoreForge } from "../src/spawn/archive.ts"; | |
| 20 | import { pruneSnapshots } from "../src/snapshot/snapshot.ts"; | |
| 21 | import { removeForge } from "../src/spawn/manage.ts"; | |
| 22 | import { copyForges, lastNightly, nightlyWords } from "../src/spawn/nightly_copy.ts"; | |
| 23 | import { quietLogs } from "./helpers/globals.ts"; | |
| 24 | ||
| 25 | quietLogs(); | |
| 26 | ||
| 27 | let dir = ""; | |
| 28 | let storeDir = ""; | |
| 29 | let parent: App; | |
| 30 | let servers: Servers; | |
| 31 | /** nighttwo, made by the first test and left running for the ones after it. */ | |
| 32 | let two: Awaited<ReturnType<typeof makeForge>> | undefined; | |
| 33 | ||
| 34 | beforeAll(async () => { | |
| 35 | dir = await mkdtemp(join(tmpdir(), "forge-nightly-")); | |
| 36 | storeDir = await mkdtemp(join(tmpdir(), "forge-nightly-store-")); | |
| 37 | parent = createApp({ dataDir: dir, url: "https://forge.test", port: 0 }); | |
| 38 | useProbe(parent, () => async () => true); | |
| 39 | useChildFetch(parent, async () => new Response("{}", { status: 503 })); | |
| 40 | const alice = await createUser(parent.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 41 | if (!alice.ok) throw new Error(alice.error); | |
| 42 | servers = await serve(parent); | |
| 43 | }, 30_000); | |
| 44 | ||
| 45 | afterAll(async () => { | |
| 46 | servers.stop(); | |
| 47 | parent.close(); | |
| 48 | await rm(dir, { recursive: true, force: true }); | |
| 49 | await rm(storeDir, { recursive: true, force: true }); | |
| 50 | }); | |
| 51 | ||
| 52 | /** A hosted forge with an account of its own in its database, left open as a running one is. */ | |
| 53 | async function makeForge(name: string, username: string) { | |
| 54 | const res = await fetch(`${servers.url}/forges/start`, { method: "POST", redirect: "manual", headers: { origin: "https://forge.test" }, body: new URLSearchParams({ name }) }); | |
| 55 | await res.body?.cancel(); | |
| 56 | expect(res.status).toBe(200); | |
| 57 | const made = (await childNamed(parent, name))!; | |
| 58 | const child = createApp({ dataDir: childDirOf(parent, made.bodyId), port: 0 }); | |
| 59 | await firstBoot(child); | |
| 60 | const u = await createUser(child.db, { origin: "seed", trusted: true, username, email: `${username}@client.test`, password: "a-good-passphrase" }); | |
| 61 | if (!u.ok) throw new Error(u.error); | |
| 62 | return { made, child }; | |
| 63 | } | |
| 64 | ||
| 65 | test("a snapshot run writes one file per hosted forge, and one restores alone", async () => { | |
| 66 | const a = await makeForge("nightone", "maria"); | |
| 67 | const b = await makeForge("nighttwo", "jonas"); | |
| 68 | two = b; | |
| 69 | const store = dirStore(storeDir); | |
| 70 | const svc = startSnapshots(parent, store, { version: "t", nightly: false }); | |
| 71 | try { | |
| 72 | await svc.now(); | |
| 73 | } finally { | |
| 74 | await svc.stop(); | |
| 75 | } | |
| 76 | for (const name of ["nightone", "nighttwo"]) { | |
| 77 | const record = nightlyRecord(parent, name)!; | |
| 78 | expect(record.key).toBe(`${NIGHTLY_PREFIX}${name}.tar.gz`); | |
| 79 | expect((await store.get(record.key))?.length).toBe(record.bytes); | |
| 80 | } | |
| 81 | ||
| 82 | // nightone is lost; nighttwo keeps running untouched while it comes back alone. | |
| 83 | a.child.close(); | |
| 84 | await removeForge(parent, "nightone"); | |
| 85 | expect(existsSync(childDirOf(parent, a.made.bodyId))).toBe(false); | |
| 86 | // A lost forge's nightly copy is offered by Restore, on the page and in the terminal alike. | |
| 87 | expect((await restorableForges(parent)).find((r) => r.name === "nightone")).toMatchObject({ nightly: true }); | |
| 88 | expect((await restorableForges(parent)).some((r) => r.name === "nighttwo")).toBe(false); | |
| 89 | const said = await restoreForge(parent, "nightone", { destination: { source: "dir", store } }); | |
| 90 | expect(said).toMatchObject({ ok: true }); | |
| 91 | expect((await listChildren(parent)).map((c) => c.name).sort()).toEqual(["nightone", "nighttwo"]); | |
| 92 | const back = createApp({ dataDir: childDirOf(parent, a.made.bodyId), port: 0 }); | |
| 93 | try { | |
| 94 | expect(back.db.query<{ n: number }, []>("SELECT count(*) AS n FROM user WHERE username = 'maria'").get()!.n).toBe(1); | |
| 95 | } finally { | |
| 96 | back.close(); | |
| 97 | } | |
| 98 | expect(b.child.db.query<{ n: number }, []>("SELECT count(*) AS n FROM user WHERE username = 'jonas'").get()!.n).toBe(1); | |
| 99 | }, 60_000); | |
| 100 | ||
| 101 | test("an unchanged forge is not sent again; one over the cap is named with its size", async () => { | |
| 102 | const b = two!; | |
| 103 | const store = dirStore(storeDir); | |
| 104 | const again = await copyForges(parent, store); | |
| 105 | expect(again.unchanged).toContain("nighttwo"); | |
| 106 | b.child.db.run("UPDATE user SET email = '[email protected]' WHERE username = 'jonas'"); | |
| 107 | b.child.db.run("PRAGMA wal_checkpoint(TRUNCATE)"); | |
| 108 | const tiny = await copyForges(parent, store, { maxBytes: 10 }); | |
| 109 | expect(tiny.skipped.map((s) => s.name)).toContain("nighttwo"); | |
| 110 | expect(tiny.skipped.find((s) => s.name === "nighttwo")!.bytes).toBeGreaterThan(10); | |
| 111 | expect(nightlyWords(tiny)).toMatch(/nighttwo skipped: \d+\.\d MiB/); | |
| 112 | // The night's outcome is kept for the Backups page, not the log alone. | |
| 113 | expect(lastNightly(parent)?.skipped.map((s) => s.name)).toContain("nighttwo"); | |
| 114 | }, 60_000); | |
| 115 | ||
| 116 | test("a store wiped of a copy is sent it again, though nothing changed here", async () => { | |
| 117 | const b = two!; | |
| 118 | const store = dirStore(storeDir); | |
| 119 | // A store wiped of a copy is sent it again, though nothing changed here. | |
| 120 | await copyForges(parent, store); | |
| 121 | expect((await copyForges(parent, store)).unchanged).toContain("nighttwo"); | |
| 122 | await store.delete(`${NIGHTLY_PREFIX}nighttwo.tar.gz`); | |
| 123 | expect((await copyForges(parent, store)).written).toContain("nighttwo"); | |
| 124 | b.child.close(); | |
| 125 | }, 60_000); | |
| 126 | ||
| 127 | test("retention leaves the nightly copies alone, and a forge comes back from the store with this host's records lost", async () => { | |
| 128 | const c = await makeForge("nightthree", "ines"); | |
| 129 | const store = dirStore(storeDir); | |
| 130 | expect((await copyForges(parent, store)).written).toContain("nightthree"); | |
| 131 | c.child.close(); | |
| 132 | await pruneSnapshots(store, 0, Date.now(), true); | |
| 133 | expect(await store.list(NIGHTLY_PREFIX)).toContain(`${NIGHTLY_PREFIX}nightthree.tar.gz`); | |
| 134 | ||
| 135 | // The parent's disk is what was lost: no record of the copy is left here. | |
| 136 | await removeForge(parent, "nightthree"); | |
| 137 | await rm(join(dir, "archive", "nightly", "nightthree.json")); | |
| 138 | expect(nightlyRecord(parent, "nightthree")).toBeUndefined(); | |
| 139 | const said = await restoreForge(parent, "nightthree", { destination: { source: "dir", store } }); | |
| 140 | expect(said).toMatchObject({ ok: true }); | |
| 141 | const made = (await childNamed(parent, "nightthree"))!; | |
| 142 | const back = createApp({ dataDir: childDirOf(parent, made.bodyId), port: 0 }); | |
| 143 | try { | |
| 144 | expect(back.db.query<{ n: number }, []>("SELECT count(*) AS n FROM user WHERE username = 'ines'").get()!.n).toBe(1); | |
| 145 | } finally { | |
| 146 | back.close(); | |
| 147 | } | |
| 148 | }, 60_000); | |
| 149 | ||
| 150 | test.skipIf(process.getuid?.() === 0)("a copy tar could not read whole is failed, not stored half-read", async () => { | |
| 151 | const d = await makeForge("nightfour", "olu"); | |
| 152 | d.child.close(); | |
| 153 | const store = dirStore(storeDir); | |
| 154 | const locked = join(childDirOf(parent, d.made.bodyId), "unreadable"); | |
| 155 | writeFileSync(locked, "x"); | |
| 156 | chmodSync(locked, 0); | |
| 157 | try { | |
| 158 | const night = await copyForges(parent, store); | |
| 159 | expect(night.failed.map((f) => f.name)).toContain("nightfour"); | |
| 160 | expect(await store.list(`${NIGHTLY_PREFIX}nightfour`)).toEqual([]); | |
| 161 | } finally { | |
| 162 | chmodSync(locked, 0o600); | |
| 163 | } | |
| 164 | }, 60_000); |
test/spawn-sites.test.ts +1 −1
| @@ -88,7 +88,7 @@ const SITES: Record<string, string> = { | ||
| 88 | 88 | "src/snapshot/drill_job.ts": |
| 89 | 89 | "runs bun on the forge's own drill_child.ts with the job as JSON on stdin; argv holds only the bun path and a fixed script, nothing from a request", |
| 90 | 90 | "src/spawn/archive.ts": |
| 91 | "tar with fixed flags on the forge's own data directory and an archive path it derived from a validated name", | |
| 91 | "tar with fixed flags on the forge's own data directory and an archive path it derived from a validated name, and gzip -n -f on a tar file it wrote itself in its own staging directory under the data directory", | |
| 92 | 92 | "src/spawn/child_db.ts": |
| 93 | 93 | "bun (process.execPath) on the forge's own child_db_reader.ts, a fixed argv with an empty environment; the directory asked about and what a request presented travel over the IPC channel, never argv", |
| 94 | 94 | "src/spawn/cell.ts": |
test/take-expect.test.ts +3
| @@ -59,6 +59,9 @@ beforeAll(async () => { | ||
| 59 | 59 | await commit("alice", name, "README.md", "Start"); |
| 60 | 60 | const forked = await forkRepo(app, bob.value, r.value); |
| 61 | 61 | if (!forked.ok) throw new Error(String(forked.error)); |
| 62 | // The forge's own follow of the next commit runs unawaited; ff opts out | |
| 63 | // before that commit, so no follow lands mid-test and moves bob/ff. | |
| 64 | if (name === "ff") setForkFollowMode(app.db, forked.value.id, "dont-follow"); | |
| 62 | 65 | await commit("alice", name, "next.txt", "Next"); |
| 63 | 66 | } |
| 64 | 67 | }, 60_000); |
new above
offline
Outcome only reaches the log. Surface skipped/failed forges on the Backups page.