Standardise shutdown signal guarding

This commit is contained in:
Cooldude2606 committed 2026-04-14 22:10:01 +01:00
1 parent e9653c13eb
commit e8cabb7196
6 files changed
+37 -75

No files matched your search

+29
View File
@@ -3,6 +3,9 @@
* @module lib/helpers
*/
import type { Logger } from "./logging";
import setBlocking from "set-blocking";
/**
* Return a string describing the type of the value passed
*
@@ -51,6 +54,32 @@ export async function timeout<T>(promise: Promise<T>, limitMs: number, timeoutRe
}
}
/**
* Catch process signals, force exit on second signal
*/
export function createShutdownGuard(logger: Logger, signalName: string, callback: () => Promise<unknown>): () => void {
let called = false;
return () => {
if (called) {
setBlocking(true);
logger.fatal(`Caught second ${signalName}, terminating immediately`);
process.exit(1);
}
called = true;
logger.info(`Caught ${signalName}, shutting down`);
callback().catch(err => {
setBlocking(true);
logger.error(err.stack);
logger.fatal("Error during shutdown, terminating immediately");
process.exit(1);
});
};
}
/**
* Helper to serialise and merge waiting calls to an async callback.
*