From 3d0f0744428493bb854ef891cc42e92e9bedfb19 Mon Sep 17 00:00:00 2001 From: Ben Davis Date: Fri, 26 Jun 2026 11:14:52 -0700 Subject: [PATCH] fix(server): bound child process shutdown --- apps/server/src/bin.ts | 6 +- .../cli/boundedChildProcessSpawner.test.ts | 255 ++++++++++++++++++ .../src/cli/boundedChildProcessSpawner.ts | 158 +++++++++++ 3 files changed, 418 insertions(+), 1 deletion(-) create mode 100644 apps/server/src/cli/boundedChildProcessSpawner.test.ts create mode 100644 apps/server/src/cli/boundedChildProcessSpawner.ts diff --git a/apps/server/src/bin.ts b/apps/server/src/bin.ts index 9aaf41893c..f387f628b4 100644 --- a/apps/server/src/bin.ts +++ b/apps/server/src/bin.ts @@ -10,12 +10,16 @@ import packageJson from "../package.json" with { type: "json" }; import { authCommand } from "./cli/auth.ts"; import { connectCommand } from "./cli/connect.ts"; import { hasCloudPublicConfig } from "./cloud/publicConfig.ts"; +import * as BoundedChildProcessSpawner from "./cli/boundedChildProcessSpawner.ts"; import { sharedServerCommandFlags } from "./cli/config.ts"; import { projectCommand } from "./cli/project.ts"; import { runServerCommand, serveCommand, startCommand } from "./cli/server.ts"; import { installNodeShutdownSignalEscalation } from "./cli/shutdownSignalEscalation.ts"; -const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer); +const CliRuntimeLayer = Layer.mergeAll( + BoundedChildProcessSpawner.layer().pipe(Layer.provideMerge(NodeServices.layer)), + NetService.layer, +); const connectPublicConfigMissingMessage = "T3 Connect commands are unavailable: this build is missing T3 Connect public configuration."; diff --git a/apps/server/src/cli/boundedChildProcessSpawner.test.ts b/apps/server/src/cli/boundedChildProcessSpawner.test.ts new file mode 100644 index 0000000000..b382dc14a4 --- /dev/null +++ b/apps/server/src/cli/boundedChildProcessSpawner.test.ts @@ -0,0 +1,255 @@ +import { NodeServices } from "@effect/platform-node"; +import { expect, it } from "@effect/vitest"; +import { HostProcessPlatform } from "@t3tools/shared/hostProcess"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Fiber from "effect/Fiber"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Scope from "effect/Scope"; +import * as Sink from "effect/Sink"; +import * as Stream from "effect/Stream"; +import { TestClock } from "effect/testing"; +import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; + +import { layer, make, type ChildProcessShutdownSignal } from "./boundedChildProcessSpawner.ts"; + +const makeHandle = (input: { + readonly pid: number; + readonly exitCode: Effect.Effect; + readonly isRunning: Effect.Effect; + readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"]; + readonly unref?: ChildProcessSpawner.ChildProcessHandle["unref"]; +}) => + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(input.pid), + exitCode: input.exitCode, + isRunning: input.isRunning, + kill: input.kill ?? (() => Effect.void), + unref: input.unref ?? Effect.succeed(Effect.void), + stdin: Sink.drain, + stdout: Stream.empty, + stderr: Stream.empty, + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }); + +const errnoCode = (cause: unknown) => + cause instanceof Error ? Reflect.get(cause, "code") : undefined; + +const isProcessAlive = (pid: number) => { + try { + process.kill(pid, 0); + return true; + } catch (cause) { + return errnoCode(cause) !== "ESRCH"; + } +}; + +const killProcessGroup = (pid: number) => { + try { + process.kill(-pid, "SIGKILL"); + } catch { + try { + process.kill(pid, "SIGKILL"); + } catch { + // The process group has already exited. + } + } +}; + +const readFixturePids = (line: string) => { + const value: unknown = JSON.parse(line); + if (typeof value !== "object" || value === null) { + throw new Error("Expected the child fixture to print an object"); + } + const pid = Reflect.get(value, "pid"); + const descendantPid = Reflect.get(value, "descendantPid"); + if (typeof pid !== "number" || typeof descendantPid !== "number") { + throw new Error("Expected numeric child fixture pids"); + } + return { pid, descendantPid }; +}; + +const waitForProcessesToStop = Effect.fn("waitForProcessesToStop")(function* ( + pids: ReadonlyArray, + timeoutMs: number, +) { + let remainingMs = timeoutMs; + while (pids.some(isProcessAlive)) { + if (remainingMs <= 0) return false; + const delayMs = Math.min(10, remainingMs); + yield* Effect.sleep(delayMs); + remainingMs -= delayMs; + } + return true; +}); + +it.effect("closes the delegate scope after a natural child exit", () => + Effect.gen(function* () { + const exited = yield* Deferred.make(); + const delegateClosed = yield* Deferred.make(); + const handle = makeHandle({ + pid: 1, + exitCode: Deferred.await(exited), + isRunning: Deferred.isDone(exited).pipe(Effect.map((done) => !done)), + }); + const delegate = ChildProcessSpawner.make(() => + Effect.gen(function* () { + yield* Effect.addFinalizer(() => Deferred.succeed(delegateClosed, undefined)); + return handle; + }), + ); + const spawner = make(delegate); + const callerScope = yield* Scope.make(); + + const spawned = yield* spawner + .spawn(ChildProcess.make("unused")) + .pipe(Effect.provideService(Scope.Scope, callerScope)); + expect(spawned.pid).toBe(handle.pid); + + yield* Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0)); + yield* Deferred.await(delegateClosed).pipe(Effect.timeout("1 second")); + yield* Scope.close(callerScope, Exit.void); + }), +); + +it.effect("preserves unref as an opt-out from scope-owned termination", () => + Effect.gen(function* () { + const exited = yield* Deferred.make(); + const signals: Array = []; + let running = true; + const handle = makeHandle({ + pid: 43, + exitCode: Deferred.await(exited), + isRunning: Effect.sync(() => running), + kill: ({ killSignal } = {}) => + Effect.sync(() => { + if (killSignal === "SIGTERM" || killSignal === "SIGKILL") signals.push(killSignal); + }), + }); + const spawner = make( + ChildProcessSpawner.make(() => Effect.succeed(handle)), + { + termGraceMs: 0, + killGraceMs: 0, + }, + ); + const callerScope = yield* Scope.make(); + const spawned = yield* spawner + .spawn(ChildProcess.make("unused")) + .pipe(Effect.provideService(Scope.Scope, callerScope)); + + const reref = yield* spawned.unref; + yield* Scope.close(callerScope, Exit.void); + + expect(signals).toEqual([]); + yield* reref; + running = false; + yield* Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0)); + }), +); + +it.effect("does not wait for the delegate's unbounded finalizer", () => + Effect.gen(function* () { + const exited = yield* Deferred.make(); + const delegateCloseStarted = yield* Deferred.make(); + const allowDelegateClose = yield* Deferred.make(); + const signals: Array = []; + let running = true; + const handle = makeHandle({ + pid: 42, + exitCode: Deferred.await(exited), + isRunning: Effect.sync(() => running), + kill: ({ killSignal } = {}) => + Effect.sync(() => { + if (killSignal !== "SIGTERM" && killSignal !== "SIGKILL") return; + signals.push(killSignal); + if (killSignal === "SIGKILL") running = false; + }), + }); + const delegate = ChildProcessSpawner.make(() => + Effect.gen(function* () { + yield* Effect.addFinalizer(() => + Deferred.succeed(delegateCloseStarted, undefined).pipe( + Effect.andThen(Deferred.await(allowDelegateClose)), + ), + ); + return handle; + }), + ); + const spawner = make(delegate, { + termGraceMs: 0, + killGraceMs: 0, + }); + const callerScope = yield* Scope.make(); + + yield* spawner + .spawn(ChildProcess.make("unused")) + .pipe(Effect.provideService(Scope.Scope, callerScope)); + yield* Scope.close(callerScope, Exit.void); + + expect(signals).toEqual(["SIGTERM", "SIGKILL"]); + yield* Deferred.await(delegateCloseStarted).pipe(Effect.timeout("1 second")); + yield* Deferred.succeed(allowDelegateClose, undefined); + yield* Deferred.succeed(exited, ChildProcessSpawner.ExitCode(137)); + }), +); + +it.effect( + "kills a TERM-ignoring Node child and its descendant without blocking scope close", + () => { + const descendantScript = ` + process.on("SIGTERM", () => {}); + process.stdout.write("ready\\n"); + setInterval(() => {}, 1_000); + `; + const childScript = ` + const { spawn } = require("node:child_process"); + process.on("SIGTERM", () => {}); + const descendant = spawn(process.execPath, ["-e", ${JSON.stringify(descendantScript)}], { + stdio: ["ignore", "pipe", "inherit"], + }); + descendant.stdout.once("data", () => { + console.log(JSON.stringify({ pid: process.pid, descendantPid: descendant.pid })); + }); + setInterval(() => {}, 1_000); + `; + const boundedLayer = layer({ + termGraceMs: 100, + killGraceMs: 1_000, + pollIntervalMs: 10, + }).pipe(Layer.provideMerge(NodeServices.layer)); + + return Effect.gen(function* () { + const platform = yield* HostProcessPlatform; + if (platform === "win32") return; + + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const callerScope = yield* Scope.make(); + const handle = yield* spawner + .spawn(ChildProcess.make(process.execPath, ["-e", childScript])) + .pipe(Effect.provideService(Scope.Scope, callerScope)); + const line = yield* handle.stdout.pipe( + Stream.decodeText(), + Stream.splitLines, + Stream.runHead, + Effect.timeout("2 seconds"), + Effect.map(Option.getOrThrow), + ); + const pids = readFixturePids(line); + yield* Effect.addFinalizer(() => Effect.sync(() => killProcessGroup(pids.pid))); + + const closeFiber = yield* Scope.close(callerScope, Exit.void).pipe( + Effect.forkDetach({ startImmediately: true }), + ); + yield* Fiber.join(closeFiber).pipe(Effect.timeout("2 seconds")); + + expect(yield* waitForProcessesToStop([pids.pid, pids.descendantPid], 2_000)).toBe(true); + expect(isProcessAlive(pids.pid)).toBe(false); + expect(isProcessAlive(pids.descendantPid)).toBe(false); + }).pipe(Effect.scoped, Effect.provide(boundedLayer), TestClock.withLive); + }, +); diff --git a/apps/server/src/cli/boundedChildProcessSpawner.ts b/apps/server/src/cli/boundedChildProcessSpawner.ts new file mode 100644 index 0000000000..8fa934ed46 --- /dev/null +++ b/apps/server/src/cli/boundedChildProcessSpawner.ts @@ -0,0 +1,158 @@ +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Layer from "effect/Layer"; +import * as Scope from "effect/Scope"; +import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; + +export type ChildProcessShutdownSignal = "SIGTERM" | "SIGKILL"; + +export interface BoundedChildProcessSpawnerOptions { + readonly termGraceMs?: number; + readonly killGraceMs?: number; + readonly pollIntervalMs?: number; +} + +const DEFAULT_TERM_GRACE_MS = 2_000; +const DEFAULT_KILL_GRACE_MS = 1_000; +const DEFAULT_POLL_INTERVAL_MS = 25; + +const normalizedDelay = (value: number | undefined, fallback: number) => + value === undefined || !Number.isFinite(value) ? fallback : Math.max(0, value); + +const isStillRunning = (handle: ChildProcessSpawner.ChildProcessHandle) => + handle.isRunning.pipe(Effect.orElseSucceed(() => true)); + +const waitUntilStopped = Effect.fn("BoundedChildProcessSpawner.waitUntilStopped")(function* ( + handle: ChildProcessSpawner.ChildProcessHandle, + timeoutMs: number, + pollIntervalMs: number, +) { + let remainingMs = timeoutMs; + + while (yield* isStillRunning(handle)) { + if (remainingMs <= 0) return false; + const delayMs = Math.min(pollIntervalMs, remainingMs); + yield* Effect.sleep(delayMs); + remainingMs -= delayMs; + } + + return true; +}); + +const closeScopeDetached = Effect.fn("BoundedChildProcessSpawner.closeScopeDetached")(function* ( + scope: Scope.Closeable, +) { + yield* Scope.close(scope, Exit.void).pipe( + Effect.ignoreCause({ log: true }), + Effect.forkDetach({ startImmediately: true }), + ); +}); + +export const make = ( + delegate: ChildProcessSpawner.ChildProcessSpawner["Service"], + options: BoundedChildProcessSpawnerOptions = {}, +) => { + const termGraceMs = normalizedDelay(options.termGraceMs, DEFAULT_TERM_GRACE_MS); + const killGraceMs = normalizedDelay(options.killGraceMs, DEFAULT_KILL_GRACE_MS); + const pollIntervalMs = Math.max( + 1, + normalizedDelay(options.pollIntervalMs, DEFAULT_POLL_INTERVAL_MS), + ); + const sendSignal = Effect.fn("BoundedChildProcessSpawner.sendSignal")(function* ( + handle: ChildProcessSpawner.ChildProcessHandle, + signal: ChildProcessShutdownSignal, + ) { + yield* handle + .kill({ killSignal: signal }) + .pipe(Effect.ignore, Effect.forkDetach({ startImmediately: true })); + }); + + const shutdown = Effect.fn("BoundedChildProcessSpawner.shutdown")(function* ( + handle: ChildProcessSpawner.ChildProcessHandle, + childScope: Scope.Closeable, + isReferenced: () => boolean, + ) { + if (isReferenced() && (yield* isStillRunning(handle))) { + yield* sendSignal(handle, "SIGTERM"); + const stoppedAfterTerm = yield* waitUntilStopped(handle, termGraceMs, pollIntervalMs); + + if (!stoppedAfterTerm) { + yield* sendSignal(handle, "SIGKILL"); + const stoppedAfterKill = yield* waitUntilStopped(handle, killGraceMs, pollIntervalMs); + if (!stoppedAfterKill) { + yield* Effect.logWarning("Child process did not stop after SIGKILL grace period", { + pid: Number(handle.pid), + killGraceMs, + }); + } + } + } + + // The platform spawner's own finalizer can wait forever for an exit event. + // Run it detached so it can finish normally without blocking the caller's + // scope when the operating system does not report an exit in time. + yield* closeScopeDetached(childScope); + }); + + const spawn = Effect.fn("BoundedChildProcessSpawner.spawn")(function* ( + command: ChildProcess.Command, + ) { + const childScope = yield* Scope.make("sequential"); + const spawned = yield* delegate + .spawn(command) + .pipe(Effect.provideService(Scope.Scope, childScope), Effect.exit); + + if (Exit.isFailure(spawned)) { + yield* closeScopeDetached(childScope); + return yield* Effect.failCause(spawned.cause); + } + + const delegateHandle = spawned.value; + let referenced = true; + const handle = ChildProcessSpawner.makeHandle({ + pid: delegateHandle.pid, + exitCode: delegateHandle.exitCode, + isRunning: delegateHandle.isRunning, + kill: delegateHandle.kill, + stdin: delegateHandle.stdin, + stdout: delegateHandle.stdout, + stderr: delegateHandle.stderr, + all: delegateHandle.all, + getInputFd: delegateHandle.getInputFd, + getOutputFd: delegateHandle.getOutputFd, + unref: delegateHandle.unref.pipe( + Effect.tap(() => + Effect.sync(() => { + referenced = false; + }), + ), + Effect.map((reref) => + reref.pipe( + Effect.tap(() => + Effect.sync(() => { + referenced = true; + }), + ), + ), + ), + ), + }); + yield* Effect.addFinalizer(() => shutdown(handle, childScope, () => referenced)); + yield* handle.exitCode.pipe( + Effect.exit, + Effect.andThen(Scope.close(childScope, Exit.void)), + Effect.ignoreCause({ log: true }), + Effect.forkDetach({ startImmediately: true }), + ); + + return handle; + }, Effect.uninterruptible); + + return ChildProcessSpawner.make(spawn); +}; + +export const layer = (options?: BoundedChildProcessSpawnerOptions) => + Layer.effect( + ChildProcessSpawner.ChildProcessSpawner, + Effect.map(ChildProcessSpawner.ChildProcessSpawner, (delegate) => make(delegate, options)), + );