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 nodes 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.
697 * @param worker - The newly created worker.
699 protected afterWorkerSetup (worker
: Worker
): void {
700 // Listen to worker messages.
701 this.registerWorkerMessageListener(worker
, this.workerListener())
705 * Creates a new worker and sets it up completely in the pool worker nodes.
707 * @returns New, completely set up worker.
709 protected createAndSetupWorker (): Worker
{
710 const worker
= this.createWorker()
712 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
713 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
714 worker
.on('error', error
=> {
715 if (this.emitter
!= null) {
716 this.emitter
.emit(PoolEvents
.error
, error
)
718 if (this.opts
.restartWorkerOnError
=== true) {
719 this.createAndSetupWorker()
722 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
723 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
724 worker
.once('exit', () => {
725 this.removeWorkerNode(worker
)
728 this.pushWorkerNode(worker
)
730 this.setWorkerStatistics(worker
)
732 this.afterWorkerSetup(worker
)
738 * Creates a new dynamic worker and sets it up completely in the pool worker nodes.
740 * @returns New, completely set up dynamic worker.
742 protected createAndSetupDynamicWorker (): Worker
{
743 const worker
= this.createAndSetupWorker()
744 this.registerWorkerMessageListener(worker
, message
=> {
745 const workerNodeKey
= this.getWorkerNodeKey(worker
)
747 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
748 (message
.kill
!= null &&
749 ((this.opts
.enableTasksQueue
=== false &&
750 this.workerNodes
[workerNodeKey
].workerUsage
.tasks
.executing
===
752 (this.opts
.enableTasksQueue
=== true &&
753 this.workerNodes
[workerNodeKey
].workerUsage
.tasks
.executing
===
755 this.tasksQueueSize(workerNodeKey
) === 0)))
757 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
758 void (this.destroyWorker(worker
) as Promise
<void>)
765 * This function is the listener registered for each worker message.
767 * @returns The listener function to execute when a message is received from a worker.
769 protected workerListener (): (message
: MessageValue
<Response
>) => void {
771 if (message
.id
!= null) {
772 // Task execution response received
773 const promiseResponse
= this.promiseResponseMap
.get(message
.id
)
774 if (promiseResponse
!= null) {
775 if (message
.taskError
!= null) {
776 if (this.emitter
!= null) {
777 this.emitter
.emit(PoolEvents
.taskError
, message
.taskError
)
779 promiseResponse
.reject(message
.taskError
.message
)
781 promiseResponse
.resolve(message
.data
as Response
)
783 this.afterTaskExecutionHook(promiseResponse
.worker
, message
)
784 this.promiseResponseMap
.delete(message
.id
)
785 const workerNodeKey
= this.getWorkerNodeKey(promiseResponse
.worker
)
787 this.opts
.enableTasksQueue
=== true &&
788 this.tasksQueueSize(workerNodeKey
) > 0
792 this.dequeueTask(workerNodeKey
) as Task
<Data
>
795 this.workerChoiceStrategyContext
.update(workerNodeKey
)
801 private checkAndEmitEvents (): void {
802 if (this.emitter
!= null) {
804 this.emitter
?.emit(PoolEvents
.busy
, this.info
)
806 if (this.type === PoolTypes
.dynamic
&& this.full
) {
807 this.emitter
?.emit(PoolEvents
.full
, this.info
)
813 * Sets the given worker node its tasks usage in the pool.
815 * @param workerNode - The worker node.
816 * @param workerUsage - The worker usage.
818 private setWorkerNodeTasksUsage (
819 workerNode
: WorkerNode
<Worker
, Data
>,
820 workerUsage
: WorkerUsage
822 workerNode
.workerUsage
= workerUsage
826 * Pushes the given worker in the pool worker nodes.
828 * @param worker - The worker.
829 * @returns The worker nodes length.
831 private pushWorkerNode (worker
: Worker
): number {
832 this.workerNodes
.push({
834 workerUsage
: this.getWorkerUsage(),
835 tasksQueue
: new Queue
<Task
<Data
>>()
837 const workerNodeKey
= this.getWorkerNodeKey(worker
)
838 this.setWorkerNodeTasksUsage(
839 this.workerNodes
[workerNodeKey
],
840 this.getWorkerUsage(workerNodeKey
)
842 return this.workerNodes
.length
846 // * Sets the given worker in the pool worker nodes.
848 // * @param workerNodeKey - The worker node key.
849 // * @param worker - The worker.
850 // * @param workerUsage - The worker usage.
851 // * @param tasksQueue - The worker task queue.
853 // private setWorkerNode (
854 // workerNodeKey: number,
856 // workerUsage: WorkerUsage,
857 // tasksQueue: Queue<Task<Data>>
859 // this.workerNodes[workerNodeKey] = {
867 * Removes the given worker from the pool worker nodes.
869 * @param worker - The worker.
871 private removeWorkerNode (worker
: Worker
): void {
872 const workerNodeKey
= this.getWorkerNodeKey(worker
)
873 if (workerNodeKey
!== -1) {
874 this.workerNodes
.splice(workerNodeKey
, 1)
875 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
879 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
880 this.beforeTaskExecutionHook(workerNodeKey
, task
)
881 this.sendToWorker(this.workerNodes
[workerNodeKey
].worker
, task
)
884 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
885 return this.workerNodes
[workerNodeKey
].tasksQueue
.enqueue(task
)
888 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
889 return this.workerNodes
[workerNodeKey
].tasksQueue
.dequeue()
892 private tasksQueueSize (workerNodeKey
: number): number {
893 return this.workerNodes
[workerNodeKey
].tasksQueue
.size
896 private tasksMaxQueueSize (workerNodeKey
: number): number {
897 return this.workerNodes
[workerNodeKey
].tasksQueue
.maxSize
900 private flushTasksQueue (workerNodeKey
: number): void {
901 if (this.tasksQueueSize(workerNodeKey
) > 0) {
902 for (let i
= 0; i
< this.tasksQueueSize(workerNodeKey
); i
++) {
905 this.dequeueTask(workerNodeKey
) as Task
<Data
>
909 this.workerNodes
[workerNodeKey
].tasksQueue
.clear()
912 private flushTasksQueues (): void {
913 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
914 this.flushTasksQueue(workerNodeKey
)
918 private setWorkerStatistics (worker
: Worker
): void {
919 this.sendToWorker(worker
, {
922 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
924 elu
: this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
930 private getWorkerUsage (workerNodeKey
?: number): WorkerUsage
{
931 const getTasksQueueSize
= (workerNodeKey
?: number): number => {
932 return workerNodeKey
!= null ? this.tasksQueueSize(workerNodeKey
) : 0
934 const getTasksMaxQueueSize
= (workerNodeKey
?: number): number => {
935 return workerNodeKey
!= null ? this.tasksMaxQueueSize(workerNodeKey
) : 0
941 get
queued (): number {
942 return getTasksQueueSize(workerNodeKey
)
944 get
maxQueued (): number {
945 return getTasksMaxQueueSize(workerNodeKey
)
953 history
: new CircularArray()
959 history
: new CircularArray()
966 history
: new CircularArray()
972 history
: new CircularArray()