1 import { randomUUID
} from
'node:crypto'
2 import { performance
} from
'node:perf_hooks'
3 import type { TransferListItem
} from
'node:worker_threads'
4 import { EventEmitterAsyncResource
} from
'node:events'
7 PromiseResponseWrapper
,
9 } from
'../utility-types'
12 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
,
22 import { KillBehaviors
} from
'../worker/worker-options'
23 import type { TaskFunction
} from
'../worker/task-functions'
31 type TasksQueueOptions
41 type MeasurementStatisticsRequirements
,
43 WorkerChoiceStrategies
,
44 type WorkerChoiceStrategy
,
45 type WorkerChoiceStrategyOptions
46 } from
'./selection-strategies/selection-strategies-types'
47 import { WorkerChoiceStrategyContext
} from
'./selection-strategies/worker-choice-strategy-context'
48 import { version
} from
'./version'
49 import { WorkerNode
} from
'./worker-node'
52 checkValidTasksQueueOptions
,
53 checkValidWorkerChoiceStrategy
,
54 updateMeasurementStatistics
58 * Base class that implements some shared logic for all poolifier pools.
60 * @typeParam Worker - Type of worker which manages this pool.
61 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
62 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
64 export abstract class AbstractPool
<
65 Worker
extends IWorker
,
68 > implements IPool
<Worker
, Data
, Response
> {
70 public readonly workerNodes
: Array<IWorkerNode
<Worker
, Data
>> = []
73 public emitter
?: EventEmitterAsyncResource
76 * The task execution response promise map:
77 * - `key`: The message id of each submitted task.
78 * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks.
80 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
82 protected promiseResponseMap
: Map
<string, PromiseResponseWrapper
<Response
>> =
83 new Map
<string, PromiseResponseWrapper
<Response
>>()
86 * Worker choice strategy context referencing a worker choice algorithm implementation.
88 protected workerChoiceStrategyContext
: WorkerChoiceStrategyContext
<
95 * Dynamic pool maximum size property placeholder.
97 protected readonly max
?: number
100 * The task functions added at runtime map:
101 * - `key`: The task function name.
102 * - `value`: The task function itself.
104 private readonly taskFunctions
: Map
<string, TaskFunction
<Data
, Response
>>
107 * Whether the pool is started or not.
109 private started
: boolean
111 * Whether the pool is starting or not.
113 private starting
: boolean
115 * The start timestamp of the pool.
117 private readonly startTimestamp
120 * Constructs a new poolifier pool.
122 * @param numberOfWorkers - Number of workers that this pool should manage.
123 * @param filePath - Path to the worker file.
124 * @param opts - Options for the pool.
127 protected readonly numberOfWorkers
: number,
128 protected readonly filePath
: string,
129 protected readonly opts
: PoolOptions
<Worker
>
131 if (!this.isMain()) {
133 'Cannot start a pool from a worker with the same type as the pool'
136 checkFilePath(this.filePath
)
137 this.checkNumberOfWorkers(this.numberOfWorkers
)
138 this.checkPoolOptions(this.opts
)
140 this.chooseWorkerNode
= this.chooseWorkerNode
.bind(this)
141 this.executeTask
= this.executeTask
.bind(this)
142 this.enqueueTask
= this.enqueueTask
.bind(this)
144 if (this.opts
.enableEvents
=== true) {
145 this.initializeEventEmitter()
147 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext
<
153 this.opts
.workerChoiceStrategy
,
154 this.opts
.workerChoiceStrategyOptions
159 this.taskFunctions
= new Map
<string, TaskFunction
<Data
, Response
>>()
162 this.starting
= false
163 if (this.opts
.startWorkers
=== true) {
167 this.startTimestamp
= performance
.now()
170 private checkNumberOfWorkers (numberOfWorkers
: number): void {
171 if (numberOfWorkers
== null) {
173 'Cannot instantiate a pool without specifying the number of workers'
175 } else if (!Number.isSafeInteger(numberOfWorkers
)) {
177 'Cannot instantiate a pool with a non safe integer number of workers'
179 } else if (numberOfWorkers
< 0) {
180 throw new RangeError(
181 'Cannot instantiate a pool with a negative number of workers'
183 } else if (this.type === PoolTypes
.fixed
&& numberOfWorkers
=== 0) {
184 throw new RangeError('Cannot instantiate a fixed pool with zero worker')
188 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
189 if (isPlainObject(opts
)) {
190 this.opts
.startWorkers
= opts
.startWorkers
?? true
191 checkValidWorkerChoiceStrategy(
192 opts
.workerChoiceStrategy
as WorkerChoiceStrategy
194 this.opts
.workerChoiceStrategy
=
195 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
196 this.checkValidWorkerChoiceStrategyOptions(
197 opts
.workerChoiceStrategyOptions
as WorkerChoiceStrategyOptions
199 this.opts
.workerChoiceStrategyOptions
= {
200 ...DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
,
201 ...opts
.workerChoiceStrategyOptions
203 this.opts
.restartWorkerOnError
= opts
.restartWorkerOnError
?? true
204 this.opts
.enableEvents
= opts
.enableEvents
?? true
205 this.opts
.enableTasksQueue
= opts
.enableTasksQueue
?? false
206 if (this.opts
.enableTasksQueue
) {
207 checkValidTasksQueueOptions(opts
.tasksQueueOptions
as TasksQueueOptions
)
208 this.opts
.tasksQueueOptions
= this.buildTasksQueueOptions(
209 opts
.tasksQueueOptions
as TasksQueueOptions
213 throw new TypeError('Invalid pool options: must be a plain object')
217 private checkValidWorkerChoiceStrategyOptions (
218 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
221 workerChoiceStrategyOptions
!= null &&
222 !isPlainObject(workerChoiceStrategyOptions
)
225 'Invalid worker choice strategy options: must be a plain object'
229 workerChoiceStrategyOptions
?.retries
!= null &&
230 !Number.isSafeInteger(workerChoiceStrategyOptions
.retries
)
233 'Invalid worker choice strategy options: retries must be an integer'
237 workerChoiceStrategyOptions
?.retries
!= null &&
238 workerChoiceStrategyOptions
.retries
< 0
240 throw new RangeError(
241 `Invalid worker choice strategy options: retries '${workerChoiceStrategyOptions.retries}' must be greater or equal than zero`
245 workerChoiceStrategyOptions
?.weights
!= null &&
246 Object.keys(workerChoiceStrategyOptions
.weights
).length
!== this.maxSize
249 'Invalid worker choice strategy options: must have a weight for each worker node'
253 workerChoiceStrategyOptions
?.measurement
!= null &&
254 !Object.values(Measurements
).includes(
255 workerChoiceStrategyOptions
.measurement
259 `Invalid worker choice strategy options: invalid measurement '${workerChoiceStrategyOptions.measurement}'`
264 private initializeEventEmitter (): void {
265 this.emitter
= new EventEmitterAsyncResource({
266 name
: `poolifier:${this.type}-${this.worker}-pool`
271 public get
info (): PoolInfo
{
276 started
: this.started
,
278 strategy
: this.opts
.workerChoiceStrategy
as WorkerChoiceStrategy
,
279 minSize
: this.minSize
,
280 maxSize
: this.maxSize
,
281 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
282 .runTime
.aggregate
&&
283 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
284 .waitTime
.aggregate
&& { utilization
: round(this.utilization
) }),
285 workerNodes
: this.workerNodes
.length
,
286 idleWorkerNodes
: this.workerNodes
.reduce(
287 (accumulator
, workerNode
) =>
288 workerNode
.usage
.tasks
.executing
=== 0
293 busyWorkerNodes
: this.workerNodes
.reduce(
294 (accumulator
, workerNode
) =>
295 workerNode
.usage
.tasks
.executing
> 0 ? accumulator
+ 1 : accumulator
,
298 executedTasks
: this.workerNodes
.reduce(
299 (accumulator
, workerNode
) =>
300 accumulator
+ workerNode
.usage
.tasks
.executed
,
303 executingTasks
: this.workerNodes
.reduce(
304 (accumulator
, workerNode
) =>
305 accumulator
+ workerNode
.usage
.tasks
.executing
,
308 ...(this.opts
.enableTasksQueue
=== true && {
309 queuedTasks
: this.workerNodes
.reduce(
310 (accumulator
, workerNode
) =>
311 accumulator
+ workerNode
.usage
.tasks
.queued
,
315 ...(this.opts
.enableTasksQueue
=== true && {
316 maxQueuedTasks
: this.workerNodes
.reduce(
317 (accumulator
, workerNode
) =>
318 accumulator
+ (workerNode
.usage
.tasks
?.maxQueued
?? 0),
322 ...(this.opts
.enableTasksQueue
=== true && {
323 backPressure
: this.hasBackPressure()
325 ...(this.opts
.enableTasksQueue
=== true && {
326 stolenTasks
: this.workerNodes
.reduce(
327 (accumulator
, workerNode
) =>
328 accumulator
+ workerNode
.usage
.tasks
.stolen
,
332 failedTasks
: this.workerNodes
.reduce(
333 (accumulator
, workerNode
) =>
334 accumulator
+ workerNode
.usage
.tasks
.failed
,
337 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
338 .runTime
.aggregate
&& {
342 ...this.workerNodes
.map(
343 workerNode
=> workerNode
.usage
.runTime
?.minimum
?? Infinity
349 ...this.workerNodes
.map(
350 workerNode
=> workerNode
.usage
.runTime
?.maximum
?? -Infinity
354 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
355 .runTime
.average
&& {
358 this.workerNodes
.reduce
<number[]>(
359 (accumulator
, workerNode
) =>
360 accumulator
.concat(workerNode
.usage
.runTime
.history
),
366 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
370 this.workerNodes
.reduce
<number[]>(
371 (accumulator
, workerNode
) =>
372 accumulator
.concat(workerNode
.usage
.runTime
.history
),
380 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
381 .waitTime
.aggregate
&& {
385 ...this.workerNodes
.map(
386 workerNode
=> workerNode
.usage
.waitTime
?.minimum
?? Infinity
392 ...this.workerNodes
.map(
393 workerNode
=> workerNode
.usage
.waitTime
?.maximum
?? -Infinity
397 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
398 .waitTime
.average
&& {
401 this.workerNodes
.reduce
<number[]>(
402 (accumulator
, workerNode
) =>
403 accumulator
.concat(workerNode
.usage
.waitTime
.history
),
409 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
410 .waitTime
.median
&& {
413 this.workerNodes
.reduce
<number[]>(
414 (accumulator
, workerNode
) =>
415 accumulator
.concat(workerNode
.usage
.waitTime
.history
),
427 * The pool readiness boolean status.
429 private get
ready (): boolean {
431 this.workerNodes
.reduce(
432 (accumulator
, workerNode
) =>
433 !workerNode
.info
.dynamic
&& workerNode
.info
.ready
442 * The approximate pool utilization.
444 * @returns The pool utilization.
446 private get
utilization (): number {
447 const poolTimeCapacity
=
448 (performance
.now() - this.startTimestamp
) * this.maxSize
449 const totalTasksRunTime
= this.workerNodes
.reduce(
450 (accumulator
, workerNode
) =>
451 accumulator
+ (workerNode
.usage
.runTime
?.aggregate
?? 0),
454 const totalTasksWaitTime
= this.workerNodes
.reduce(
455 (accumulator
, workerNode
) =>
456 accumulator
+ (workerNode
.usage
.waitTime
?.aggregate
?? 0),
459 return (totalTasksRunTime
+ totalTasksWaitTime
) / poolTimeCapacity
465 * If it is `'dynamic'`, it provides the `max` property.
467 protected abstract get
type (): PoolType
472 protected abstract get
worker (): WorkerType
475 * The pool minimum size.
477 protected get
minSize (): number {
478 return this.numberOfWorkers
482 * The pool maximum size.
484 protected get
maxSize (): number {
485 return this.max
?? this.numberOfWorkers
489 * Checks if the worker id sent in the received message from a worker is valid.
491 * @param message - The received message.
492 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the worker id is invalid.
494 private checkMessageWorkerId (message
: MessageValue
<Data
| Response
>): void {
495 if (message
.workerId
== null) {
496 throw new Error('Worker message received without worker id')
498 message
.workerId
!= null &&
499 this.getWorkerNodeKeyByWorkerId(message
.workerId
) === -1
502 `Worker message received from unknown worker '${message.workerId}'`
508 * Gets the given worker its worker node key.
510 * @param worker - The worker.
511 * @returns The worker node key if found in the pool worker nodes, `-1` otherwise.
513 private getWorkerNodeKeyByWorker (worker
: Worker
): number {
514 return this.workerNodes
.findIndex(
515 workerNode
=> workerNode
.worker
=== worker
520 * Gets the worker node key given its worker id.
522 * @param workerId - The worker id.
523 * @returns The worker node key if the worker id is found in the pool worker nodes, `-1` otherwise.
525 private getWorkerNodeKeyByWorkerId (workerId
: number | undefined): number {
526 return this.workerNodes
.findIndex(
527 workerNode
=> workerNode
.info
.id
=== workerId
532 public setWorkerChoiceStrategy (
533 workerChoiceStrategy
: WorkerChoiceStrategy
,
534 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
536 checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
537 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
538 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
539 this.opts
.workerChoiceStrategy
541 if (workerChoiceStrategyOptions
!= null) {
542 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
544 for (const [workerNodeKey
, workerNode
] of this.workerNodes
.entries()) {
545 workerNode
.resetUsage()
546 this.sendStatisticsMessageToWorker(workerNodeKey
)
551 public setWorkerChoiceStrategyOptions (
552 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
554 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
555 this.opts
.workerChoiceStrategyOptions
= {
556 ...DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
,
557 ...workerChoiceStrategyOptions
559 this.workerChoiceStrategyContext
.setOptions(
560 this.opts
.workerChoiceStrategyOptions
565 public enableTasksQueue (
567 tasksQueueOptions
?: TasksQueueOptions
569 if (this.opts
.enableTasksQueue
=== true && !enable
) {
570 this.unsetTaskStealing()
571 this.unsetTasksStealingOnBackPressure()
572 this.flushTasksQueues()
574 this.opts
.enableTasksQueue
= enable
575 this.setTasksQueueOptions(tasksQueueOptions
as TasksQueueOptions
)
579 public setTasksQueueOptions (tasksQueueOptions
: TasksQueueOptions
): void {
580 if (this.opts
.enableTasksQueue
=== true) {
581 checkValidTasksQueueOptions(tasksQueueOptions
)
582 this.opts
.tasksQueueOptions
=
583 this.buildTasksQueueOptions(tasksQueueOptions
)
584 this.setTasksQueueSize(this.opts
.tasksQueueOptions
.size
as number)
585 if (this.opts
.tasksQueueOptions
.taskStealing
=== true) {
586 this.setTaskStealing()
588 this.unsetTaskStealing()
590 if (this.opts
.tasksQueueOptions
.tasksStealingOnBackPressure
=== true) {
591 this.setTasksStealingOnBackPressure()
593 this.unsetTasksStealingOnBackPressure()
595 } else if (this.opts
.tasksQueueOptions
!= null) {
596 delete this.opts
.tasksQueueOptions
600 private buildTasksQueueOptions (
601 tasksQueueOptions
: TasksQueueOptions
602 ): TasksQueueOptions
{
605 size
: Math.pow(this.maxSize
, 2),
608 tasksStealingOnBackPressure
: true
614 private setTasksQueueSize (size
: number): void {
615 for (const workerNode
of this.workerNodes
) {
616 workerNode
.tasksQueueBackPressureSize
= size
620 private setTaskStealing (): void {
621 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
622 this.workerNodes
[workerNodeKey
].onEmptyQueue
=
623 this.taskStealingOnEmptyQueue
.bind(this)
627 private unsetTaskStealing (): void {
628 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
629 delete this.workerNodes
[workerNodeKey
].onEmptyQueue
633 private setTasksStealingOnBackPressure (): void {
634 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
635 this.workerNodes
[workerNodeKey
].onBackPressure
=
636 this.tasksStealingOnBackPressure
.bind(this)
640 private unsetTasksStealingOnBackPressure (): void {
641 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
642 delete this.workerNodes
[workerNodeKey
].onBackPressure
647 * Whether the pool is full or not.
649 * The pool filling boolean status.
651 protected get
full (): boolean {
652 return this.workerNodes
.length
>= this.maxSize
656 * Whether the pool is busy or not.
658 * The pool busyness boolean status.
660 protected abstract get
busy (): boolean
663 * Whether worker nodes are executing concurrently their tasks quota or not.
665 * @returns Worker nodes busyness boolean status.
667 protected internalBusy (): boolean {
668 if (this.opts
.enableTasksQueue
=== true) {
670 this.workerNodes
.findIndex(
672 workerNode
.info
.ready
&&
673 workerNode
.usage
.tasks
.executing
<
674 (this.opts
.tasksQueueOptions
?.concurrency
as number)
679 this.workerNodes
.findIndex(
681 workerNode
.info
.ready
&& workerNode
.usage
.tasks
.executing
=== 0
686 private async sendTaskFunctionOperationToWorker (
687 workerNodeKey
: number,
688 message
: MessageValue
<Data
>
689 ): Promise
<boolean> {
690 return await new Promise
<boolean>((resolve
, reject
) => {
691 const taskFunctionOperationListener
= (
692 message
: MessageValue
<Response
>
694 this.checkMessageWorkerId(message
)
695 const workerId
= this.getWorkerInfo(workerNodeKey
).id
as number
697 message
.taskFunctionOperationStatus
!= null &&
698 message
.workerId
=== workerId
700 if (message
.taskFunctionOperationStatus
) {
702 } else if (!message
.taskFunctionOperationStatus
) {
705 `Task function operation '${
706 message.taskFunctionOperation as string
707 }' failed on worker ${message.workerId} with error: '${
708 message.workerError?.message as string
713 this.deregisterWorkerMessageListener(
714 this.getWorkerNodeKeyByWorkerId(message
.workerId
),
715 taskFunctionOperationListener
719 this.registerWorkerMessageListener(
721 taskFunctionOperationListener
723 this.sendToWorker(workerNodeKey
, message
)
727 private async sendTaskFunctionOperationToWorkers (
728 message
: MessageValue
<Data
>
729 ): Promise
<boolean> {
730 return await new Promise
<boolean>((resolve
, reject
) => {
731 const responsesReceived
= new Array<MessageValue
<Response
>>()
732 const taskFunctionOperationsListener
= (
733 message
: MessageValue
<Response
>
735 this.checkMessageWorkerId(message
)
736 if (message
.taskFunctionOperationStatus
!= null) {
737 responsesReceived
.push(message
)
738 if (responsesReceived
.length
=== this.workerNodes
.length
) {
740 responsesReceived
.every(
741 message
=> message
.taskFunctionOperationStatus
=== true
746 responsesReceived
.some(
747 message
=> message
.taskFunctionOperationStatus
=== false
750 const errorResponse
= responsesReceived
.find(
751 response
=> response
.taskFunctionOperationStatus
=== false
755 `Task function operation '${
756 message.taskFunctionOperation as string
757 }' failed on worker ${
758 errorResponse?.workerId as number
760 errorResponse?.workerError?.message as string
765 this.deregisterWorkerMessageListener(
766 this.getWorkerNodeKeyByWorkerId(message
.workerId
),
767 taskFunctionOperationsListener
772 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
773 this.registerWorkerMessageListener(
775 taskFunctionOperationsListener
777 this.sendToWorker(workerNodeKey
, message
)
783 public hasTaskFunction (name
: string): boolean {
784 for (const workerNode
of this.workerNodes
) {
786 Array.isArray(workerNode
.info
.taskFunctionNames
) &&
787 workerNode
.info
.taskFunctionNames
.includes(name
)
796 public async addTaskFunction (
798 fn
: TaskFunction
<Data
, Response
>
799 ): Promise
<boolean> {
800 if (typeof name
!== 'string') {
801 throw new TypeError('name argument must be a string')
803 if (typeof name
=== 'string' && name
.trim().length
=== 0) {
804 throw new TypeError('name argument must not be an empty string')
806 if (typeof fn
!== 'function') {
807 throw new TypeError('fn argument must be a function')
809 const opResult
= await this.sendTaskFunctionOperationToWorkers({
810 taskFunctionOperation
: 'add',
811 taskFunctionName
: name
,
812 taskFunction
: fn
.toString()
814 this.taskFunctions
.set(name
, fn
)
819 public async removeTaskFunction (name
: string): Promise
<boolean> {
820 if (!this.taskFunctions
.has(name
)) {
822 'Cannot remove a task function not handled on the pool side'
825 const opResult
= await this.sendTaskFunctionOperationToWorkers({
826 taskFunctionOperation
: 'remove',
827 taskFunctionName
: name
829 this.deleteTaskFunctionWorkerUsages(name
)
830 this.taskFunctions
.delete(name
)
835 public listTaskFunctionNames (): string[] {
836 for (const workerNode
of this.workerNodes
) {
838 Array.isArray(workerNode
.info
.taskFunctionNames
) &&
839 workerNode
.info
.taskFunctionNames
.length
> 0
841 return workerNode
.info
.taskFunctionNames
848 public async setDefaultTaskFunction (name
: string): Promise
<boolean> {
849 return await this.sendTaskFunctionOperationToWorkers({
850 taskFunctionOperation
: 'default',
851 taskFunctionName
: name
855 private deleteTaskFunctionWorkerUsages (name
: string): void {
856 for (const workerNode
of this.workerNodes
) {
857 workerNode
.deleteTaskFunctionWorkerUsage(name
)
861 private shallExecuteTask (workerNodeKey
: number): boolean {
863 this.tasksQueueSize(workerNodeKey
) === 0 &&
864 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
<
865 (this.opts
.tasksQueueOptions
?.concurrency
as number)
870 public async execute (
873 transferList
?: TransferListItem
[]
874 ): Promise
<Response
> {
875 return await new Promise
<Response
>((resolve
, reject
) => {
877 reject(new Error('Cannot execute a task on not started pool'))
880 if (name
!= null && typeof name
!== 'string') {
881 reject(new TypeError('name argument must be a string'))
886 typeof name
=== 'string' &&
887 name
.trim().length
=== 0
889 reject(new TypeError('name argument must not be an empty string'))
892 if (transferList
!= null && !Array.isArray(transferList
)) {
893 reject(new TypeError('transferList argument must be an array'))
896 const timestamp
= performance
.now()
897 const workerNodeKey
= this.chooseWorkerNode()
898 const task
: Task
<Data
> = {
899 name
: name
?? DEFAULT_TASK_NAME
,
900 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
901 data
: data
?? ({} as Data
),
906 this.promiseResponseMap
.set(task
.taskId
as string, {
912 this.opts
.enableTasksQueue
=== false ||
913 (this.opts
.enableTasksQueue
=== true &&
914 this.shallExecuteTask(workerNodeKey
))
916 this.executeTask(workerNodeKey
, task
)
918 this.enqueueTask(workerNodeKey
, task
)
924 public start (): void {
927 this.workerNodes
.reduce(
928 (accumulator
, workerNode
) =>
929 !workerNode
.info
.dynamic
? accumulator
+ 1 : accumulator
,
931 ) < this.numberOfWorkers
933 this.createAndSetupWorkerNode()
935 this.starting
= false
940 public async destroy (): Promise
<void> {
942 this.workerNodes
.map(async (_
, workerNodeKey
) => {
943 await this.destroyWorkerNode(workerNodeKey
)
946 this.emitter
?.emit(PoolEvents
.destroy
, this.info
)
947 this.emitter
?.emitDestroy()
951 protected async sendKillMessageToWorker (
952 workerNodeKey
: number
954 await new Promise
<void>((resolve
, reject
) => {
955 const killMessageListener
= (message
: MessageValue
<Response
>): void => {
956 this.checkMessageWorkerId(message
)
957 if (message
.kill
=== 'success') {
959 } else if (message
.kill
=== 'failure') {
962 `Kill message handling failed on worker ${
963 message.workerId as number
969 this.registerWorkerMessageListener(workerNodeKey
, killMessageListener
)
970 this.sendToWorker(workerNodeKey
, { kill
: true })
975 * Terminates the worker node given its worker node key.
977 * @param workerNodeKey - The worker node key.
979 protected abstract destroyWorkerNode (workerNodeKey
: number): Promise
<void>
982 * Setup hook to execute code before worker nodes are created in the abstract constructor.
987 protected setupHook (): void {
988 /* Intentionally empty */
992 * Should return whether the worker is the main worker or not.
994 protected abstract isMain (): boolean
997 * Hook executed before the worker task execution.
1000 * @param workerNodeKey - The worker node key.
1001 * @param task - The task to execute.
1003 protected beforeTaskExecutionHook (
1004 workerNodeKey
: number,
1007 if (this.workerNodes
[workerNodeKey
]?.usage
!= null) {
1008 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
1009 ++workerUsage
.tasks
.executing
1010 this.updateWaitTimeWorkerUsage(workerUsage
, task
)
1013 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
1014 this.workerNodes
[workerNodeKey
].getTaskFunctionWorkerUsage(
1018 const taskFunctionWorkerUsage
= this.workerNodes
[
1020 ].getTaskFunctionWorkerUsage(task
.name
as string) as WorkerUsage
1021 ++taskFunctionWorkerUsage
.tasks
.executing
1022 this.updateWaitTimeWorkerUsage(taskFunctionWorkerUsage
, task
)
1027 * Hook executed after the worker task execution.
1028 * Can be overridden.
1030 * @param workerNodeKey - The worker node key.
1031 * @param message - The received message.
1033 protected afterTaskExecutionHook (
1034 workerNodeKey
: number,
1035 message
: MessageValue
<Response
>
1037 if (this.workerNodes
[workerNodeKey
]?.usage
!= null) {
1038 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
1039 this.updateTaskStatisticsWorkerUsage(workerUsage
, message
)
1040 this.updateRunTimeWorkerUsage(workerUsage
, message
)
1041 this.updateEluWorkerUsage(workerUsage
, message
)
1044 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
1045 this.workerNodes
[workerNodeKey
].getTaskFunctionWorkerUsage(
1046 message
.taskPerformance
?.name
as string
1049 const taskFunctionWorkerUsage
= this.workerNodes
[
1051 ].getTaskFunctionWorkerUsage(
1052 message
.taskPerformance
?.name
as string
1054 this.updateTaskStatisticsWorkerUsage(taskFunctionWorkerUsage
, message
)
1055 this.updateRunTimeWorkerUsage(taskFunctionWorkerUsage
, message
)
1056 this.updateEluWorkerUsage(taskFunctionWorkerUsage
, message
)
1061 * Whether the worker node shall update its task function worker usage or not.
1063 * @param workerNodeKey - The worker node key.
1064 * @returns `true` if the worker node shall update its task function worker usage, `false` otherwise.
1066 private shallUpdateTaskFunctionWorkerUsage (workerNodeKey
: number): boolean {
1067 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
1069 workerInfo
!= null &&
1070 Array.isArray(workerInfo
.taskFunctionNames
) &&
1071 workerInfo
.taskFunctionNames
.length
> 2
1075 private updateTaskStatisticsWorkerUsage (
1076 workerUsage
: WorkerUsage
,
1077 message
: MessageValue
<Response
>
1079 const workerTaskStatistics
= workerUsage
.tasks
1081 workerTaskStatistics
.executing
!= null &&
1082 workerTaskStatistics
.executing
> 0
1084 --workerTaskStatistics
.executing
1086 if (message
.workerError
== null) {
1087 ++workerTaskStatistics
.executed
1089 ++workerTaskStatistics
.failed
1093 private updateRunTimeWorkerUsage (
1094 workerUsage
: WorkerUsage
,
1095 message
: MessageValue
<Response
>
1097 if (message
.workerError
!= null) {
1100 updateMeasurementStatistics(
1101 workerUsage
.runTime
,
1102 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
,
1103 message
.taskPerformance
?.runTime
?? 0
1107 private updateWaitTimeWorkerUsage (
1108 workerUsage
: WorkerUsage
,
1111 const timestamp
= performance
.now()
1112 const taskWaitTime
= timestamp
- (task
.timestamp
?? timestamp
)
1113 updateMeasurementStatistics(
1114 workerUsage
.waitTime
,
1115 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().waitTime
,
1120 private updateEluWorkerUsage (
1121 workerUsage
: WorkerUsage
,
1122 message
: MessageValue
<Response
>
1124 if (message
.workerError
!= null) {
1127 const eluTaskStatisticsRequirements
: MeasurementStatisticsRequirements
=
1128 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
1129 updateMeasurementStatistics(
1130 workerUsage
.elu
.active
,
1131 eluTaskStatisticsRequirements
,
1132 message
.taskPerformance
?.elu
?.active
?? 0
1134 updateMeasurementStatistics(
1135 workerUsage
.elu
.idle
,
1136 eluTaskStatisticsRequirements
,
1137 message
.taskPerformance
?.elu
?.idle
?? 0
1139 if (eluTaskStatisticsRequirements
.aggregate
) {
1140 if (message
.taskPerformance
?.elu
!= null) {
1141 if (workerUsage
.elu
.utilization
!= null) {
1142 workerUsage
.elu
.utilization
=
1143 (workerUsage
.elu
.utilization
+
1144 message
.taskPerformance
.elu
.utilization
) /
1147 workerUsage
.elu
.utilization
= message
.taskPerformance
.elu
.utilization
1154 * Chooses a worker node for the next task.
1156 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
1158 * @returns The chosen worker node key
1160 private chooseWorkerNode (): number {
1161 if (this.shallCreateDynamicWorker()) {
1162 const workerNodeKey
= this.createAndSetupDynamicWorkerNode()
1164 this.workerChoiceStrategyContext
.getStrategyPolicy().dynamicWorkerUsage
1166 return workerNodeKey
1169 return this.workerChoiceStrategyContext
.execute()
1173 * Conditions for dynamic worker creation.
1175 * @returns Whether to create a dynamic worker or not.
1177 private shallCreateDynamicWorker (): boolean {
1178 return this.type === PoolTypes
.dynamic
&& !this.full
&& this.internalBusy()
1182 * Sends a message to worker given its worker node key.
1184 * @param workerNodeKey - The worker node key.
1185 * @param message - The message.
1186 * @param transferList - The optional array of transferable objects.
1188 protected abstract sendToWorker (
1189 workerNodeKey
: number,
1190 message
: MessageValue
<Data
>,
1191 transferList
?: TransferListItem
[]
1195 * Creates a new worker.
1197 * @returns Newly created worker.
1199 protected abstract createWorker (): Worker
1202 * Creates a new, completely set up worker node.
1204 * @returns New, completely set up worker node key.
1206 protected createAndSetupWorkerNode (): number {
1207 const worker
= this.createWorker()
1209 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
1210 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
1211 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
1212 worker
.on('error', error
=> {
1213 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
1214 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
1215 workerInfo
.ready
= false
1216 this.workerNodes
[workerNodeKey
].closeChannel()
1217 this.emitter
?.emit(PoolEvents
.error
, error
)
1221 this.opts
.restartWorkerOnError
=== true
1223 if (workerInfo
.dynamic
) {
1224 this.createAndSetupDynamicWorkerNode()
1226 this.createAndSetupWorkerNode()
1229 if (this.started
&& this.opts
.enableTasksQueue
=== true) {
1230 this.redistributeQueuedTasks(workerNodeKey
)
1233 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
1234 worker
.once('exit', () => {
1235 this.removeWorkerNode(worker
)
1238 const workerNodeKey
= this.addWorkerNode(worker
)
1240 this.afterWorkerNodeSetup(workerNodeKey
)
1242 return workerNodeKey
1246 * Creates a new, completely set up dynamic worker node.
1248 * @returns New, completely set up dynamic worker node key.
1250 protected createAndSetupDynamicWorkerNode (): number {
1251 const workerNodeKey
= this.createAndSetupWorkerNode()
1252 this.registerWorkerMessageListener(workerNodeKey
, message
=> {
1253 this.checkMessageWorkerId(message
)
1254 const localWorkerNodeKey
= this.getWorkerNodeKeyByWorkerId(
1257 const workerUsage
= this.workerNodes
[localWorkerNodeKey
].usage
1258 // Kill message received from worker
1260 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
1261 (isKillBehavior(KillBehaviors
.SOFT
, message
.kill
) &&
1262 ((this.opts
.enableTasksQueue
=== false &&
1263 workerUsage
.tasks
.executing
=== 0) ||
1264 (this.opts
.enableTasksQueue
=== true &&
1265 workerUsage
.tasks
.executing
=== 0 &&
1266 this.tasksQueueSize(localWorkerNodeKey
) === 0)))
1268 this.destroyWorkerNode(localWorkerNodeKey
).catch(error
=> {
1269 this.emitter
?.emit(PoolEvents
.error
, error
)
1273 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
1274 this.sendToWorker(workerNodeKey
, {
1277 if (this.taskFunctions
.size
> 0) {
1278 for (const [taskFunctionName
, taskFunction
] of this.taskFunctions
) {
1279 this.sendTaskFunctionOperationToWorker(workerNodeKey
, {
1280 taskFunctionOperation
: 'add',
1282 taskFunction
: taskFunction
.toString()
1284 this.emitter
?.emit(PoolEvents
.error
, error
)
1288 workerInfo
.dynamic
= true
1290 this.workerChoiceStrategyContext
.getStrategyPolicy().dynamicWorkerReady
||
1291 this.workerChoiceStrategyContext
.getStrategyPolicy().dynamicWorkerUsage
1293 workerInfo
.ready
= true
1295 this.checkAndEmitDynamicWorkerCreationEvents()
1296 return workerNodeKey
1300 * Registers a listener callback on the worker given its worker node key.
1302 * @param workerNodeKey - The worker node key.
1303 * @param listener - The message listener callback.
1305 protected abstract registerWorkerMessageListener
<
1306 Message
extends Data
| Response
1308 workerNodeKey
: number,
1309 listener
: (message
: MessageValue
<Message
>) => void
1313 * Registers once a listener callback on the worker given its worker node key.
1315 * @param workerNodeKey - The worker node key.
1316 * @param listener - The message listener callback.
1318 protected abstract registerOnceWorkerMessageListener
<
1319 Message
extends Data
| Response
1321 workerNodeKey
: number,
1322 listener
: (message
: MessageValue
<Message
>) => void
1326 * Deregisters a listener callback on the worker given its worker node key.
1328 * @param workerNodeKey - The worker node key.
1329 * @param listener - The message listener callback.
1331 protected abstract deregisterWorkerMessageListener
<
1332 Message
extends Data
| Response
1334 workerNodeKey
: number,
1335 listener
: (message
: MessageValue
<Message
>) => void
1339 * Method hooked up after a worker node has been newly created.
1340 * Can be overridden.
1342 * @param workerNodeKey - The newly created worker node key.
1344 protected afterWorkerNodeSetup (workerNodeKey
: number): void {
1345 // Listen to worker messages.
1346 this.registerWorkerMessageListener(workerNodeKey
, this.workerListener())
1347 // Send the startup message to worker.
1348 this.sendStartupMessageToWorker(workerNodeKey
)
1349 // Send the statistics message to worker.
1350 this.sendStatisticsMessageToWorker(workerNodeKey
)
1351 if (this.opts
.enableTasksQueue
=== true) {
1352 if (this.opts
.tasksQueueOptions
?.taskStealing
=== true) {
1353 this.workerNodes
[workerNodeKey
].onEmptyQueue
=
1354 this.taskStealingOnEmptyQueue
.bind(this)
1356 if (this.opts
.tasksQueueOptions
?.tasksStealingOnBackPressure
=== true) {
1357 this.workerNodes
[workerNodeKey
].onBackPressure
=
1358 this.tasksStealingOnBackPressure
.bind(this)
1364 * Sends the startup message to worker given its worker node key.
1366 * @param workerNodeKey - The worker node key.
1368 protected abstract sendStartupMessageToWorker (workerNodeKey
: number): void
1371 * Sends the statistics message to worker given its worker node key.
1373 * @param workerNodeKey - The worker node key.
1375 private sendStatisticsMessageToWorker (workerNodeKey
: number): void {
1376 this.sendToWorker(workerNodeKey
, {
1379 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1381 elu
: this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1387 private redistributeQueuedTasks (workerNodeKey
: number): void {
1388 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1389 const destinationWorkerNodeKey
= this.workerNodes
.reduce(
1390 (minWorkerNodeKey
, workerNode
, workerNodeKey
, workerNodes
) => {
1391 return workerNode
.info
.ready
&&
1392 workerNode
.usage
.tasks
.queued
<
1393 workerNodes
[minWorkerNodeKey
].usage
.tasks
.queued
1399 const task
= this.dequeueTask(workerNodeKey
) as Task
<Data
>
1400 if (this.shallExecuteTask(destinationWorkerNodeKey
)) {
1401 this.executeTask(destinationWorkerNodeKey
, task
)
1403 this.enqueueTask(destinationWorkerNodeKey
, task
)
1408 private updateTaskStolenStatisticsWorkerUsage (
1409 workerNodeKey
: number,
1412 const workerNode
= this.workerNodes
[workerNodeKey
]
1413 if (workerNode
?.usage
!= null) {
1414 ++workerNode
.usage
.tasks
.stolen
1417 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
1418 workerNode
.getTaskFunctionWorkerUsage(taskName
) != null
1420 const taskFunctionWorkerUsage
= workerNode
.getTaskFunctionWorkerUsage(
1423 ++taskFunctionWorkerUsage
.tasks
.stolen
1427 private taskStealingOnEmptyQueue (workerId
: number): void {
1428 const destinationWorkerNodeKey
= this.getWorkerNodeKeyByWorkerId(workerId
)
1429 const workerNodes
= this.workerNodes
1432 (workerNodeA
, workerNodeB
) =>
1433 workerNodeB
.usage
.tasks
.queued
- workerNodeA
.usage
.tasks
.queued
1435 const sourceWorkerNode
= workerNodes
.find(
1437 workerNode
.info
.ready
&&
1438 workerNode
.info
.id
!== workerId
&&
1439 workerNode
.usage
.tasks
.queued
> 0
1441 if (sourceWorkerNode
!= null) {
1442 const task
= sourceWorkerNode
.popTask() as Task
<Data
>
1443 if (this.shallExecuteTask(destinationWorkerNodeKey
)) {
1444 this.executeTask(destinationWorkerNodeKey
, task
)
1446 this.enqueueTask(destinationWorkerNodeKey
, task
)
1448 this.updateTaskStolenStatisticsWorkerUsage(
1449 destinationWorkerNodeKey
,
1455 private tasksStealingOnBackPressure (workerId
: number): void {
1456 const sizeOffset
= 1
1457 if ((this.opts
.tasksQueueOptions
?.size
as number) <= sizeOffset
) {
1460 const sourceWorkerNode
=
1461 this.workerNodes
[this.getWorkerNodeKeyByWorkerId(workerId
)]
1462 const workerNodes
= this.workerNodes
1465 (workerNodeA
, workerNodeB
) =>
1466 workerNodeA
.usage
.tasks
.queued
- workerNodeB
.usage
.tasks
.queued
1468 for (const [workerNodeKey
, workerNode
] of workerNodes
.entries()) {
1470 sourceWorkerNode
.usage
.tasks
.queued
> 0 &&
1471 workerNode
.info
.ready
&&
1472 workerNode
.info
.id
!== workerId
&&
1473 workerNode
.usage
.tasks
.queued
<
1474 (this.opts
.tasksQueueOptions
?.size
as number) - sizeOffset
1476 const task
= sourceWorkerNode
.popTask() as Task
<Data
>
1477 if (this.shallExecuteTask(workerNodeKey
)) {
1478 this.executeTask(workerNodeKey
, task
)
1480 this.enqueueTask(workerNodeKey
, task
)
1482 this.updateTaskStolenStatisticsWorkerUsage(
1491 * This method is the listener registered for each worker message.
1493 * @returns The listener function to execute when a message is received from a worker.
1495 protected workerListener (): (message
: MessageValue
<Response
>) => void {
1497 this.checkMessageWorkerId(message
)
1498 if (message
.ready
!= null && message
.taskFunctionNames
!= null) {
1499 // Worker ready response received from worker
1500 this.handleWorkerReadyResponse(message
)
1501 } else if (message
.taskId
!= null) {
1502 // Task execution response received from worker
1503 this.handleTaskExecutionResponse(message
)
1504 } else if (message
.taskFunctionNames
!= null) {
1505 // Task function names message received from worker
1507 this.getWorkerNodeKeyByWorkerId(message
.workerId
)
1508 ).taskFunctionNames
= message
.taskFunctionNames
1513 private handleWorkerReadyResponse (message
: MessageValue
<Response
>): void {
1514 if (message
.ready
=== false) {
1516 `Worker ${message.workerId as number} failed to initialize`
1519 const workerInfo
= this.getWorkerInfo(
1520 this.getWorkerNodeKeyByWorkerId(message
.workerId
)
1522 workerInfo
.ready
= message
.ready
as boolean
1523 workerInfo
.taskFunctionNames
= message
.taskFunctionNames
1525 this.emitter
?.emit(PoolEvents
.ready
, this.info
)
1529 private handleTaskExecutionResponse (message
: MessageValue
<Response
>): void {
1530 const { taskId
, workerError
, data
} = message
1531 const promiseResponse
= this.promiseResponseMap
.get(taskId
as string)
1532 if (promiseResponse
!= null) {
1533 if (workerError
!= null) {
1534 this.emitter
?.emit(PoolEvents
.taskError
, workerError
)
1535 promiseResponse
.reject(workerError
.message
)
1537 promiseResponse
.resolve(data
as Response
)
1539 const workerNodeKey
= promiseResponse
.workerNodeKey
1540 this.afterTaskExecutionHook(workerNodeKey
, message
)
1541 this.workerChoiceStrategyContext
.update(workerNodeKey
)
1542 this.promiseResponseMap
.delete(taskId
as string)
1544 this.opts
.enableTasksQueue
=== true &&
1545 this.tasksQueueSize(workerNodeKey
) > 0 &&
1546 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
<
1547 (this.opts
.tasksQueueOptions
?.concurrency
as number)
1551 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1557 private checkAndEmitTaskExecutionEvents (): void {
1559 this.emitter
?.emit(PoolEvents
.busy
, this.info
)
1563 private checkAndEmitTaskQueuingEvents (): void {
1564 if (this.hasBackPressure()) {
1565 this.emitter
?.emit(PoolEvents
.backPressure
, this.info
)
1569 private checkAndEmitDynamicWorkerCreationEvents (): void {
1570 if (this.type === PoolTypes
.dynamic
) {
1572 this.emitter
?.emit(PoolEvents
.full
, this.info
)
1578 * Gets the worker information given its worker node key.
1580 * @param workerNodeKey - The worker node key.
1581 * @returns The worker information.
1583 protected getWorkerInfo (workerNodeKey
: number): WorkerInfo
{
1584 return this.workerNodes
[workerNodeKey
].info
1588 * Adds the given worker in the pool worker nodes.
1590 * @param worker - The worker.
1591 * @returns The added worker node key.
1592 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the added worker node is not found.
1594 private addWorkerNode (worker
: Worker
): number {
1595 const workerNode
= new WorkerNode
<Worker
, Data
>(
1597 this.opts
.tasksQueueOptions
?.size
?? Math.pow(this.maxSize
, 2)
1599 // Flag the worker node as ready at pool startup.
1600 if (this.starting
) {
1601 workerNode
.info
.ready
= true
1603 this.workerNodes
.push(workerNode
)
1604 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
1605 if (workerNodeKey
=== -1) {
1606 throw new Error('Worker added not found in worker nodes')
1608 return workerNodeKey
1612 * Removes the given worker from the pool worker nodes.
1614 * @param worker - The worker.
1616 private removeWorkerNode (worker
: Worker
): void {
1617 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
1618 if (workerNodeKey
!== -1) {
1619 this.workerNodes
.splice(workerNodeKey
, 1)
1620 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
1625 public hasWorkerNodeBackPressure (workerNodeKey
: number): boolean {
1627 this.opts
.enableTasksQueue
=== true &&
1628 this.workerNodes
[workerNodeKey
].hasBackPressure()
1632 private hasBackPressure (): boolean {
1634 this.opts
.enableTasksQueue
=== true &&
1635 this.workerNodes
.findIndex(
1636 workerNode
=> !workerNode
.hasBackPressure()
1642 * Executes the given task on the worker given its worker node key.
1644 * @param workerNodeKey - The worker node key.
1645 * @param task - The task to execute.
1647 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
1648 this.beforeTaskExecutionHook(workerNodeKey
, task
)
1649 this.sendToWorker(workerNodeKey
, task
, task
.transferList
)
1650 this.checkAndEmitTaskExecutionEvents()
1653 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
1654 const tasksQueueSize
= this.workerNodes
[workerNodeKey
].enqueueTask(task
)
1655 this.checkAndEmitTaskQueuingEvents()
1656 return tasksQueueSize
1659 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
1660 return this.workerNodes
[workerNodeKey
].dequeueTask()
1663 private tasksQueueSize (workerNodeKey
: number): number {
1664 return this.workerNodes
[workerNodeKey
].tasksQueueSize()
1667 protected flushTasksQueue (workerNodeKey
: number): void {
1668 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1671 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1674 this.workerNodes
[workerNodeKey
].clearTasksQueue()
1677 private flushTasksQueues (): void {
1678 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
1679 this.flushTasksQueue(workerNodeKey
)