dnc/manager.js
2021-10-23 12:30:10 +02:00

83 lines
2 KiB
JavaScript

const manager = function(process){
var t = this;
async function exitHandler(options, exitCode) {
t.shutdown().then(()=>{
setTimeout(function() {
process.exit();
}, 1000);
}).catch(()=>{
setTimeout(function() {
process.exit();
}, 10000);
});
}
[`SIGINT`, `SIGUSR1`, `SIGUSR2`,`SIGTERM`].forEach((eventType) => {
process.on(eventType, exitHandler.bind(null, eventType));
});
var shutdownTasks = []
t.addShutdownTask = function(task,maxDuration=5000){
shutdownTasks.push({t:task,d:maxDuration});
};
t.shutdown = function(){
return new Promise((res,rej)=>{
console.log("Shuting down ...");
var maxDuration = 1000;
var running = 0;
var timeout = null;
function mayShutdown(force=false){
if(running==0||force){
if(timeout!=null)clearInterval(timeout);
res();
}
}
running++;
for (var i = 0; i < shutdownTasks.length; i++) {
try {
if(shutdownTasks[i].d>maxDuration)maxDuration=shutdownTasks[i].d;
running++;
let a = shutdownTasks[i].t();
if(typeof a.then == "function"){
a.then(()=>{
running--;
mayShutdown();
});
}else{
running--;
if(shutdownTasks.length-1 == i){
mayShutdown();
}
}
} catch (e) {
running--;
mayShutdown();
}
}
running--;
timeout = setTimeout(function () {
timeout = null;
mayShutdown(true);
}, maxDuration);
mayShutdown();
});
};
t.saveShutdown = function(){
return new Promise((res,rej)=>{
t.shutdown().then(()=>{
setTimeout(function() { //some save time
process.exit();
}, 1000);
}).catch(()=>{
setTimeout(function() { //shutdown on error with more save time
process.exit();
}, 10000);
});
});
}
}
export default manager;