-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathworker_wrapper.js
662 lines (579 loc) · 18.1 KB
/
worker_wrapper.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
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
const cluster = require('cluster'),
RPC = require('./rpc'),
RPCCallback = require('./rpc-callback'),
EventEmitterEx = require('./event_emitter_ex'),
Port = require('./port'),
LusterWorkerWrapperError = require('./errors').LusterWorkerWrapperError;
/**
* Identifier for next constructed WorkerWrapper.
* Usage restricted to WorkerWrapper constructor only.
* @type {Number}
* @private
*/
let nextId = 0;
/**
* @class WorkerWrapperOptions
* @property {Number|String} port Port number or socket path which worker can listen
* @property {Boolean} [persistent=true] While `persistent === true` worker will be restarted on exit
* @property {Number} [forkTimeout=false]
* Time (in ms) to wait from 'fork' event to 'online' before launch if failed.
* If evaluates to `false` then forkTimeout will not set.
* @property {Number} [stopTimeout=false]
* Time (in ms) to wait from 'disconnect' event to 'exit' before `worker.kill` call
* If evaluates to `false` then stopTimeout will not set.
* @property {Number} [exitThreshold=false]
* @property {Number} [allowedSequentialDeaths=0]
* How many times worker can die in `exitThreshold` time before will be marked as dead.
*/
class WorkerWrapperOptions {
constructor(options) {
this.persistent = typeof options.persistent === 'undefined' ? true : options.persistent;
this.forkTimeout = options.forkTimeout;
this.stopTimeout = options.stopTimeout;
this.exitThreshold = options.exitThreshold;
this.allowedSequentialDeaths = options.allowedSequentialDeaths || 0;
this.port = options.port;
this.masterInspectPort = options.masterInspectPort;
}
get port() {
return this._port;
}
/**
* Setter of `this.options.port` affects value of the `isListeningUnixSocket` property.
* @memberOf WorkerWrapperOptions
* @property {Number|String} port
* @public
*/
set port(value) {
if (!(value instanceof Port)) {
value = new Port(value);
}
return this._port = value;
}
}
/**
* @event WorkerWrapper#state
* @param {WorkerWrapperState} state Actual WorkerWrapper state
* @see WorkerWrapper.STATES for possible `state` values.
*/
/**
* @constructor
* @class WorkerWrapper
* @augments EventEmitterEx
* @param {Master} master
* @param {WorkerWrapperOptions} options
*
* # Worker wrapper state transitions
*
* WorkerWrapper has 'stopped' state by default (once created).
* External events can
*/
class WorkerWrapper extends EventEmitterEx {
constructor(master, options) {
super();
if (options &&
typeof options.maxListeners !== 'undefined' &&
options.maxListeners > this.getMaxListeners()) {
this.setMaxListeners(options.maxListeners);
}
/**
* WorkerWrapper state. Must be set via private method `WorkerWrapper#_setState(value)`,
* not directly. Can be retrieved via `WorkerWrapper#state` getter.
* @see WorkerWrapper.STATES for possible values.
* @type WorkerWrapperState
*/
this._state = WorkerWrapper.STATES.STOPPED;
/**
* @type WorkerWrapperOptions
* @public
* @readonly
*/
this.options = new WorkerWrapperOptions(options);
this._wid = ++nextId;
/**
* Indicates worker restarting in progress.
* Changing `restarting` property value outside WorkerWrapper and it inheritors is not recommended.
* @property {Boolean} restarting
* @memberOf {WorkerWrapper}
* @public
*/
this.restarting = false;
/**
* Indicates worker stopping in progress.
* Changing `stopping` property value outside WorkerWrapper and it inheritors is not recommended.
* @property {Boolean} stopping
* @memberOf {WorkerWrapper}
* @public
*/
this.stopping = false;
/**
* Worker can be marked as dead on sequential fails of launch attempt.
* Dead worker will not be restarted on event WorkerWrapper#state('stopped').
* Internally in the WorkerWrapper worker can be marked as dead, but never go alive again.
* To revive the worker something outside of the WorkerWrapper
* must set the `dead` property value to `false`.
* @public
* @type {Boolean}
*/
this.dead = false;
/**
* Port for node v8 debugger on this worker.
* @type {Number}
* @public
*/
this.inspectPort = this.options.masterInspectPort + this.wid;
/**
* Number of sequential deaths when worker life time was less than `exitThreshold` option value.
* @type {Number}
* @private
*/
this._sequentialDeaths = 0;
/**
* Time of the last WorkerWrapper#state('running') event.
* @type {Number}
*/
this.startTime = null;
/**
* Indicates whether ready() method was called in worker
* @public
* @type {Boolean}
*/
this.ready = false;
/**
* @type {Master}
* @private
*/
this._master = master;
/**
* Listen for cluster#fork and worker events.
* @see WorkerWrapper#_proxyEvents to know about repeating worker events on WorkerWrapper instance.
*/
cluster.on('fork', this._onFork.bind(this));
this.on('online', this._onOnline.bind(this));
this.on('disconnect', this._onDisconnect.bind(this));
this.on('exit', this._onExit.bind(this));
WorkerWrapper._RPC_EVENTS.forEach(event => {
master.on('received worker ' + event, WorkerWrapper.createEventTranslator(event).bind(this));
});
this.on('ready', this._onReady.bind(this));
}
/**
* @property {Number} wid Persistent WorkerWrapper identifier
* @memberOf {WorkerWrapper}
* @public
* @readonly
*/
get wid() {
return this._wid;
}
/**
* @property {Number} pid System process identifier
* @memberOf {WorkerWrapper}
* @public
* @readonly
*/
get pid() {
return this.process.pid;
}
/**
* Current WorkerWrapper instance state
* @see WorkerWrapper.STATES for possible values.
* @property {WorkerWrapperState} state
* @memberOf {WorkerWrapper}
* @public
* @readonly
*/
get state() {
return this._state;
}
/**
* @see WorkerWrapper.STATES for possible `state` argument values
* @param {WorkerWrapperState} state
* @private
* @fires WorkerWrapper#state
*/
_setState(state) {
this._state = state;
this['_onState' + state[0].toUpperCase() + state.slice(1)]();
this.emit('state', state);
}
static createEventTranslator(event) {
return /** @this {WorkerWrapper} */function(worker) {
if (this._worker && worker.id === this._worker.id) {
this.emit(event);
}
};
}
_onReady() {
this.ready = true;
}
/**
* @private
*/
_onExit() {
this.ready = false;
this._setState(WorkerWrapper.STATES.STOPPED);
}
/**
* event:_worker#disconnect handler
* @private
*/
_onDisconnect() {
// "disconnect" and "exit" may be triggered in any order:
// https://nodejs.org/docs/latest-v22.x/api/cluster.html#clusterworkers
// Check state is stoppable for coordination.
if (this.isRunning()) {
this.ready = false;
this._setState(WorkerWrapper.STATES.STOPPING);
}
}
/**
* @event WorkerWrapper#ready
*/
/**
* event:_worker#online handler
* @fires WorkerWrapper#ready
* @private
*/
_onOnline() {
this._setState(WorkerWrapper.STATES.RUNNING);
// pass some of the {WorkerWrapper} properties to {Worker}
this.remoteCall(RPC.fns.worker.applyForeignProperties, {
pid: this.process.pid
});
}
/**
* event:cluster#fork handler
* @private
*/
_onFork(worker) {
if (this._worker && worker.id === this._worker.id) {
this.emit('fork');
this._setState(WorkerWrapper.STATES.LAUNCHING);
}
}
/**
* event:state('launching') handler
* @private
*/
_onStateLaunching() {
this.restarting = false;
if (this.options.forkTimeout) {
this.launchTimeout = setTimeout(() => {
this.launchTimeout = null;
if (this._worker !== null) {
this._worker.kill();
}
}, this.options.forkTimeout);
}
}
/**
* event:state('running') handler
* @private
*/
_onStateRunning() {
if (this.launchTimeout) {
clearTimeout(this.launchTimeout);
this.launchTimeout = null;
}
this.startTime = Date.now();
}
/**
* event:state('stopping') handler
* @private
*/
_onStateStopping() {
this._scheduleForceStop();
}
/**
* event:state('stopped') handler
* @private
*/
_onStateStopped() {
this._cancelForceStop();
// increase sequential deaths count if worker life time less
// than `exitThreshold` option value (and option was passed to constructor).
if (this.options.exitThreshold &&
Date.now() - this.startTime < this.options.exitThreshold &&
!this.restarting &&
!this.stopping) {
this._sequentialDeaths++;
}
// mark worker as dead if too much sequential deaths
if (this._sequentialDeaths > this.options.allowedSequentialDeaths) {
this.dead = true;
}
this._worker = null;
// start worker again if it persistent or in the restarting state
// and isn't marked as dead
if (((this.options.persistent && !this.stopping) || this.restarting) && !this.dead) {
setImmediate(this.run.bind(this));
}
this.stopping = false;
}
/**
* @returns {Boolean}
*/
isRunning() {
return this.state === WorkerWrapper.STATES.LAUNCHING ||
this.state === WorkerWrapper.STATES.RUNNING;
}
/**
* @event WorkerWrapper#error
* @param {LusterError} error
*/
/**
* Spawn a worker
* @fires WorkerWrapper#error if worker already running
* @fires WorkerWrapper#state('launching') on success
* @returns {WorkerWrapper} self
*/
run() {
if (this.isRunning()) {
this.emit('error',
LusterWorkerWrapperError.createError(
LusterWorkerWrapperError.CODES.INVALID_ATTEMPT_TO_CHANGE_STATE,
{
wid: this.wid,
pid: this.process.pid,
state: this.state,
targetState: WorkerWrapper.STATES.LAUNCHING
}));
return this;
}
setImmediate(() => {
// this call of setup sets inspectPort for node js debugger
// it should be here so that every worker can receive the same debugger port after restarting
if (this.inspectPort) {
this._master.setup({inspectPort: this.inspectPort});
}
/** @private */
this._worker = cluster.fork({
port: this.options.port,
LUSTER_WID: this.wid,
});
/** @private */
this._remoteCall = RPC.createCaller(this._worker);
this._proxyEvents();
});
return this;
}
/**
* Disconnect worker to stop it.
* @fires WorkerWrapper#error if worker status is 'stopped' or 'stopping'
* @fires WorkerWrapper#status('stopping') on success
* @returns {WorkerWrapper}
*/
stop() {
if (!this.isRunning()) {
this.emit('error',
LusterWorkerWrapperError.createError(
LusterWorkerWrapperError.CODES.INVALID_ATTEMPT_TO_CHANGE_STATE,
{
wid: this.wid,
pid: this.process.pid,
state: this.state,
targetState: WorkerWrapper.STATES.STOPPING
}));
return this;
}
this.emit('stop');
this.stopping = true;
const stopPid = this._worker && this.pid;
setImmediate(() => {
// state can be changed before function call
if (this.isRunning()) {
this.remoteCallWithCallback({
command: RPC.fns.worker.suspend,
callback: () => {
// Worker could die while suspend was in-flight, i.e. on endless loop, and _onStateStopped will drop _worker
// Or a new one could be started already
if (this._worker && (this.pid === stopPid)) {
this._worker.disconnect();
}
}
});
this._scheduleForceStop();
}
});
return this;
}
/**
* Set WorkerWrapper#restarting to `true` and stop it,
* which leads to worker restart.
*/
restart() {
this.restarting = true;
this.stop();
}
/**
* Call Worker method via RPC
* @method
* @param {String} name of called command in the worker
* @param {...*} args
*/
remoteCall(name, ...args) {
if (this.isRunning()) {
this._remoteCall(name, ...args);
} else {
this.emit('error',
LusterWorkerWrapperError.createError(
LusterWorkerWrapperError.CODES.REMOTE_COMMAND_CALL_TO_STOPPED_WORKER,
{
wid: this.wid,
pid: this.process.pid,
command: name
}));
}
}
// proxy some properties to WorkerWrapper#_worker
get id() {
return this._worker.id;
}
get process() {
return this._worker.process;
}
get suicide() {
return this._worker.suicide;
}
// proxy some methods to WorkerWrapper#_worker
send(...args) {
this._worker.send(...args);
}
disconnect() {
this._worker.disconnect();
}
/**
* repeat events from WorkerWrapper#_worker on WorkerWrapper
* @private
*/
_proxyEvents() {
WorkerWrapper._PROXY_EVENTS
.forEach(eventName => {
this._worker.on(eventName, this.emit.bind(this, eventName));
});
}
inspect() {
return 'WW{ id:' + this.wid + ', state: ' + this.state + '}';
}
broadcastEvent(...args) {
//TODO args here passed as single array, but remoteCall can handle multiple args
this.remoteCall(RPC.fns.worker.broadcastMasterEvent, args);
}
/**
* Do a remote call to worker, wait for worker to handle it, then execute registered callback
* @method
* @param {String} opts.command
* @param {Function} opts.callback
* @param {Number} [opts.timeout] in milliseconds
* @param {*} [opts.data]
* @public
*/
remoteCallWithCallback(opts) {
const callbackId = RPCCallback.setCallback(this, opts.command, opts.callback, opts.timeout);
this.remoteCall(opts.command, opts.data, callbackId);
}
/**
* Schedule a forceful worker stop using signal.
* Only schedules timeout if it was not set yet.
* @private
*/
_scheduleForceStop() {
// We could schedule force stop either when `stop` method is called or when `disconnected` event received from
// worker. In most cases `stop` will be called and then `disconnected` event will fire, therefore we shall
// make sure we do not re-run the force stop timer.
if (this.options.stopTimeout && !this.stopTimeout) {
this.stopTimeout = setTimeout(() => {
this.stopTimeout = null;
if (this._worker !== null) {
this._worker.process.kill();
}
}, this.options.stopTimeout);
}
}
/**
* Clears a forceful worker stop.
* @private
*/
_cancelForceStop() {
if (this.stopTimeout) {
clearTimeout(this.stopTimeout);
this.stopTimeout = null;
}
}
/**
* Adds this worker to master's restart queue
* @public
*/
softRestart() {
this._master.scheduleWorkerRestart(this);
}
}
/**
* Possible WorkerWrapper instance states.
* @property {Object} STATES
* @memberOf WorkerWrapper
* @typedef WorkerWrapperState
* @enum
* @readonly
* @public
* @static
*/
Object.defineProperty(WorkerWrapper, 'STATES', {
value: Object.freeze({
STOPPED: 'stopped',
LAUNCHING: 'launching',
RUNNING: 'running',
STOPPING: 'stopping'
}),
enumerable: true
});
/**
* Events to repeat from WorkerWrapper#_worker on WorkerWrapper instance
* @memberOf WorkerWrapper
* @property {String[]} _PROXY_EVENTS
* @static
* @private
*/
Object.defineProperty(WorkerWrapper, '_PROXY_EVENTS', {
value: Object.freeze([
'message',
'online',
'listening',
'disconnect',
'exit'
]),
enumerable: true
});
/**
* Events received from workers via IPC
* @memberOf WorkerWrapper
* @property {String[]} _RPC_EVENTS
* @static
* @private
*/
Object.defineProperty(WorkerWrapper, '_RPC_EVENTS', {
value: Object.freeze([
'configured',
'extension loaded',
'initialized',
'loaded',
'ready'
]),
enumerable: true
});
/**
* All events which can be emitted by WorkerWrapper
* @memberOf WorkerWrapper
* @property {String[]} EVENTS
* @static
*/
Object.defineProperty(WorkerWrapper, 'EVENTS', {
value: Object.freeze(
['error', 'state', 'fork']
.concat(WorkerWrapper._PROXY_EVENTS)
.concat(WorkerWrapper._RPC_EVENTS)
),
enumerable: true
});
module.exports = WorkerWrapper;