-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathapp.js
More file actions
210 lines (181 loc) · 5.02 KB
/
app.js
File metadata and controls
210 lines (181 loc) · 5.02 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
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
'use strict';
const { sleep } = require('../../../timer');
const workerThreads = require('worker_threads');
const { BaseAppWorker, BaseAppUtils } = require('../../base/app');
class AppWorker extends BaseAppWorker {
#id = 0;
#threadId = -1;
#state = 'none';
constructor(instance, id) {
super(instance);
this.#id = id;
this.#threadId = instance.threadId;
}
get id() {
return this.#id;
}
get workerId() {
return this.#threadId;
}
get state() {
return this.#state;
}
set state(val) {
this.#state = val;
}
get exitedAfterDisconnect() {
return true;
}
get exitCode() {
return this.instance.exitCode;
}
send(...args) {
this.instance.postMessage(...args);
}
clean() {
this.instance.removeAllListeners();
}
static on(event, callback) {
workerThreads.parentPort.on(event, callback);
}
static send(data) {
workerThreads.parentPort.postMessage(data);
}
static kill() {
process.exit(1);
}
static gracefulExit(options) {
const { beforeExit } = options;
process.on('exit', async code => {
if (typeof beforeExit === 'function') {
await beforeExit();
}
process.exit(code);
});
}
}
class AppUtils extends BaseAppUtils {
#appWorkers = [];
#forkSingle(appPath, options, id) {
// start app worker
const worker = new workerThreads.Worker(appPath, options);
// wrap app worker
const appWorker = new AppWorker(worker, id);
this.#appWorkers.push(appWorker);
this.emit('worker_forked', appWorker);
appWorker.disableRefork = true;
worker.on('message', msg => {
if (typeof msg === 'string') {
msg = {
action: msg,
data: msg,
};
}
msg.from = 'app';
this.messenger.send(msg);
});
this.log('[master] app_worker#%s (tid:%s) start', appWorker.id, appWorker.workerId);
// send debug message, due to `brk` scence, send here instead of app_worker.js
let debugPort = process.debugPort;
if (this.options.isDebug) {
debugPort++;
this.messenger.send({
to: 'parent',
from: 'app',
action: 'debug',
data: {
debugPort,
pid: appWorker.workerId,
},
});
}
// handle worker listening
worker.on('message', ({ action, data: address }) => {
if (action !== 'listening') {
return;
}
if (!address) {
return;
}
appWorker.state = 'listening';
this.messenger.send({
action: 'app-start',
data: {
workerId: appWorker.workerId,
address,
},
to: 'master',
from: 'app',
});
});
// handle worker exit
worker.on('exit', async code => {
this.log('[master] app_worker#%s (tid:%s) exit with code: %s', appWorker.id, appWorker.workerId, code);
// remove worker from workers array
const idx = this.#appWorkers.indexOf(appWorker);
if (idx !== -1) {
this.#appWorkers.splice(idx, 1);
}
// remove all listeners to avoid memory leak
worker.removeAllListeners();
appWorker.state = 'dead';
try {
this.messenger.send({
action: 'app-exit',
data: {
workerId: appWorker.workerId,
code,
},
to: 'master',
from: 'app',
});
} catch (err) {
this.log('[master][warning] app_worker#%s (tid:%s) send "app-exit" message error: %s',
appWorker.id, appWorker.workerId, err);
}
if (appWorker.disableRefork) {
return;
}
// refork app worker
this.log('[master] app_worker#%s (tid:%s) refork after 1s', appWorker.id, appWorker.workerId);
await sleep(1000);
this.#forkSingle(appPath, options, id);
});
}
fork() {
this.startTime = Date.now();
this.startSuccessCount = 0;
if (this.options.reusePort) {
if (!this.options.port) {
throw new Error('options.port must be specified when reusePort is enabled');
}
for (let i = 0; i < this.options.workers; i++) {
const argv = [ JSON.stringify(this.options) ];
const appWorkerId = i + 1;
this.#forkSingle(this.getAppWorkerFile(), { argv }, appWorkerId);
}
} else {
const ports = this.options.ports;
if (!ports.length) {
ports.push(this.options.port);
}
this.options.workers = ports.length;
let i = 0;
do {
const options = Object.assign({}, this.options, { port: ports[i] });
const argv = [ JSON.stringify(options) ];
this.#forkSingle(this.getAppWorkerFile(), { argv }, ++i);
} while (i < ports.length);
}
return this;
}
async kill() {
for (const appWorker of this.#appWorkers) {
this.log('[master] kill app_worker#%s (tid:%s) (worker_threads) by worker.terminate()', appWorker.id, appWorker.workerId);
appWorker.disableRefork = true;
appWorker.instance.removeAllListeners();
appWorker.instance.terminate();
}
}
}
module.exports = { AppWorker, AppUtils };