diff --git a/apps/server/src/bin.ts b/apps/server/src/bin.ts index ddfbf5e3ec..9aaf41893c 100644 --- a/apps/server/src/bin.ts +++ b/apps/server/src/bin.ts @@ -13,6 +13,7 @@ import { hasCloudPublicConfig } from "./cloud/publicConfig.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); @@ -54,9 +55,12 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) => export const cli = makeCli(); if (import.meta.main) { + const removeShutdownSignalEscalation = installNodeShutdownSignalEscalation(); + Command.run(cli, { version: packageJson.version }).pipe( Effect.scoped, Effect.provide(CliRuntimeLayer), + Effect.ensuring(Effect.sync(removeShutdownSignalEscalation)), NodeRuntime.runMain, ); } diff --git a/apps/server/src/cli/shutdownSignalEscalation.test.ts b/apps/server/src/cli/shutdownSignalEscalation.test.ts new file mode 100644 index 0000000000..fcb2797bf4 --- /dev/null +++ b/apps/server/src/cli/shutdownSignalEscalation.test.ts @@ -0,0 +1,111 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + installShutdownSignalEscalation, + type ShutdownSignal, + type ShutdownSignalEscalationOptions, +} from "./shutdownSignalEscalation.ts"; + +const makeHarness = () => { + const listeners: Record void>> = { + SIGINT: new Set(), + SIGTERM: new Set(), + }; + const exitCodes: Array = []; + const timers = new Map void; readonly delayMs: number }>(); + const clearedTimers: Array = []; + let nextTimerHandle = 1; + + const options = { + process: { + addSignalListener: (signal, listener) => { + listeners[signal].add(listener); + }, + removeSignalListener: (signal, listener) => { + listeners[signal].delete(listener); + }, + exit: (code) => { + exitCodes.push(code); + }, + }, + timers: { + setTimeout: (callback, delayMs) => { + const handle = nextTimerHandle; + nextTimerHandle += 1; + timers.set(handle, { callback, delayMs }); + return handle; + }, + clearTimeout: (handle) => { + clearedTimers.push(handle); + timers.delete(handle); + }, + }, + } satisfies ShutdownSignalEscalationOptions; + + const emit = (signal: ShutdownSignal) => { + for (const listener of listeners[signal]) listener(); + }; + + const runNextTimer = () => { + const next = timers.entries().next(); + if (next.done) throw new Error("Expected a pending timer"); + const [handle, timer] = next.value; + timers.delete(handle); + timer.callback(); + }; + + return { clearedTimers, emit, exitCodes, listeners, options, runNextTimer, timers }; +}; + +describe("installShutdownSignalEscalation", () => { + it.each([ + ["SIGINT", 130], + ["SIGTERM", 143], + ] as const)("gives the first %s a bounded graceful-shutdown window", (signal, exitCode) => { + const harness = makeHarness(); + const dispose = installShutdownSignalEscalation({ + ...harness.options, + forceExitAfterMs: 2_500, + }); + + harness.emit(signal); + + expect(harness.exitCodes).toEqual([]); + expect([...harness.timers.values()].map((timer) => timer.delayMs)).toEqual([2_500]); + + harness.runNextTimer(); + + expect(harness.exitCodes).toEqual([exitCode]); + dispose(); + }); + + it("uses the second signal's conventional exit code immediately", () => { + const harness = makeHarness(); + const dispose = installShutdownSignalEscalation(harness.options); + + harness.emit("SIGTERM"); + harness.emit("SIGINT"); + + expect(harness.exitCodes).toEqual([130]); + expect(harness.clearedTimers).toEqual([1]); + expect(harness.timers.size).toBe(0); + dispose(); + }); + + it("removes both listeners and cancels the deadline when disposed", () => { + const harness = makeHarness(); + const dispose = installShutdownSignalEscalation(harness.options); + + harness.emit("SIGINT"); + dispose(); + dispose(); + + expect(harness.listeners.SIGINT.size).toBe(0); + expect(harness.listeners.SIGTERM.size).toBe(0); + expect(harness.clearedTimers).toEqual([1]); + expect(harness.timers.size).toBe(0); + + harness.emit("SIGINT"); + expect(harness.exitCodes).toEqual([]); + }); +}); diff --git a/apps/server/src/cli/shutdownSignalEscalation.ts b/apps/server/src/cli/shutdownSignalEscalation.ts new file mode 100644 index 0000000000..54abfd2931 --- /dev/null +++ b/apps/server/src/cli/shutdownSignalEscalation.ts @@ -0,0 +1,94 @@ +// @effect-diagnostics nodeBuiltinImport:off - This module is the CLI process and signal boundary. +import * as NodeProcess from "node:process"; +import * as NodeTimers from "node:timers"; + +export type ShutdownSignal = "SIGINT" | "SIGTERM"; + +export interface ShutdownSignalProcessHooks { + readonly addSignalListener: (signal: ShutdownSignal, listener: () => void) => void; + readonly removeSignalListener: (signal: ShutdownSignal, listener: () => void) => void; + readonly exit: (code: number) => void; +} + +export interface ShutdownSignalTimerHooks { + readonly setTimeout: (callback: () => void, delayMs: number) => TimerHandle; + readonly clearTimeout: (handle: TimerHandle) => void; +} + +export interface ShutdownSignalEscalationOptions { + readonly process: ShutdownSignalProcessHooks; + readonly timers: ShutdownSignalTimerHooks; + readonly forceExitAfterMs?: number; +} + +const defaultForceExitAfterMs = 10_000; + +const conventionalExitCode = (signal: ShutdownSignal) => (signal === "SIGINT" ? 130 : 143); + +export const installShutdownSignalEscalation = ({ + process: processHooks, + timers, + forceExitAfterMs = defaultForceExitAfterMs, +}: ShutdownSignalEscalationOptions) => { + let firstSignal: ShutdownSignal | undefined; + let forceExitTimer: { readonly handle: TimerHandle } | undefined; + let disposed = false; + + const clearForceExitTimer = () => { + if (forceExitTimer === undefined) return; + timers.clearTimeout(forceExitTimer.handle); + forceExitTimer = undefined; + }; + + const forceExit = (signal: ShutdownSignal) => { + clearForceExitTimer(); + processHooks.exit(conventionalExitCode(signal)); + }; + + const handleSignal = (signal: ShutdownSignal) => { + if (firstSignal !== undefined) { + forceExit(signal); + return; + } + + firstSignal = signal; + forceExitTimer = { + handle: timers.setTimeout(() => { + forceExitTimer = undefined; + processHooks.exit(conventionalExitCode(signal)); + }, forceExitAfterMs), + }; + }; + + const handleSigint = () => handleSignal("SIGINT"); + const handleSigterm = () => handleSignal("SIGTERM"); + + processHooks.addSignalListener("SIGINT", handleSigint); + processHooks.addSignalListener("SIGTERM", handleSigterm); + + return () => { + if (disposed) return; + disposed = true; + processHooks.removeSignalListener("SIGINT", handleSigint); + processHooks.removeSignalListener("SIGTERM", handleSigterm); + clearForceExitTimer(); + }; +}; + +export const installNodeShutdownSignalEscalation = () => + installShutdownSignalEscalation({ + process: { + addSignalListener: (signal, listener) => { + NodeProcess.on(signal, listener); + }, + removeSignalListener: (signal, listener) => { + NodeProcess.removeListener(signal, listener); + }, + exit: (code) => NodeProcess.exit(code), + }, + timers: { + // @effect-diagnostics-next-line globalTimers:off - The forced exit deadline must outlive a stuck Effect shutdown. + setTimeout: (callback, delayMs) => NodeTimers.setTimeout(callback, delayMs), + clearTimeout: (handle) => NodeTimers.clearTimeout(handle), + }, + });