|
| 1 | +import { fork } from "node:child_process"; |
| 2 | +import { dirname, resolve } from "node:path"; |
| 3 | +import { fileURLToPath } from "node:url"; |
| 4 | +import { afterEach, describe, expect, it } from "vitest"; |
| 5 | + |
| 6 | +const here = dirname(fileURLToPath(import.meta.url)); |
| 7 | +const WORKER_PATH = resolve(here, "../../packages/engine/dist/workers/main.js"); |
| 8 | +const WORKER_FLAG = "--sidequest-worker"; |
| 9 | + |
| 10 | +/** |
| 11 | + * Forks the built worker module with the given argv and resolves with the first IPC message it |
| 12 | + * emits, or `null` if none arrives within the timeout. The worker is always killed afterwards. |
| 13 | + */ |
| 14 | +function forkWorkerAndCaptureFirstMessage(argv, timeoutMs = 2000) { |
| 15 | + return new Promise((resolvePromise, rejectPromise) => { |
| 16 | + const child = fork(WORKER_PATH, argv, { stdio: "ignore" }); |
| 17 | + const timer = setTimeout(() => { |
| 18 | + child.kill(); |
| 19 | + resolvePromise(null); |
| 20 | + }, timeoutMs); |
| 21 | + |
| 22 | + child.once("message", (msg) => { |
| 23 | + clearTimeout(timer); |
| 24 | + child.kill(); |
| 25 | + resolvePromise(msg); |
| 26 | + }); |
| 27 | + child.once("error", (err) => { |
| 28 | + clearTimeout(timer); |
| 29 | + child.kill(); |
| 30 | + rejectPromise(err); |
| 31 | + }); |
| 32 | + }); |
| 33 | +} |
| 34 | + |
| 35 | +describe("worker bootstrap gating (issue #175)", () => { |
| 36 | + let lastChild; |
| 37 | + |
| 38 | + afterEach(() => { |
| 39 | + lastChild?.kill(); |
| 40 | + lastChild = undefined; |
| 41 | + }); |
| 42 | + |
| 43 | + it("does NOT emit a 'ready' message when forked without the sentinel flag", async () => { |
| 44 | + // Reproduces a Vitest `pool: 'forks'` worker that transitively imports the engine: the process |
| 45 | + // has an IPC channel (process.send) but is not a Sidequest worker, so the module must stay inert. |
| 46 | + const msg = await forkWorkerAndCaptureFirstMessage([]); |
| 47 | + expect(msg).toBeNull(); |
| 48 | + }); |
| 49 | + |
| 50 | + it("emits 'ready' when forked with the sentinel flag", async () => { |
| 51 | + const msg = await forkWorkerAndCaptureFirstMessage([WORKER_FLAG]); |
| 52 | + expect(msg).toBe("ready"); |
| 53 | + }); |
| 54 | +}); |
0 commit comments