import { mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { describe, expect, it } from "vitest"; import { LineProcess } from "../src/lib/line-process.js"; /** * Fake JSON-line worker. `die-once` exits with SIGTERM on the first process only * (Node reports that as exit code null). `die-always` does it on every process. */ const WORKER = ` import { createInterface } from "node:readline"; import { existsSync, writeFileSync } from "node:fs"; const marker = process.argv[2]; const mode = process.argv[3]; process.stdout.write(JSON.stringify({ ready: true }) + "\\n"); if ((mode === "die-once" && !existsSync(marker)) || mode === "die-always") { if (mode === "die-once") writeFileSync(marker, "1"); process.kill(process.pid, "SIGTERM"); } else { const lines = createInterface({ input: process.stdin }); lines.on("line", (line) => { const msg = JSON.parse(line); process.stdout.write(JSON.stringify({ id: msg.id, width: 2 }) + "\\n"); }); } `; describe("line process", () => { it("retries a signal death once and names the signal if it dies again", async () => { const dir = await mkdtemp(path.join(tmpdir(), "pr-lp-")); const script = path.join(dir, "worker.mjs"); const marker = path.join(dir, "died"); await writeFile(script, WORKER); const once = new LineProcess({ name: "face worker", bin: process.execPath, args: [script, marker, "die-once"], timeoutMs: 5_000 }); const always = new LineProcess({ name: "face worker", bin: process.execPath, args: [script, marker, "die-always"], timeoutMs: 5_000 }); try { await expect(once.request({ path: "a.jpg" })).resolves.toMatchObject({ width: 2 }); await expect(always.request({ path: "a.jpg" })).rejects.toThrow(/face worker exited \(signal SIGTERM\)/); } finally { await once.close(); await always.close(); await rm(dir, { recursive: true, force: true }); } }); it("does not report an intentional close as a worker crash", async () => { const dir = await mkdtemp(path.join(tmpdir(), "pr-lp-")); const script = path.join(dir, "worker.mjs"); await writeFile(script, WORKER); const proc = new LineProcess({ name: "face worker", bin: process.execPath, args: [script, path.join(dir, "m"), "stay"], timeoutMs: 5_000 }); try { await expect(proc.request({ path: "a.jpg" })).resolves.toMatchObject({ width: 2 }); await proc.close(); await expect(proc.request({ path: "b.jpg" })).rejects.toThrow(/engine_unavailable/); } finally { await rm(dir, { recursive: true, force: true }); } }); });