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
.usage
.tasks
.executing
=== 0
254 busyWorkerNodes
: this.workerNodes
.reduce(
255 (accumulator
, workerNode
) =>
256 workerNode
.usage
.tasks
.executing
> 0 ? accumulator
+ 1 : accumulator
,
259 executedTasks
: this.workerNodes
.reduce(
260 (accumulator
, workerNode
) =>
261 accumulator
+ workerNode
.usage
.tasks
.executed
,
264 executingTasks
: this.workerNodes
.reduce(
265 (accumulator
, workerNode
) =>
266 accumulator
+ workerNode
.usage
.tasks
.executing
,
269 queuedTasks
: this.workerNodes
.reduce(
270 (accumulator
, workerNode
) =>
271 accumulator
+ workerNode
.usage
.tasks
.queued
,
274 maxQueuedTasks
: this.workerNodes
.reduce(
275 (accumulator
, workerNode
) =>
276 accumulator
+ workerNode
.usage
.tasks
.maxQueued
,
279 failedTasks
: this.workerNodes
.reduce(
280 (accumulator
, workerNode
) =>
281 accumulator
+ workerNode
.usage
.tasks
.failed
,
290 * If it is `'dynamic'`, it provides the `max` property.
292 protected abstract get
type (): PoolType
295 * Gets the worker type.
297 protected abstract get
worker (): WorkerType
302 protected abstract get
minSize (): number
307 protected abstract get
maxSize (): number
310 * Gets the given worker its worker node key.
312 * @param worker - The worker.
313 * @returns The worker node key if found in the pool worker nodes, `-1` otherwise.
315 private getWorkerNodeKey (worker
: Worker
): number {
316 return this.workerNodes
.findIndex(
317 workerNode
=> workerNode
.worker
=== worker
322 public setWorkerChoiceStrategy (
323 workerChoiceStrategy
: WorkerChoiceStrategy
,
324 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
326 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
327 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
328 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
329 this.opts
.workerChoiceStrategy
331 if (workerChoiceStrategyOptions
!= null) {
332 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
334 for (const [workerNodeKey
, workerNode
] of this.workerNodes
.entries()) {
335 this.setWorkerNodeTasksUsage(
337 this.getWorkerUsage(workerNodeKey
)
339 this.setWorkerStatistics(workerNode
.worker
)
344 public setWorkerChoiceStrategyOptions (
345 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
347 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
348 this.opts
.workerChoiceStrategyOptions
= workerChoiceStrategyOptions
349 this.workerChoiceStrategyContext
.setOptions(
350 this.opts
.workerChoiceStrategyOptions
355 public enableTasksQueue (
357 tasksQueueOptions
?: TasksQueueOptions
359 if (this.opts
.enableTasksQueue
=== true && !enable
) {
360 this.flushTasksQueues()
362 this.opts
.enableTasksQueue
= enable
363 this.setTasksQueueOptions(tasksQueueOptions
as TasksQueueOptions
)
367 public setTasksQueueOptions (tasksQueueOptions
: TasksQueueOptions
): void {
368 if (this.opts
.enableTasksQueue
=== true) {
369 this.checkValidTasksQueueOptions(tasksQueueOptions
)
370 this.opts
.tasksQueueOptions
=
371 this.buildTasksQueueOptions(tasksQueueOptions
)
372 } else if (this.opts
.tasksQueueOptions
!= null) {
373 delete this.opts
.tasksQueueOptions
377 private buildTasksQueueOptions (
378 tasksQueueOptions
: TasksQueueOptions
379 ): TasksQueueOptions
{
381 concurrency
: tasksQueueOptions
?.concurrency
?? 1
386 * Whether the pool is full or not.
388 * The pool filling boolean status.
390 protected get
full (): boolean {
391 return this.workerNodes
.length
>= this.maxSize
395 * Whether the pool is busy or not.
397 * The pool busyness boolean status.
399 protected abstract get
busy (): boolean
402 * Whether worker nodes are executing at least one task.
404 * @returns Worker nodes busyness boolean status.
406 protected internalBusy (): boolean {
408 this.workerNodes
.findIndex(workerNode
=> {
409 return workerNode
.usage
.tasks
.executing
=== 0
415 public async execute (data
?: Data
, name
?: string): Promise
<Response
> {
416 const timestamp
= performance
.now()
417 const workerNodeKey
= this.chooseWorkerNode()
418 const submittedTask
: Task
<Data
> = {
420 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
421 data
: data
?? ({} as Data
),
423 id
: crypto
.randomUUID()
425 const res
= new Promise
<Response
>((resolve
, reject
) => {
426 this.promiseResponseMap
.set(submittedTask
.id
as string, {
429 worker
: this.workerNodes
[workerNodeKey
].worker
433 this.opts
.enableTasksQueue
=== true &&
435 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
>=
436 ((this.opts
.tasksQueueOptions
as TasksQueueOptions
)
437 .concurrency
as number))
439 this.enqueueTask(workerNodeKey
, submittedTask
)
441 this.executeTask(workerNodeKey
, submittedTask
)
443 this.checkAndEmitEvents()
444 // eslint-disable-next-line @typescript-eslint/return-await
449 public async destroy (): Promise
<void> {
451 this.workerNodes
.map(async (workerNode
, workerNodeKey
) => {
452 this.flushTasksQueue(workerNodeKey
)
453 // FIXME: wait for tasks to be finished
454 await this.destroyWorker(workerNode
.worker
)
460 * Terminates the given worker.
462 * @param worker - A worker within `workerNodes`.
464 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
467 * Setup hook to execute code before worker nodes are created in the abstract constructor.
472 protected setupHook (): void {
473 // Intentionally empty
477 * Should return whether the worker is the main worker or not.
479 protected abstract isMain (): boolean
482 * Hook executed before the worker task execution.
485 * @param workerNodeKey - The worker node key.
486 * @param task - The task to execute.
488 protected beforeTaskExecutionHook (
489 workerNodeKey
: number,
492 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
493 ++workerUsage
.tasks
.executing
494 this.updateWaitTimeWorkerUsage(workerUsage
, task
)
498 * Hook executed after the worker task execution.
501 * @param worker - The worker.
502 * @param message - The received message.
504 protected afterTaskExecutionHook (
506 message
: MessageValue
<Response
>
508 const workerUsage
= this.workerNodes
[this.getWorkerNodeKey(worker
)].usage
509 this.updateTaskStatisticsWorkerUsage(workerUsage
, message
)
510 this.updateRunTimeWorkerUsage(workerUsage
, message
)
511 this.updateEluWorkerUsage(workerUsage
, message
)
514 private updateTaskStatisticsWorkerUsage (
515 workerUsage
: WorkerUsage
,
516 message
: MessageValue
<Response
>
518 const workerTaskStatistics
= workerUsage
.tasks
519 --workerTaskStatistics
.executing
520 ++workerTaskStatistics
.executed
521 if (message
.taskError
!= null) {
522 ++workerTaskStatistics
.failed
526 private updateRunTimeWorkerUsage (
527 workerUsage
: WorkerUsage
,
528 message
: MessageValue
<Response
>
531 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
534 workerUsage
.runTime
.aggregate
+= message
.taskPerformance
?.runTime
?? 0
536 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
538 workerUsage
.tasks
.executed
!== 0
540 workerUsage
.runTime
.average
=
541 workerUsage
.runTime
.aggregate
/
542 (workerUsage
.tasks
.executed
- workerUsage
.tasks
.failed
)
545 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
547 message
.taskPerformance
?.runTime
!= null
549 workerUsage
.runTime
.history
.push(message
.taskPerformance
.runTime
)
550 workerUsage
.runTime
.median
= median(workerUsage
.runTime
.history
)
555 private updateWaitTimeWorkerUsage (
556 workerUsage
: WorkerUsage
,
559 const timestamp
= performance
.now()
560 const taskWaitTime
= timestamp
- (task
.timestamp
?? timestamp
)
562 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().waitTime
565 workerUsage
.waitTime
.aggregate
+= taskWaitTime
?? 0
567 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
569 workerUsage
.tasks
.executed
!== 0
571 workerUsage
.waitTime
.average
=
572 workerUsage
.waitTime
.aggregate
/
573 (workerUsage
.tasks
.executed
- workerUsage
.tasks
.failed
)
576 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
580 workerUsage
.waitTime
.history
.push(taskWaitTime
)
581 workerUsage
.waitTime
.median
= median(workerUsage
.waitTime
.history
)
586 private updateEluWorkerUsage (
587 workerUsage
: WorkerUsage
,
588 message
: MessageValue
<Response
>
591 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
594 if (workerUsage
.elu
!= null && message
.taskPerformance
?.elu
!= null) {
595 workerUsage
.elu
.idle
.aggregate
+= message
.taskPerformance
.elu
.idle
596 workerUsage
.elu
.active
.aggregate
+= message
.taskPerformance
.elu
.active
597 workerUsage
.elu
.utilization
=
598 (workerUsage
.elu
.utilization
+
599 message
.taskPerformance
.elu
.utilization
) /
601 } else if (message
.taskPerformance
?.elu
!= null) {
602 workerUsage
.elu
.idle
.aggregate
= message
.taskPerformance
.elu
.idle
603 workerUsage
.elu
.active
.aggregate
= message
.taskPerformance
.elu
.active
604 workerUsage
.elu
.utilization
= message
.taskPerformance
.elu
.utilization
607 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
609 workerUsage
.tasks
.executed
!== 0
611 const executedTasks
=
612 workerUsage
.tasks
.executed
- workerUsage
.tasks
.failed
613 workerUsage
.elu
.idle
.average
=
614 workerUsage
.elu
.idle
.aggregate
/ executedTasks
615 workerUsage
.elu
.active
.average
=
616 workerUsage
.elu
.active
.aggregate
/ executedTasks
619 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
621 message
.taskPerformance
?.elu
!= null
623 workerUsage
.elu
.idle
.history
.push(message
.taskPerformance
.elu
.idle
)
624 workerUsage
.elu
.active
.history
.push(message
.taskPerformance
.elu
.active
)
625 workerUsage
.elu
.idle
.median
= median(workerUsage
.elu
.idle
.history
)
626 workerUsage
.elu
.active
.median
= median(workerUsage
.elu
.active
.history
)
632 * Chooses a worker node for the next task.
634 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
636 * @returns The worker node key
638 private chooseWorkerNode (): number {
639 if (this.shallCreateDynamicWorker()) {
640 const worker
= this.createAndSetupDynamicWorker()
642 this.workerChoiceStrategyContext
.getStrategyPolicy().useDynamicWorker
644 return this.getWorkerNodeKey(worker
)
647 return this.workerChoiceStrategyContext
.execute()
651 * Conditions for dynamic worker creation.
653 * @returns Whether to create a dynamic worker or not.
655 private shallCreateDynamicWorker (): boolean {
656 return this.type === PoolTypes
.dynamic
&& !this.full
&& this.internalBusy()
660 * Sends a message to the given worker.
662 * @param worker - The worker which should receive the message.
663 * @param message - The message.
665 protected abstract sendToWorker (
667 message
: MessageValue
<Data
>
671 * Registers a listener callback on the given worker.
673 * @param worker - The worker which should register a listener.
674 * @param listener - The message listener callback.
676 private registerWorkerMessageListener
<Message
extends Data
| Response
>(
678 listener
: (message
: MessageValue
<Message
>) => void
680 worker
.on('message', listener
as MessageHandler
<Worker
>)
684 * Creates a new worker.
686 * @returns Newly created worker.
688 protected abstract createWorker (): Worker
691 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
694 * @param worker - The newly created worker.
696 protected afterWorkerSetup (worker
: Worker
): void {
697 // Listen to worker messages.
698 this.registerWorkerMessageListener(worker
, this.workerListener())
702 * Creates a new worker and sets it up completely in the pool worker nodes.
704 * @returns New, completely set up worker.
706 protected createAndSetupWorker (): Worker
{
707 const worker
= this.createWorker()
709 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
710 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
711 worker
.on('error', error
=> {
712 if (this.emitter
!= null) {
713 this.emitter
.emit(PoolEvents
.error
, error
)
715 if (this.opts
.restartWorkerOnError
=== true) {
716 this.createAndSetupWorker()
719 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
720 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
721 worker
.once('exit', () => {
722 this.removeWorkerNode(worker
)
725 this.pushWorkerNode(worker
)
727 this.setWorkerStatistics(worker
)
729 this.afterWorkerSetup(worker
)
735 * Creates a new dynamic worker and sets it up completely in the pool worker nodes.
737 * @returns New, completely set up dynamic worker.
739 protected createAndSetupDynamicWorker (): Worker
{
740 const worker
= this.createAndSetupWorker()
741 this.registerWorkerMessageListener(worker
, message
=> {
742 const workerNodeKey
= this.getWorkerNodeKey(worker
)
744 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
745 (message
.kill
!= null &&
746 ((this.opts
.enableTasksQueue
=== false &&
747 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
=== 0) ||
748 (this.opts
.enableTasksQueue
=== true &&
749 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
=== 0 &&
750 this.tasksQueueSize(workerNodeKey
) === 0)))
752 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
753 void (this.destroyWorker(worker
) as Promise
<void>)
760 * This function is the listener registered for each worker message.
762 * @returns The listener function to execute when a message is received from a worker.
764 protected workerListener (): (message
: MessageValue
<Response
>) => void {
766 if (message
.id
!= null) {
767 // Task execution response received
768 const promiseResponse
= this.promiseResponseMap
.get(message
.id
)
769 if (promiseResponse
!= null) {
770 if (message
.taskError
!= null) {
771 if (this.emitter
!= null) {
772 this.emitter
.emit(PoolEvents
.taskError
, message
.taskError
)
774 promiseResponse
.reject(message
.taskError
.message
)
776 promiseResponse
.resolve(message
.data
as Response
)
778 this.afterTaskExecutionHook(promiseResponse
.worker
, message
)
779 this.promiseResponseMap
.delete(message
.id
)
780 const workerNodeKey
= this.getWorkerNodeKey(promiseResponse
.worker
)
782 this.opts
.enableTasksQueue
=== true &&
783 this.tasksQueueSize(workerNodeKey
) > 0
787 this.dequeueTask(workerNodeKey
) as Task
<Data
>
790 this.workerChoiceStrategyContext
.update(workerNodeKey
)
796 private checkAndEmitEvents (): void {
797 if (this.emitter
!= null) {
799 this.emitter
?.emit(PoolEvents
.busy
, this.info
)
801 if (this.type === PoolTypes
.dynamic
&& this.full
) {
802 this.emitter
?.emit(PoolEvents
.full
, this.info
)
808 * Sets the given worker node its tasks usage in the pool.
810 * @param workerNode - The worker node.
811 * @param workerUsage - The worker usage.
813 private setWorkerNodeTasksUsage (
814 workerNode
: WorkerNode
<Worker
, Data
>,
815 workerUsage
: WorkerUsage
817 workerNode
.usage
= workerUsage
821 * Pushes the given worker in the pool worker nodes.
823 * @param worker - The worker.
824 * @returns The worker nodes length.
826 private pushWorkerNode (worker
: Worker
): number {
827 this.workerNodes
.push({
829 usage
: this.getWorkerUsage(),
830 tasksQueue
: new Queue
<Task
<Data
>>()
832 const workerNodeKey
= this.getWorkerNodeKey(worker
)
833 this.setWorkerNodeTasksUsage(
834 this.workerNodes
[workerNodeKey
],
835 this.getWorkerUsage(workerNodeKey
)
837 return this.workerNodes
.length
841 // * Sets the given worker in the pool worker nodes.
843 // * @param workerNodeKey - The worker node key.
844 // * @param worker - The worker.
845 // * @param workerUsage - The worker usage.
846 // * @param tasksQueue - The worker task queue.
848 // private setWorkerNode (
849 // workerNodeKey: number,
851 // workerUsage: WorkerUsage,
852 // tasksQueue: Queue<Task<Data>>
854 // this.workerNodes[workerNodeKey] = {
856 // usage: workerUsage,
862 * Removes the given worker from the pool worker nodes.
864 * @param worker - The worker.
866 private removeWorkerNode (worker
: Worker
): void {
867 const workerNodeKey
= this.getWorkerNodeKey(worker
)
868 if (workerNodeKey
!== -1) {
869 this.workerNodes
.splice(workerNodeKey
, 1)
870 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
874 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
875 this.beforeTaskExecutionHook(workerNodeKey
, task
)
876 this.sendToWorker(this.workerNodes
[workerNodeKey
].worker
, task
)
879 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
880 return this.workerNodes
[workerNodeKey
].tasksQueue
.enqueue(task
)
883 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
884 return this.workerNodes
[workerNodeKey
].tasksQueue
.dequeue()
887 private tasksQueueSize (workerNodeKey
: number): number {
888 return this.workerNodes
[workerNodeKey
].tasksQueue
.size
891 private tasksMaxQueueSize (workerNodeKey
: number): number {
892 return this.workerNodes
[workerNodeKey
].tasksQueue
.maxSize
895 private flushTasksQueue (workerNodeKey
: number): void {
896 if (this.tasksQueueSize(workerNodeKey
) > 0) {
897 for (let i
= 0; i
< this.tasksQueueSize(workerNodeKey
); i
++) {
900 this.dequeueTask(workerNodeKey
) as Task
<Data
>
904 this.workerNodes
[workerNodeKey
].tasksQueue
.clear()
907 private flushTasksQueues (): void {
908 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
909 this.flushTasksQueue(workerNodeKey
)
913 private setWorkerStatistics (worker
: Worker
): void {
914 this.sendToWorker(worker
, {
917 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
919 elu
: this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
925 private getWorkerUsage (workerNodeKey
?: number): WorkerUsage
{
926 const getTasksQueueSize
= (workerNodeKey
?: number): number => {
927 return workerNodeKey
!= null ? this.tasksQueueSize(workerNodeKey
) : 0
929 const getTasksMaxQueueSize
= (workerNodeKey
?: number): number => {
930 return workerNodeKey
!= null ? this.tasksMaxQueueSize(workerNodeKey
) : 0
936 get
queued (): number {
937 return getTasksQueueSize(workerNodeKey
)
939 get
maxQueued (): number {
940 return getTasksMaxQueueSize(workerNodeKey
)
948 history
: new CircularArray()
954 history
: new CircularArray()
961 history
: new CircularArray()
967 history
: new CircularArray()