-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
122 lines (105 loc) · 3.31 KB
/
index.js
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
const handledEvents = ["SIGINT", "SIGTERM", "SIGQUIT"];
const dependencyTree = new Map(); // name => [dependency name, ...]
const handlers = new Map(); // name => [handler, ...]
const shutdownErrorHandlers = [];
/**
* Gracefully terminate application's modules on shutdown.
* @param {string} [name] - Name of the handler.
* @param {array} [dependencies] - Which handlers should be processed first.
* @param {function} handler - Async or sync function which handles shutdown.
*/
module.exports.onShutdown = function (name, dependencies, handler) {
handler =
typeof name === "function"
? name
: typeof dependencies === "function"
? dependencies
: handler;
dependencies =
name instanceof Array
? name
: dependencies instanceof Array
? dependencies
: [];
name = typeof name === "string" ? name : Math.random().toString(36);
if (dependencies.reduce((acc, dep) => acc || testForCycles(dep), false)) {
throw new Error(
`Adding shutdown handler "${name}" will create a dependency loop: aborting`
);
}
dependencyTree.set(
name,
Array.from(new Set((dependencyTree.get(name) || []).concat(dependencies)))
);
if (!handlers.has(name)) {
handlers.set(name, []);
}
handlers.get(name).push(handler);
};
/**
* Optional export to handle shutdown errors.
* @param {function} callback
*/
module.exports.onShutdownError = function (callback) {
shutdownErrorHandlers.push(callback);
};
async function shutdown(name, promisesMap) {
if (promisesMap.has(name)) {
return await promisesMap.get(name);
}
const nodeCompletedPromise = (async function () {
const dependencies = dependencyTree.get(name) || [];
// Wait for all dependencies to shut down.
await Promise.all(dependencies.map((dep) => shutdown(dep, promisesMap)));
// Shutdown this item.
const allHandlers = handlers.get(name) || [];
if (allHandlers.length) {
await Promise.all(allHandlers.map((f) => f()));
}
})();
promisesMap.set(name, nodeCompletedPromise);
await nodeCompletedPromise;
}
let shuttingDown = false;
handledEvents.forEach((event) =>
process.removeAllListeners(event).addListener(event, () => {
if (shuttingDown) {
return;
}
shuttingDown = true;
// Get all unreferenced nodes.
const unreferencedNames = getAllUnreferencedNames();
const visited = new Map();
Promise.all(unreferencedNames.map((name) => shutdown(name, visited)))
.then(() => exit(0))
.catch((e) => {
Promise.all(shutdownErrorHandlers.map((f) => f(e)))
.then(() => exit(42759))
.catch(() => exit(42758));
});
})
);
// -------- Utility functions -------- \\
function testForCycles(name, visitedSet = new Set()) {
// Return true if the cycle is found.
if (visitedSet.has(name)) {
return true;
}
visitedSet.add(name);
// If any of the cycles found in dependencies, return true.
return (dependencyTree.get(name) || []).reduce(
(acc, name) => acc || testForCycles(name),
false
);
}
function getAllUnreferencedNames() {
const allNodes = new Set(Array.from(dependencyTree.keys()));
Array.from(dependencyTree.values()).forEach((deps) =>
deps.forEach((dep) => allNodes.delete(dep))
);
return Array.from(allNodes);
}
/* STUBBED - DO NOT EDIT */
function exit(code) {
process.exit(code);
}