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 structured-cloneable data.
44 * @typeParam Response - Type of execution response. This can only be structured-cloneable 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
) =>
273 accumulator
+ workerNode
.workerUsage
.tasks
.queued
,
276 maxQueuedTasks
: this.workerNodes
.reduce(
277 (accumulator
, workerNode
) =>
278 accumulator
+ workerNode
.workerUsage
.tasks
.maxQueued
,
281 failedTasks
: this.workerNodes
.reduce(
282 (accumulator
, workerNode
) =>
283 accumulator
+ workerNode
.workerUsage
.tasks
.failed
,
292 * If it is `'dynamic'`, it provides the `max` property.
294 protected abstract get
type (): PoolType
297 * Gets the worker type.
299 protected abstract get
worker (): WorkerType
304 protected abstract get
minSize (): number
309 protected abstract get
maxSize (): number
312 * Gets the given worker its worker node key.
314 * @param worker - The worker.
315 * @returns The worker node key if the worker is found in the pool worker nodes, `-1` otherwise.
317 private getWorkerNodeKey (worker
: Worker
): number {
318 return this.workerNodes
.findIndex(
319 workerNode
=> workerNode
.worker
=== worker
324 public setWorkerChoiceStrategy (
325 workerChoiceStrategy
: WorkerChoiceStrategy
,
326 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
328 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
329 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
330 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
331 this.opts
.workerChoiceStrategy
333 if (workerChoiceStrategyOptions
!= null) {
334 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
336 for (const [workerNodeKey
, workerNode
] of this.workerNodes
.entries()) {
337 this.setWorkerNodeTasksUsage(
339 this.getWorkerUsage(workerNodeKey
)
341 this.setWorkerStatistics(workerNode
.worker
)
346 public setWorkerChoiceStrategyOptions (
347 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
349 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
350 this.opts
.workerChoiceStrategyOptions
= workerChoiceStrategyOptions
351 this.workerChoiceStrategyContext
.setOptions(
352 this.opts
.workerChoiceStrategyOptions
357 public enableTasksQueue (
359 tasksQueueOptions
?: TasksQueueOptions
361 if (this.opts
.enableTasksQueue
=== true && !enable
) {
362 this.flushTasksQueues()
364 this.opts
.enableTasksQueue
= enable
365 this.setTasksQueueOptions(tasksQueueOptions
as TasksQueueOptions
)
369 public setTasksQueueOptions (tasksQueueOptions
: TasksQueueOptions
): void {
370 if (this.opts
.enableTasksQueue
=== true) {
371 this.checkValidTasksQueueOptions(tasksQueueOptions
)
372 this.opts
.tasksQueueOptions
=
373 this.buildTasksQueueOptions(tasksQueueOptions
)
374 } else if (this.opts
.tasksQueueOptions
!= null) {
375 delete this.opts
.tasksQueueOptions
379 private buildTasksQueueOptions (
380 tasksQueueOptions
: TasksQueueOptions
381 ): TasksQueueOptions
{
383 concurrency
: tasksQueueOptions
?.concurrency
?? 1
388 * Whether the pool is full or not.
390 * The pool filling boolean status.
392 protected get
full (): boolean {
393 return this.workerNodes
.length
>= this.maxSize
397 * Whether the pool is busy or not.
399 * The pool busyness boolean status.
401 protected abstract get
busy (): boolean
404 * Whether worker nodes are executing at least one task.
406 * @returns Worker nodes busyness boolean status.
408 protected internalBusy (): boolean {
410 this.workerNodes
.findIndex(workerNode
=> {
411 return workerNode
.workerUsage
.tasks
.executing
=== 0
417 public async execute (data
?: Data
, name
?: string): Promise
<Response
> {
418 const timestamp
= performance
.now()
419 const workerNodeKey
= this.chooseWorkerNode()
420 const submittedTask
: Task
<Data
> = {
422 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
423 data
: data
?? ({} as Data
),
425 id
: crypto
.randomUUID()
427 const res
= new Promise
<Response
>((resolve
, reject
) => {
428 this.promiseResponseMap
.set(submittedTask
.id
as string, {
431 worker
: this.workerNodes
[workerNodeKey
].worker
435 this.opts
.enableTasksQueue
=== true &&
437 this.workerNodes
[workerNodeKey
].workerUsage
.tasks
.executing
>=
438 ((this.opts
.tasksQueueOptions
as TasksQueueOptions
)
439 .concurrency
as number))
441 this.enqueueTask(workerNodeKey
, submittedTask
)
443 this.executeTask(workerNodeKey
, submittedTask
)
445 this.checkAndEmitEvents()
446 // eslint-disable-next-line @typescript-eslint/return-await
451 public async destroy (): Promise
<void> {
453 this.workerNodes
.map(async (workerNode
, workerNodeKey
) => {
454 this.flushTasksQueue(workerNodeKey
)
455 // FIXME: wait for tasks to be finished
456 await this.destroyWorker(workerNode
.worker
)
462 * Terminates the given worker.
464 * @param worker - A worker within `workerNodes`.
466 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
469 * Setup hook to execute code before worker node are created in the abstract constructor.
474 protected setupHook (): void {
475 // Intentionally empty
479 * Should return whether the worker is the main worker or not.
481 protected abstract isMain (): boolean
484 * Hook executed before the worker task execution.
487 * @param workerNodeKey - The worker node key.
488 * @param task - The task to execute.
490 protected beforeTaskExecutionHook (
491 workerNodeKey
: number,
494 const workerUsage
= this.workerNodes
[workerNodeKey
].workerUsage
495 ++workerUsage
.tasks
.executing
496 this.updateWaitTimeWorkerUsage(workerUsage
, task
)
500 * Hook executed after the worker task execution.
503 * @param worker - The worker.
504 * @param message - The received message.
506 protected afterTaskExecutionHook (
508 message
: MessageValue
<Response
>
511 this.workerNodes
[this.getWorkerNodeKey(worker
)].workerUsage
512 this.updateTaskStatisticsWorkerUsage(workerUsage
, message
)
513 this.updateRunTimeWorkerUsage(workerUsage
, message
)
514 this.updateEluWorkerUsage(workerUsage
, message
)
517 private updateTaskStatisticsWorkerUsage (
518 workerUsage
: WorkerUsage
,
519 message
: MessageValue
<Response
>
521 const workerTaskStatistics
= workerUsage
.tasks
522 --workerTaskStatistics
.executing
523 ++workerTaskStatistics
.executed
524 if (message
.taskError
!= null) {
525 ++workerTaskStatistics
.failed
529 private updateRunTimeWorkerUsage (
530 workerUsage
: WorkerUsage
,
531 message
: MessageValue
<Response
>
534 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
537 workerUsage
.runTime
.aggregate
+= message
.taskPerformance
?.runTime
?? 0
539 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
541 workerUsage
.tasks
.executed
!== 0
543 workerUsage
.runTime
.average
=
544 workerUsage
.runTime
.aggregate
/
545 (workerUsage
.tasks
.executed
- workerUsage
.tasks
.failed
)
548 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
550 message
.taskPerformance
?.runTime
!= null
552 workerUsage
.runTime
.history
.push(message
.taskPerformance
.runTime
)
553 workerUsage
.runTime
.median
= median(workerUsage
.runTime
.history
)
558 private updateWaitTimeWorkerUsage (
559 workerUsage
: WorkerUsage
,
562 const timestamp
= performance
.now()
563 const taskWaitTime
= timestamp
- (task
.timestamp
?? timestamp
)
565 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().waitTime
568 workerUsage
.waitTime
.aggregate
+= taskWaitTime
?? 0
570 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
572 workerUsage
.tasks
.executed
!== 0
574 workerUsage
.waitTime
.average
=
575 workerUsage
.waitTime
.aggregate
/
576 (workerUsage
.tasks
.executed
- workerUsage
.tasks
.failed
)
579 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
583 workerUsage
.waitTime
.history
.push(taskWaitTime
)
584 workerUsage
.waitTime
.median
= median(workerUsage
.waitTime
.history
)
589 private updateEluWorkerUsage (
590 workerUsage
: WorkerUsage
,
591 message
: MessageValue
<Response
>
594 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
597 if (workerUsage
.elu
!= null && message
.taskPerformance
?.elu
!= null) {
598 workerUsage
.elu
.idle
.aggregate
+= message
.taskPerformance
.elu
.idle
599 workerUsage
.elu
.active
.aggregate
+= message
.taskPerformance
.elu
.active
600 workerUsage
.elu
.utilization
=
601 (workerUsage
.elu
.utilization
+
602 message
.taskPerformance
.elu
.utilization
) /
604 } else if (message
.taskPerformance
?.elu
!= null) {
605 workerUsage
.elu
.idle
.aggregate
= message
.taskPerformance
.elu
.idle
606 workerUsage
.elu
.active
.aggregate
= message
.taskPerformance
.elu
.active
607 workerUsage
.elu
.utilization
= message
.taskPerformance
.elu
.utilization
610 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
612 workerUsage
.tasks
.executed
!== 0
614 const executedTasks
=
615 workerUsage
.tasks
.executed
- workerUsage
.tasks
.failed
616 workerUsage
.elu
.idle
.average
=
617 workerUsage
.elu
.idle
.aggregate
/ executedTasks
618 workerUsage
.elu
.active
.average
=
619 workerUsage
.elu
.active
.aggregate
/ executedTasks
622 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
624 message
.taskPerformance
?.elu
!= null
626 workerUsage
.elu
.idle
.history
.push(message
.taskPerformance
.elu
.idle
)
627 workerUsage
.elu
.active
.history
.push(message
.taskPerformance
.elu
.active
)
628 workerUsage
.elu
.idle
.median
= median(workerUsage
.elu
.idle
.history
)
629 workerUsage
.elu
.active
.median
= median(workerUsage
.elu
.active
.history
)
635 * Chooses a worker node for the next task.
637 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
639 * @returns The worker node key
641 private chooseWorkerNode (): number {
642 if (this.shallCreateDynamicWorker()) {
643 const worker
= this.createAndSetupDynamicWorker()
645 this.workerChoiceStrategyContext
.getStrategyPolicy().useDynamicWorker
647 return this.getWorkerNodeKey(worker
)
650 return this.workerChoiceStrategyContext
.execute()
654 * Conditions for dynamic worker creation.
656 * @returns Whether to create a dynamic worker or not.
658 private shallCreateDynamicWorker (): boolean {
659 return this.type === PoolTypes
.dynamic
&& !this.full
&& this.internalBusy()
663 * Sends a message to the given worker.
665 * @param worker - The worker which should receive the message.
666 * @param message - The message.
668 protected abstract sendToWorker (
670 message
: MessageValue
<Data
>
674 * Registers a listener callback on the given worker.
676 * @param worker - The worker which should register a listener.
677 * @param listener - The message listener callback.
679 private registerWorkerMessageListener
<Message
extends Data
| Response
>(
681 listener
: (message
: MessageValue
<Message
>) => void
683 worker
.on('message', listener
as MessageHandler
<Worker
>)
687 * Creates a new worker.
689 * @returns Newly created worker.
691 protected abstract createWorker (): Worker
694 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
696 * @param worker - The newly created worker.
698 private afterWorkerSetup (worker
: Worker
): void {
699 // Listen to worker messages.
700 this.registerWorkerMessageListener(worker
, this.workerListener())
704 * Creates a new worker and sets it up completely in the pool worker nodes.
706 * @returns New, completely set up worker.
708 protected createAndSetupWorker (): Worker
{
709 const worker
= this.createWorker()
711 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
712 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
713 worker
.on('error', error
=> {
714 if (this.emitter
!= null) {
715 this.emitter
.emit(PoolEvents
.error
, error
)
717 if (this.opts
.restartWorkerOnError
=== true) {
718 this.createAndSetupWorker()
721 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
722 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
723 worker
.once('exit', () => {
724 this.removeWorkerNode(worker
)
727 this.pushWorkerNode(worker
)
729 this.setWorkerStatistics(worker
)
731 this.afterWorkerSetup(worker
)
737 * Creates a new dynamic worker and sets it up completely in the pool worker nodes.
739 * @returns New, completely set up dynamic worker.
741 protected createAndSetupDynamicWorker (): Worker
{
742 const worker
= this.createAndSetupWorker()
743 this.registerWorkerMessageListener(worker
, message
=> {
744 const workerNodeKey
= this.getWorkerNodeKey(worker
)
746 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
747 (message
.kill
!= null &&
748 ((this.opts
.enableTasksQueue
=== false &&
749 this.workerNodes
[workerNodeKey
].workerUsage
.tasks
.executing
===
751 (this.opts
.enableTasksQueue
=== true &&
752 this.workerNodes
[workerNodeKey
].workerUsage
.tasks
.executing
===
754 this.tasksQueueSize(workerNodeKey
) === 0)))
756 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
757 void (this.destroyWorker(worker
) as Promise
<void>)
764 * This function is the listener registered for each worker message.
766 * @returns The listener function to execute when a message is received from a worker.
768 protected workerListener (): (message
: MessageValue
<Response
>) => void {
770 if (message
.id
!= null) {
771 // Task execution response received
772 const promiseResponse
= this.promiseResponseMap
.get(message
.id
)
773 if (promiseResponse
!= null) {
774 if (message
.taskError
!= null) {
775 if (this.emitter
!= null) {
776 this.emitter
.emit(PoolEvents
.taskError
, message
.taskError
)
778 promiseResponse
.reject(message
.taskError
.message
)
780 promiseResponse
.resolve(message
.data
as Response
)
782 this.afterTaskExecutionHook(promiseResponse
.worker
, message
)
783 this.promiseResponseMap
.delete(message
.id
)
784 const workerNodeKey
= this.getWorkerNodeKey(promiseResponse
.worker
)
786 this.opts
.enableTasksQueue
=== true &&
787 this.tasksQueueSize(workerNodeKey
) > 0
791 this.dequeueTask(workerNodeKey
) as Task
<Data
>
794 this.workerChoiceStrategyContext
.update(workerNodeKey
)
800 private checkAndEmitEvents (): void {
801 if (this.emitter
!= null) {
803 this.emitter
?.emit(PoolEvents
.busy
, this.info
)
805 if (this.type === PoolTypes
.dynamic
&& this.full
) {
806 this.emitter
?.emit(PoolEvents
.full
, this.info
)
812 * Sets the given worker node its tasks usage in the pool.
814 * @param workerNode - The worker node.
815 * @param workerUsage - The worker usage.
817 private setWorkerNodeTasksUsage (
818 workerNode
: WorkerNode
<Worker
, Data
>,
819 workerUsage
: WorkerUsage
821 workerNode
.workerUsage
= workerUsage
825 * Pushes the given worker in the pool worker nodes.
827 * @param worker - The worker.
828 * @returns The worker nodes length.
830 private pushWorkerNode (worker
: Worker
): number {
831 this.workerNodes
.push({
833 workerUsage
: this.getWorkerUsage(),
834 tasksQueue
: new Queue
<Task
<Data
>>()
836 const workerNodeKey
= this.getWorkerNodeKey(worker
)
837 this.setWorkerNodeTasksUsage(
838 this.workerNodes
[workerNodeKey
],
839 this.getWorkerUsage(workerNodeKey
)
841 return this.workerNodes
.length
845 // * Sets the given worker in the pool worker nodes.
847 // * @param workerNodeKey - The worker node key.
848 // * @param worker - The worker.
849 // * @param workerUsage - The worker usage.
850 // * @param tasksQueue - The worker task queue.
852 // private setWorkerNode (
853 // workerNodeKey: number,
855 // workerUsage: WorkerUsage,
856 // tasksQueue: Queue<Task<Data>>
858 // this.workerNodes[workerNodeKey] = {
866 * Removes the given worker from the pool worker nodes.
868 * @param worker - The worker.
870 private removeWorkerNode (worker
: Worker
): void {
871 const workerNodeKey
= this.getWorkerNodeKey(worker
)
872 if (workerNodeKey
!== -1) {
873 this.workerNodes
.splice(workerNodeKey
, 1)
874 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
878 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
879 this.beforeTaskExecutionHook(workerNodeKey
, task
)
880 this.sendToWorker(this.workerNodes
[workerNodeKey
].worker
, task
)
883 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
884 return this.workerNodes
[workerNodeKey
].tasksQueue
.enqueue(task
)
887 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
888 return this.workerNodes
[workerNodeKey
].tasksQueue
.dequeue()
891 private tasksQueueSize (workerNodeKey
: number): number {
892 return this.workerNodes
[workerNodeKey
].tasksQueue
.size
895 private tasksMaxQueueSize (workerNodeKey
: number): number {
896 return this.workerNodes
[workerNodeKey
].tasksQueue
.maxSize
899 private flushTasksQueue (workerNodeKey
: number): void {
900 if (this.tasksQueueSize(workerNodeKey
) > 0) {
901 for (let i
= 0; i
< this.tasksQueueSize(workerNodeKey
); i
++) {
904 this.dequeueTask(workerNodeKey
) as Task
<Data
>
908 this.workerNodes
[workerNodeKey
].tasksQueue
.clear()
911 private flushTasksQueues (): void {
912 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
913 this.flushTasksQueue(workerNodeKey
)
917 private setWorkerStatistics (worker
: Worker
): void {
918 this.sendToWorker(worker
, {
921 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
923 elu
: this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
929 private getWorkerUsage (workerNodeKey
?: number): WorkerUsage
{
930 const getTasksQueueSize
= (workerNodeKey
?: number): number => {
931 return workerNodeKey
!= null ? this.tasksQueueSize(workerNodeKey
) : 0
933 const getTasksMaxQueueSize
= (workerNodeKey
?: number): number => {
934 return workerNodeKey
!= null ? this.tasksMaxQueueSize(workerNodeKey
) : 0
940 get
queued (): number {
941 return getTasksQueueSize(workerNodeKey
)
943 get
maxQueued (): number {
944 return getTasksMaxQueueSize(workerNodeKey
)
952 history
: new CircularArray()
958 history
: new CircularArray()
965 history
: new CircularArray()
971 history
: new CircularArray()