fix(cli): force exit when graceful shutdown stalls

This commit is contained in:
Ben Davis committed 2026-06-26 11:06:06 -07:00
1 parent a49d7a7010
commit 1d0fc944a2
3 files changed
+209

No files matched your search

+4
View File
@@ -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,
);
}
@@ -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<ShutdownSignal, Set<() => void>> = {
SIGINT: new Set(),
SIGTERM: new Set(),
};
const exitCodes: Array<number> = [];
const timers = new Map<number, { readonly callback: () => void; readonly delayMs: number }>();
const clearedTimers: Array<number> = [];
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<number>;
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([]);
});
});
@@ -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<TimerHandle> {
readonly setTimeout: (callback: () => void, delayMs: number) => TimerHandle;
readonly clearTimeout: (handle: TimerHandle) => void;
}
export interface ShutdownSignalEscalationOptions<TimerHandle> {
readonly process: ShutdownSignalProcessHooks;
readonly timers: ShutdownSignalTimerHooks<TimerHandle>;
readonly forceExitAfterMs?: number;
}
const defaultForceExitAfterMs = 10_000;
const conventionalExitCode = (signal: ShutdownSignal) => (signal === "SIGINT" ? 130 : 143);
export const installShutdownSignalEscalation = <TimerHandle>({
process: processHooks,
timers,
forceExitAfterMs = defaultForceExitAfterMs,
}: ShutdownSignalEscalationOptions<TimerHandle>) => {
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),
},
});