-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
70 lines (54 loc) · 1.43 KB
/
server.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
'use strict';
try {
process.chdir(__dirname);
} catch (err) {
// ignore
}
// cache before wild-config
const argv = process.argv.slice(2);
const logger = require('./lib/logger');
const pathlib = require('path');
const { Worker, SHARE_ENV } = require('worker_threads');
const config = require('wild-config');
process.title = config.process.title;
let closing = false;
let workers = new Map();
let spawnWorker = type => {
if (closing) {
return;
}
if (!workers.has(type)) {
workers.set(type, new Set());
}
let worker = new Worker(pathlib.join(__dirname, 'workers', `${type}.js`), {
argv,
env: SHARE_ENV
});
workers.get(type).add(worker);
worker.on('exit', exitCode => {
workers.get(type).delete(worker);
if (closing) {
return;
}
// spawning a new worker trigger reassign
logger.error({ msg: 'Worker exited', exitCode });
setTimeout(() => spawnWorker(type), 1000);
});
};
if (config.web.enabled) {
// single worker for HTTP
spawnWorker('web');
}
const closeProcess = code => {
if (closing) {
return;
}
closing = true;
setTimeout(() => {
process.exit(code);
}, 10);
};
process.on('uncaughtException', () => closeProcess(1));
process.on('unhandledRejection', () => closeProcess(2));
process.on('SIGTERM', () => closeProcess(0));
process.on('SIGINT', () => closeProcess(0));