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
,
33 WorkerChoiceStrategies
,
34 type WorkerChoiceStrategy
,
35 type WorkerChoiceStrategyOptions
36 } from
'./selection-strategies/selection-strategies-types'
37 import { WorkerChoiceStrategyContext
} from
'./selection-strategies/worker-choice-strategy-context'
40 * Base class that implements some shared logic for all poolifier pools.
42 * @typeParam Worker - Type of worker which manages this pool.
43 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
44 * @typeParam Response - Type of execution response. This can only be serializable data.
46 export abstract class AbstractPool
<
47 Worker
extends IWorker
,
50 > implements IPool
<Worker
, Data
, Response
> {
52 public readonly workerNodes
: Array<WorkerNode
<Worker
, Data
>> = []
55 public readonly emitter
?: PoolEmitter
58 * The execution response promise map.
60 * - `key`: The message id of each submitted task.
61 * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks.
63 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
65 protected promiseResponseMap
: Map
<
67 PromiseResponseWrapper
<Worker
, Response
>
68 > = new Map
<string, PromiseResponseWrapper
<Worker
, Response
>>()
71 * Worker choice strategy context referencing a worker choice algorithm implementation.
73 protected workerChoiceStrategyContext
: WorkerChoiceStrategyContext
<
80 * Constructs a new poolifier pool.
82 * @param numberOfWorkers - Number of workers that this pool should manage.
83 * @param filePath - Path to the worker file.
84 * @param opts - Options for the pool.
87 protected readonly numberOfWorkers
: number,
88 protected readonly filePath
: string,
89 protected readonly opts
: PoolOptions
<Worker
>
92 throw new Error('Cannot start a pool from a worker!')
94 this.checkNumberOfWorkers(this.numberOfWorkers
)
95 this.checkFilePath(this.filePath
)
96 this.checkPoolOptions(this.opts
)
98 this.chooseWorkerNode
= this.chooseWorkerNode
.bind(this)
99 this.executeTask
= this.executeTask
.bind(this)
100 this.enqueueTask
= this.enqueueTask
.bind(this)
101 this.checkAndEmitEvents
= this.checkAndEmitEvents
.bind(this)
103 if (this.opts
.enableEvents
=== true) {
104 this.emitter
= new PoolEmitter()
106 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext
<
112 this.opts
.workerChoiceStrategy
,
113 this.opts
.workerChoiceStrategyOptions
118 for (let i
= 1; i
<= this.numberOfWorkers
; i
++) {
119 this.createAndSetupWorker()
123 private checkFilePath (filePath
: string): void {
126 (typeof filePath
=== 'string' && filePath
.trim().length
=== 0)
128 throw new Error('Please specify a file with a worker implementation')
132 private checkNumberOfWorkers (numberOfWorkers
: number): void {
133 if (numberOfWorkers
== null) {
135 'Cannot instantiate a pool without specifying the number of workers'
137 } else if (!Number.isSafeInteger(numberOfWorkers
)) {
139 'Cannot instantiate a pool with a non safe integer number of workers'
141 } else if (numberOfWorkers
< 0) {
142 throw new RangeError(
143 'Cannot instantiate a pool with a negative number of workers'
145 } else if (this.type === PoolTypes
.fixed
&& numberOfWorkers
=== 0) {
146 throw new Error('Cannot instantiate a fixed pool with no worker')
150 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
151 if (isPlainObject(opts
)) {
152 this.opts
.workerChoiceStrategy
=
153 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
154 this.checkValidWorkerChoiceStrategy(this.opts
.workerChoiceStrategy
)
155 this.opts
.workerChoiceStrategyOptions
=
156 opts
.workerChoiceStrategyOptions
??
157 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
158 this.checkValidWorkerChoiceStrategyOptions(
159 this.opts
.workerChoiceStrategyOptions
161 this.opts
.restartWorkerOnError
= opts
.restartWorkerOnError
?? true
162 this.opts
.enableEvents
= opts
.enableEvents
?? true
163 this.opts
.enableTasksQueue
= opts
.enableTasksQueue
?? false
164 if (this.opts
.enableTasksQueue
) {
165 this.checkValidTasksQueueOptions(
166 opts
.tasksQueueOptions
as TasksQueueOptions
168 this.opts
.tasksQueueOptions
= this.buildTasksQueueOptions(
169 opts
.tasksQueueOptions
as TasksQueueOptions
173 throw new TypeError('Invalid pool options: must be a plain object')
177 private checkValidWorkerChoiceStrategy (
178 workerChoiceStrategy
: WorkerChoiceStrategy
180 if (!Object.values(WorkerChoiceStrategies
).includes(workerChoiceStrategy
)) {
182 `Invalid worker choice strategy '${workerChoiceStrategy}'`
187 private checkValidWorkerChoiceStrategyOptions (
188 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
190 if (!isPlainObject(workerChoiceStrategyOptions
)) {
192 'Invalid worker choice strategy options: must be a plain object'
196 workerChoiceStrategyOptions
.weights
!= null &&
197 Object.keys(workerChoiceStrategyOptions
.weights
).length
!== this.maxSize
200 'Invalid worker choice strategy options: must have a weight for each worker node'
204 workerChoiceStrategyOptions
.measurement
!= null &&
205 !Object.values(Measurements
).includes(
206 workerChoiceStrategyOptions
.measurement
210 `Invalid worker choice strategy options: invalid measurement '${workerChoiceStrategyOptions.measurement}'`
215 private checkValidTasksQueueOptions (
216 tasksQueueOptions
: TasksQueueOptions
218 if (tasksQueueOptions
!= null && !isPlainObject(tasksQueueOptions
)) {
219 throw new TypeError('Invalid tasks queue options: must be a plain object')
222 tasksQueueOptions
?.concurrency
!= null &&
223 !Number.isSafeInteger(tasksQueueOptions
.concurrency
)
226 'Invalid worker tasks concurrency: must be an integer'
230 tasksQueueOptions
?.concurrency
!= null &&
231 tasksQueueOptions
.concurrency
<= 0
234 `Invalid worker tasks concurrency '${tasksQueueOptions.concurrency}'`
240 public get
info (): PoolInfo
{
244 minSize
: this.minSize
,
245 maxSize
: this.maxSize
,
246 workerNodes
: this.workerNodes
.length
,
247 idleWorkerNodes
: this.workerNodes
.reduce(
248 (accumulator
, workerNode
) =>
249 workerNode
.workerUsage
.tasks
.executing
=== 0
254 busyWorkerNodes
: this.workerNodes
.reduce(
255 (accumulator
, workerNode
) =>
256 workerNode
.workerUsage
.tasks
.executing
> 0
261 executedTasks
: this.workerNodes
.reduce(
262 (accumulator
, workerNode
) =>
263 accumulator
+ workerNode
.workerUsage
.tasks
.executed
,
266 executingTasks
: this.workerNodes
.reduce(
267 (accumulator
, workerNode
) =>
268 accumulator
+ workerNode
.workerUsage
.tasks
.executing
,
271 queuedTasks
: this.workerNodes
.reduce(
272 (accumulator
, workerNode
) => accumulator
+ workerNode
.tasksQueue
.size
,
275 maxQueuedTasks
: this.workerNodes
.reduce(
276 (accumulator
, workerNode
) =>
277 accumulator
+ workerNode
.tasksQueue
.maxSize
,
280 failedTasks
: this.workerNodes
.reduce(
281 (accumulator
, workerNode
) =>
282 accumulator
+ workerNode
.workerUsage
.tasks
.failed
,
291 * If it is `'dynamic'`, it provides the `max` property.
293 protected abstract get
type (): PoolType
296 * Gets the worker type.
298 protected abstract get
worker (): WorkerType
303 protected abstract get
minSize (): number
308 protected abstract get
maxSize (): number
311 * Gets the given worker its worker node key.
313 * @param worker - The worker.
314 * @returns The worker node key if the worker is found in the pool worker nodes, `-1` otherwise.
316 private getWorkerNodeKey (worker
: Worker
): number {
317 return this.workerNodes
.findIndex(
318 workerNode
=> workerNode
.worker
=== worker
323 public setWorkerChoiceStrategy (
324 workerChoiceStrategy
: WorkerChoiceStrategy
,
325 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
327 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
328 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
329 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
330 this.opts
.workerChoiceStrategy
332 if (workerChoiceStrategyOptions
!= null) {
333 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
335 for (const workerNode
of this.workerNodes
) {
336 this.setWorkerNodeTasksUsage(
338 this.getWorkerUsage(workerNode
.worker
)
340 this.setWorkerStatistics(workerNode
.worker
)
345 public setWorkerChoiceStrategyOptions (
346 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
348 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
349 this.opts
.workerChoiceStrategyOptions
= workerChoiceStrategyOptions
350 this.workerChoiceStrategyContext
.setOptions(
351 this.opts
.workerChoiceStrategyOptions
356 public enableTasksQueue (
358 tasksQueueOptions
?: TasksQueueOptions
360 if (this.opts
.enableTasksQueue
=== true && !enable
) {
361 this.flushTasksQueues()
363 this.opts
.enableTasksQueue
= enable
364 this.setTasksQueueOptions(tasksQueueOptions
as TasksQueueOptions
)
368 public setTasksQueueOptions (tasksQueueOptions
: TasksQueueOptions
): void {
369 if (this.opts
.enableTasksQueue
=== true) {
370 this.checkValidTasksQueueOptions(tasksQueueOptions
)
371 this.opts
.tasksQueueOptions
=
372 this.buildTasksQueueOptions(tasksQueueOptions
)
373 } else if (this.opts
.tasksQueueOptions
!= null) {
374 delete this.opts
.tasksQueueOptions
378 private buildTasksQueueOptions (
379 tasksQueueOptions
: TasksQueueOptions
380 ): TasksQueueOptions
{
382 concurrency
: tasksQueueOptions
?.concurrency
?? 1
387 * Whether the pool is full or not.
389 * The pool filling boolean status.
391 protected get
full (): boolean {
392 return this.workerNodes
.length
>= this.maxSize
396 * Whether the pool is busy or not.
398 * The pool busyness boolean status.
400 protected abstract get
busy (): boolean
403 * Whether worker nodes are executing at least one task.
405 * @returns Worker nodes busyness boolean status.
407 protected internalBusy (): boolean {
409 this.workerNodes
.findIndex(workerNode
=> {
410 return workerNode
.workerUsage
.tasks
.executing
=== 0
416 public async execute (data
?: Data
, name
?: string): Promise
<Response
> {
417 const timestamp
= performance
.now()
418 const workerNodeKey
= this.chooseWorkerNode()
419 const submittedTask
: Task
<Data
> = {
421 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
422 data
: data
?? ({} as Data
),
424 id
: crypto
.randomUUID()
426 const res
= new Promise
<Response
>((resolve
, reject
) => {
427 this.promiseResponseMap
.set(submittedTask
.id
as string, {
430 worker
: this.workerNodes
[workerNodeKey
].worker
434 this.opts
.enableTasksQueue
=== true &&
436 this.workerNodes
[workerNodeKey
].workerUsage
.tasks
.executing
>=
437 ((this.opts
.tasksQueueOptions
as TasksQueueOptions
)
438 .concurrency
as number))
440 this.enqueueTask(workerNodeKey
, submittedTask
)
442 this.executeTask(workerNodeKey
, submittedTask
)
444 this.checkAndEmitEvents()
445 // eslint-disable-next-line @typescript-eslint/return-await
450 public async destroy (): Promise
<void> {
452 this.workerNodes
.map(async (workerNode
, workerNodeKey
) => {
453 this.flushTasksQueue(workerNodeKey
)
454 // FIXME: wait for tasks to be finished
455 await this.destroyWorker(workerNode
.worker
)
461 * Terminates the given worker.
463 * @param worker - A worker within `workerNodes`.
465 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
468 * Setup hook to execute code before worker node are created in the abstract constructor.
473 protected setupHook (): void {
474 // Intentionally empty
478 * Should return whether the worker is the main worker or not.
480 protected abstract isMain (): boolean
483 * Hook executed before the worker task execution.
486 * @param workerNodeKey - The worker node key.
487 * @param task - The task to execute.
489 protected beforeTaskExecutionHook (
490 workerNodeKey
: number,
493 const workerUsage
= this.workerNodes
[workerNodeKey
].workerUsage
494 ++workerUsage
.tasks
.executing
495 this.updateWaitTimeWorkerUsage(workerUsage
, task
)
499 * Hook executed after the worker task execution.
502 * @param worker - The worker.
503 * @param message - The received message.
505 protected afterTaskExecutionHook (
507 message
: MessageValue
<Response
>
510 this.workerNodes
[this.getWorkerNodeKey(worker
)].workerUsage
511 this.updateTaskStatisticsWorkerUsage(workerUsage
, message
)
512 this.updateRunTimeWorkerUsage(workerUsage
, message
)
513 this.updateEluWorkerUsage(workerUsage
, message
)
516 private updateTaskStatisticsWorkerUsage (
517 workerUsage
: WorkerUsage
,
518 message
: MessageValue
<Response
>
520 const workerTaskStatistics
= workerUsage
.tasks
521 --workerTaskStatistics
.executing
522 ++workerTaskStatistics
.executed
523 if (message
.taskError
!= null) {
524 ++workerTaskStatistics
.failed
528 private updateRunTimeWorkerUsage (
529 workerUsage
: WorkerUsage
,
530 message
: MessageValue
<Response
>
533 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
536 workerUsage
.runTime
.aggregate
+= message
.taskPerformance
?.runTime
?? 0
538 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
540 workerUsage
.tasks
.executed
!== 0
542 workerUsage
.runTime
.average
=
543 workerUsage
.runTime
.aggregate
/
544 (workerUsage
.tasks
.executed
- workerUsage
.tasks
.failed
)
547 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
549 message
.taskPerformance
?.runTime
!= null
551 workerUsage
.runTime
.history
.push(message
.taskPerformance
.runTime
)
552 workerUsage
.runTime
.median
= median(workerUsage
.runTime
.history
)
557 private updateWaitTimeWorkerUsage (
558 workerUsage
: WorkerUsage
,
561 const timestamp
= performance
.now()
562 const taskWaitTime
= timestamp
- (task
.timestamp
?? timestamp
)
564 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().waitTime
567 workerUsage
.waitTime
.aggregate
+= taskWaitTime
?? 0
569 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
571 workerUsage
.tasks
.executed
!== 0
573 workerUsage
.waitTime
.average
=
574 workerUsage
.waitTime
.aggregate
/
575 (workerUsage
.tasks
.executed
- workerUsage
.tasks
.failed
)
578 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
582 workerUsage
.waitTime
.history
.push(taskWaitTime
)
583 workerUsage
.waitTime
.median
= median(workerUsage
.waitTime
.history
)
588 private updateEluWorkerUsage (
589 workerUsage
: WorkerUsage
,
590 message
: MessageValue
<Response
>
593 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
596 if (workerUsage
.elu
!= null && message
.taskPerformance
?.elu
!= null) {
597 workerUsage
.elu
.idle
.aggregate
+= message
.taskPerformance
.elu
.idle
598 workerUsage
.elu
.active
.aggregate
+= message
.taskPerformance
.elu
.active
599 workerUsage
.elu
.utilization
=
600 (workerUsage
.elu
.utilization
+
601 message
.taskPerformance
.elu
.utilization
) /
603 } else if (message
.taskPerformance
?.elu
!= null) {
604 workerUsage
.elu
.idle
.aggregate
= message
.taskPerformance
.elu
.idle
605 workerUsage
.elu
.active
.aggregate
= message
.taskPerformance
.elu
.active
606 workerUsage
.elu
.utilization
= message
.taskPerformance
.elu
.utilization
609 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
611 workerUsage
.tasks
.executed
!== 0
613 const executedTasks
=
614 workerUsage
.tasks
.executed
- workerUsage
.tasks
.failed
615 workerUsage
.elu
.idle
.average
=
616 workerUsage
.elu
.idle
.aggregate
/ executedTasks
617 workerUsage
.elu
.active
.average
=
618 workerUsage
.elu
.active
.aggregate
/ executedTasks
621 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
623 message
.taskPerformance
?.elu
!= null
625 workerUsage
.elu
.idle
.history
.push(message
.taskPerformance
.elu
.idle
)
626 workerUsage
.elu
.active
.history
.push(message
.taskPerformance
.elu
.active
)
627 workerUsage
.elu
.idle
.median
= median(workerUsage
.elu
.idle
.history
)
628 workerUsage
.elu
.active
.median
= median(workerUsage
.elu
.active
.history
)
634 * Chooses a worker node for the next task.
636 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
638 * @returns The worker node key
640 private chooseWorkerNode (): number {
641 if (this.shallCreateDynamicWorker()) {
642 const worker
= this.createAndSetupDynamicWorker()
644 this.workerChoiceStrategyContext
.getStrategyPolicy().useDynamicWorker
646 return this.getWorkerNodeKey(worker
)
649 return this.workerChoiceStrategyContext
.execute()
653 * Conditions for dynamic worker creation.
655 * @returns Whether to create a dynamic worker or not.
657 private shallCreateDynamicWorker (): boolean {
658 return this.type === PoolTypes
.dynamic
&& !this.full
&& this.internalBusy()
662 * Sends a message to the given worker.
664 * @param worker - The worker which should receive the message.
665 * @param message - The message.
667 protected abstract sendToWorker (
669 message
: MessageValue
<Data
>
673 * Registers a listener callback on the given worker.
675 * @param worker - The worker which should register a listener.
676 * @param listener - The message listener callback.
678 protected abstract registerWorkerMessageListener
<
679 Message
extends Data
| Response
680 >(worker
: Worker
, listener
: (message
: MessageValue
<Message
>) => void): void
683 * Creates a new worker.
685 * @returns Newly created worker.
687 protected abstract createWorker (): Worker
690 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
692 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
694 * @param worker - The newly created worker.
696 protected abstract afterWorkerSetup (worker
: Worker
): void
699 * Creates a new worker and sets it up completely in the pool worker nodes.
701 * @returns New, completely set up worker.
703 protected createAndSetupWorker (): Worker
{
704 const worker
= this.createWorker()
706 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
707 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
708 worker
.on('error', error
=> {
709 if (this.emitter
!= null) {
710 this.emitter
.emit(PoolEvents
.error
, error
)
712 if (this.opts
.restartWorkerOnError
=== true) {
713 this.createAndSetupWorker()
716 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
717 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
718 worker
.once('exit', () => {
719 this.removeWorkerNode(worker
)
722 this.pushWorkerNode(worker
)
724 this.setWorkerStatistics(worker
)
726 this.afterWorkerSetup(worker
)
732 * Creates a new dynamic worker and sets it up completely in the pool worker nodes.
734 * @returns New, completely set up dynamic worker.
736 protected createAndSetupDynamicWorker (): Worker
{
737 const worker
= this.createAndSetupWorker()
738 this.registerWorkerMessageListener(worker
, message
=> {
739 const workerNodeKey
= this.getWorkerNodeKey(worker
)
741 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
742 (message
.kill
!= null &&
743 ((this.opts
.enableTasksQueue
=== false &&
744 this.workerNodes
[workerNodeKey
].workerUsage
.tasks
.executing
===
746 (this.opts
.enableTasksQueue
=== true &&
747 this.workerNodes
[workerNodeKey
].workerUsage
.tasks
.executing
===
749 this.tasksQueueSize(workerNodeKey
) === 0)))
751 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
752 void (this.destroyWorker(worker
) as Promise
<void>)
759 * This function is the listener registered for each worker message.
761 * @returns The listener function to execute when a message is received from a worker.
763 protected workerListener (): (message
: MessageValue
<Response
>) => void {
765 if (message
.id
!= null) {
766 // Task execution response received
767 const promiseResponse
= this.promiseResponseMap
.get(message
.id
)
768 if (promiseResponse
!= null) {
769 if (message
.taskError
!= null) {
770 if (this.emitter
!= null) {
771 this.emitter
.emit(PoolEvents
.taskError
, message
.taskError
)
773 promiseResponse
.reject(message
.taskError
.message
)
775 promiseResponse
.resolve(message
.data
as Response
)
777 this.afterTaskExecutionHook(promiseResponse
.worker
, message
)
778 this.promiseResponseMap
.delete(message
.id
)
779 const workerNodeKey
= this.getWorkerNodeKey(promiseResponse
.worker
)
781 this.opts
.enableTasksQueue
=== true &&
782 this.tasksQueueSize(workerNodeKey
) > 0
786 this.dequeueTask(workerNodeKey
) as Task
<Data
>
789 this.workerChoiceStrategyContext
.update(workerNodeKey
)
795 private checkAndEmitEvents (): void {
796 if (this.emitter
!= null) {
798 this.emitter
?.emit(PoolEvents
.busy
, this.info
)
800 if (this.type === PoolTypes
.dynamic
&& this.full
) {
801 this.emitter
?.emit(PoolEvents
.full
, this.info
)
807 * Sets the given worker node its tasks usage in the pool.
809 * @param workerNode - The worker node.
810 * @param workerUsage - The worker usage.
812 private setWorkerNodeTasksUsage (
813 workerNode
: WorkerNode
<Worker
, Data
>,
814 workerUsage
: WorkerUsage
816 workerNode
.workerUsage
= workerUsage
820 * Pushes the given worker in the pool worker nodes.
822 * @param worker - The worker.
823 * @returns The worker nodes length.
825 private pushWorkerNode (worker
: Worker
): number {
826 return this.workerNodes
.push({
828 workerUsage
: this.getWorkerUsage(worker
),
829 tasksQueue
: new Queue
<Task
<Data
>>()
834 // * Sets the given worker in the pool worker nodes.
836 // * @param workerNodeKey - The worker node key.
837 // * @param worker - The worker.
838 // * @param workerUsage - The worker usage.
839 // * @param tasksQueue - The worker task queue.
841 // private setWorkerNode (
842 // workerNodeKey: number,
844 // workerUsage: WorkerUsage,
845 // tasksQueue: Queue<Task<Data>>
847 // this.workerNodes[workerNodeKey] = {
855 * Removes the given worker from the pool worker nodes.
857 * @param worker - The worker.
859 private removeWorkerNode (worker
: Worker
): void {
860 const workerNodeKey
= this.getWorkerNodeKey(worker
)
861 if (workerNodeKey
!== -1) {
862 this.workerNodes
.splice(workerNodeKey
, 1)
863 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
867 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
868 this.beforeTaskExecutionHook(workerNodeKey
, task
)
869 this.sendToWorker(this.workerNodes
[workerNodeKey
].worker
, task
)
872 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
873 return this.workerNodes
[workerNodeKey
].tasksQueue
.enqueue(task
)
876 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
877 return this.workerNodes
[workerNodeKey
].tasksQueue
.dequeue()
880 private tasksQueueSize (workerNodeKey
: number): number {
881 return this.workerNodes
[workerNodeKey
].tasksQueue
.size
884 private flushTasksQueue (workerNodeKey
: number): void {
885 if (this.tasksQueueSize(workerNodeKey
) > 0) {
886 for (let i
= 0; i
< this.tasksQueueSize(workerNodeKey
); i
++) {
889 this.dequeueTask(workerNodeKey
) as Task
<Data
>
895 private flushTasksQueues (): void {
896 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
897 this.flushTasksQueue(workerNodeKey
)
901 private setWorkerStatistics (worker
: Worker
): void {
902 this.sendToWorker(worker
, {
905 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
907 elu
: this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
913 private getWorkerUsage (worker
: Worker
): WorkerUsage
{
915 tasks
: this.getTaskStatistics(worker
),
920 history
: new CircularArray()
926 history
: new CircularArray()
933 history
: new CircularArray()
939 history
: new CircularArray()
946 private getTaskStatistics (worker
: Worker
): TaskStatistics
{
948 this.workerNodes
[this.getWorkerNodeKey(worker
)]?.tasksQueue
?.size
952 get
queued (): number {
953 return queueSize
?? 0