1 import crypto from
'node:crypto'
2 import { performance
} from
'node:perf_hooks'
3 import type { MessageValue
, PromiseResponseWrapper
} from
'../utility-types'
5 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
,
10 import { KillBehaviors
, isKillBehavior
} from
'../worker/worker-options'
11 import { CircularArray
} from
'../circular-array'
12 import { Queue
} from
'../queue'
21 type TasksQueueOptions
,
32 WorkerChoiceStrategies
,
33 type WorkerChoiceStrategy
,
34 type WorkerChoiceStrategyOptions
35 } from
'./selection-strategies/selection-strategies-types'
36 import { WorkerChoiceStrategyContext
} from
'./selection-strategies/worker-choice-strategy-context'
39 * Base class that implements some shared logic for all poolifier pools.
41 * @typeParam Worker - Type of worker which manages this pool.
42 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
43 * @typeParam Response - Type of execution response. This can only be serializable data.
45 export abstract class AbstractPool
<
46 Worker
extends IWorker
,
49 > implements IPool
<Worker
, Data
, Response
> {
51 public readonly workerNodes
: Array<WorkerNode
<Worker
, Data
>> = []
54 public readonly emitter
?: PoolEmitter
57 * The execution response promise map.
59 * - `key`: The message id of each submitted task.
60 * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks.
62 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
64 protected promiseResponseMap
: Map
<
66 PromiseResponseWrapper
<Worker
, Response
>
67 > = new Map
<string, PromiseResponseWrapper
<Worker
, Response
>>()
70 * Worker choice strategy context referencing a worker choice algorithm implementation.
72 protected workerChoiceStrategyContext
: WorkerChoiceStrategyContext
<
79 * Constructs a new poolifier pool.
81 * @param numberOfWorkers - Number of workers that this pool should manage.
82 * @param filePath - Path to the worker file.
83 * @param opts - Options for the pool.
86 protected readonly numberOfWorkers
: number,
87 protected readonly filePath
: string,
88 protected readonly opts
: PoolOptions
<Worker
>
91 throw new Error('Cannot start a pool from a worker!')
93 this.checkNumberOfWorkers(this.numberOfWorkers
)
94 this.checkFilePath(this.filePath
)
95 this.checkPoolOptions(this.opts
)
97 this.chooseWorkerNode
= this.chooseWorkerNode
.bind(this)
98 this.executeTask
= this.executeTask
.bind(this)
99 this.enqueueTask
= this.enqueueTask
.bind(this)
100 this.checkAndEmitEvents
= this.checkAndEmitEvents
.bind(this)
102 if (this.opts
.enableEvents
=== true) {
103 this.emitter
= new PoolEmitter()
105 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext
<
111 this.opts
.workerChoiceStrategy
,
112 this.opts
.workerChoiceStrategyOptions
117 for (let i
= 1; i
<= this.numberOfWorkers
; i
++) {
118 this.createAndSetupWorker()
122 private checkFilePath (filePath
: string): void {
125 (typeof filePath
=== 'string' && filePath
.trim().length
=== 0)
127 throw new Error('Please specify a file with a worker implementation')
131 private checkNumberOfWorkers (numberOfWorkers
: number): void {
132 if (numberOfWorkers
== null) {
134 'Cannot instantiate a pool without specifying the number of workers'
136 } else if (!Number.isSafeInteger(numberOfWorkers
)) {
138 'Cannot instantiate a pool with a non safe integer number of workers'
140 } else if (numberOfWorkers
< 0) {
141 throw new RangeError(
142 'Cannot instantiate a pool with a negative number of workers'
144 } else if (this.type === PoolTypes
.fixed
&& numberOfWorkers
=== 0) {
145 throw new Error('Cannot instantiate a fixed pool with no worker')
149 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
150 if (isPlainObject(opts
)) {
151 this.opts
.workerChoiceStrategy
=
152 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
153 this.checkValidWorkerChoiceStrategy(this.opts
.workerChoiceStrategy
)
154 this.opts
.workerChoiceStrategyOptions
=
155 opts
.workerChoiceStrategyOptions
??
156 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
157 this.checkValidWorkerChoiceStrategyOptions(
158 this.opts
.workerChoiceStrategyOptions
160 this.opts
.restartWorkerOnError
= opts
.restartWorkerOnError
?? true
161 this.opts
.enableEvents
= opts
.enableEvents
?? true
162 this.opts
.enableTasksQueue
= opts
.enableTasksQueue
?? false
163 if (this.opts
.enableTasksQueue
) {
164 this.checkValidTasksQueueOptions(
165 opts
.tasksQueueOptions
as TasksQueueOptions
167 this.opts
.tasksQueueOptions
= this.buildTasksQueueOptions(
168 opts
.tasksQueueOptions
as TasksQueueOptions
172 throw new TypeError('Invalid pool options: must be a plain object')
176 private checkValidWorkerChoiceStrategy (
177 workerChoiceStrategy
: WorkerChoiceStrategy
179 if (!Object.values(WorkerChoiceStrategies
).includes(workerChoiceStrategy
)) {
181 `Invalid worker choice strategy '${workerChoiceStrategy}'`
186 private checkValidWorkerChoiceStrategyOptions (
187 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
189 if (!isPlainObject(workerChoiceStrategyOptions
)) {
191 'Invalid worker choice strategy options: must be a plain object'
195 workerChoiceStrategyOptions
.weights
!= null &&
196 Object.keys(workerChoiceStrategyOptions
.weights
).length
!== this.maxSize
199 'Invalid worker choice strategy options: must have a weight for each worker node'
204 private checkValidTasksQueueOptions (
205 tasksQueueOptions
: TasksQueueOptions
207 if (tasksQueueOptions
!= null && !isPlainObject(tasksQueueOptions
)) {
208 throw new TypeError('Invalid tasks queue options: must be a plain object')
210 if ((tasksQueueOptions
?.concurrency
as number) <= 0) {
212 `Invalid worker tasks concurrency '${
213 tasksQueueOptions.concurrency as number
220 public get
info (): PoolInfo
{
224 minSize
: this.minSize
,
225 maxSize
: this.maxSize
,
226 workerNodes
: this.workerNodes
.length
,
227 idleWorkerNodes
: this.workerNodes
.reduce(
228 (accumulator
, workerNode
) =>
229 workerNode
.workerUsage
.tasks
.executing
=== 0
234 busyWorkerNodes
: this.workerNodes
.reduce(
235 (accumulator
, workerNode
) =>
236 workerNode
.workerUsage
.tasks
.executing
> 0
241 executedTasks
: this.workerNodes
.reduce(
242 (accumulator
, workerNode
) =>
243 accumulator
+ workerNode
.workerUsage
.tasks
.executed
,
246 executingTasks
: this.workerNodes
.reduce(
247 (accumulator
, workerNode
) =>
248 accumulator
+ workerNode
.workerUsage
.tasks
.executing
,
251 queuedTasks
: this.workerNodes
.reduce(
252 (accumulator
, workerNode
) => accumulator
+ workerNode
.tasksQueue
.size
,
255 maxQueuedTasks
: this.workerNodes
.reduce(
256 (accumulator
, workerNode
) =>
257 accumulator
+ workerNode
.tasksQueue
.maxSize
,
260 failedTasks
: this.workerNodes
.reduce(
261 (accumulator
, workerNode
) =>
262 accumulator
+ workerNode
.workerUsage
.tasks
.failed
,
271 * If it is `'dynamic'`, it provides the `max` property.
273 protected abstract get
type (): PoolType
276 * Gets the worker type.
278 protected abstract get
worker (): WorkerType
283 protected abstract get
minSize (): number
288 protected abstract get
maxSize (): number
291 * Gets the given worker its worker node key.
293 * @param worker - The worker.
294 * @returns The worker node key if the worker is found in the pool worker nodes, `-1` otherwise.
296 private getWorkerNodeKey (worker
: Worker
): number {
297 return this.workerNodes
.findIndex(
298 workerNode
=> workerNode
.worker
=== worker
303 public setWorkerChoiceStrategy (
304 workerChoiceStrategy
: WorkerChoiceStrategy
,
305 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
307 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
308 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
309 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
310 this.opts
.workerChoiceStrategy
312 if (workerChoiceStrategyOptions
!= null) {
313 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
315 for (const workerNode
of this.workerNodes
) {
316 this.setWorkerNodeTasksUsage(
318 this.getWorkerUsage(workerNode
.worker
)
320 this.setWorkerStatistics(workerNode
.worker
)
325 public setWorkerChoiceStrategyOptions (
326 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
328 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
329 this.opts
.workerChoiceStrategyOptions
= workerChoiceStrategyOptions
330 this.workerChoiceStrategyContext
.setOptions(
331 this.opts
.workerChoiceStrategyOptions
336 public enableTasksQueue (
338 tasksQueueOptions
?: TasksQueueOptions
340 if (this.opts
.enableTasksQueue
=== true && !enable
) {
341 this.flushTasksQueues()
343 this.opts
.enableTasksQueue
= enable
344 this.setTasksQueueOptions(tasksQueueOptions
as TasksQueueOptions
)
348 public setTasksQueueOptions (tasksQueueOptions
: TasksQueueOptions
): void {
349 if (this.opts
.enableTasksQueue
=== true) {
350 this.checkValidTasksQueueOptions(tasksQueueOptions
)
351 this.opts
.tasksQueueOptions
=
352 this.buildTasksQueueOptions(tasksQueueOptions
)
353 } else if (this.opts
.tasksQueueOptions
!= null) {
354 delete this.opts
.tasksQueueOptions
358 private buildTasksQueueOptions (
359 tasksQueueOptions
: TasksQueueOptions
360 ): TasksQueueOptions
{
362 concurrency
: tasksQueueOptions
?.concurrency
?? 1
367 * Whether the pool is full or not.
369 * The pool filling boolean status.
371 protected get
full (): boolean {
372 return this.workerNodes
.length
>= this.maxSize
376 * Whether the pool is busy or not.
378 * The pool busyness boolean status.
380 protected abstract get
busy (): boolean
383 * Whether worker nodes are executing at least one task.
385 * @returns Worker nodes busyness boolean status.
387 protected internalBusy (): boolean {
389 this.workerNodes
.findIndex(workerNode
=> {
390 return workerNode
.workerUsage
.tasks
.executing
=== 0
396 public async execute (data
?: Data
, name
?: string): Promise
<Response
> {
397 const timestamp
= performance
.now()
398 const workerNodeKey
= this.chooseWorkerNode()
399 const submittedTask
: Task
<Data
> = {
401 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
402 data
: data
?? ({} as Data
),
404 id
: crypto
.randomUUID()
406 const res
= new Promise
<Response
>((resolve
, reject
) => {
407 this.promiseResponseMap
.set(submittedTask
.id
as string, {
410 worker
: this.workerNodes
[workerNodeKey
].worker
414 this.opts
.enableTasksQueue
=== true &&
416 this.workerNodes
[workerNodeKey
].workerUsage
.tasks
.executing
>=
417 ((this.opts
.tasksQueueOptions
as TasksQueueOptions
)
418 .concurrency
as number))
420 this.enqueueTask(workerNodeKey
, submittedTask
)
422 this.executeTask(workerNodeKey
, submittedTask
)
424 this.workerChoiceStrategyContext
.update(workerNodeKey
)
425 this.checkAndEmitEvents()
426 // eslint-disable-next-line @typescript-eslint/return-await
431 public async destroy (): Promise
<void> {
433 this.workerNodes
.map(async (workerNode
, workerNodeKey
) => {
434 this.flushTasksQueue(workerNodeKey
)
435 // FIXME: wait for tasks to be finished
436 await this.destroyWorker(workerNode
.worker
)
442 * Terminates the given worker.
444 * @param worker - A worker within `workerNodes`.
446 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
449 * Setup hook to execute code before worker node are created in the abstract constructor.
454 protected setupHook (): void {
455 // Intentionally empty
459 * Should return whether the worker is the main worker or not.
461 protected abstract isMain (): boolean
464 * Hook executed before the worker task execution.
467 * @param workerNodeKey - The worker node key.
468 * @param task - The task to execute.
470 protected beforeTaskExecutionHook (
471 workerNodeKey
: number,
474 const workerUsage
= this.workerNodes
[workerNodeKey
].workerUsage
475 ++workerUsage
.tasks
.executing
476 this.updateWaitTimeWorkerUsage(workerUsage
, task
)
480 * Hook executed after the worker task execution.
483 * @param worker - The worker.
484 * @param message - The received message.
486 protected afterTaskExecutionHook (
488 message
: MessageValue
<Response
>
491 this.workerNodes
[this.getWorkerNodeKey(worker
)].workerUsage
492 this.updateTaskStatisticsWorkerUsage(workerUsage
, message
)
493 this.updateRunTimeWorkerUsage(workerUsage
, message
)
494 this.updateEluWorkerUsage(workerUsage
, message
)
497 private updateTaskStatisticsWorkerUsage (
498 workerUsage
: WorkerUsage
,
499 message
: MessageValue
<Response
>
501 const workerTaskStatistics
= workerUsage
.tasks
502 --workerTaskStatistics
.executing
503 ++workerTaskStatistics
.executed
504 if (message
.taskError
!= null) {
505 ++workerTaskStatistics
.failed
509 private updateRunTimeWorkerUsage (
510 workerUsage
: WorkerUsage
,
511 message
: MessageValue
<Response
>
514 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
517 workerUsage
.runTime
.aggregate
+= message
.taskPerformance
?.runTime
?? 0
519 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
521 workerUsage
.tasks
.executed
!== 0
523 workerUsage
.runTime
.average
=
524 workerUsage
.runTime
.aggregate
/
525 (workerUsage
.tasks
.executed
- workerUsage
.tasks
.failed
)
528 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
530 message
.taskPerformance
?.runTime
!= null
532 workerUsage
.runTime
.history
.push(message
.taskPerformance
.runTime
)
533 workerUsage
.runTime
.median
= median(workerUsage
.runTime
.history
)
538 private updateWaitTimeWorkerUsage (
539 workerUsage
: WorkerUsage
,
542 const timestamp
= performance
.now()
543 const taskWaitTime
= timestamp
- (task
.timestamp
?? timestamp
)
545 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().waitTime
548 workerUsage
.waitTime
.aggregate
+= taskWaitTime
?? 0
550 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
552 workerUsage
.tasks
.executed
!== 0
554 workerUsage
.waitTime
.average
=
555 workerUsage
.waitTime
.aggregate
/
556 (workerUsage
.tasks
.executed
- workerUsage
.tasks
.failed
)
559 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
563 workerUsage
.waitTime
.history
.push(taskWaitTime
)
564 workerUsage
.waitTime
.median
= median(workerUsage
.waitTime
.history
)
569 private updateEluWorkerUsage (
570 workerUsage
: WorkerUsage
,
571 message
: MessageValue
<Response
>
574 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
577 if (workerUsage
.elu
!= null && message
.taskPerformance
?.elu
!= null) {
578 workerUsage
.elu
.idle
.aggregate
+= message
.taskPerformance
.elu
.idle
579 workerUsage
.elu
.active
.aggregate
+= message
.taskPerformance
.elu
.active
580 workerUsage
.elu
.utilization
=
581 (workerUsage
.elu
.utilization
+
582 message
.taskPerformance
.elu
.utilization
) /
584 } else if (message
.taskPerformance
?.elu
!= null) {
585 workerUsage
.elu
.idle
.aggregate
= message
.taskPerformance
.elu
.idle
586 workerUsage
.elu
.active
.aggregate
= message
.taskPerformance
.elu
.active
587 workerUsage
.elu
.utilization
= message
.taskPerformance
.elu
.utilization
590 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
592 workerUsage
.tasks
.executed
!== 0
594 const executedTasks
=
595 workerUsage
.tasks
.executed
- workerUsage
.tasks
.failed
596 workerUsage
.elu
.idle
.average
=
597 workerUsage
.elu
.idle
.aggregate
/ executedTasks
598 workerUsage
.elu
.active
.average
=
599 workerUsage
.elu
.active
.aggregate
/ executedTasks
602 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
604 message
.taskPerformance
?.elu
!= null
606 workerUsage
.elu
.idle
.history
.push(message
.taskPerformance
.elu
.idle
)
607 workerUsage
.elu
.active
.history
.push(message
.taskPerformance
.elu
.active
)
608 workerUsage
.elu
.idle
.median
= median(workerUsage
.elu
.idle
.history
)
609 workerUsage
.elu
.active
.median
= median(workerUsage
.elu
.active
.history
)
615 * Chooses a worker node for the next task.
617 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
619 * @returns The worker node key
621 private chooseWorkerNode (): number {
622 if (this.shallCreateDynamicWorker()) {
623 const worker
= this.createAndSetupDynamicWorker()
625 this.workerChoiceStrategyContext
.getStrategyPolicy().useDynamicWorker
627 return this.getWorkerNodeKey(worker
)
630 return this.workerChoiceStrategyContext
.execute()
634 * Conditions for dynamic worker creation.
636 * @returns Whether to create a dynamic worker or not.
638 private shallCreateDynamicWorker (): boolean {
639 return this.type === PoolTypes
.dynamic
&& !this.full
&& this.internalBusy()
643 * Sends a message to the given worker.
645 * @param worker - The worker which should receive the message.
646 * @param message - The message.
648 protected abstract sendToWorker (
650 message
: MessageValue
<Data
>
654 * Registers a listener callback on the given worker.
656 * @param worker - The worker which should register a listener.
657 * @param listener - The message listener callback.
659 protected abstract registerWorkerMessageListener
<
660 Message
extends Data
| Response
661 >(worker
: Worker
, listener
: (message
: MessageValue
<Message
>) => void): void
664 * Creates a new worker.
666 * @returns Newly created worker.
668 protected abstract createWorker (): Worker
671 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
673 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
675 * @param worker - The newly created worker.
677 protected abstract afterWorkerSetup (worker
: Worker
): void
680 * Creates a new worker and sets it up completely in the pool worker nodes.
682 * @returns New, completely set up worker.
684 protected createAndSetupWorker (): Worker
{
685 const worker
= this.createWorker()
687 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
688 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
689 worker
.on('error', error
=> {
690 if (this.emitter
!= null) {
691 this.emitter
.emit(PoolEvents
.error
, error
)
693 if (this.opts
.restartWorkerOnError
=== true) {
694 this.createAndSetupWorker()
697 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
698 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
699 worker
.once('exit', () => {
700 this.removeWorkerNode(worker
)
703 this.pushWorkerNode(worker
)
705 this.setWorkerStatistics(worker
)
707 this.afterWorkerSetup(worker
)
713 * Creates a new dynamic worker and sets it up completely in the pool worker nodes.
715 * @returns New, completely set up dynamic worker.
717 protected createAndSetupDynamicWorker (): Worker
{
718 const worker
= this.createAndSetupWorker()
719 this.registerWorkerMessageListener(worker
, message
=> {
720 const currentWorkerNodeKey
= this.getWorkerNodeKey(worker
)
722 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
723 (message
.kill
!= null &&
724 ((this.opts
.enableTasksQueue
=== false &&
725 this.workerNodes
[currentWorkerNodeKey
].workerUsage
.tasks
727 (this.opts
.enableTasksQueue
=== true &&
728 this.workerNodes
[currentWorkerNodeKey
].workerUsage
.tasks
730 this.tasksQueueSize(currentWorkerNodeKey
) === 0)))
732 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
733 void (this.destroyWorker(worker
) as Promise
<void>)
740 * This function is the listener registered for each worker message.
742 * @returns The listener function to execute when a message is received from a worker.
744 protected workerListener (): (message
: MessageValue
<Response
>) => void {
746 if (message
.id
!= null) {
747 // Task execution response received
748 const promiseResponse
= this.promiseResponseMap
.get(message
.id
)
749 if (promiseResponse
!= null) {
750 if (message
.taskError
!= null) {
751 promiseResponse
.reject(message
.taskError
.message
)
752 if (this.emitter
!= null) {
753 this.emitter
.emit(PoolEvents
.taskError
, message
.taskError
)
756 promiseResponse
.resolve(message
.data
as Response
)
758 this.afterTaskExecutionHook(promiseResponse
.worker
, message
)
759 this.promiseResponseMap
.delete(message
.id
)
760 const workerNodeKey
= this.getWorkerNodeKey(promiseResponse
.worker
)
762 this.opts
.enableTasksQueue
=== true &&
763 this.tasksQueueSize(workerNodeKey
) > 0
767 this.dequeueTask(workerNodeKey
) as Task
<Data
>
769 this.workerChoiceStrategyContext
.update(workerNodeKey
)
776 private checkAndEmitEvents (): void {
777 if (this.emitter
!= null) {
779 this.emitter
?.emit(PoolEvents
.busy
, this.info
)
781 if (this.type === PoolTypes
.dynamic
&& this.full
) {
782 this.emitter
?.emit(PoolEvents
.full
, this.info
)
788 * Sets the given worker node its tasks usage in the pool.
790 * @param workerNode - The worker node.
791 * @param workerUsage - The worker usage.
793 private setWorkerNodeTasksUsage (
794 workerNode
: WorkerNode
<Worker
, Data
>,
795 workerUsage
: WorkerUsage
797 workerNode
.workerUsage
= workerUsage
801 * Pushes the given worker in the pool worker nodes.
803 * @param worker - The worker.
804 * @returns The worker nodes length.
806 private pushWorkerNode (worker
: Worker
): number {
807 return this.workerNodes
.push({
809 workerUsage
: this.getWorkerUsage(worker
),
810 tasksQueue
: new Queue
<Task
<Data
>>()
815 // * Sets the given worker in the pool worker nodes.
817 // * @param workerNodeKey - The worker node key.
818 // * @param worker - The worker.
819 // * @param workerUsage - The worker usage.
820 // * @param tasksQueue - The worker task queue.
822 // private setWorkerNode (
823 // workerNodeKey: number,
825 // workerUsage: WorkerUsage,
826 // tasksQueue: Queue<Task<Data>>
828 // this.workerNodes[workerNodeKey] = {
836 * Removes the given worker from the pool worker nodes.
838 * @param worker - The worker.
840 private removeWorkerNode (worker
: Worker
): void {
841 const workerNodeKey
= this.getWorkerNodeKey(worker
)
842 if (workerNodeKey
!== -1) {
843 this.workerNodes
.splice(workerNodeKey
, 1)
844 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
848 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
849 this.beforeTaskExecutionHook(workerNodeKey
, task
)
850 this.sendToWorker(this.workerNodes
[workerNodeKey
].worker
, task
)
853 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
854 return this.workerNodes
[workerNodeKey
].tasksQueue
.enqueue(task
)
857 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
858 return this.workerNodes
[workerNodeKey
].tasksQueue
.dequeue()
861 private tasksQueueSize (workerNodeKey
: number): number {
862 return this.workerNodes
[workerNodeKey
].tasksQueue
.size
865 private flushTasksQueue (workerNodeKey
: number): void {
866 if (this.tasksQueueSize(workerNodeKey
) > 0) {
867 for (let i
= 0; i
< this.tasksQueueSize(workerNodeKey
); i
++) {
870 this.dequeueTask(workerNodeKey
) as Task
<Data
>
876 private flushTasksQueues (): void {
877 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
878 this.flushTasksQueue(workerNodeKey
)
882 private setWorkerStatistics (worker
: Worker
): void {
883 this.sendToWorker(worker
, {
886 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
888 elu
: this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
894 private getWorkerUsage (worker
: Worker
): WorkerUsage
{
896 tasks
: this.getTaskStatistics(worker
),
901 history
: new CircularArray()
907 history
: new CircularArray()
914 history
: new CircularArray()
920 history
: new CircularArray()
927 private getTaskStatistics (worker
: Worker
): TaskStatistics
{
929 this.workerNodes
[this.getWorkerNodeKey(worker
)]?.tasksQueue
?.size
933 get
queued (): number {
934 return queueSize
?? 0