Skip to content

Commit

Permalink
fix(cosmic-swingset): straighten out shutdown signals and exit code
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelfig committed Feb 10, 2022
1 parent a9bc83d commit 118fc21
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions packages/cosmic-swingset/src/shutdown.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,33 +4,35 @@ import anylogger from 'anylogger';

const console = anylogger('shutdown');

export const makeFreshShutdown = () => {
export const makeFreshShutdown = (verbose = true) => {
const shutdownThunks = new Set();

let shuttingDown = false;
/** @type {NodeJS.SignalsListener & NodeJS.BeforeExitListener} */
const shutdown = code => {
const sig = typeof code === 'string' && code.startsWith('SIG');
if (sig) {
process.exitCode = 99;
process.exitCode = 98;
}
if (shuttingDown) {
process.exit();
return;
}
shuttingDown = true;
console.error('Shutting down cleanly...');
// Allow an explicit exit to terminate the process.
process.off('beforeExit', shutdown);
verbose && console.error(`Shutting down cleanly...`);
const shutdowners = [...shutdownThunks.keys()];
shutdownThunks.clear();
Promise.allSettled([...shutdowners].map(t => Promise.resolve().then(t)))
.then(statuses => {
for (const status of statuses) {
if (status.status === 'rejected') {
console.warn(status.reason);
verbose && console.warn(status.reason);
}
}
console.log('Process terminated!');
verbose && console.warn('Process terminated!');
})
.catch(error => console.warn('Error shutting down', error))
.catch(error => verbose && console.warn('Error shutting down', error))
.finally(() => {
process.exit();
});
Expand All @@ -39,7 +41,6 @@ export const makeFreshShutdown = () => {
// gracefully shut down the thunks on process exit
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);
process.on('SIGQUIT', shutdown);
process.on('beforeExit', shutdown);
process.on('uncaughtException', e => {
console.error(e);
Expand All @@ -57,9 +58,11 @@ export const makeFreshShutdown = () => {
};

let cachedShutdown = null;
export const makeCachedShutdown = () => {
export const makeCachedShutdown = (...args) => {
// It's possible our caller has specified different arguments.
// Since they control verbosity only, first-one-wins is acceptable.
if (!cachedShutdown) {
cachedShutdown = makeFreshShutdown();
cachedShutdown = makeFreshShutdown(...args);
}
return cachedShutdown;
};
Expand Down

0 comments on commit 118fc21

Please sign in to comment.