Public: anyone can read this; the crew can change it.
The restore drill records how long each part took — download, decompress, open, migrate — and its budget follows the snapshot's size #2730
scout/forge:scout/2719-the-restore-drill-records-how-long-each → main 1 commit fork
11 files
changed +308
−54
docs/RECOVERY.md +6 −3
| @@ -100,9 +100,9 @@ which line it stops at. | ||
| 100 | 100 | |
| 101 | 101 | - **manifest** — reading the snapshot's list of files and bundles. Likely the |
| 102 | 102 | manifest object is missing or damaged. Check the object exists in the store. |
| 103 | - **files** — fetching the plain files. Likely a slow or failing store. Check | |
| 104 | how far it got against the manifest's file count, then retry. | |
| 105 | - **unpack** — unpacking the fetched files into the data directory. Likely the | |
| 103 | - **download** — fetching the files; the database's parts decompress as they | |
| 104 | land. Likely a slow or failing store. Check how far it got, then retry. | |
| 105 | - **decompress** — what is left of unpacking once the download ends. Likely the | |
| 106 | 106 | disk is full or the archive is damaged. Check free space. |
| 107 | 107 | - **bundles** — cloning each repository from its bundle. Likely a slow store |
| 108 | 108 | or many repositories. Compare its counts with the snapshot's and retry the |
| @@ -110,6 +110,9 @@ which line it stops at. | ||
| 110 | 110 | - **key** — restoring the secret key, opened with the passphrase. Likely the |
| 111 | 111 | passphrase is missing or wrong. Check `FORGE_SNAPSHOT_PASSPHRASE`. |
| 112 | 112 | |
| 113 | After the restore the card adds **open** (reading the database) and | |
| 114 | **migrate** (the restored forge booting until health; slow means a long migration). | |
| 115 | ||
| 113 | 116 | ## What a snapshot does NOT hold |
| 114 | 117 | |
| 115 | 118 | - Sealed values, unless the passphrase was set: they stay sealed and are set |
src/snapshot/drill.ts +16 −4
| @@ -77,7 +77,8 @@ export function formatSpan(ms: number): string { | ||
| 77 | 77 | |
| 78 | 78 | /** One restore phase and the milliseconds it took. */ |
| 79 | 79 | export interface PhaseTime { |
| 80 | readonly phase: Progress["phase"]; | |
| 80 | /** A restore phase, then `open` (the database read) and `migrate` (the restored forge booting). */ | |
| 81 | readonly phase: Progress["phase"] | "open" | "migrate"; | |
| 81 | 82 | readonly ms: number; |
| 82 | 83 | } |
| 83 | 84 | |
| @@ -151,11 +152,13 @@ export async function runDrill(deps: DrillDeps): Promise<DrillResult> { | ||
| 151 | 152 | // When each restore phase was first reported, and when the restore ended. |
| 152 | 153 | const began: { phase: Progress["phase"]; at: number }[] = []; |
| 153 | 154 | let restoreEnd: number | undefined; |
| 155 | let openEnd: number | undefined; | |
| 156 | let bootEnd: number | undefined; | |
| 154 | 157 | let health: DrillResult["health"] = "unreached"; |
| 155 | 158 | try { |
| 156 | 159 | // One clock for the whole drill, so a hang in any step ends it red. |
| 157 | 160 | const left = (): number => Math.max(1, started + budgetMs - performance.now()); |
| 158 | const newest = (await within(listSnapshots(deps.store), left(), budget))[0]; | |
| 161 | const newest = (await within(listSnapshots(deps.store.bounded?.(budgetMs) ?? deps.store), left(), budget))[0]; | |
| 159 | 162 | if (newest === undefined) throw new Error("the store holds no snapshot"); |
| 160 | 163 | snapshotId = newest.name; |
| 161 | 164 | sized = snapshotBytes(newest); |
| @@ -167,7 +170,8 @@ export async function runDrill(deps: DrillDeps): Promise<DrillResult> { | ||
| 167 | 170 | scratch = mkdtempSync(join(parent, "restore-")); |
| 168 | 171 | const target = join(scratch, "data"); |
| 169 | 172 | await within( |
| 170 | restore(deps.store, newest.name, target, { | |
| 173 | // Every get, tried as often as the store tries it, fits the budget. | |
| 174 | restore(deps.store.bounded?.(budgetMs) ?? deps.store, newest.name, target, { | |
| 171 | 175 | passphrase: deps.passphrase, |
| 172 | 176 | onProgress: (p) => { |
| 173 | 177 | progress = p; |
| @@ -228,11 +232,13 @@ export async function runDrill(deps: DrillDeps): Promise<DrillResult> { | ||
| 228 | 232 | } |
| 229 | 233 | |
| 230 | 234 | step = "health"; |
| 235 | openEnd = performance.now(); | |
| 231 | 236 | const booted = await within( |
| 232 | 237 | (deps.boot ?? bootRestored)(target, left()), |
| 233 | 238 | left(), |
| 234 | 239 | budget, |
| 235 | 240 | ); |
| 241 | bootEnd = performance.now(); | |
| 236 | 242 | health = booted.ok ? "ok" : "failed"; |
| 237 | 243 | if (!booted.ok) throw new Error(booted.reason); |
| 238 | 244 | } catch (error) { |
| @@ -255,10 +261,16 @@ export async function runDrill(deps: DrillDeps): Promise<DrillResult> { | ||
| 255 | 261 | |
| 256 | 262 | function finish(failedStep: DrillStep | null): DrillResult { |
| 257 | 263 | const end = restoreEnd ?? performance.now(); |
| 258 | const phases = began.map((b, i) => ({ | |
| 264 | const now = performance.now(); | |
| 265 | const phases: PhaseTime[] = began.map((b, i) => ({ | |
| 259 | 266 | phase: b.phase, |
| 260 | 267 | ms: Math.max(0, Math.round((began[i + 1]?.at ?? end) - b.at)), |
| 261 | 268 | })); |
| 269 | // The steps after the restore: reading the database, then the boot that migrates it. | |
| 270 | if (restoreEnd !== undefined) { | |
| 271 | phases.push({ phase: "open", ms: Math.max(0, Math.round((openEnd ?? now) - restoreEnd)) }); | |
| 272 | if (openEnd !== undefined) phases.push({ phase: "migrate", ms: Math.max(0, Math.round((bootEnd ?? now) - openEnd)) }); | |
| 273 | } | |
| 262 | 274 | return { |
| 263 | 275 | at, |
| 264 | 276 | snapshotId, |
src/snapshot/drills.ts +6 −2
| @@ -22,7 +22,10 @@ interface Row { | ||
| 22 | 22 | phases: string | null; |
| 23 | 23 | } |
| 24 | 24 | |
| 25 | const PHASES = new Set(["manifest", "files", "unpack", "bundles", "key"]); | |
| 25 | const PHASES = new Set(["manifest", "download", "decompress", "open", "migrate", "bundles", "key"]); | |
| 26 | ||
| 27 | /** Names drills were stored under before they said what the time was spent on. */ | |
| 28 | const LEGACY: Record<string, string> = { files: "download", unpack: "decompress" }; | |
| 26 | 29 | |
| 27 | 30 | /** The stored JSON as phases; anything that is not a list of known phases with whole ms reads as none. */ |
| 28 | 31 | export function parsePhases(raw: string | null): { phases: PhaseTime[]; budgetMs: number } { |
| @@ -35,7 +38,8 @@ export function parsePhases(raw: string | null): { phases: PhaseTime[]; budgetMs | ||
| 35 | 38 | if (!Array.isArray(phases) || typeof budgetMs !== "number" || !Number.isFinite(budgetMs) || budgetMs < 0) return none; |
| 36 | 39 | const out: PhaseTime[] = []; |
| 37 | 40 | for (const p of phases) { |
| 38 | const { phase, ms } = (p ?? {}) as { phase?: unknown; ms?: unknown }; | |
| 41 | const { phase: stored, ms } = (p ?? {}) as { phase?: unknown; ms?: unknown }; | |
| 42 | const phase = typeof stored === "string" ? (LEGACY[stored] ?? stored) : stored; | |
| 39 | 43 | if (typeof phase !== "string" || !PHASES.has(phase) || typeof ms !== "number" || !Number.isFinite(ms) || ms < 0) return none; |
| 40 | 44 | out.push({ phase: phase as PhaseTime["phase"], ms }); |
| 41 | 45 | } |
src/snapshot/parts.ts +60 −1
| @@ -11,9 +11,13 @@ | ||
| 11 | 11 | * the parts back in order, joins them, and unpacks to exactly the bytes |
| 12 | 12 | * that went in, or refuses. |
| 13 | 13 | * |
| 14 | * Plain data in, plain data out: no store, no files. | |
| 14 | * Plain data in, plain data out, except `unpacker`, which writes the one file it is given. | |
| 15 | 15 | */ |
| 16 | 16 | |
| 17 | import { createWriteStream, renameSync, rmSync } from "node:fs"; | |
| 18 | import { pipeline } from "node:stream/promises"; | |
| 19 | import { createZstdDecompress } from "node:zlib"; | |
| 20 | ||
| 17 | 21 | /** A part's size: one put carries it within its own deadline at the floor rate (27 s at 5 Mbit/s). */ |
| 18 | 22 | export const PART_BYTES = 16 * 1_048_576; |
| 19 | 23 | |
| @@ -106,3 +110,58 @@ export function isPackedFile(v: unknown): v is PackedFile { | ||
| 106 | 110 | (p["parts"] as number) >= 1 |
| 107 | 111 | ); |
| 108 | 112 | } |
| 113 | ||
| 114 | /** | |
| 115 | * A packed file unpacked as its parts arrive: each part, in order, goes | |
| 116 | * into a streaming decompressor that writes `out`, so unpacking overlaps | |
| 117 | * the download and the whole compressed file is never joined in memory. | |
| 118 | * Parts may be offered in any order; one waits for the parts before it. | |
| 119 | * `finish` closes the file and checks the sizes the manifest gives. | |
| 120 | */ | |
| 121 | export function unpacker(p: PackedFile, out: string) { | |
| 122 | const decoder = createZstdDecompress(); | |
| 123 | // The file appears under its own name only once it is whole. | |
| 124 | const partial = `${out}.unpacking`; | |
| 125 | const done = pipeline(decoder, createWriteStream(partial)); | |
| 126 | done.catch(() => {}); | |
| 127 | const waiting = new Map<number, Uint8Array>(); | |
| 128 | let next = 0; | |
| 129 | let fed = 0; | |
| 130 | let produced = 0; | |
| 131 | decoder.on("data", (chunk: Buffer) => { | |
| 132 | produced += chunk.byteLength; | |
| 133 | }); | |
| 134 | const write = (body: Uint8Array): Promise<void> => | |
| 135 | new Promise((resolve, reject) => { | |
| 136 | decoder.write(body, (error) => (error ? reject(error) : resolve())); | |
| 137 | }); | |
| 138 | return { | |
| 139 | async feed(n: number, body: Uint8Array): Promise<void> { | |
| 140 | if (!Number.isSafeInteger(n) || n < 0 || n >= p.parts) | |
| 141 | throw new Error(`${p.path} has no part ${n}`); | |
| 142 | waiting.set(n, body); | |
| 143 | for (let part = waiting.get(next); part !== undefined; part = waiting.get(next)) { | |
| 144 | waiting.delete(next); | |
| 145 | next++; | |
| 146 | fed += part.byteLength; | |
| 147 | await write(part); | |
| 148 | } | |
| 149 | }, | |
| 150 | async finish(): Promise<void> { | |
| 151 | if (next !== p.parts) | |
| 152 | throw new Error(`${p.path} came back in ${next} parts, not ${p.parts}`); | |
| 153 | if (fed !== p.packedBytes) | |
| 154 | throw new Error(`${p.path}'s parts are ${fed} bytes, not ${p.packedBytes}`); | |
| 155 | decoder.end(); | |
| 156 | await done; | |
| 157 | if (produced !== p.bytes) | |
| 158 | throw new Error(`${p.path} unpacks to ${produced} bytes, not ${p.bytes}`); | |
| 159 | renameSync(partial, out); | |
| 160 | }, | |
| 161 | /** Abandon a file that cannot be finished: nothing of it is left on disk. */ | |
| 162 | abort(): void { | |
| 163 | decoder.destroy(); | |
| 164 | rmSync(partial, { force: true }); | |
| 165 | }, | |
| 166 | }; | |
| 167 | } |
src/snapshot/restore.ts +28 −25
| @@ -20,8 +20,10 @@ | ||
| 20 | 20 | * `FORGE_SNAPSHOT_DIR` for a directory store. |
| 21 | 21 | * |
| 22 | 22 | * A file that went up compressed in parts (the database, `parts.ts`) |
| 23 | * comes back whole: its parts read in order, joined, unpacked, and checked | |
| 24 | * against the size the manifest gives it. | |
| 23 | * comes back whole: its parts stream into the decompressor as they land, | |
| 24 | * so decompressing overlaps the download, and the result is checked | |
| 25 | * against the size the manifest gives it. The `decompress` phase is what | |
| 26 | * is left to do once the download ends. | |
| 25 | 27 | * |
| 26 | 28 | * The key comes back only from its wrapped form and the operator's |
| 27 | 29 | * passphrase (`FORGE_SNAPSHOT_PASSPHRASE`). A wrong passphrase refuses the |
| @@ -46,7 +48,7 @@ import { | ||
| 46 | 48 | type Manifest, |
| 47 | 49 | } from "./snapshot.ts"; |
| 48 | 50 | import { unwrapKey, WRAPPED_KEY } from "./wrap.ts"; |
| 49 | import { isPackedFile, partPaths, unpack, type PackedFile } from "./parts.ts"; | |
| 51 | import { isPackedFile, partPaths, unpacker, type PackedFile } from "./parts.ts"; | |
| 50 | 52 | import { resolveDestination } from "./destination.ts"; |
| 51 | 53 | import type { Store } from "./store.ts"; |
| 52 | 54 | |
| @@ -62,7 +64,7 @@ export interface Restored { | ||
| 62 | 64 | |
| 63 | 65 | /** Where a restore is, as plain data: `done` of `total` in `phase`, `bytes` so far in it. */ |
| 64 | 66 | export interface Progress { |
| 65 | readonly phase: "manifest" | "files" | "unpack" | "bundles" | "key"; | |
| 67 | readonly phase: "manifest" | "download" | "decompress" | "bundles" | "key"; | |
| 66 | 68 | readonly done: number; |
| 67 | 69 | readonly total: number; |
| 68 | 70 | readonly bytes: number; |
| @@ -208,26 +210,32 @@ export async function restoreSnapshot( | ||
| 208 | 210 | for (const file of packed) |
| 209 | 211 | for (const [n, path] of partPaths(file).entries()) |
| 210 | 212 | partOf.set(path, { file, n }); |
| 211 | const gathered = new Map<string, Uint8Array[]>(); | |
| 212 | 213 | mkdirSync(dataDir, { recursive: true }); |
| 214 | const unpackers = new Map<string, ReturnType<typeof unpacker>>(); | |
| 215 | const seen = new Set<string>(); | |
| 216 | for (const file of packed) { | |
| 217 | const out = join(dataDir, file.path); | |
| 218 | mkdirSync(dirname(out), { recursive: true }); | |
| 219 | unpackers.set(file.path, unpacker(file, out)); | |
| 220 | } | |
| 213 | 221 | |
| 214 | 222 | let files = 0; |
| 215 | 223 | let repos = 0; |
| 216 | 224 | const bundles: { at: number; owner: string; name: string; file: string }[] = []; |
| 217 | 225 | let fetched = 0; |
| 218 | 226 | let fetchedBytes = 0; |
| 219 | say("files", 0, manifest.files.length, 0); | |
| 227 | try { | |
| 228 | say("download", 0, manifest.files.length, 0); | |
| 220 | 229 | await fetchAll(store, prefix, manifest.files, async (entry, body, at) => { |
| 221 | 230 | fetched++; |
| 222 | 231 | fetchedBytes += entry.bytes; |
| 223 | say("files", fetched, manifest.files.length, fetchedBytes); | |
| 232 | say("download", fetched, manifest.files.length, fetchedBytes); | |
| 224 | 233 | if (entry.path === WRAPPED_KEY) return; |
| 225 | 234 | // A part waits for the rest of its file. |
| 226 | 235 | const part = partOf.get(entry.path); |
| 227 | 236 | if (part !== undefined) { |
| 228 | const got = gathered.get(part.file.path) ?? []; | |
| 229 | got[part.n] = body; | |
| 230 | gathered.set(part.file.path, got); | |
| 237 | seen.add(entry.path); | |
| 238 | await unpackers.get(part.file.path)!.feed(part.n, body); | |
| 231 | 239 | return; |
| 232 | 240 | } |
| 233 | 241 | // A day's run logs in one object come back as the logs they were. |
| @@ -259,24 +267,19 @@ export async function restoreSnapshot( | ||
| 259 | 267 | bundles.sort((a, b) => a.at - b.at); |
| 260 | 268 | let unpacked = 0; |
| 261 | 269 | let unpackedBytes = 0; |
| 262 | say("unpack", 0, packed.length, 0); | |
| 270 | say("decompress", 0, packed.length, 0); | |
| 263 | 271 | for (const file of packed) { |
| 264 | const got = gathered.get(file.path) ?? []; | |
| 265 | const parts = partPaths(file).map((path, n) => { | |
| 266 | const body = got[n]; | |
| 267 | if (body === undefined) | |
| 268 | throw new Error(`snapshot ${name} is missing ${path}`); | |
| 269 | return body; | |
| 270 | }); | |
| 271 | gathered.delete(file.path); | |
| 272 | const target = join(dataDir, file.path); | |
| 273 | mkdirSync(dirname(target), { recursive: true }); | |
| 274 | const whole = await unpack(file, parts); | |
| 275 | await Bun.write(target, whole); | |
| 272 | for (const path of partPaths(file)) | |
| 273 | if (!seen.has(path)) throw new Error(`snapshot ${name} is missing ${path}`); | |
| 274 | await unpackers.get(file.path)!.finish(); | |
| 276 | 275 | files++; |
| 277 | 276 | unpacked++; |
| 278 | unpackedBytes += whole.byteLength; | |
| 279 | say("unpack", unpacked, packed.length, unpackedBytes); | |
| 277 | unpackedBytes += file.bytes; | |
| 278 | say("decompress", unpacked, packed.length, unpackedBytes); | |
| 279 | } | |
| 280 | } catch (error) { | |
| 281 | for (const u of unpackers.values()) u.abort(); | |
| 282 | throw error; | |
| 280 | 283 | } |
| 281 | 284 | // Each repository is its own clone, so several at once: a forge of |
| 282 | 285 | // hundreds of them spent the drill's minutes here, one after another. |
src/snapshot/store.ts +23 −1
| @@ -21,6 +21,11 @@ export interface Store { | ||
| 21 | 21 | /** The next path segment under `prefix`: the "directories", not the keys. */ |
| 22 | 22 | names(prefix: string): Promise<string[]>; |
| 23 | 23 | delete(key: string): Promise<void>; |
| 24 | /** | |
| 25 | * The same store with every read held inside `budgetMs` however often it | |
| 26 | * is tried (`callDeadlineMs`); a store that does not retry has none. | |
| 27 | */ | |
| 28 | bounded?(budgetMs: number): Store; | |
| 24 | 29 | } |
| 25 | 30 | |
| 26 | 31 | /** The S3 credentials as the platform hands them to an app. */ |
| @@ -58,6 +63,17 @@ export const SLACK_MS = 60_000; | ||
| 58 | 63 | /** How long a read, a listing or a delete may go unanswered. */ |
| 59 | 64 | export const CALL_DEADLINE_MS = 180_000; |
| 60 | 65 | |
| 66 | /** | |
| 67 | * The deadline each attempt of a read gets so that all its attempts and the | |
| 68 | * waits between them add up to no more than `budgetMs`: attempts × deadline | |
| 69 | * + waits ≤ budget. Never more than `CALL_DEADLINE_MS`, never less than 1 ms. | |
| 70 | */ | |
| 71 | export function callDeadlineMs(budgetMs: number, attempts = 5, baseMs = 500): number { | |
| 72 | const waits = baseMs * (2 ** (attempts - 1) - 1); | |
| 73 | const each = Math.floor((budgetMs - waits) / attempts); | |
| 74 | return Math.max(1, Math.min(CALL_DEADLINE_MS, each)); | |
| 75 | } | |
| 76 | ||
| 61 | 77 | /** How long a put of `bytes` may take before it counts as failed: its bytes at the floor rate, plus slack. */ |
| 62 | 78 | export const deadlineFor = ( |
| 63 | 79 | bytes: number, |
| @@ -94,13 +110,18 @@ export function withRetries( | ||
| 94 | 110 | deadlineMs?: number; |
| 95 | 111 | floorBytesPerS?: number; |
| 96 | 112 | slackMs?: number; |
| 113 | /** Hold every read, listing and delete, retries included, inside this many ms. */ | |
| 114 | budgetMs?: number; | |
| 97 | 115 | sleep?: (ms: number) => Promise<void>; |
| 98 | 116 | } = {}, |
| 99 | 117 | ): Store { |
| 100 | 118 | const attempts = Math.max(1, options.attempts ?? 5); |
| 101 | 119 | const baseMs = options.baseMs ?? 500; |
| 102 | 120 | const fixed = options.deadlineMs; |
| 103 | const callMs = fixed ?? CALL_DEADLINE_MS; | |
| 121 | const callMs = Math.min( | |
| 122 | fixed ?? CALL_DEADLINE_MS, | |
| 123 | options.budgetMs === undefined ? Infinity : callDeadlineMs(options.budgetMs, attempts, baseMs), | |
| 124 | ); | |
| 104 | 125 | const putMs = (body: Uint8Array | string): number => |
| 105 | 126 | fixed ?? deadlineFor(sizeOf(body), options.floorBytesPerS, options.slackMs); |
| 106 | 127 | const sleep = options.sleep ?? ((ms) => Bun.sleep(ms)); |
| @@ -125,6 +146,7 @@ export function withRetries( | ||
| 125 | 146 | return { |
| 126 | 147 | where: inner.where, |
| 127 | 148 | ...(inner.dir === undefined ? {} : { dir: inner.dir }), |
| 149 | bounded: (budgetMs) => withRetries(inner, { ...options, budgetMs }), | |
| 128 | 150 | put: (key, body) => |
| 129 | 151 | tried(`put ${key}`, putMs(body), () => inner.put(key, body)), |
| 130 | 152 | get: (key) => tried(`get ${key}`, callMs, () => inner.get(key)), |
src/web/pages/backups.ts +4 −3
| @@ -90,12 +90,13 @@ function keyNote( | ||
| 90 | 90 | </p>`; |
| 91 | 91 | } |
| 92 | 92 | |
| 93 | /** "6 min 12 s of its 14 min budget: files 58 s, ..."; empty for a drill that kept no phases. */ | |
| 94 | function drillTiming(d: DrillResult): string { | |
| 93 | /** "6 min 12 s of its 14 min budget: download 58 s, ...; slowest: bundles"; empty for a drill that kept no phases. */ | |
| 94 | export function drillTiming(d: DrillResult): string { | |
| 95 | 95 | if (d.phases.length === 0 || d.budgetMs <= 0) return ""; |
| 96 | const slowest = d.phases.reduce((a, p) => (p.ms > a.ms ? p : a)); | |
| 96 | 97 | return `${formatSpan(d.ms)} of its ${formatBudget(d.budgetMs)} budget: ${d.phases |
| 97 | 98 | .map((p) => `${p.phase} ${formatSpan(p.ms)}`) |
| 98 | .join(", ")}`; | |
| 99 | .join(", ")}${d.phases.length > 1 ? `; slowest: ${slowest.phase}` : ""}`; | |
| 99 | 100 | } |
| 100 | 101 | |
| 101 | 102 | /** The last drill in one line, and the button to run another. */ |
test/drill-slow.test.ts +1 −1
| @@ -12,7 +12,7 @@ const drill = (over: Partial<DrillResult>): DrillResult => ({ | ||
| 12 | 12 | verdict: "green", |
| 13 | 13 | failedStep: null, |
| 14 | 14 | phases: [ |
| 15 | { phase: "files", ms: 1 * MIN }, | |
| 15 | { phase: "download", ms: 1 * MIN }, | |
| 16 | 16 | { phase: "bundles", ms: 9 * MIN }, |
| 17 | 17 | ], |
| 18 | 18 | budgetMs: 11 * MIN, |
test/snapshot-drill-parts.test.ts added +150
| @@ -0,0 +1,150 @@ | ||
| 1 | /** | |
| 2 | * The drill's time, part by part (#2719): a 400 MB snapshot behind a | |
| 3 | * throttled store restores inside its budget and the card names the | |
| 4 | * slowest part; downloads stream into decompression; the gets' deadlines | |
| 5 | * times their attempts never exceed the budget. | |
| 6 | */ | |
| 7 | ||
| 8 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 9 | import { Database } from "bun:sqlite"; | |
| 10 | import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; | |
| 11 | import { randomBytes } from "node:crypto"; | |
| 12 | import { rm } from "node:fs/promises"; | |
| 13 | import { tmpdir } from "node:os"; | |
| 14 | import { join } from "node:path"; | |
| 15 | import { drillBudgetMs, runDrill } from "../src/snapshot/drill.ts"; | |
| 16 | import { pack, partPath, unpacker } from "../src/snapshot/parts.ts"; | |
| 17 | import { callDeadlineMs, CALL_DEADLINE_MS, dirStore, withRetries, type Store } from "../src/snapshot/store.ts"; | |
| 18 | import { drillTiming } from "../src/web/pages/backups.ts"; | |
| 19 | ||
| 20 | const NAME = "2026-10-19T08-00-00Z"; | |
| 21 | const prefix = `snapshots/${NAME}/`; | |
| 22 | const MB = 1_048_576; | |
| 23 | ||
| 24 | let root: string; | |
| 25 | beforeAll(() => { | |
| 26 | root = mkdtempSync(join(tmpdir(), "forge-drill-parts-")); | |
| 27 | }); | |
| 28 | afterAll(async () => { | |
| 29 | await rm(root, { recursive: true, force: true }); | |
| 30 | }); | |
| 31 | ||
| 32 | /** A forge database with the tables the drill counts, then padded with zeros to `size` bytes. */ | |
| 33 | function paddedDatabase(size: number): Uint8Array { | |
| 34 | const file = join(root, "made.db"); | |
| 35 | const db = new Database(file); | |
| 36 | for (const t of ["repo", "issue", "user", "pull", "app"]) db.run(`create table ${t} (id integer primary key)`); | |
| 37 | db.run("create table secret (name text, scope text, value_enc text)"); | |
| 38 | db.run("create table app_env (app_id text, name text, value_enc text)"); | |
| 39 | db.close(); | |
| 40 | const real = readFileSync(file); | |
| 41 | const out = new Uint8Array(size); | |
| 42 | out.set(real); | |
| 43 | return out; | |
| 44 | } | |
| 45 | ||
| 46 | /** A store that answers each get after a pause that grows with the bytes, like a slow link. */ | |
| 47 | function throttled(inner: Store, msPerKiB: number, gets: { n: number }): Store { | |
| 48 | return { | |
| 49 | ...inner, | |
| 50 | async get(key) { | |
| 51 | const body = await inner.get(key); | |
| 52 | gets.n++; | |
| 53 | await Bun.sleep(5 + ((body?.byteLength ?? 0) / 1024) * msPerKiB); | |
| 54 | return body; | |
| 55 | }, | |
| 56 | }; | |
| 57 | } | |
| 58 | ||
| 59 | describe("a 400 MB snapshot through a throttled store", () => { | |
| 60 | test("restores within its budget and the card names the slowest part", async () => { | |
| 61 | const db = paddedDatabase(400 * MB); | |
| 62 | const { packed, parts } = await pack("forge.db", db, 2048); | |
| 63 | const inner = dirStore(join(root, "store")); | |
| 64 | for (const [i, part] of parts.entries()) await inner.put(prefix + partPath("forge.db", i), part); | |
| 65 | const files = parts.map((part, i) => ({ path: partPath("forge.db", i), bytes: part.byteLength })); | |
| 66 | await inner.put( | |
| 67 | `${prefix}manifest.json`, | |
| 68 | JSON.stringify({ | |
| 69 | name: NAME, | |
| 70 | startedAt: "2026-10-19T08:00:00.000Z", | |
| 71 | finishedAt: "2026-10-19T08:01:00.000Z", | |
| 72 | version: "t", | |
| 73 | repos: 0, | |
| 74 | apps: 0, | |
| 75 | files, | |
| 76 | packed: [packed], | |
| 77 | bytes: packed.bytes, | |
| 78 | key: "none", | |
| 79 | }), | |
| 80 | ); | |
| 81 | expect(parts.length).toBeGreaterThan(2); | |
| 82 | ||
| 83 | const gets = { n: 0 }; | |
| 84 | const r = await runDrill({ | |
| 85 | store: throttled(inner, 4, gets), | |
| 86 | dataDir: join(root, "drill-data"), | |
| 87 | boot: async () => { | |
| 88 | await Bun.sleep(60); | |
| 89 | return { ok: true, reason: "" }; | |
| 90 | }, | |
| 91 | }); | |
| 92 | expect(r.reason).toBeNull(); | |
| 93 | expect(r.verdict).toBe("green"); | |
| 94 | expect(r.budgetMs).toBe(drillBudgetMs(400 * MB)); | |
| 95 | expect(r.ms).toBeLessThan(r.budgetMs); | |
| 96 | expect(r.phases.map((p) => p.phase)).toEqual(["manifest", "download", "decompress", "bundles", "key", "open", "migrate"]); | |
| 97 | const slowest = r.phases.reduce((a, p) => (p.ms > a.ms ? p : a)); | |
| 98 | expect(drillTiming(r)).toContain(`slowest: ${slowest.phase}`); | |
| 99 | expect(drillTiming(r)).toMatch(/download [\d.]+ (ms|s)|download \d+ ms/); | |
| 100 | }, 60_000); | |
| 101 | }); | |
| 102 | ||
| 103 | describe("downloads stream into decompression", () => { | |
| 104 | test("parts offered out of order unpack to the file once the gap fills, and only then appear", async () => { | |
| 105 | const body = new Uint8Array(randomBytes(300_000)); | |
| 106 | const { packed, parts } = await pack("forge.db", body, 1024); | |
| 107 | expect(parts.length).toBeGreaterThan(3); | |
| 108 | const out = join(root, "streamed.db"); | |
| 109 | const u = unpacker(packed, out); | |
| 110 | for (let n = parts.length - 1; n >= 1; n--) await u.feed(n, parts[n]!); | |
| 111 | expect(await Bun.file(out).exists()).toBe(false); | |
| 112 | await u.feed(0, parts[0]!); | |
| 113 | await u.finish(); | |
| 114 | expect(new Uint8Array(readFileSync(out))).toEqual(body); | |
| 115 | }); | |
| 116 | ||
| 117 | test("a part short of the manifest's size is refused and leaves no file", async () => { | |
| 118 | const { packed, parts } = await pack("forge.db", new Uint8Array(5000).fill(3), 512); | |
| 119 | const out = join(root, "short.db"); | |
| 120 | const u = unpacker({ ...packed, packedBytes: packed.packedBytes + 1 }, out); | |
| 121 | for (const [n, part] of parts.entries()) await u.feed(n, part); | |
| 122 | await expect(u.finish()).rejects.toThrow("bytes, not"); | |
| 123 | u.abort(); | |
| 124 | expect(await Bun.file(out).exists()).toBe(false); | |
| 125 | writeFileSync(join(root, "keep"), ""); | |
| 126 | }); | |
| 127 | }); | |
| 128 | ||
| 129 | describe("the gets' deadlines fit the budget", () => { | |
| 130 | test("deadline × attempts plus the waits never exceed any budget", () => { | |
| 131 | for (const budget of [1_000, 30_000, 600_000, 2_700_000]) { | |
| 132 | const each = callDeadlineMs(budget); | |
| 133 | expect(each).toBeLessThanOrEqual(CALL_DEADLINE_MS); | |
| 134 | if (budget >= 10_000) expect(each * 5 + 500 * 15).toBeLessThanOrEqual(budget); | |
| 135 | } | |
| 136 | expect(callDeadlineMs(600_000)).toBe(118_500); | |
| 137 | expect(callDeadlineMs(2_700_000)).toBe(CALL_DEADLINE_MS); | |
| 138 | expect(callDeadlineMs(30_000)).toBe(4_500); | |
| 139 | }); | |
| 140 | ||
| 141 | test("a bounded store gives up on a get that never answers inside the budget", async () => { | |
| 142 | const hung: Store = { ...dirStore(join(root, "hung")), get: () => new Promise(() => {}) }; | |
| 143 | const sleeps: number[] = []; | |
| 144 | const store = withRetries(hung, { attempts: 3, baseMs: 10, sleep: async (ms) => void sleeps.push(ms) }); | |
| 145 | const started = performance.now(); | |
| 146 | await expect(store.bounded!(300).get("k")).rejects.toThrow("get k failed after 3 attempts"); | |
| 147 | // 3 attempts of (300 − 30) / 3 = 90 ms each. | |
| 148 | expect(performance.now() - started).toBeLessThan(300); | |
| 149 | }); | |
| 150 | }); |
test/snapshot-drill-phases.test.ts +9 −9
| @@ -60,10 +60,10 @@ describe("drill phases", () => { | ||
| 60 | 60 | |
| 61 | 61 | test("a green drill keeps the phases a stubbed restore reported, and the budget", async () => { |
| 62 | 62 | const r = await drill((async (s: never, n: never, t: never, o: { onProgress?: (p: unknown) => void }) => { |
| 63 | o.onProgress?.({ phase: "files", done: 0, total: 2, bytes: 0 }); | |
| 63 | o.onProgress?.({ phase: "download", done: 0, total: 2, bytes: 0 }); | |
| 64 | 64 | await sleep(30); |
| 65 | o.onProgress?.({ phase: "files", done: 2, total: 2, bytes: 9 }); | |
| 66 | o.onProgress?.({ phase: "unpack", done: 0, total: 1, bytes: 0 }); | |
| 65 | o.onProgress?.({ phase: "download", done: 2, total: 2, bytes: 9 }); | |
| 66 | o.onProgress?.({ phase: "decompress", done: 0, total: 1, bytes: 0 }); | |
| 67 | 67 | await sleep(30); |
| 68 | 68 | o.onProgress?.({ phase: "key", done: 0, total: 1, bytes: 0 }); |
| 69 | 69 | return restoreSnapshot(s, n, t, {}); |
| @@ -71,7 +71,7 @@ describe("drill phases", () => { | ||
| 71 | 71 | expect(r.verdict).toBe("green"); |
| 72 | 72 | expect(r.budgetMs).toBeGreaterThanOrEqual(600_000); |
| 73 | 73 | expect(r.budgetMs).toBeLessThan(601_000); |
| 74 | expect(r.phases.map((p) => p.phase)).toEqual(["files", "unpack", "key"]); | |
| 74 | expect(r.phases.map((p) => p.phase)).toEqual(["download", "decompress", "key", "open", "migrate"]); | |
| 75 | 75 | expect(r.phases[0]!.ms).toBeGreaterThanOrEqual(25); |
| 76 | 76 | expect(r.phases[1]!.ms).toBeGreaterThanOrEqual(25); |
| 77 | 77 | }); |
| @@ -99,7 +99,7 @@ describe("drill phases", () => { | ||
| 99 | 99 | verdict: "green", |
| 100 | 100 | failedStep: null, |
| 101 | 101 | phases: [ |
| 102 | { phase: "files", ms: 58_000 }, | |
| 102 | { phase: "download", ms: 58_000 }, | |
| 103 | 103 | { phase: "bundles", ms: 290_000 }, |
| 104 | 104 | ], |
| 105 | 105 | budgetMs: 840_000, |
| @@ -114,7 +114,7 @@ describe("drill phases", () => { | ||
| 114 | 114 | }); |
| 115 | 115 | |
| 116 | 116 | test("stored JSON that is not phases reads as none", () => { |
| 117 | for (const bad of ["x", "[]", '{"phases":[{"phase":"<b>","ms":1}],"budgetMs":5}', '{"phases":[{"phase":"files","ms":-1}],"budgetMs":5}', '{"phases":"a","budgetMs":5}']) | |
| 117 | for (const bad of ["x", "[]", '{"phases":[{"phase":"<b>","ms":1}],"budgetMs":5}', '{"phases":[{"phase":"download","ms":-1}],"budgetMs":5}', '{"phases":"a","budgetMs":5}']) | |
| 118 | 118 | expect(parsePhases(bad)).toEqual({ phases: [], budgetMs: 0 }); |
| 119 | 119 | }); |
| 120 | 120 | |
| @@ -163,8 +163,8 @@ describe("the Backups page line", () => { | ||
| 163 | 163 | verdict: "green", |
| 164 | 164 | failedStep: null, |
| 165 | 165 | phases: [ |
| 166 | { phase: "files", ms: 58_000 }, | |
| 167 | { phase: "unpack", ms: 20_000 }, | |
| 166 | { phase: "download", ms: 58_000 }, | |
| 167 | { phase: "decompress", ms: 20_000 }, | |
| 168 | 168 | { phase: "bundles", ms: 290_000 }, |
| 169 | 169 | { phase: "key", ms: 1_000 }, |
| 170 | 170 | ], |
| @@ -172,7 +172,7 @@ describe("the Backups page line", () => { | ||
| 172 | 172 | reason: null, |
| 173 | 173 | ...over, |
| 174 | 174 | }); |
| 175 | const LINE = "6 min 12 s of its 14 min budget: files 58 s, unpack 20 s, bundles 4 min 50 s, key 1 s"; | |
| 175 | const LINE = "6 min 12 s of its 14 min budget: download 58 s, decompress 20 s, bundles 4 min 50 s, key 1 s"; | |
| 176 | 176 | const backups = async (): Promise<string> => { |
| 177 | 177 | const r = await fetch(`${servers.url}/signin`, { |
| 178 | 178 | method: "POST", |
test/snapshot-restore-progress.test.ts +5 −5
| @@ -49,13 +49,13 @@ test("progress runs through the phases with done rising to total and bytes addin | ||
| 49 | 49 | await rm(root, { recursive: true, force: true }); |
| 50 | 50 | } |
| 51 | 51 | const order = [...new Set(seen.map((p) => p.phase))]; |
| 52 | expect(order).toEqual(["manifest", "files", "unpack", "bundles", "key"]); | |
| 52 | expect(order).toEqual(["manifest", "download", "decompress", "bundles", "key"]); | |
| 53 | 53 | const of = (phase: string) => seen.filter((p) => p.phase === phase); |
| 54 | expect(of("files").map((p) => p.done)).toEqual([0, 1, 2, 3, 4, 5]); | |
| 55 | expect(of("files").every((p) => p.total === 5)).toBe(true); | |
| 56 | expect(of("files").at(-1)!.bytes).toBe(files.reduce((s, f) => s + f.bytes, 0)); | |
| 54 | expect(of("download").map((p) => p.done)).toEqual([0, 1, 2, 3, 4, 5]); | |
| 55 | expect(of("download").every((p) => p.total === 5)).toBe(true); | |
| 56 | expect(of("download").at(-1)!.bytes).toBe(files.reduce((s, f) => s + f.bytes, 0)); | |
| 57 | 57 | expect(of("bundles").map((p) => p.done)).toEqual([0, 1, 2]); |
| 58 | 58 | expect(of("bundles").at(-1)).toEqual({ phase: "bundles", done: 2, total: 2, bytes: 40 + 50 }); |
| 59 | expect(of("unpack")).toEqual([{ phase: "unpack", done: 0, total: 0, bytes: 0 }]); | |
| 59 | expect(of("decompress")).toEqual([{ phase: "decompress", done: 0, total: 0, bytes: 0 }]); | |
| 60 | 60 | expect(of("key")).toEqual([{ phase: "key", done: 0, total: 0, bytes: 0 }]); |
| 61 | 61 | }); |
new above
offline