/
node-cluster.ts
77 lines (68 loc) · 1.85 KB
/
node-cluster.ts
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
import os from "node:os";
import cluster from "node:cluster";
import { getGracefulShutdownConfig } from "../shutdown";
import { trapUnhandledNodeErrors } from "../utils";
function runMaster() {
const numberOfWorkers =
Number.parseInt(process.env.NITRO_CLUSTER_WORKERS || "") ||
(os.cpus().length > 0 ? os.cpus().length : 1);
for (let i = 0; i < numberOfWorkers; i++) {
cluster.fork();
}
// Restore worker on exit
let isShuttingDown = false;
cluster.on("exit", () => {
if (!isShuttingDown) {
cluster.fork();
}
});
// Graceful shutdown
const shutdownConfig = getGracefulShutdownConfig();
if (!shutdownConfig.disabled) {
async function onShutdown() {
if (isShuttingDown) {
return;
}
isShuttingDown = true;
await new Promise<void>((resolve) => {
const timeout = setTimeout(() => {
console.warn(
"[nitro] [cluster] Timeout reached for graceful shutdown. Forcing exit."
);
resolve();
}, shutdownConfig.timeout);
cluster.on("exit", () => {
if (
Object.values(cluster.workers || {}).every((w) => !w || w.isDead())
) {
clearTimeout(timeout);
resolve();
} else {
// Wait for other workers to die...
}
});
});
if (shutdownConfig.forceExit) {
// eslint-disable-next-line unicorn/no-process-exit
process.exit(0);
}
}
for (const signal of shutdownConfig.signals) {
process.once(signal, onShutdown);
}
}
}
function runWorker() {
import("./node-server").catch((error) => {
console.error(error);
// eslint-disable-next-line unicorn/no-process-exit
process.exit(1);
});
}
// Trap unhandled errors
trapUnhandledNodeErrors();
if (cluster.isPrimary) {
runMaster();
} else {
runWorker();
}