/** @file Run real workerd processes for tests. */ import { spawn } from "node:child_process"; import { rm } from "node:fs/promises"; import { connect, createServer } from "node:net"; import { join } from "node:path"; export const here = new URL("..", import.meta.url).pathname; // the package binary, not the .bin shim: the shim forks it, so a kill would orphan workerd const workerd = join(here, "node_modules/workerd/bin/workerd"); export const freePort = () => new Promise((resolve) => { const s = createServer().listen(0, "127.0.0.1", () => { const { port } = s.address(); s.close(() => resolve(port)); }); }); /** Resolves once something accepts connections at `opts` (a port or a socket path). */ export const accepting = (opts) => new Promise((resolve) => { const s = connect(opts, () => (s.end(), resolve(true))); s.on("error", () => resolve(false)); }); /** * Run workerd on `config` until `stop()`; resolves once `listening` accepts. * * @param {string} config * @param {string[]} args socket, directory, and external overrides * @param {{ port: number } | { path: string }} listening * @param {string[]} stale socket files a crash leaves behind; bind() would fail on them */ export const startWorkerd = async (config, args, listening, stale = []) => { for (const f of stale) await rm(f, { force: true }); const child = spawn(workerd, ["serve", "--experimental", join(here, config), ...args], { stdio: ["ignore", process.env.WORKERD_LOG ? "inherit" : "ignore", "pipe"], }); let log = ""; // WORKERD_LOG=1 echoes workerd's stderr, for debugging child.stderr.on("data", (c) => (process.env.WORKERD_LOG ? process.stderr.write(c) : (log += c))); const exited = new Promise((resolve) => child.on("exit", resolve)); for (let i = 0; i < 100; i++) { // SIGKILL: a crash is the harder durability test if (await accepting(listening)) return { stop: () => (child.kill("SIGKILL"), exited) }; await new Promise((r) => setTimeout(r, 50)); } child.kill("SIGKILL"); throw new Error(`workerd did not start: ${log}`); };