-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
abstract-pool.ts
2245 lines (2141 loc) · 71.1 KB
/
abstract-pool.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
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
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { AsyncResource } from 'node:async_hooks'
import { randomUUID } from 'node:crypto'
import { EventEmitterAsyncResource } from 'node:events'
import { performance } from 'node:perf_hooks'
import type { TransferListItem } from 'node:worker_threads'
import type {
MessageValue,
PromiseResponseWrapper,
Task,
TaskFunctionProperties
} from '../utility-types.js'
import {
average,
buildTaskFunctionProperties,
DEFAULT_TASK_NAME,
EMPTY_FUNCTION,
exponentialDelay,
isKillBehavior,
isPlainObject,
max,
median,
min,
round,
sleep
} from '../utils.js'
import type {
TaskFunction,
TaskFunctionObject
} from '../worker/task-functions.js'
import { KillBehaviors } from '../worker/worker-options.js'
import {
type IPool,
PoolEvents,
type PoolInfo,
type PoolOptions,
type PoolType,
PoolTypes,
type TasksQueueOptions
} from './pool.js'
import {
Measurements,
WorkerChoiceStrategies,
type WorkerChoiceStrategy,
type WorkerChoiceStrategyOptions
} from './selection-strategies/selection-strategies-types.js'
import { WorkerChoiceStrategiesContext } from './selection-strategies/worker-choice-strategies-context.js'
import {
checkFilePath,
checkValidPriority,
checkValidTasksQueueOptions,
checkValidWorkerChoiceStrategy,
getDefaultTasksQueueOptions,
updateEluWorkerUsage,
updateRunTimeWorkerUsage,
updateTaskStatisticsWorkerUsage,
updateWaitTimeWorkerUsage,
waitWorkerNodeEvents
} from './utils.js'
import { version } from './version.js'
import type {
IWorker,
IWorkerNode,
WorkerInfo,
WorkerNodeEventDetail,
WorkerType
} from './worker.js'
import { WorkerNode } from './worker-node.js'
/**
* Base class that implements some shared logic for all poolifier pools.
*
* @typeParam Worker - Type of worker which manages this pool.
* @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
* @typeParam Response - Type of execution response. This can only be structured-cloneable data.
*/
export abstract class AbstractPool<
Worker extends IWorker,
Data = unknown,
Response = unknown
> implements IPool<Worker, Data, Response> {
/** @inheritDoc */
public readonly workerNodes: Array<IWorkerNode<Worker, Data>> = []
/** @inheritDoc */
public emitter?: EventEmitterAsyncResource
/**
* The task execution response promise map:
* - `key`: The message id of each submitted task.
* - `value`: An object that contains task's worker node key, execution response promise resolve and reject callbacks, async resource.
*
* When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
*/
protected promiseResponseMap: Map<
`${string}-${string}-${string}-${string}-${string}`,
PromiseResponseWrapper<Response>
> = new Map<
`${string}-${string}-${string}-${string}-${string}`,
PromiseResponseWrapper<Response>
>()
/**
* Worker choice strategies context referencing worker choice algorithms implementation.
*/
protected workerChoiceStrategiesContext?: WorkerChoiceStrategiesContext<
Worker,
Data,
Response
>
/**
* The task functions added at runtime map:
* - `key`: The task function name.
* - `value`: The task function object.
*/
private readonly taskFunctions: Map<
string,
TaskFunctionObject<Data, Response>
>
/**
* Whether the pool is started or not.
*/
private started: boolean
/**
* Whether the pool is starting or not.
*/
private starting: boolean
/**
* Whether the pool is destroying or not.
*/
private destroying: boolean
/**
* Whether the minimum number of workers is starting or not.
*/
private startingMinimumNumberOfWorkers: boolean
/**
* Whether the pool ready event has been emitted or not.
*/
private readyEventEmitted: boolean
/**
* The start timestamp of the pool.
*/
private startTimestamp?: number
/**
* Constructs a new poolifier pool.
*
* @param minimumNumberOfWorkers - Minimum number of workers that this pool manages.
* @param filePath - Path to the worker file.
* @param opts - Options for the pool.
* @param maximumNumberOfWorkers - Maximum number of workers that this pool manages.
*/
public constructor (
protected readonly minimumNumberOfWorkers: number,
protected readonly filePath: string,
protected readonly opts: PoolOptions<Worker>,
protected readonly maximumNumberOfWorkers?: number
) {
if (!this.isMain()) {
throw new Error(
'Cannot start a pool from a worker with the same type as the pool'
)
}
this.checkPoolType()
checkFilePath(this.filePath)
this.checkMinimumNumberOfWorkers(this.minimumNumberOfWorkers)
this.checkPoolOptions(this.opts)
this.chooseWorkerNode = this.chooseWorkerNode.bind(this)
this.executeTask = this.executeTask.bind(this)
this.enqueueTask = this.enqueueTask.bind(this)
if (this.opts.enableEvents === true) {
this.initEventEmitter()
}
this.workerChoiceStrategiesContext = new WorkerChoiceStrategiesContext<
Worker,
Data,
Response
>(
this,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
[this.opts.workerChoiceStrategy!],
this.opts.workerChoiceStrategyOptions
)
this.setupHook()
this.taskFunctions = new Map<string, TaskFunctionObject<Data, Response>>()
this.started = false
this.starting = false
this.destroying = false
this.readyEventEmitted = false
this.startingMinimumNumberOfWorkers = false
if (this.opts.startWorkers === true) {
this.start()
}
}
private checkPoolType (): void {
if (this.type === PoolTypes.fixed && this.maximumNumberOfWorkers != null) {
throw new Error(
'Cannot instantiate a fixed pool with a maximum number of workers specified at initialization'
)
}
}
private checkMinimumNumberOfWorkers (
minimumNumberOfWorkers: number | undefined
): void {
if (minimumNumberOfWorkers == null) {
throw new Error(
'Cannot instantiate a pool without specifying the number of workers'
)
} else if (!Number.isSafeInteger(minimumNumberOfWorkers)) {
throw new TypeError(
'Cannot instantiate a pool with a non safe integer number of workers'
)
} else if (minimumNumberOfWorkers < 0) {
throw new RangeError(
'Cannot instantiate a pool with a negative number of workers'
)
} else if (this.type === PoolTypes.fixed && minimumNumberOfWorkers === 0) {
throw new RangeError('Cannot instantiate a fixed pool with zero worker')
}
}
private checkPoolOptions (opts: PoolOptions<Worker>): void {
if (isPlainObject(opts)) {
this.opts.startWorkers = opts.startWorkers ?? true
checkValidWorkerChoiceStrategy(opts.workerChoiceStrategy)
this.opts.workerChoiceStrategy =
opts.workerChoiceStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN
this.checkValidWorkerChoiceStrategyOptions(
opts.workerChoiceStrategyOptions
)
if (opts.workerChoiceStrategyOptions != null) {
this.opts.workerChoiceStrategyOptions = opts.workerChoiceStrategyOptions
}
this.opts.restartWorkerOnError = opts.restartWorkerOnError ?? true
this.opts.enableEvents = opts.enableEvents ?? true
this.opts.enableTasksQueue = opts.enableTasksQueue ?? false
if (this.opts.enableTasksQueue) {
checkValidTasksQueueOptions(opts.tasksQueueOptions)
this.opts.tasksQueueOptions = this.buildTasksQueueOptions(
opts.tasksQueueOptions
)
}
} else {
throw new TypeError('Invalid pool options: must be a plain object')
}
}
private checkValidWorkerChoiceStrategyOptions (
workerChoiceStrategyOptions: WorkerChoiceStrategyOptions | undefined
): void {
if (
workerChoiceStrategyOptions != null &&
!isPlainObject(workerChoiceStrategyOptions)
) {
throw new TypeError(
'Invalid worker choice strategy options: must be a plain object'
)
}
if (
workerChoiceStrategyOptions?.weights != null &&
Object.keys(workerChoiceStrategyOptions.weights).length !==
(this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers)
) {
throw new Error(
'Invalid worker choice strategy options: must have a weight for each worker node'
)
}
if (
workerChoiceStrategyOptions?.measurement != null &&
!Object.values(Measurements).includes(
workerChoiceStrategyOptions.measurement
)
) {
throw new Error(
`Invalid worker choice strategy options: invalid measurement '${workerChoiceStrategyOptions.measurement}'`
)
}
}
private initEventEmitter (): void {
this.emitter = new EventEmitterAsyncResource({
name: `poolifier:${this.type}-${this.worker}-pool`
})
}
/** @inheritDoc */
public get info (): PoolInfo {
return {
version,
type: this.type,
worker: this.worker,
started: this.started,
ready: this.ready,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
defaultStrategy: this.opts.workerChoiceStrategy!,
strategyRetries: this.workerChoiceStrategiesContext?.retriesCount ?? 0,
minSize: this.minimumNumberOfWorkers,
maxSize: this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers,
...(this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements()
.runTime.aggregate === true &&
this.workerChoiceStrategiesContext.getTaskStatisticsRequirements()
.waitTime.aggregate && {
utilization: round(this.utilization)
}),
workerNodes: this.workerNodes.length,
idleWorkerNodes: this.workerNodes.reduce(
(accumulator, workerNode) =>
workerNode.usage.tasks.executing === 0
? accumulator + 1
: accumulator,
0
),
...(this.opts.enableTasksQueue === true && {
stealingWorkerNodes: this.workerNodes.reduce(
(accumulator, workerNode) =>
workerNode.info.stealing ? accumulator + 1 : accumulator,
0
)
}),
busyWorkerNodes: this.workerNodes.reduce(
(accumulator, _, workerNodeKey) =>
this.isWorkerNodeBusy(workerNodeKey) ? accumulator + 1 : accumulator,
0
),
executedTasks: this.workerNodes.reduce(
(accumulator, workerNode) =>
accumulator + workerNode.usage.tasks.executed,
0
),
executingTasks: this.workerNodes.reduce(
(accumulator, workerNode) =>
accumulator + workerNode.usage.tasks.executing,
0
),
...(this.opts.enableTasksQueue === true && {
queuedTasks: this.workerNodes.reduce(
(accumulator, workerNode) =>
accumulator + workerNode.usage.tasks.queued,
0
)
}),
...(this.opts.enableTasksQueue === true && {
maxQueuedTasks: this.workerNodes.reduce(
(accumulator, workerNode) =>
accumulator + (workerNode.usage.tasks.maxQueued ?? 0),
0
)
}),
...(this.opts.enableTasksQueue === true && {
backPressure: this.hasBackPressure()
}),
...(this.opts.enableTasksQueue === true && {
stolenTasks: this.workerNodes.reduce(
(accumulator, workerNode) =>
accumulator + workerNode.usage.tasks.stolen,
0
)
}),
failedTasks: this.workerNodes.reduce(
(accumulator, workerNode) =>
accumulator + workerNode.usage.tasks.failed,
0
),
...(this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements()
.runTime.aggregate === true && {
runTime: {
minimum: round(
min(
...this.workerNodes.map(
workerNode => workerNode.usage.runTime.minimum ?? Infinity
)
)
),
maximum: round(
max(
...this.workerNodes.map(
workerNode => workerNode.usage.runTime.maximum ?? -Infinity
)
)
),
...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements()
.runTime.average && {
average: round(
average(
this.workerNodes.reduce<number[]>(
(accumulator, workerNode) =>
accumulator.concat(workerNode.usage.runTime.history),
[]
)
)
)
}),
...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements()
.runTime.median && {
median: round(
median(
this.workerNodes.reduce<number[]>(
(accumulator, workerNode) =>
accumulator.concat(workerNode.usage.runTime.history),
[]
)
)
)
})
}
}),
...(this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements()
.waitTime.aggregate === true && {
waitTime: {
minimum: round(
min(
...this.workerNodes.map(
workerNode => workerNode.usage.waitTime.minimum ?? Infinity
)
)
),
maximum: round(
max(
...this.workerNodes.map(
workerNode => workerNode.usage.waitTime.maximum ?? -Infinity
)
)
),
...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements()
.waitTime.average && {
average: round(
average(
this.workerNodes.reduce<number[]>(
(accumulator, workerNode) =>
accumulator.concat(workerNode.usage.waitTime.history),
[]
)
)
)
}),
...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements()
.waitTime.median && {
median: round(
median(
this.workerNodes.reduce<number[]>(
(accumulator, workerNode) =>
accumulator.concat(workerNode.usage.waitTime.history),
[]
)
)
)
})
}
}),
...(this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements()
.elu.aggregate === true && {
elu: {
idle: {
minimum: round(
min(
...this.workerNodes.map(
workerNode => workerNode.usage.elu.idle.minimum ?? Infinity
)
)
),
maximum: round(
max(
...this.workerNodes.map(
workerNode => workerNode.usage.elu.idle.maximum ?? -Infinity
)
)
),
...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements()
.elu.average && {
average: round(
average(
this.workerNodes.reduce<number[]>(
(accumulator, workerNode) =>
accumulator.concat(workerNode.usage.elu.idle.history),
[]
)
)
)
}),
...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements()
.elu.median && {
median: round(
median(
this.workerNodes.reduce<number[]>(
(accumulator, workerNode) =>
accumulator.concat(workerNode.usage.elu.idle.history),
[]
)
)
)
})
},
active: {
minimum: round(
min(
...this.workerNodes.map(
workerNode => workerNode.usage.elu.active.minimum ?? Infinity
)
)
),
maximum: round(
max(
...this.workerNodes.map(
workerNode => workerNode.usage.elu.active.maximum ?? -Infinity
)
)
),
...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements()
.elu.average && {
average: round(
average(
this.workerNodes.reduce<number[]>(
(accumulator, workerNode) =>
accumulator.concat(workerNode.usage.elu.active.history),
[]
)
)
)
}),
...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements()
.elu.median && {
median: round(
median(
this.workerNodes.reduce<number[]>(
(accumulator, workerNode) =>
accumulator.concat(workerNode.usage.elu.active.history),
[]
)
)
)
})
},
utilization: {
average: round(
average(
this.workerNodes.map(
workerNode => workerNode.usage.elu.utilization ?? 0
)
)
),
median: round(
median(
this.workerNodes.map(
workerNode => workerNode.usage.elu.utilization ?? 0
)
)
)
}
}
})
}
}
/**
* The pool readiness boolean status.
*/
private get ready (): boolean {
if (this.empty) {
return false
}
return (
this.workerNodes.reduce(
(accumulator, workerNode) =>
!workerNode.info.dynamic && workerNode.info.ready
? accumulator + 1
: accumulator,
0
) >= this.minimumNumberOfWorkers
)
}
/**
* The pool emptiness boolean status.
*/
protected get empty (): boolean {
return this.minimumNumberOfWorkers === 0 && this.workerNodes.length === 0
}
/**
* The approximate pool utilization.
*
* @returns The pool utilization.
*/
private get utilization (): number {
if (this.startTimestamp == null) {
return 0
}
const poolTimeCapacity =
(performance.now() - this.startTimestamp) *
(this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers)
const totalTasksRunTime = this.workerNodes.reduce(
(accumulator, workerNode) =>
accumulator + (workerNode.usage.runTime.aggregate ?? 0),
0
)
const totalTasksWaitTime = this.workerNodes.reduce(
(accumulator, workerNode) =>
accumulator + (workerNode.usage.waitTime.aggregate ?? 0),
0
)
return (totalTasksRunTime + totalTasksWaitTime) / poolTimeCapacity
}
/**
* The pool type.
*
* If it is `'dynamic'`, it provides the `max` property.
*/
protected abstract get type (): PoolType
/**
* The worker type.
*/
protected abstract get worker (): WorkerType
/**
* Checks if the worker id sent in the received message from a worker is valid.
*
* @param message - The received message.
* @throws {@link https://nodejs.org/api/errors.html#class-error} If the worker id is invalid.
*/
private checkMessageWorkerId (message: MessageValue<Data | Response>): void {
if (message.workerId == null) {
throw new Error('Worker message received without worker id')
} else if (this.getWorkerNodeKeyByWorkerId(message.workerId) === -1) {
throw new Error(
`Worker message received from unknown worker '${message.workerId}'`
)
}
}
/**
* Gets the worker node key given its worker id.
*
* @param workerId - The worker id.
* @returns The worker node key if the worker id is found in the pool worker nodes, `-1` otherwise.
*/
private getWorkerNodeKeyByWorkerId (workerId: number | undefined): number {
return this.workerNodes.findIndex(
workerNode => workerNode.info.id === workerId
)
}
/** @inheritDoc */
public setWorkerChoiceStrategy (
workerChoiceStrategy: WorkerChoiceStrategy,
workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions
): void {
let requireSync = false
checkValidWorkerChoiceStrategy(workerChoiceStrategy)
if (workerChoiceStrategyOptions != null) {
requireSync = !this.setWorkerChoiceStrategyOptions(
workerChoiceStrategyOptions
)
}
if (workerChoiceStrategy !== this.opts.workerChoiceStrategy) {
this.opts.workerChoiceStrategy = workerChoiceStrategy
this.workerChoiceStrategiesContext?.setDefaultWorkerChoiceStrategy(
this.opts.workerChoiceStrategy,
this.opts.workerChoiceStrategyOptions
)
requireSync = true
}
if (requireSync) {
this.workerChoiceStrategiesContext?.syncWorkerChoiceStrategies(
this.getWorkerChoiceStrategies(),
this.opts.workerChoiceStrategyOptions
)
for (const workerNodeKey of this.workerNodes.keys()) {
this.sendStatisticsMessageToWorker(workerNodeKey)
}
}
}
/** @inheritDoc */
public setWorkerChoiceStrategyOptions (
workerChoiceStrategyOptions: WorkerChoiceStrategyOptions | undefined
): boolean {
this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions)
if (workerChoiceStrategyOptions != null) {
this.opts.workerChoiceStrategyOptions = workerChoiceStrategyOptions
this.workerChoiceStrategiesContext?.setOptions(
this.opts.workerChoiceStrategyOptions
)
this.workerChoiceStrategiesContext?.syncWorkerChoiceStrategies(
this.getWorkerChoiceStrategies(),
this.opts.workerChoiceStrategyOptions
)
for (const workerNodeKey of this.workerNodes.keys()) {
this.sendStatisticsMessageToWorker(workerNodeKey)
}
return true
}
return false
}
/** @inheritDoc */
public enableTasksQueue (
enable: boolean,
tasksQueueOptions?: TasksQueueOptions
): void {
if (this.opts.enableTasksQueue === true && !enable) {
this.unsetTaskStealing()
this.unsetTasksStealingOnBackPressure()
this.flushTasksQueues()
}
this.opts.enableTasksQueue = enable
this.setTasksQueueOptions(tasksQueueOptions)
}
/** @inheritDoc */
public setTasksQueueOptions (
tasksQueueOptions: TasksQueueOptions | undefined
): void {
if (this.opts.enableTasksQueue === true) {
checkValidTasksQueueOptions(tasksQueueOptions)
this.opts.tasksQueueOptions =
this.buildTasksQueueOptions(tasksQueueOptions)
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
this.setTasksQueueSize(this.opts.tasksQueueOptions.size!)
if (this.opts.tasksQueueOptions.taskStealing === true) {
this.unsetTaskStealing()
this.setTaskStealing()
} else {
this.unsetTaskStealing()
}
if (this.opts.tasksQueueOptions.tasksStealingOnBackPressure === true) {
this.unsetTasksStealingOnBackPressure()
this.setTasksStealingOnBackPressure()
} else {
this.unsetTasksStealingOnBackPressure()
}
} else if (this.opts.tasksQueueOptions != null) {
delete this.opts.tasksQueueOptions
}
}
private buildTasksQueueOptions (
tasksQueueOptions: TasksQueueOptions | undefined
): TasksQueueOptions {
return {
...getDefaultTasksQueueOptions(
this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers
),
...tasksQueueOptions
}
}
private setTasksQueueSize (size: number): void {
for (const workerNode of this.workerNodes) {
workerNode.tasksQueueBackPressureSize = size
}
}
private setTaskStealing (): void {
for (const workerNodeKey of this.workerNodes.keys()) {
this.workerNodes[workerNodeKey].on('idle', this.handleWorkerNodeIdleEvent)
}
}
private unsetTaskStealing (): void {
for (const workerNodeKey of this.workerNodes.keys()) {
this.workerNodes[workerNodeKey].off(
'idle',
this.handleWorkerNodeIdleEvent
)
}
}
private setTasksStealingOnBackPressure (): void {
for (const workerNodeKey of this.workerNodes.keys()) {
this.workerNodes[workerNodeKey].on(
'backPressure',
this.handleWorkerNodeBackPressureEvent
)
}
}
private unsetTasksStealingOnBackPressure (): void {
for (const workerNodeKey of this.workerNodes.keys()) {
this.workerNodes[workerNodeKey].off(
'backPressure',
this.handleWorkerNodeBackPressureEvent
)
}
}
/**
* Whether the pool is full or not.
*
* The pool filling boolean status.
*/
protected get full (): boolean {
return (
this.workerNodes.length >=
(this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers)
)
}
/**
* Whether the pool is busy or not.
*
* The pool busyness boolean status.
*/
protected abstract get busy (): boolean
/**
* Whether worker nodes are executing concurrently their tasks quota or not.
*
* @returns Worker nodes busyness boolean status.
*/
protected internalBusy (): boolean {
if (this.opts.enableTasksQueue === true) {
return (
this.workerNodes.findIndex(
workerNode =>
workerNode.info.ready &&
workerNode.usage.tasks.executing <
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
this.opts.tasksQueueOptions!.concurrency!
) === -1
)
}
return (
this.workerNodes.findIndex(
workerNode =>
workerNode.info.ready && workerNode.usage.tasks.executing === 0
) === -1
)
}
private isWorkerNodeBusy (workerNodeKey: number): boolean {
if (this.opts.enableTasksQueue === true) {
return (
this.workerNodes[workerNodeKey].usage.tasks.executing >=
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
this.opts.tasksQueueOptions!.concurrency!
)
}
return this.workerNodes[workerNodeKey].usage.tasks.executing > 0
}
private async sendTaskFunctionOperationToWorker (
workerNodeKey: number,
message: MessageValue<Data>
): Promise<boolean> {
return await new Promise<boolean>((resolve, reject) => {
const taskFunctionOperationListener = (
message: MessageValue<Response>
): void => {
this.checkMessageWorkerId(message)
const workerId = this.getWorkerInfo(workerNodeKey)?.id
if (
message.taskFunctionOperationStatus != null &&
message.workerId === workerId
) {
if (message.taskFunctionOperationStatus) {
resolve(true)
} else {
reject(
new Error(
`Task function operation '${message.taskFunctionOperation}' failed on worker ${message.workerId} with error: '${message.workerError?.message}'`
)
)
}
this.deregisterWorkerMessageListener(
this.getWorkerNodeKeyByWorkerId(message.workerId),
taskFunctionOperationListener
)
}
}
this.registerWorkerMessageListener(
workerNodeKey,
taskFunctionOperationListener
)
this.sendToWorker(workerNodeKey, message)
})
}
private async sendTaskFunctionOperationToWorkers (
message: MessageValue<Data>
): Promise<boolean> {
return await new Promise<boolean>((resolve, reject) => {
const responsesReceived = new Array<MessageValue<Response>>()
const taskFunctionOperationsListener = (
message: MessageValue<Response>
): void => {
this.checkMessageWorkerId(message)
if (message.taskFunctionOperationStatus != null) {
responsesReceived.push(message)
if (responsesReceived.length === this.workerNodes.length) {
if (
responsesReceived.every(
message => message.taskFunctionOperationStatus === true
)
) {
resolve(true)
} else if (
responsesReceived.some(
message => message.taskFunctionOperationStatus === false
)
) {
const errorResponse = responsesReceived.find(
response => response.taskFunctionOperationStatus === false
)
reject(
new Error(
`Task function operation '${
message.taskFunctionOperation as string
}' failed on worker ${errorResponse?.workerId} with error: '${
errorResponse?.workerError?.message
}'`
)
)
}
this.deregisterWorkerMessageListener(
this.getWorkerNodeKeyByWorkerId(message.workerId),
taskFunctionOperationsListener
)
}
}
}
for (const workerNodeKey of this.workerNodes.keys()) {
this.registerWorkerMessageListener(
workerNodeKey,
taskFunctionOperationsListener
)
this.sendToWorker(workerNodeKey, message)
}
})
}
/** @inheritDoc */
public hasTaskFunction (name: string): boolean {
return this.listTaskFunctionsProperties().some(
taskFunctionProperties => taskFunctionProperties.name === name
)
}
/** @inheritDoc */
public async addTaskFunction (
name: string,
fn: TaskFunction<Data, Response> | TaskFunctionObject<Data, Response>
): Promise<boolean> {
if (typeof name !== 'string') {
throw new TypeError('name argument must be a string')
}
if (typeof name === 'string' && name.trim().length === 0) {
throw new TypeError('name argument must not be an empty string')
}
if (typeof fn === 'function') {
fn = { taskFunction: fn } satisfies TaskFunctionObject<Data, Response>
}
if (typeof fn.taskFunction !== 'function') {
throw new TypeError('taskFunction property must be a function')
}
checkValidPriority(fn.priority)
checkValidWorkerChoiceStrategy(fn.strategy)
const opResult = await this.sendTaskFunctionOperationToWorkers({
taskFunctionOperation: 'add',
taskFunctionProperties: buildTaskFunctionProperties(name, fn),
taskFunction: fn.taskFunction.toString()
})
this.taskFunctions.set(name, fn)
this.workerChoiceStrategiesContext?.syncWorkerChoiceStrategies(
this.getWorkerChoiceStrategies()
)
for (const workerNodeKey of this.workerNodes.keys()) {
this.sendStatisticsMessageToWorker(workerNodeKey)
}
return opResult
}
/** @inheritDoc */
public async removeTaskFunction (name: string): Promise<boolean> {
if (!this.taskFunctions.has(name)) {
throw new Error(
'Cannot remove a task function not handled on the pool side'
)
}
const opResult = await this.sendTaskFunctionOperationToWorkers({
taskFunctionOperation: 'remove',
taskFunctionProperties: buildTaskFunctionProperties(
name,
this.taskFunctions.get(name)
)
})
for (const workerNode of this.workerNodes) {
workerNode.deleteTaskFunctionWorkerUsage(name)
}
this.taskFunctions.delete(name)