diff --git a/packages/client/src/effect/service.ts b/packages/client/src/effect/service.ts index 4ec16aa7fcb..65c0eaff8bc 100644 --- a/packages/client/src/effect/service.ts +++ b/packages/client/src/effect/service.ts @@ -5,6 +5,7 @@ import { defaultEnsureTiming, ensureTiming, type EnsureTiming } from "../service import { matchesVersion } from "../service-version.js" import { PtyHandoff } from "../pty-handoff.js" import { decide, fallback, headers, probeResult, same } from "../service-probe.js" +import { processStopped } from "../service-process.js" export * from "../service.js" export { headers } @@ -168,26 +169,26 @@ const registered = Effect.fnUntraced(function* (file?: string, timeout?: number) const poll = (timing: EnsureTiming) => Schedule.max([Schedule.spaced(timing.stopPollInterval), Schedule.recurs(timing.stopPollAttempts)]) -const signal = (pid: number, name: NodeJS.Signals) => - Effect.try({ try: () => process.kill(pid, name), catch: (cause) => cause }).pipe(Effect.ignore) +const signal = (pid: number, name: NodeJS.Signals, timing: EnsureTiming) => + Effect.try({ + try: () => (timing.signal ? timing.signal(pid, name) : process.kill(pid, name)), + catch: (cause) => cause, + }).pipe(Effect.ignore) const stopped = Effect.fnUntraced(function* (pid: number) { - const running = yield* Effect.try({ try: () => process.kill(pid, 0), catch: () => false }).pipe( - Effect.orElseSucceed(() => false), - ) - if (!running) return true + if (yield* Effect.promise(() => processStopped(pid))) return true return yield* Effect.fail(new Error(`Server process ${pid} is still running`)) }) const terminate = Effect.fnUntraced(function* (info: Info, options: { readonly file?: string }, timing: EnsureTiming) { const current = yield* read(options.file) if (current === undefined || !same(current, info)) return - yield* signal(info.pid, "SIGTERM") + yield* signal(info.pid, "SIGTERM", timing) const done = yield* stopped(info.pid).pipe(Effect.retry(poll(timing)), Effect.option) // The registration can disappear or change hands before this process exits. Only the PID we // signalled can tell us whether it has stopped, so escalate based on that process. if (Option.isNone(done)) { - yield* signal(info.pid, "SIGKILL") + yield* signal(info.pid, "SIGKILL", timing) yield* stopped(info.pid).pipe(Effect.retry(poll(timing))) } const latest = yield* read(options.file) diff --git a/packages/client/src/promise/service.ts b/packages/client/src/promise/service.ts index 5d5d0bad4a1..d7db21be7f7 100644 --- a/packages/client/src/promise/service.ts +++ b/packages/client/src/promise/service.ts @@ -5,6 +5,7 @@ import { defaultEnsureTiming, ensureTiming, type EnsureTiming } from "../service import { matchesVersion } from "../service-version.js" import { PtyHandoff } from "../pty-handoff.js" import { decide, fallback, headers, probeResult, same } from "../service-probe.js" +import { processStopped } from "../service-process.js" export * from "../service.js" export { fallback, headers } @@ -127,24 +128,19 @@ async function registered(file?: string, timeout?: number) { return { info, ...(await probeResult(info, timeout)) } } -function signal(pid: number, name: NodeJS.Signals) { +function signal(pid: number, name: NodeJS.Signals, timing: EnsureTiming) { try { + if (timing.signal) { + timing.signal(pid, name) + return + } process.kill(pid, name) } catch {} } -function stopped(pid: number) { - try { - process.kill(pid, 0) - return false - } catch { - return true - } -} - async function waitUntilStopped(pid: number, timing: EnsureTiming) { for (let attempt = 0; attempt <= timing.stopPollAttempts; attempt++) { - if (stopped(pid)) return true + if (await processStopped(pid)) return true if (attempt < timing.stopPollAttempts) await delay(timing.stopPollInterval) } return false @@ -153,11 +149,11 @@ async function waitUntilStopped(pid: number, timing: EnsureTiming) { async function terminate(info: Info, options: { readonly file?: string }, timing: EnsureTiming) { const current = await read(options.file) if (current === undefined || !same(current, info)) return - signal(info.pid, "SIGTERM") + signal(info.pid, "SIGTERM", timing) // The registration can disappear or change hands before this process exits. Only the PID we // signalled can tell us whether it has stopped, so escalate based on that process. if (!(await waitUntilStopped(info.pid, timing))) { - signal(info.pid, "SIGKILL") + signal(info.pid, "SIGKILL", timing) if (!(await waitUntilStopped(info.pid, timing))) throw new Error(`Server process ${info.pid} is still running`) } const latest = await read(options.file) diff --git a/packages/client/src/service-contender.ts b/packages/client/src/service-contender.ts index 79542c30a44..7da6067f4ca 100644 --- a/packages/client/src/service-contender.ts +++ b/packages/client/src/service-contender.ts @@ -10,6 +10,9 @@ export type ServiceContender = { } const stderrLimit = 8 * 1024 +// Keep live handles referenced until the child exits so the runtime's process watcher still +// reaps detached contenders after `ensure()` returns, while `unref()` lets this client exit. +const liveContenders = new Set() export function spawnServiceContender( command: string, @@ -22,6 +25,10 @@ export function spawnServiceContender( stdio: ["ignore", "ignore", "pipe"], env: { ...process.env, ...env }, }) + liveContenders.add(child) + const forget = () => { + liveContenders.delete(child) + } let error: Error | undefined let closed = false let stderr = Buffer.alloc(0) @@ -35,9 +42,12 @@ export function spawnServiceContender( child.stderr?.on("data", onStderr) if (child.stderr !== null && "unref" in child.stderr && typeof child.stderr.unref === "function") child.stderr.unref() child.once("error", (cause) => { + forget() error = new Error("Failed to start server", { cause }) }) + child.once("exit", forget) child.once("close", () => { + forget() closed = true }) child.unref() diff --git a/packages/client/src/service-process.ts b/packages/client/src/service-process.ts new file mode 100644 index 00000000000..abdf8baada5 --- /dev/null +++ b/packages/client/src/service-process.ts @@ -0,0 +1,61 @@ +import { execFile } from "node:child_process" +import { readFile } from "node:fs/promises" + +// Shared by the Effect and Promise clients. Keep this module free of Effect so the +// Promise client never loads the Effect runtime. + +export function parseLinuxProcState(stat: string) { + const close = stat.lastIndexOf(")") + if (close < 0) return undefined + return stat.slice(close + 1).trimStart()[0] +} + +export function parsePsState(output: string) { + return output.trim()[0] +} + +export function isZombieState(state: string | undefined) { + return state === "Z" +} + +function alive(pid: number) { + try { + process.kill(pid, 0) + return true + } catch { + return false + } +} + +function psState(pid: number) { + return new Promise((resolve) => { + execFile("ps", ["-o", "state=", "-p", String(pid)], (error, stdout) => { + if (error) { + resolve(undefined) + return + } + resolve(parsePsState(stdout)) + }) + }) +} + +/** + * Whether `pid` has exited, including POSIX `` zombies whose parent has not + * reaped them yet (which still answer `kill(pid, 0)` until waited on). + */ +export async function processStopped(pid: number, platform = process.platform): Promise { + if (!alive(pid)) return true + if (platform === "win32") return false + if (platform === "linux") { + const stat = await readFile(`/proc/${pid}/stat`, "utf8").catch((error: unknown) => + error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ESRCH") + ? null + : undefined, + ) + if (stat === null) return true + if (stat !== undefined) return isZombieState(parseLinuxProcState(stat)) + } + const state = await psState(pid) + if (state === undefined) return !alive(pid) + return isZombieState(state) +} diff --git a/packages/client/src/service-timing.ts b/packages/client/src/service-timing.ts index 03db9f6cb2c..536e7f8d6da 100644 --- a/packages/client/src/service-timing.ts +++ b/packages/client/src/service-timing.ts @@ -6,6 +6,7 @@ export type EnsureTiming = { readonly promiseTimeout: number readonly stopPollInterval: number readonly stopPollAttempts: number + readonly signal?: (pid: number, name: NodeJS.Signals) => void } const timings = new WeakMap() diff --git a/packages/client/test/promise-service.test.ts b/packages/client/test/promise-service.test.ts index c0cdb746736..d0505056da4 100644 --- a/packages/client/test/promise-service.test.ts +++ b/packages/client/test/promise-service.test.ts @@ -8,6 +8,7 @@ import { stoppedExitCode, } from "./fixture/service-fixture" import { accelerate } from "./fixture/service-timing" +import { withEnsureTiming } from "../src/service-timing" const ensure = accelerate(Service.ensure) const stop = accelerate(Service.stop) @@ -308,6 +309,39 @@ test("stop escalates when the registration disappears before the process exits", test.skipIf(process.platform === "win32")( "stop fails when the process survives SIGKILL", + async () => { + await using fixture = await serviceFixture() + const registration = fixture.registration + const existing = fixture.spawn("lingering", "60000") + await fixture.waitForFile() + const original = await Bun.file(registration).json() + + try { + await expect( + Service.stop( + withEnsureTiming( + { file: registration }, + { + stopPollInterval: 5, + stopPollAttempts: 20, + signal: (pid, name) => { + if (name !== "SIGKILL") process.kill(pid, name) + }, + }, + ), + ), + ).rejects.toThrow(`Server process ${original.pid} is still running`) + expect(await Bun.file(registration + ".signal").text()).toBe("SIGTERM") + } finally { + existing.kill("SIGKILL") + await existing.exited + } + }, + 15_000, +) + +test.skipIf(process.platform === "win32")( + "stop treats an unreaped zombie service process as stopped", async () => { await using fixture = await serviceFixture() const registration = fixture.registration @@ -315,8 +349,11 @@ test.skipIf(process.platform === "win32")( await fixture.waitForFile() const original = await Bun.file(registration).json() - await expect(stop({ file: registration })).rejects.toThrow(`Server process ${original.pid} is still running`) - expect(await Bun.file(registration + ".signal").text()).toBe("SIGTERM") + await stop({ file: registration }) + + expect(() => process.kill(original.pid, 0)).not.toThrow() + await expectNotListening(original.url) + expect(await Bun.file(registration).exists()).toBe(false) }, 15_000, ) diff --git a/packages/client/test/service-process.test.ts b/packages/client/test/service-process.test.ts new file mode 100644 index 00000000000..765e9ff5636 --- /dev/null +++ b/packages/client/test/service-process.test.ts @@ -0,0 +1,31 @@ +import { expect, test } from "bun:test" +import { isZombieState, parseLinuxProcState, parsePsState, processStopped } from "../src/service-process" + +test("parses Linux /proc//stat state even when comm contains spaces and parentheses", () => { + expect(parseLinuxProcState("2117 (opencode) Z 1 2117 2117 0 -1")).toBe("Z") + expect(parseLinuxProcState("2117 (opencode (serve)) Z 1 2117 2117 0 -1")).toBe("Z") + expect(parseLinuxProcState("2117 (opencode (serve)) S 1 2117 2117 0 -1")).toBe("S") + expect(parseLinuxProcState("2117 (opencode) D 1 2117 2117 0 -1")).toBe("D") + expect(parseLinuxProcState("malformed")).toBeUndefined() +}) + +test("parses ps state output and identifies zombie states", () => { + expect(parsePsState("Z\n")).toBe("Z") + expect(parsePsState(" Z+ \n")).toBe("Z") + expect(parsePsState("ZN\n")).toBe("Z") + expect(parsePsState("S+\n")).toBe("S") + expect(parsePsState("")).toBeUndefined() + expect(isZombieState("Z")).toBe(true) + expect(isZombieState("S")).toBe(false) + expect(isZombieState("D")).toBe(false) + expect(isZombieState(undefined)).toBe(false) +}) + +test("reports the current process as running and an exited process as stopped", async () => { + expect(await processStopped(process.pid)).toBe(false) + + const child = Bun.spawn([process.execPath, "-e", "process.exit(0)"], { stdout: "ignore", stderr: "ignore" }) + const pid = child.pid + await child.exited + expect(await processStopped(pid)).toBe(true) +}) diff --git a/packages/client/test/service.test.ts b/packages/client/test/service.test.ts index 81101f273ab..cce9433f143 100644 --- a/packages/client/test/service.test.ts +++ b/packages/client/test/service.test.ts @@ -11,6 +11,7 @@ import { stoppedExitCode, } from "./fixture/service-fixture" import { accelerate } from "./fixture/service-timing" +import { withEnsureTiming } from "../src/service-timing" const ensure = accelerate(Service.ensure) const stop = accelerate(Service.stop) @@ -229,6 +230,41 @@ test("stop escalates when the registration disappears before the process exits", test.skipIf(process.platform === "win32")( "stop fails when the process survives SIGKILL", + async () => { + await using fixture = await serviceFixture() + const registration = fixture.registration + const existing = fixture.spawn("lingering", "60000") + await fixture.waitForFile() + const original = await Bun.file(registration).json() + + try { + await expect( + run( + Service.stop( + withEnsureTiming( + { file: registration }, + { + stopPollInterval: 5, + stopPollAttempts: 20, + signal: (pid, name) => { + if (name !== "SIGKILL") process.kill(pid, name) + }, + }, + ), + ), + ), + ).rejects.toThrow(`Server process ${original.pid} is still running`) + expect(await Bun.file(registration + ".signal").text()).toBe("SIGTERM") + } finally { + existing.kill("SIGKILL") + await existing.exited + } + }, + 15_000, +) + +test.skipIf(process.platform === "win32")( + "stop treats an unreaped zombie service process as stopped", async () => { await using fixture = await serviceFixture() const registration = fixture.registration @@ -236,8 +272,38 @@ test.skipIf(process.platform === "win32")( await fixture.waitForFile() const original = await Bun.file(registration).json() - await expect(run(stop({ file: registration }))).rejects.toThrow(`Server process ${original.pid} is still running`) - expect(await Bun.file(registration + ".signal").text()).toBe("SIGTERM") + await run(stop({ file: registration })) + + // The zombie remains in the process table until its parent exits, yet the service is stopped. + expect(() => process.kill(original.pid, 0)).not.toThrow() + await expectNotListening(original.url) + expect(await Bun.file(registration).exists()).toBe(false) + }, + 15_000, +) + +test.skipIf(process.platform === "win32")( + "evicts an unresponsive unreaped service that becomes a zombie", + async () => { + await using fixture = await serviceFixture() + const registration = fixture.registration + fixture.spawnUnreaped("hanging") + await fixture.waitForFile() + const original = await Bun.file(registration).json() + + const endpoint = await run( + ensure({ + file: registration, + version: "test", + command: fixture.command("delayed", "10"), + }), + ) + const replacement = await Bun.file(registration).json() + fixture.track(replacement.pid) + + expect(() => process.kill(original.pid, 0)).not.toThrow() + expect(replacement.pid).not.toBe(original.pid) + expect(endpoint.url).toBe(replacement.url) }, 15_000, )