30 lines
1.0 KiB
JavaScript
30 lines
1.0 KiB
JavaScript
// Keep the store locked until writers finish, or until the process exits.
|
|
export function installShutdown(store, drain, { timeout = 5000 } = {}) {
|
|
const release = () => {
|
|
try { store.close(); }
|
|
catch { console.error('Could not remove the access store lock. Check file permissions.'); process.exitCode = 1; }
|
|
};
|
|
process.once('exit', release);
|
|
let stopping;
|
|
const stop = () => {
|
|
if (stopping) return stopping;
|
|
const deadline = setTimeout(() => {
|
|
console.error('Shutdown timed out; exiting and releasing the access store lock.');
|
|
process.exit(1);
|
|
}, timeout).unref();
|
|
stopping = Promise.resolve().then(drain).catch(() => {
|
|
console.error('Gateway shutdown failed.');
|
|
// Do not unlock while unfinished jobs could still write to the store.
|
|
process.exit(1);
|
|
}).then(() => {
|
|
clearTimeout(deadline);
|
|
release();
|
|
});
|
|
return stopping;
|
|
};
|
|
// Keep handlers installed so repeated Ctrl+C cannot interrupt cleanup.
|
|
process.on('SIGINT', stop);
|
|
process.on('SIGTERM', stop);
|
|
return stop;
|
|
}
|