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 #2732

Parked opened this
Closed without merging

scout/forge:scout/2719-the-restore-drill-records-how-long-each → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
11 files changed +308 −54
docs/RECOVERY.md +6 −3
@@ -100,9 +100,9 @@ which line it stops at.
100100
101101 - **manifest** — reading the snapshot's list of files and bundles. Likely the
102102 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
106106 disk is full or the archive is damaged. Check free space.
107107 - **bundles** — cloning each repository from its bundle. Likely a slow store
108108 or many repositories. Compare its counts with the snapshot's and retry the
@@ -110,6 +110,9 @@ which line it stops at.
110110 - **key** — restoring the secret key, opened with the passphrase. Likely the
111111 passphrase is missing or wrong. Check `FORGE_SNAPSHOT_PASSPHRASE`.
112112
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
113116 ## What a snapshot does NOT hold
114117
115118 - 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 {
7777
7878 /** One restore phase and the milliseconds it took. */
7979 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";
8182 readonly ms: number;
8283 }
8384
@@ -151,11 +152,13 @@ export async function runDrill(deps: DrillDeps): Promise<DrillResult> {
151152 // When each restore phase was first reported, and when the restore ended.
152153 const began: { phase: Progress["phase"]; at: number }[] = [];
153154 let restoreEnd: number | undefined;
155 let openEnd: number | undefined;
156 let bootEnd: number | undefined;
154157 let health: DrillResult["health"] = "unreached";
155158 try {
156159 // One clock for the whole drill, so a hang in any step ends it red.
157160 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];
159162 if (newest === undefined) throw new Error("the store holds no snapshot");
160163 snapshotId = newest.name;
161164 sized = snapshotBytes(newest);
@@ -167,7 +170,8 @@ export async function runDrill(deps: DrillDeps): Promise<DrillResult> {
167170 scratch = mkdtempSync(join(parent, "restore-"));
168171 const target = join(scratch, "data");
169172 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, {
171175 passphrase: deps.passphrase,
172176 onProgress: (p) => {
173177 progress = p;
@@ -228,11 +232,13 @@ export async function runDrill(deps: DrillDeps): Promise<DrillResult> {
228232 }
229233
230234 step = "health";
235 openEnd = performance.now();
231236 const booted = await within(
232237 (deps.boot ?? bootRestored)(target, left()),
233238 left(),
234239 budget,
235240 );
241 bootEnd = performance.now();
236242 health = booted.ok ? "ok" : "failed";
237243 if (!booted.ok) throw new Error(booted.reason);
238244 } catch (error) {
@@ -255,10 +261,16 @@ export async function runDrill(deps: DrillDeps): Promise<DrillResult> {
255261
256262 function finish(failedStep: DrillStep | null): DrillResult {
257263 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) => ({
259266 phase: b.phase,
260267 ms: Math.max(0, Math.round((began[i + 1]?.at ?? end) - b.at)),
261268 }));
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 }
262274 return {
263275 at,
264276 snapshotId,
src/snapshot/drills.ts +6 −2
@@ -22,7 +22,10 @@ interface Row {
2222 phases: string | null;
2323 }
2424
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" };
2629
2730 /** The stored JSON as phases; anything that is not a list of known phases with whole ms reads as none. */
2831 export function parsePhases(raw: string | null): { phases: PhaseTime[]; budgetMs: number } {
@@ -35,7 +38,8 @@ export function parsePhases(raw: string | null): { phases: PhaseTime[]; budgetMs
3538 if (!Array.isArray(phases) || typeof budgetMs !== "number" || !Number.isFinite(budgetMs) || budgetMs < 0) return none;
3639 const out: PhaseTime[] = [];
3740 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;
3943 if (typeof phase !== "string" || !PHASES.has(phase) || typeof ms !== "number" || !Number.isFinite(ms) || ms < 0) return none;
4044 out.push({ phase: phase as PhaseTime["phase"], ms });
4145 }
src/snapshot/parts.ts +60 −1
@@ -11,9 +11,13 @@
1111 * the parts back in order, joins them, and unpacks to exactly the bytes
1212 * that went in, or refuses.
1313 *
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.
1515 */
1616
17 import { createWriteStream, renameSync, rmSync } from "node:fs";
18 import { pipeline } from "node:stream/promises";
19 import { createZstdDecompress } from "node:zlib";
20
1721 /** A part's size: one put carries it within its own deadline at the floor rate (27 s at 5 Mbit/s). */
1822 export const PART_BYTES = 16 * 1_048_576;
1923
@@ -106,3 +110,58 @@ export function isPackedFile(v: unknown): v is PackedFile {
106110 (p["parts"] as number) >= 1
107111 );
108112 }
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 @@
2020 * `FORGE_SNAPSHOT_DIR` for a directory store.
2121 *
2222 * 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.
2527 *
2628 * The key comes back only from its wrapped form and the operator's
2729 * passphrase (`FORGE_SNAPSHOT_PASSPHRASE`). A wrong passphrase refuses the
@@ -46,7 +48,7 @@ import {
4648 type Manifest,
4749 } from "./snapshot.ts";
4850 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";
5052 import { resolveDestination } from "./destination.ts";
5153 import type { Store } from "./store.ts";
5254
@@ -62,7 +64,7 @@ export interface Restored {
6264
6365 /** Where a restore is, as plain data: `done` of `total` in `phase`, `bytes` so far in it. */
6466 export interface Progress {
65 readonly phase: "manifest" | "files" | "unpack" | "bundles" | "key";
67 readonly phase: "manifest" | "download" | "decompress" | "bundles" | "key";
6668 readonly done: number;
6769 readonly total: number;
6870 readonly bytes: number;
@@ -208,26 +210,32 @@ export async function restoreSnapshot(
208210 for (const file of packed)
209211 for (const [n, path] of partPaths(file).entries())
210212 partOf.set(path, { file, n });
211 const gathered = new Map<string, Uint8Array[]>();
212213 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 }
213221
214222 let files = 0;
215223 let repos = 0;
216224 const bundles: { at: number; owner: string; name: string; file: string }[] = [];
217225 let fetched = 0;
218226 let fetchedBytes = 0;
219 say("files", 0, manifest.files.length, 0);
227 try {
228 say("download", 0, manifest.files.length, 0);
220229 await fetchAll(store, prefix, manifest.files, async (entry, body, at) => {
221230 fetched++;
222231 fetchedBytes += entry.bytes;
223 say("files", fetched, manifest.files.length, fetchedBytes);
232 say("download", fetched, manifest.files.length, fetchedBytes);
224233 if (entry.path === WRAPPED_KEY) return;
225234 // A part waits for the rest of its file.
226235 const part = partOf.get(entry.path);
227236 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);
231239 return;
232240 }
233241 // A day's run logs in one object come back as the logs they were.
@@ -259,24 +267,19 @@ export async function restoreSnapshot(
259267 bundles.sort((a, b) => a.at - b.at);
260268 let unpacked = 0;
261269 let unpackedBytes = 0;
262 say("unpack", 0, packed.length, 0);
270 say("decompress", 0, packed.length, 0);
263271 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();
276275 files++;
277276 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;
280283 }
281284 // Each repository is its own clone, so several at once: a forge of
282285 // 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 {
2121 /** The next path segment under `prefix`: the "directories", not the keys. */
2222 names(prefix: string): Promise<string[]>;
2323 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;
2429 }
2530
2631 /** The S3 credentials as the platform hands them to an app. */
@@ -58,6 +63,17 @@ export const SLACK_MS = 60_000;
5863 /** How long a read, a listing or a delete may go unanswered. */
5964 export const CALL_DEADLINE_MS = 180_000;
6065
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
6177 /** How long a put of `bytes` may take before it counts as failed: its bytes at the floor rate, plus slack. */
6278 export const deadlineFor = (
6379 bytes: number,
@@ -94,13 +110,18 @@ export function withRetries(
94110 deadlineMs?: number;
95111 floorBytesPerS?: number;
96112 slackMs?: number;
113 /** Hold every read, listing and delete, retries included, inside this many ms. */
114 budgetMs?: number;
97115 sleep?: (ms: number) => Promise<void>;
98116 } = {},
99117 ): Store {
100118 const attempts = Math.max(1, options.attempts ?? 5);
101119 const baseMs = options.baseMs ?? 500;
102120 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 );
104125 const putMs = (body: Uint8Array | string): number =>
105126 fixed ?? deadlineFor(sizeOf(body), options.floorBytesPerS, options.slackMs);
106127 const sleep = options.sleep ?? ((ms) => Bun.sleep(ms));
@@ -125,6 +146,7 @@ export function withRetries(
125146 return {
126147 where: inner.where,
127148 ...(inner.dir === undefined ? {} : { dir: inner.dir }),
149 bounded: (budgetMs) => withRetries(inner, { ...options, budgetMs }),
128150 put: (key, body) =>
129151 tried(`put ${key}`, putMs(body), () => inner.put(key, body)),
130152 get: (key) => tried(`get ${key}`, callMs, () => inner.get(key)),
src/web/pages/backups.ts +4 −3
@@ -90,12 +90,13 @@ function keyNote(
9090 </p>`;
9191 }
9292
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 {
9595 if (d.phases.length === 0 || d.budgetMs <= 0) return "";
96 const slowest = d.phases.reduce((a, p) => (p.ms > a.ms ? p : a));
9697 return `${formatSpan(d.ms)} of its ${formatBudget(d.budgetMs)} budget: ${d.phases
9798 .map((p) => `${p.phase} ${formatSpan(p.ms)}`)
98 .join(", ")}`;
99 .join(", ")}${d.phases.length > 1 ? `; slowest: ${slowest.phase}` : ""}`;
99100 }
100101
101102 /** 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 => ({
1212 verdict: "green",
1313 failedStep: null,
1414 phases: [
15 { phase: "files", ms: 1 * MIN },
15 { phase: "download", ms: 1 * MIN },
1616 { phase: "bundles", ms: 9 * MIN },
1717 ],
1818 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", () => {
6060
6161 test("a green drill keeps the phases a stubbed restore reported, and the budget", async () => {
6262 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 });
6464 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 });
6767 await sleep(30);
6868 o.onProgress?.({ phase: "key", done: 0, total: 1, bytes: 0 });
6969 return restoreSnapshot(s, n, t, {});
@@ -71,7 +71,7 @@ describe("drill phases", () => {
7171 expect(r.verdict).toBe("green");
7272 expect(r.budgetMs).toBeGreaterThanOrEqual(600_000);
7373 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"]);
7575 expect(r.phases[0]!.ms).toBeGreaterThanOrEqual(25);
7676 expect(r.phases[1]!.ms).toBeGreaterThanOrEqual(25);
7777 });
@@ -99,7 +99,7 @@ describe("drill phases", () => {
9999 verdict: "green",
100100 failedStep: null,
101101 phases: [
102 { phase: "files", ms: 58_000 },
102 { phase: "download", ms: 58_000 },
103103 { phase: "bundles", ms: 290_000 },
104104 ],
105105 budgetMs: 840_000,
@@ -114,7 +114,7 @@ describe("drill phases", () => {
114114 });
115115
116116 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}'])
118118 expect(parsePhases(bad)).toEqual({ phases: [], budgetMs: 0 });
119119 });
120120
@@ -163,8 +163,8 @@ describe("the Backups page line", () => {
163163 verdict: "green",
164164 failedStep: null,
165165 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 },
168168 { phase: "bundles", ms: 290_000 },
169169 { phase: "key", ms: 1_000 },
170170 ],
@@ -172,7 +172,7 @@ describe("the Backups page line", () => {
172172 reason: null,
173173 ...over,
174174 });
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";
176176 const backups = async (): Promise<string> => {
177177 const r = await fetch(`${servers.url}/signin`, {
178178 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
4949 await rm(root, { recursive: true, force: true });
5050 }
5151 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"]);
5353 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));
5757 expect(of("bundles").map((p) => p.done)).toEqual([0, 1, 2]);
5858 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 }]);
6060 expect(of("key")).toEqual([{ phase: "key", done: 0, total: 0, bytes: 0 }]);
6161 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs