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
,
12 import { KillBehaviors
} from
'../worker/worker-options'
13 import { CircularArray
} from
'../circular-array'
14 import { Queue
} from
'../queue'
23 type TasksQueueOptions
,
36 WorkerChoiceStrategies
,
37 type WorkerChoiceStrategy
,
38 type WorkerChoiceStrategyOptions
39 } from
'./selection-strategies/selection-strategies-types'
40 import { WorkerChoiceStrategyContext
} from
'./selection-strategies/worker-choice-strategy-context'
43 * Base class that implements some shared logic for all poolifier pools.
45 * @typeParam Worker - Type of worker which manages this pool.
46 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
47 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
49 export abstract class AbstractPool
<
50 Worker
extends IWorker
,
53 > implements IPool
<Worker
, Data
, Response
> {
55 public readonly workerNodes
: Array<WorkerNode
<Worker
, Data
>> = []
58 public readonly emitter
?: PoolEmitter
61 * The execution response promise map.
63 * - `key`: The message id of each submitted task.
64 * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks.
66 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
68 protected promiseResponseMap
: Map
<
70 PromiseResponseWrapper
<Worker
, Response
>
71 > = new Map
<string, PromiseResponseWrapper
<Worker
, Response
>>()
74 * Worker choice strategy context referencing a worker choice algorithm implementation.
76 protected workerChoiceStrategyContext
: WorkerChoiceStrategyContext
<
83 * The start timestamp of the pool.
85 private readonly startTimestamp
88 * Constructs a new poolifier pool.
90 * @param numberOfWorkers - Number of workers that this pool should manage.
91 * @param filePath - Path to the worker file.
92 * @param opts - Options for the pool.
95 protected readonly numberOfWorkers
: number,
96 protected readonly filePath
: string,
97 protected readonly opts
: PoolOptions
<Worker
>
100 throw new Error('Cannot start a pool from a worker!')
102 this.checkNumberOfWorkers(this.numberOfWorkers
)
103 this.checkFilePath(this.filePath
)
104 this.checkPoolOptions(this.opts
)
106 this.chooseWorkerNode
= this.chooseWorkerNode
.bind(this)
107 this.executeTask
= this.executeTask
.bind(this)
108 this.enqueueTask
= this.enqueueTask
.bind(this)
109 this.checkAndEmitEvents
= this.checkAndEmitEvents
.bind(this)
111 if (this.opts
.enableEvents
=== true) {
112 this.emitter
= new PoolEmitter()
114 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext
<
120 this.opts
.workerChoiceStrategy
,
121 this.opts
.workerChoiceStrategyOptions
126 while (this.workerNodes
.length
< this.numberOfWorkers
) {
127 this.createAndSetupWorker()
130 this.startTimestamp
= performance
.now()
133 private checkFilePath (filePath
: string): void {
136 (typeof filePath
=== 'string' && filePath
.trim().length
=== 0)
138 throw new Error('Please specify a file with a worker implementation')
142 private checkNumberOfWorkers (numberOfWorkers
: number): void {
143 if (numberOfWorkers
== null) {
145 'Cannot instantiate a pool without specifying the number of workers'
147 } else if (!Number.isSafeInteger(numberOfWorkers
)) {
149 'Cannot instantiate a pool with a non safe integer number of workers'
151 } else if (numberOfWorkers
< 0) {
152 throw new RangeError(
153 'Cannot instantiate a pool with a negative number of workers'
155 } else if (this.type === PoolTypes
.fixed
&& numberOfWorkers
=== 0) {
156 throw new Error('Cannot instantiate a fixed pool with no worker')
160 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
161 if (isPlainObject(opts
)) {
162 this.opts
.workerChoiceStrategy
=
163 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
164 this.checkValidWorkerChoiceStrategy(this.opts
.workerChoiceStrategy
)
165 this.opts
.workerChoiceStrategyOptions
=
166 opts
.workerChoiceStrategyOptions
??
167 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
168 this.checkValidWorkerChoiceStrategyOptions(
169 this.opts
.workerChoiceStrategyOptions
171 this.opts
.restartWorkerOnError
= opts
.restartWorkerOnError
?? true
172 this.opts
.enableEvents
= opts
.enableEvents
?? true
173 this.opts
.enableTasksQueue
= opts
.enableTasksQueue
?? false
174 if (this.opts
.enableTasksQueue
) {
175 this.checkValidTasksQueueOptions(
176 opts
.tasksQueueOptions
as TasksQueueOptions
178 this.opts
.tasksQueueOptions
= this.buildTasksQueueOptions(
179 opts
.tasksQueueOptions
as TasksQueueOptions
183 throw new TypeError('Invalid pool options: must be a plain object')
187 private checkValidWorkerChoiceStrategy (
188 workerChoiceStrategy
: WorkerChoiceStrategy
190 if (!Object.values(WorkerChoiceStrategies
).includes(workerChoiceStrategy
)) {
192 `Invalid worker choice strategy '${workerChoiceStrategy}'`
197 private checkValidWorkerChoiceStrategyOptions (
198 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
200 if (!isPlainObject(workerChoiceStrategyOptions
)) {
202 'Invalid worker choice strategy options: must be a plain object'
206 workerChoiceStrategyOptions
.weights
!= null &&
207 Object.keys(workerChoiceStrategyOptions
.weights
).length
!== this.maxSize
210 'Invalid worker choice strategy options: must have a weight for each worker node'
214 workerChoiceStrategyOptions
.measurement
!= null &&
215 !Object.values(Measurements
).includes(
216 workerChoiceStrategyOptions
.measurement
220 `Invalid worker choice strategy options: invalid measurement '${workerChoiceStrategyOptions.measurement}'`
225 private checkValidTasksQueueOptions (
226 tasksQueueOptions
: TasksQueueOptions
228 if (tasksQueueOptions
!= null && !isPlainObject(tasksQueueOptions
)) {
229 throw new TypeError('Invalid tasks queue options: must be a plain object')
232 tasksQueueOptions
?.concurrency
!= null &&
233 !Number.isSafeInteger(tasksQueueOptions
.concurrency
)
236 'Invalid worker tasks concurrency: must be an integer'
240 tasksQueueOptions
?.concurrency
!= null &&
241 tasksQueueOptions
.concurrency
<= 0
244 `Invalid worker tasks concurrency '${tasksQueueOptions.concurrency}'`
250 public get
info (): PoolInfo
{
254 minSize
: this.minSize
,
255 maxSize
: this.maxSize
,
256 utilization
: round(this.utilization
),
257 workerNodes
: this.workerNodes
.length
,
258 idleWorkerNodes
: this.workerNodes
.reduce(
259 (accumulator
, workerNode
) =>
260 workerNode
.usage
.tasks
.executing
=== 0
265 busyWorkerNodes
: this.workerNodes
.reduce(
266 (accumulator
, workerNode
) =>
267 workerNode
.usage
.tasks
.executing
> 0 ? accumulator
+ 1 : accumulator
,
270 executedTasks
: this.workerNodes
.reduce(
271 (accumulator
, workerNode
) =>
272 accumulator
+ workerNode
.usage
.tasks
.executed
,
275 executingTasks
: this.workerNodes
.reduce(
276 (accumulator
, workerNode
) =>
277 accumulator
+ workerNode
.usage
.tasks
.executing
,
280 queuedTasks
: this.workerNodes
.reduce(
281 (accumulator
, workerNode
) =>
282 accumulator
+ workerNode
.usage
.tasks
.queued
,
285 maxQueuedTasks
: this.workerNodes
.reduce(
286 (accumulator
, workerNode
) =>
287 accumulator
+ workerNode
.usage
.tasks
.maxQueued
,
290 failedTasks
: this.workerNodes
.reduce(
291 (accumulator
, workerNode
) =>
292 accumulator
+ workerNode
.usage
.tasks
.failed
,
299 * Gets the pool run time.
301 * @returns The pool run time in milliseconds.
303 private get
runTime (): number {
304 return performance
.now() - this.startTimestamp
308 * Gets the approximate pool utilization.
310 * @returns The pool utilization.
312 private get
utilization (): number {
313 const poolRunTimeCapacity
= this.runTime
* this.maxSize
314 const totalTasksRunTime
= this.workerNodes
.reduce(
315 (accumulator
, workerNode
) =>
316 accumulator
+ workerNode
.usage
.runTime
.aggregate
,
319 const totalTasksWaitTime
= this.workerNodes
.reduce(
320 (accumulator
, workerNode
) =>
321 accumulator
+ workerNode
.usage
.waitTime
.aggregate
,
324 return (totalTasksRunTime
+ totalTasksWaitTime
) / poolRunTimeCapacity
330 * If it is `'dynamic'`, it provides the `max` property.
332 protected abstract get
type (): PoolType
335 * Gets the worker type.
337 protected abstract get
worker (): WorkerType
342 protected abstract get
minSize (): number
347 protected abstract get
maxSize (): number
350 * Get the worker given its id.
352 * @param workerId - The worker id.
353 * @returns The worker if found in the pool worker nodes, `undefined` otherwise.
355 private getWorkerById (workerId
: number): Worker
| undefined {
356 return this.workerNodes
.find(workerNode
=> workerNode
.info
.id
=== workerId
)
361 * Gets the given worker its worker node key.
363 * @param worker - The worker.
364 * @returns The worker node key if found in the pool worker nodes, `-1` otherwise.
366 private getWorkerNodeKey (worker
: Worker
): number {
367 return this.workerNodes
.findIndex(
368 workerNode
=> workerNode
.worker
=== worker
373 public setWorkerChoiceStrategy (
374 workerChoiceStrategy
: WorkerChoiceStrategy
,
375 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
377 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
378 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
379 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
380 this.opts
.workerChoiceStrategy
382 if (workerChoiceStrategyOptions
!= null) {
383 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
385 for (const [workerNodeKey
, workerNode
] of this.workerNodes
.entries()) {
386 this.setWorkerNodeTasksUsage(
388 this.getWorkerUsage(workerNodeKey
)
390 this.setWorkerStatistics(workerNode
.worker
)
395 public setWorkerChoiceStrategyOptions (
396 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
398 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
399 this.opts
.workerChoiceStrategyOptions
= workerChoiceStrategyOptions
400 this.workerChoiceStrategyContext
.setOptions(
401 this.opts
.workerChoiceStrategyOptions
406 public enableTasksQueue (
408 tasksQueueOptions
?: TasksQueueOptions
410 if (this.opts
.enableTasksQueue
=== true && !enable
) {
411 this.flushTasksQueues()
413 this.opts
.enableTasksQueue
= enable
414 this.setTasksQueueOptions(tasksQueueOptions
as TasksQueueOptions
)
418 public setTasksQueueOptions (tasksQueueOptions
: TasksQueueOptions
): void {
419 if (this.opts
.enableTasksQueue
=== true) {
420 this.checkValidTasksQueueOptions(tasksQueueOptions
)
421 this.opts
.tasksQueueOptions
=
422 this.buildTasksQueueOptions(tasksQueueOptions
)
423 } else if (this.opts
.tasksQueueOptions
!= null) {
424 delete this.opts
.tasksQueueOptions
428 private buildTasksQueueOptions (
429 tasksQueueOptions
: TasksQueueOptions
430 ): TasksQueueOptions
{
432 concurrency
: tasksQueueOptions
?.concurrency
?? 1
437 * Whether the pool is full or not.
439 * The pool filling boolean status.
441 protected get
full (): boolean {
442 return this.workerNodes
.length
>= this.maxSize
446 * Whether the pool is busy or not.
448 * The pool busyness boolean status.
450 protected abstract get
busy (): boolean
453 * Whether worker nodes are executing at least one task.
455 * @returns Worker nodes busyness boolean status.
457 protected internalBusy (): boolean {
459 this.workerNodes
.findIndex(workerNode
=> {
460 return workerNode
.usage
.tasks
.executing
=== 0
466 public async execute (data
?: Data
, name
?: string): Promise
<Response
> {
467 const timestamp
= performance
.now()
468 const workerNodeKey
= this.chooseWorkerNode()
469 const submittedTask
: Task
<Data
> = {
471 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
472 data
: data
?? ({} as Data
),
474 id
: crypto
.randomUUID()
476 const res
= new Promise
<Response
>((resolve
, reject
) => {
477 this.promiseResponseMap
.set(submittedTask
.id
as string, {
480 worker
: this.workerNodes
[workerNodeKey
].worker
484 this.opts
.enableTasksQueue
=== true &&
486 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
>=
487 ((this.opts
.tasksQueueOptions
as TasksQueueOptions
)
488 .concurrency
as number))
490 this.enqueueTask(workerNodeKey
, submittedTask
)
492 this.executeTask(workerNodeKey
, submittedTask
)
494 this.checkAndEmitEvents()
495 // eslint-disable-next-line @typescript-eslint/return-await
500 public async destroy (): Promise
<void> {
502 this.workerNodes
.map(async (workerNode
, workerNodeKey
) => {
503 this.flushTasksQueue(workerNodeKey
)
504 // FIXME: wait for tasks to be finished
505 await this.destroyWorker(workerNode
.worker
)
511 * Terminates the given worker.
513 * @param worker - A worker within `workerNodes`.
515 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
518 * Setup hook to execute code before worker nodes are created in the abstract constructor.
523 protected setupHook (): void {
524 // Intentionally empty
528 * Should return whether the worker is the main worker or not.
530 protected abstract isMain (): boolean
533 * Hook executed before the worker task execution.
536 * @param workerNodeKey - The worker node key.
537 * @param task - The task to execute.
539 protected beforeTaskExecutionHook (
540 workerNodeKey
: number,
543 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
544 ++workerUsage
.tasks
.executing
545 this.updateWaitTimeWorkerUsage(workerUsage
, task
)
549 * Hook executed after the worker task execution.
552 * @param worker - The worker.
553 * @param message - The received message.
555 protected afterTaskExecutionHook (
557 message
: MessageValue
<Response
>
559 const workerUsage
= this.workerNodes
[this.getWorkerNodeKey(worker
)].usage
560 this.updateTaskStatisticsWorkerUsage(workerUsage
, message
)
561 this.updateRunTimeWorkerUsage(workerUsage
, message
)
562 this.updateEluWorkerUsage(workerUsage
, message
)
565 private updateTaskStatisticsWorkerUsage (
566 workerUsage
: WorkerUsage
,
567 message
: MessageValue
<Response
>
569 const workerTaskStatistics
= workerUsage
.tasks
570 --workerTaskStatistics
.executing
571 ++workerTaskStatistics
.executed
572 if (message
.taskError
!= null) {
573 ++workerTaskStatistics
.failed
577 private updateRunTimeWorkerUsage (
578 workerUsage
: WorkerUsage
,
579 message
: MessageValue
<Response
>
582 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
585 workerUsage
.runTime
.aggregate
+= message
.taskPerformance
?.runTime
?? 0
587 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
589 workerUsage
.tasks
.executed
!== 0
591 workerUsage
.runTime
.average
=
592 workerUsage
.runTime
.aggregate
/
593 (workerUsage
.tasks
.executed
- workerUsage
.tasks
.failed
)
596 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
598 message
.taskPerformance
?.runTime
!= null
600 workerUsage
.runTime
.history
.push(message
.taskPerformance
.runTime
)
601 workerUsage
.runTime
.median
= median(workerUsage
.runTime
.history
)
606 private updateWaitTimeWorkerUsage (
607 workerUsage
: WorkerUsage
,
610 const timestamp
= performance
.now()
611 const taskWaitTime
= timestamp
- (task
.timestamp
?? timestamp
)
613 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().waitTime
616 workerUsage
.waitTime
.aggregate
+= taskWaitTime
?? 0
618 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
620 workerUsage
.tasks
.executed
!== 0
622 workerUsage
.waitTime
.average
=
623 workerUsage
.waitTime
.aggregate
/
624 (workerUsage
.tasks
.executed
- workerUsage
.tasks
.failed
)
627 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
631 workerUsage
.waitTime
.history
.push(taskWaitTime
)
632 workerUsage
.waitTime
.median
= median(workerUsage
.waitTime
.history
)
637 private updateEluWorkerUsage (
638 workerUsage
: WorkerUsage
,
639 message
: MessageValue
<Response
>
642 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
645 if (workerUsage
.elu
!= null && message
.taskPerformance
?.elu
!= null) {
646 workerUsage
.elu
.idle
.aggregate
+= message
.taskPerformance
.elu
.idle
647 workerUsage
.elu
.active
.aggregate
+= message
.taskPerformance
.elu
.active
648 workerUsage
.elu
.utilization
=
649 (workerUsage
.elu
.utilization
+
650 message
.taskPerformance
.elu
.utilization
) /
652 } else if (message
.taskPerformance
?.elu
!= null) {
653 workerUsage
.elu
.idle
.aggregate
= message
.taskPerformance
.elu
.idle
654 workerUsage
.elu
.active
.aggregate
= message
.taskPerformance
.elu
.active
655 workerUsage
.elu
.utilization
= message
.taskPerformance
.elu
.utilization
658 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
660 workerUsage
.tasks
.executed
!== 0
662 const executedTasks
=
663 workerUsage
.tasks
.executed
- workerUsage
.tasks
.failed
664 workerUsage
.elu
.idle
.average
=
665 workerUsage
.elu
.idle
.aggregate
/ executedTasks
666 workerUsage
.elu
.active
.average
=
667 workerUsage
.elu
.active
.aggregate
/ executedTasks
670 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
672 message
.taskPerformance
?.elu
!= null
674 workerUsage
.elu
.idle
.history
.push(message
.taskPerformance
.elu
.idle
)
675 workerUsage
.elu
.active
.history
.push(message
.taskPerformance
.elu
.active
)
676 workerUsage
.elu
.idle
.median
= median(workerUsage
.elu
.idle
.history
)
677 workerUsage
.elu
.active
.median
= median(workerUsage
.elu
.active
.history
)
683 * Chooses a worker node for the next task.
685 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
687 * @returns The worker node key
689 private chooseWorkerNode (): number {
690 if (this.shallCreateDynamicWorker()) {
691 const worker
= this.createAndSetupDynamicWorker()
693 this.workerChoiceStrategyContext
.getStrategyPolicy().useDynamicWorker
695 return this.getWorkerNodeKey(worker
)
698 return this.workerChoiceStrategyContext
.execute()
702 * Conditions for dynamic worker creation.
704 * @returns Whether to create a dynamic worker or not.
706 private shallCreateDynamicWorker (): boolean {
707 return this.type === PoolTypes
.dynamic
&& !this.full
&& this.internalBusy()
711 * Sends a message to the given worker.
713 * @param worker - The worker which should receive the message.
714 * @param message - The message.
716 protected abstract sendToWorker (
718 message
: MessageValue
<Data
>
722 * Registers a listener callback on the given worker.
724 * @param worker - The worker which should register a listener.
725 * @param listener - The message listener callback.
727 private registerWorkerMessageListener
<Message
extends Data
| Response
>(
729 listener
: (message
: MessageValue
<Message
>) => void
731 worker
.on('message', listener
as MessageHandler
<Worker
>)
735 * Creates a new worker.
737 * @returns Newly created worker.
739 protected abstract createWorker (): Worker
742 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
745 * @param worker - The newly created worker.
747 protected afterWorkerSetup (worker
: Worker
): void {
748 // Listen to worker messages.
749 this.registerWorkerMessageListener(worker
, this.workerListener())
753 * Creates a new worker and sets it up completely in the pool worker nodes.
755 * @returns New, completely set up worker.
757 protected createAndSetupWorker (): Worker
{
758 const worker
= this.createWorker()
760 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
761 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
762 worker
.on('error', error
=> {
763 if (this.emitter
!= null) {
764 this.emitter
.emit(PoolEvents
.error
, error
)
766 if (this.opts
.restartWorkerOnError
=== true) {
767 this.createAndSetupWorker()
770 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
771 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
772 worker
.once('exit', () => {
773 this.removeWorkerNode(worker
)
776 this.pushWorkerNode(worker
)
778 this.setWorkerStatistics(worker
)
780 this.afterWorkerSetup(worker
)
786 * Creates a new dynamic worker and sets it up completely in the pool worker nodes.
788 * @returns New, completely set up dynamic worker.
790 protected createAndSetupDynamicWorker (): Worker
{
791 const worker
= this.createAndSetupWorker()
792 this.registerWorkerMessageListener(worker
, message
=> {
793 const workerNodeKey
= this.getWorkerNodeKey(worker
)
795 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
796 (message
.kill
!= null &&
797 ((this.opts
.enableTasksQueue
=== false &&
798 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
=== 0) ||
799 (this.opts
.enableTasksQueue
=== true &&
800 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
=== 0 &&
801 this.tasksQueueSize(workerNodeKey
) === 0)))
803 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
804 void (this.destroyWorker(worker
) as Promise
<void>)
811 * This function is the listener registered for each worker message.
813 * @returns The listener function to execute when a message is received from a worker.
815 protected workerListener (): (message
: MessageValue
<Response
>) => void {
817 if (message
.workerId
!= null && message
.started
!= null) {
818 // Worker started message received
819 const worker
= this.getWorkerById(message
.workerId
)
820 if (worker
!= null) {
821 this.workerNodes
[this.getWorkerNodeKey(worker
)].info
.started
=
825 `Worker started message received from unknown worker '${message.workerId}'`
828 } else if (message
.id
!= null) {
829 // Task execution response received
830 const promiseResponse
= this.promiseResponseMap
.get(message
.id
)
831 if (promiseResponse
!= null) {
832 if (message
.taskError
!= null) {
833 if (this.emitter
!= null) {
834 this.emitter
.emit(PoolEvents
.taskError
, message
.taskError
)
836 promiseResponse
.reject(message
.taskError
.message
)
838 promiseResponse
.resolve(message
.data
as Response
)
840 this.afterTaskExecutionHook(promiseResponse
.worker
, message
)
841 this.promiseResponseMap
.delete(message
.id
)
842 const workerNodeKey
= this.getWorkerNodeKey(promiseResponse
.worker
)
844 this.opts
.enableTasksQueue
=== true &&
845 this.tasksQueueSize(workerNodeKey
) > 0
849 this.dequeueTask(workerNodeKey
) as Task
<Data
>
852 this.workerChoiceStrategyContext
.update(workerNodeKey
)
858 private checkAndEmitEvents (): void {
859 if (this.emitter
!= null) {
861 this.emitter
?.emit(PoolEvents
.busy
, this.info
)
863 if (this.type === PoolTypes
.dynamic
&& this.full
) {
864 this.emitter
?.emit(PoolEvents
.full
, this.info
)
870 * Sets the given worker node its tasks usage in the pool.
872 * @param workerNode - The worker node.
873 * @param workerUsage - The worker usage.
875 private setWorkerNodeTasksUsage (
876 workerNode
: WorkerNode
<Worker
, Data
>,
877 workerUsage
: WorkerUsage
879 workerNode
.usage
= workerUsage
883 * Pushes the given worker in the pool worker nodes.
885 * @param worker - The worker.
886 * @returns The worker nodes length.
888 private pushWorkerNode (worker
: Worker
): number {
889 this.workerNodes
.push({
891 info
: { id
: this.getWorkerId(worker
), started
: true },
892 usage
: this.getWorkerUsage(),
893 tasksQueue
: new Queue
<Task
<Data
>>()
895 const workerNodeKey
= this.getWorkerNodeKey(worker
)
896 this.setWorkerNodeTasksUsage(
897 this.workerNodes
[workerNodeKey
],
898 this.getWorkerUsage(workerNodeKey
)
900 return this.workerNodes
.length
904 * Gets the worker id.
906 * @param worker - The worker.
907 * @returns The worker id.
909 private getWorkerId (worker
: Worker
): number | undefined {
910 if (this.worker
=== WorkerTypes
.thread
) {
911 return worker
.threadId
912 } else if (this.worker
=== WorkerTypes
.cluster
) {
918 // * Sets the given worker in the pool worker nodes.
920 // * @param workerNodeKey - The worker node key.
921 // * @param worker - The worker.
922 // * @param workerInfo - The worker info.
923 // * @param workerUsage - The worker usage.
924 // * @param tasksQueue - The worker task queue.
926 // private setWorkerNode (
927 // workerNodeKey: number,
929 // workerInfo: WorkerInfo,
930 // workerUsage: WorkerUsage,
931 // tasksQueue: Queue<Task<Data>>
933 // this.workerNodes[workerNodeKey] = {
936 // usage: workerUsage,
942 * Removes the given worker from the pool worker nodes.
944 * @param worker - The worker.
946 private removeWorkerNode (worker
: Worker
): void {
947 const workerNodeKey
= this.getWorkerNodeKey(worker
)
948 if (workerNodeKey
!== -1) {
949 this.workerNodes
.splice(workerNodeKey
, 1)
950 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
954 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
955 this.beforeTaskExecutionHook(workerNodeKey
, task
)
956 this.sendToWorker(this.workerNodes
[workerNodeKey
].worker
, task
)
959 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
960 return this.workerNodes
[workerNodeKey
].tasksQueue
.enqueue(task
)
963 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
964 return this.workerNodes
[workerNodeKey
].tasksQueue
.dequeue()
967 private tasksQueueSize (workerNodeKey
: number): number {
968 return this.workerNodes
[workerNodeKey
].tasksQueue
.size
971 private tasksMaxQueueSize (workerNodeKey
: number): number {
972 return this.workerNodes
[workerNodeKey
].tasksQueue
.maxSize
975 private flushTasksQueue (workerNodeKey
: number): void {
976 if (this.tasksQueueSize(workerNodeKey
) > 0) {
977 for (let i
= 0; i
< this.tasksQueueSize(workerNodeKey
); i
++) {
980 this.dequeueTask(workerNodeKey
) as Task
<Data
>
984 this.workerNodes
[workerNodeKey
].tasksQueue
.clear()
987 private flushTasksQueues (): void {
988 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
989 this.flushTasksQueue(workerNodeKey
)
993 private setWorkerStatistics (worker
: Worker
): void {
994 this.sendToWorker(worker
, {
997 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
999 elu
: this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1005 private getWorkerUsage (workerNodeKey
?: number): WorkerUsage
{
1006 const getTasksQueueSize
= (workerNodeKey
?: number): number => {
1007 return workerNodeKey
!= null ? this.tasksQueueSize(workerNodeKey
) : 0
1009 const getTasksMaxQueueSize
= (workerNodeKey
?: number): number => {
1010 return workerNodeKey
!= null ? this.tasksMaxQueueSize(workerNodeKey
) : 0
1016 get
queued (): number {
1017 return getTasksQueueSize(workerNodeKey
)
1019 get
maxQueued (): number {
1020 return getTasksMaxQueueSize(workerNodeKey
)
1028 history
: new CircularArray()
1034 history
: new CircularArray()
1041 history
: new CircularArray()
1047 history
: new CircularArray()