forked from VeriNode-Labs/VeriNode-Backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshutdown.js
More file actions
53 lines (53 loc) · 1.65 KB
/
Copy pathshutdown.js
File metadata and controls
53 lines (53 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
const http = require("http");
function setupGracefulShutdown(server, options = {}) {
const drainTimeout = options.drainTimeout || 30000;
const persistTimeout = options.persistTimeout || 10000;
const forceTimeout = options.forceTimeout || 60000;
let isShuttingDown = false;
const activeConnections = new Set();
server.on("connection", (s) => {
activeConnections.add(s);
s.on("close", () => activeConnections.delete(s));
});
async function handleShutdown(signal) {
if (isShuttingDown) return;
isShuttingDown = true;
setTimeout(() => process.exit(1), forceTimeout);
try {
await new Promise((r) => {
server.close(() => r());
for (const s of activeConnections) {
if (!s.writableEnded && s.setHeader) {
s.setHeader("Connection", "close");
}
}
});
await new Promise((r) => {
const t = setTimeout(() => r(), drainTimeout);
const c = setInterval(() => {
if (activeConnections.size === 0) {
clearInterval(c); clearTimeout(t); r();
}
}, 100);
});
await new Promise((r, j) => {
const t = setTimeout(() => j(), persistTimeout);
if (options.onPersist) {
options.onPersist().then(() => {
clearTimeout(t); r();
}).catch((e) => {
clearTimeout(t); j(e);
});
} else {
clearTimeout(t); r();
}
});
process.exit(0);
} catch (e) {
process.exit(1);
}
}
process.on("SIGTERM", () => handleShutdown("SIGTERM"));
process.on("SIGINT", () => handleShutdown("SIGINT"));
}
module.exports = setupGracefulShutdown;