import { spawn } from "node:child_process"; import { mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { expect, it } from "vitest"; import { Devdocs } from "../src/engine.ts"; import type { Options } from "../src/types.ts"; it("keeps the prior revision servable after killing a separate Pi-side owner mid-refresh", async () => { const root = await mkdtemp(join(tmpdir(), "devdocs-crash-")); const path = join(root, "manual.md"), options: Options = { databasePath: join(root, "cache.db"), sources: [ { id: "manual", target: "widget", path, version: "1", format: "markdown", private: false, }, ], enabledSources: ["manual"], offline: false, cacheBytes: 1048576, ttlMs: 0, }; let docs: Devdocs | undefined; let child: ReturnType | undefined; try { await writeFile( path, "# Transactions\nPrior committed transactions remain available.", ); docs = new Devdocs(options); const found = await docs.search({ target: "widget", query: "transactions", cwd: root, }); expect(found.status).toBe("ok"); if (found.status !== "ok") throw new Error("fixture initial search failed"); const ref = found.results[0]!.ref; await docs.close(); docs = undefined; await writeFile( path, "# Transactions\nReplacement transactions must not appear before publication.", ); child = spawn( process.execPath, [ "--no-warnings", fileURLToPath(new URL("./crash-child.ts", import.meta.url)), JSON.stringify(options), ], { cwd: root, stdio: ["ignore", "ignore", "ignore", "ipc"] }, ); const running = child; await new Promise((resolve, reject) => { const timer = setTimeout( () => reject(new Error("crash fixture never reached refresh barrier")), 5000, ); running.once("message", () => { clearTimeout(timer); resolve(); }); running.once("error", (error) => { clearTimeout(timer); reject(error); }); running.once("exit", () => { clearTimeout(timer); reject(new Error("crash fixture exited before barrier")); }); }); await new Promise((resolve) => { running.once("exit", () => resolve()); running.kill("SIGKILL"); }); child = undefined; docs = new Devdocs({ ...options, offline: true }); const read = await docs.read([ref], 2000, root); expect(read.sections[0]?.content).toContain("Prior committed"); expect(read.sections[0]?.content).not.toContain("Replacement"); } finally { if (child) await new Promise((resolve) => { child?.once("exit", () => resolve()); child?.kill("SIGKILL"); }); await docs?.close(); await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50, }); } });