@juspay/neurolink
Version:
The pipe layer of an AI nervous system: one interface connecting provider neurons to your application, across three inference types — generate, stream and decide. `decide` returns typed, calibrated judgements from a non-generative model (~400ms, ~$0.00002
90 lines • 3.13 kB
JavaScript
/** One signal owner per CLI process. Proxy lifecycles own their drain and exit;
* ordinary commands only need a bounded, best-effort telemetry flush. */
let owner;
let cleanupTask;
let cleanupPromise;
let shutdownPromise;
let installed = false;
let cleanupTimeoutMs = 5_000;
/** Install ordinary-command cleanup and its maximum flush duration. */
export function initializeCliLifecycle(cleanup, timeoutMs = 5_000) {
cleanupTask = cleanup;
cleanupTimeoutMs = timeoutMs;
installSignals();
}
/** Delegate signals to a long-lived command that owns draining and exit. */
export function registerCliShutdownOwner(handler) {
owner = handler;
installSignals();
}
/** Flush ordinary commands once; an active shutdown owner manages its own cleanup. */
export function cleanupCliLifecycle() {
if (owner) {
return Promise.resolve();
}
cleanupPromise ??= runBoundedCliCleanup(() => cleanupTask?.() ?? Promise.resolve(), cleanupTimeoutMs, () => {
// A stalled exporter may retain handles after Promise.race settles.
// A newly registered owner still retains control of draining and exit.
if (!owner) {
process.exit(process.exitCode ?? 0);
}
});
return cleanupPromise;
}
/** Bound best-effort cleanup without allowing rejection to escape a signal handler. */
export async function runBoundedCliCleanup(cleanup, timeoutMs = 5_000, onTimeout) {
let timer;
let timedOut = false;
try {
await Promise.race([
Promise.resolve().then(cleanup),
new Promise((_, reject) => {
timer = setTimeout(() => {
timedOut = true;
reject(new Error("telemetry flush deadline exceeded"));
}, timeoutMs);
}),
]);
}
catch (error) {
process.stderr.write(`[cli] cleanup failed: ${error instanceof Error ? error.message : String(error)}\n`);
}
finally {
clearTimeout(timer);
}
if (timedOut) {
onTimeout?.();
}
}
/** Install one process-wide signal dispatcher and reuse the first shutdown promise. */
function installSignals() {
if (installed) {
return;
}
installed = true;
for (const signal of ["SIGINT", "SIGTERM"]) {
process.on(signal, () => {
shutdownPromise ??= Promise.resolve()
.then(async () => {
if (!owner) {
await cleanupCliLifecycle();
}
// Startup may register the proxy owner while the flush is pending.
if (owner) {
await owner(signal);
}
else {
process.exit(process.exitCode ?? 0);
}
})
.catch((error) => {
process.stderr.write(`[cli] shutdown failed: ${error instanceof Error ? error.message : String(error)}\n`);
process.exit(1);
});
});
}
process.once("beforeExit", () => {
void cleanupCliLifecycle();
});
}
//# sourceMappingURL=lifecycle.js.map