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'
41 import { version
} from
'./version'
44 * Base class that implements some shared logic for all poolifier pools.
46 * @typeParam Worker - Type of worker which manages this pool.
47 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
48 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
50 export abstract class AbstractPool
<
51 Worker
extends IWorker
,
54 > implements IPool
<Worker
, Data
, Response
> {
56 public readonly workerNodes
: Array<WorkerNode
<Worker
, Data
>> = []
59 public readonly emitter
?: PoolEmitter
62 * The execution response promise map.
64 * - `key`: The message id of each submitted task.
65 * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks.
67 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
69 protected promiseResponseMap
: Map
<
71 PromiseResponseWrapper
<Worker
, Response
>
72 > = new Map
<string, PromiseResponseWrapper
<Worker
, Response
>>()
75 * Worker choice strategy context referencing a worker choice algorithm implementation.
77 protected workerChoiceStrategyContext
: WorkerChoiceStrategyContext
<
84 * The start timestamp of the pool.
86 private readonly startTimestamp
89 * Constructs a new poolifier pool.
91 * @param numberOfWorkers - Number of workers that this pool should manage.
92 * @param filePath - Path to the worker file.
93 * @param opts - Options for the pool.
96 protected readonly numberOfWorkers
: number,
97 protected readonly filePath
: string,
98 protected readonly opts
: PoolOptions
<Worker
>
100 if (!this.isMain()) {
101 throw new Error('Cannot start a pool from a worker!')
103 this.checkNumberOfWorkers(this.numberOfWorkers
)
104 this.checkFilePath(this.filePath
)
105 this.checkPoolOptions(this.opts
)
107 this.chooseWorkerNode
= this.chooseWorkerNode
.bind(this)
108 this.executeTask
= this.executeTask
.bind(this)
109 this.enqueueTask
= this.enqueueTask
.bind(this)
110 this.checkAndEmitEvents
= this.checkAndEmitEvents
.bind(this)
112 if (this.opts
.enableEvents
=== true) {
113 this.emitter
= new PoolEmitter()
115 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext
<
121 this.opts
.workerChoiceStrategy
,
122 this.opts
.workerChoiceStrategyOptions
127 while (this.workerNodes
.length
< this.numberOfWorkers
) {
128 this.createAndSetupWorker()
131 this.startTimestamp
= performance
.now()
134 private checkFilePath (filePath
: string): void {
137 (typeof filePath
=== 'string' && filePath
.trim().length
=== 0)
139 throw new Error('Please specify a file with a worker implementation')
143 private checkNumberOfWorkers (numberOfWorkers
: number): void {
144 if (numberOfWorkers
== null) {
146 'Cannot instantiate a pool without specifying the number of workers'
148 } else if (!Number.isSafeInteger(numberOfWorkers
)) {
150 'Cannot instantiate a pool with a non safe integer number of workers'
152 } else if (numberOfWorkers
< 0) {
153 throw new RangeError(
154 'Cannot instantiate a pool with a negative number of workers'
156 } else if (this.type === PoolTypes
.fixed
&& numberOfWorkers
=== 0) {
157 throw new Error('Cannot instantiate a fixed pool with no worker')
161 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
162 if (isPlainObject(opts
)) {
163 this.opts
.workerChoiceStrategy
=
164 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
165 this.checkValidWorkerChoiceStrategy(this.opts
.workerChoiceStrategy
)
166 this.opts
.workerChoiceStrategyOptions
=
167 opts
.workerChoiceStrategyOptions
??
168 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
169 this.checkValidWorkerChoiceStrategyOptions(
170 this.opts
.workerChoiceStrategyOptions
172 this.opts
.restartWorkerOnError
= opts
.restartWorkerOnError
?? true
173 this.opts
.enableEvents
= opts
.enableEvents
?? true
174 this.opts
.enableTasksQueue
= opts
.enableTasksQueue
?? false
175 if (this.opts
.enableTasksQueue
) {
176 this.checkValidTasksQueueOptions(
177 opts
.tasksQueueOptions
as TasksQueueOptions
179 this.opts
.tasksQueueOptions
= this.buildTasksQueueOptions(
180 opts
.tasksQueueOptions
as TasksQueueOptions
184 throw new TypeError('Invalid pool options: must be a plain object')
188 private checkValidWorkerChoiceStrategy (
189 workerChoiceStrategy
: WorkerChoiceStrategy
191 if (!Object.values(WorkerChoiceStrategies
).includes(workerChoiceStrategy
)) {
193 `Invalid worker choice strategy '${workerChoiceStrategy}'`
198 private checkValidWorkerChoiceStrategyOptions (
199 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
201 if (!isPlainObject(workerChoiceStrategyOptions
)) {
203 'Invalid worker choice strategy options: must be a plain object'
207 workerChoiceStrategyOptions
.weights
!= null &&
208 Object.keys(workerChoiceStrategyOptions
.weights
).length
!== this.maxSize
211 'Invalid worker choice strategy options: must have a weight for each worker node'
215 workerChoiceStrategyOptions
.measurement
!= null &&
216 !Object.values(Measurements
).includes(
217 workerChoiceStrategyOptions
.measurement
221 `Invalid worker choice strategy options: invalid measurement '${workerChoiceStrategyOptions.measurement}'`
226 private checkValidTasksQueueOptions (
227 tasksQueueOptions
: TasksQueueOptions
229 if (tasksQueueOptions
!= null && !isPlainObject(tasksQueueOptions
)) {
230 throw new TypeError('Invalid tasks queue options: must be a plain object')
233 tasksQueueOptions
?.concurrency
!= null &&
234 !Number.isSafeInteger(tasksQueueOptions
.concurrency
)
237 'Invalid worker tasks concurrency: must be an integer'
241 tasksQueueOptions
?.concurrency
!= null &&
242 tasksQueueOptions
.concurrency
<= 0
245 `Invalid worker tasks concurrency '${tasksQueueOptions.concurrency}'`
251 public get
info (): PoolInfo
{
256 minSize
: this.minSize
,
257 maxSize
: this.maxSize
,
258 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
259 .runTime
.aggregate
&&
260 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
261 .waitTime
.aggregate
&& { utilization
: round(this.utilization
) }),
262 workerNodes
: this.workerNodes
.length
,
263 idleWorkerNodes
: this.workerNodes
.reduce(
264 (accumulator
, workerNode
) =>
265 workerNode
.usage
.tasks
.executing
=== 0
270 busyWorkerNodes
: this.workerNodes
.reduce(
271 (accumulator
, workerNode
) =>
272 workerNode
.usage
.tasks
.executing
> 0 ? accumulator
+ 1 : accumulator
,
275 executedTasks
: this.workerNodes
.reduce(
276 (accumulator
, workerNode
) =>
277 accumulator
+ workerNode
.usage
.tasks
.executed
,
280 executingTasks
: this.workerNodes
.reduce(
281 (accumulator
, workerNode
) =>
282 accumulator
+ workerNode
.usage
.tasks
.executing
,
285 queuedTasks
: this.workerNodes
.reduce(
286 (accumulator
, workerNode
) =>
287 accumulator
+ workerNode
.usage
.tasks
.queued
,
290 maxQueuedTasks
: this.workerNodes
.reduce(
291 (accumulator
, workerNode
) =>
292 accumulator
+ workerNode
.usage
.tasks
.maxQueued
,
295 failedTasks
: this.workerNodes
.reduce(
296 (accumulator
, workerNode
) =>
297 accumulator
+ workerNode
.usage
.tasks
.failed
,
304 * Gets the pool run time.
306 * @returns The pool run time in milliseconds.
308 private get
runTime (): number {
309 return performance
.now() - this.startTimestamp
313 * Gets the approximate pool utilization.
315 * @returns The pool utilization.
317 private get
utilization (): number {
318 const poolRunTimeCapacity
= this.runTime
* this.maxSize
319 const totalTasksRunTime
= this.workerNodes
.reduce(
320 (accumulator
, workerNode
) =>
321 accumulator
+ workerNode
.usage
.runTime
.aggregate
,
324 const totalTasksWaitTime
= this.workerNodes
.reduce(
325 (accumulator
, workerNode
) =>
326 accumulator
+ workerNode
.usage
.waitTime
.aggregate
,
329 return (totalTasksRunTime
+ totalTasksWaitTime
) / poolRunTimeCapacity
335 * If it is `'dynamic'`, it provides the `max` property.
337 protected abstract get
type (): PoolType
340 * Gets the worker type.
342 protected abstract get
worker (): WorkerType
347 protected abstract get
minSize (): number
352 protected abstract get
maxSize (): number
355 * Get the worker given its id.
357 * @param workerId - The worker id.
358 * @returns The worker if found in the pool worker nodes, `undefined` otherwise.
360 private getWorkerById (workerId
: number): Worker
| undefined {
361 return this.workerNodes
.find(workerNode
=> workerNode
.info
.id
=== workerId
)
366 * Gets the given worker its worker node key.
368 * @param worker - The worker.
369 * @returns The worker node key if found in the pool worker nodes, `-1` otherwise.
371 private getWorkerNodeKey (worker
: Worker
): number {
372 return this.workerNodes
.findIndex(
373 workerNode
=> workerNode
.worker
=== worker
378 public setWorkerChoiceStrategy (
379 workerChoiceStrategy
: WorkerChoiceStrategy
,
380 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
382 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
383 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
384 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
385 this.opts
.workerChoiceStrategy
387 if (workerChoiceStrategyOptions
!= null) {
388 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
390 for (const [workerNodeKey
, workerNode
] of this.workerNodes
.entries()) {
391 this.setWorkerNodeTasksUsage(
393 this.getWorkerUsage(workerNodeKey
)
395 this.setWorkerStatistics(workerNode
.worker
)
400 public setWorkerChoiceStrategyOptions (
401 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
403 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
404 this.opts
.workerChoiceStrategyOptions
= workerChoiceStrategyOptions
405 this.workerChoiceStrategyContext
.setOptions(
406 this.opts
.workerChoiceStrategyOptions
411 public enableTasksQueue (
413 tasksQueueOptions
?: TasksQueueOptions
415 if (this.opts
.enableTasksQueue
=== true && !enable
) {
416 this.flushTasksQueues()
418 this.opts
.enableTasksQueue
= enable
419 this.setTasksQueueOptions(tasksQueueOptions
as TasksQueueOptions
)
423 public setTasksQueueOptions (tasksQueueOptions
: TasksQueueOptions
): void {
424 if (this.opts
.enableTasksQueue
=== true) {
425 this.checkValidTasksQueueOptions(tasksQueueOptions
)
426 this.opts
.tasksQueueOptions
=
427 this.buildTasksQueueOptions(tasksQueueOptions
)
428 } else if (this.opts
.tasksQueueOptions
!= null) {
429 delete this.opts
.tasksQueueOptions
433 private buildTasksQueueOptions (
434 tasksQueueOptions
: TasksQueueOptions
435 ): TasksQueueOptions
{
437 concurrency
: tasksQueueOptions
?.concurrency
?? 1
442 * Whether the pool is full or not.
444 * The pool filling boolean status.
446 protected get
full (): boolean {
447 return this.workerNodes
.length
>= this.maxSize
451 * Whether the pool is busy or not.
453 * The pool busyness boolean status.
455 protected abstract get
busy (): boolean
458 * Whether worker nodes are executing at least one task.
460 * @returns Worker nodes busyness boolean status.
462 protected internalBusy (): boolean {
464 this.workerNodes
.findIndex(workerNode
=> {
465 return workerNode
.usage
.tasks
.executing
=== 0
471 public async execute (data
?: Data
, name
?: string): Promise
<Response
> {
472 const timestamp
= performance
.now()
473 const workerNodeKey
= this.chooseWorkerNode()
474 const submittedTask
: Task
<Data
> = {
476 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
477 data
: data
?? ({} as Data
),
479 id
: crypto
.randomUUID()
481 const res
= new Promise
<Response
>((resolve
, reject
) => {
482 this.promiseResponseMap
.set(submittedTask
.id
as string, {
485 worker
: this.workerNodes
[workerNodeKey
].worker
489 this.opts
.enableTasksQueue
=== true &&
491 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
>=
492 ((this.opts
.tasksQueueOptions
as TasksQueueOptions
)
493 .concurrency
as number))
495 this.enqueueTask(workerNodeKey
, submittedTask
)
497 this.executeTask(workerNodeKey
, submittedTask
)
499 this.checkAndEmitEvents()
500 // eslint-disable-next-line @typescript-eslint/return-await
505 public async destroy (): Promise
<void> {
507 this.workerNodes
.map(async (workerNode
, workerNodeKey
) => {
508 this.flushTasksQueue(workerNodeKey
)
509 // FIXME: wait for tasks to be finished
510 const workerExitPromise
= new Promise
<void>(resolve
=> {
511 workerNode
.worker
.on('exit', () => {
515 await this.destroyWorker(workerNode
.worker
)
516 await workerExitPromise
522 * Terminates the given worker.
524 * @param worker - A worker within `workerNodes`.
526 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
529 * Setup hook to execute code before worker nodes are created in the abstract constructor.
534 protected setupHook (): void {
535 // Intentionally empty
539 * Should return whether the worker is the main worker or not.
541 protected abstract isMain (): boolean
544 * Hook executed before the worker task execution.
547 * @param workerNodeKey - The worker node key.
548 * @param task - The task to execute.
550 protected beforeTaskExecutionHook (
551 workerNodeKey
: number,
554 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
555 ++workerUsage
.tasks
.executing
556 this.updateWaitTimeWorkerUsage(workerUsage
, task
)
560 * Hook executed after the worker task execution.
563 * @param worker - The worker.
564 * @param message - The received message.
566 protected afterTaskExecutionHook (
568 message
: MessageValue
<Response
>
570 const workerUsage
= this.workerNodes
[this.getWorkerNodeKey(worker
)].usage
571 this.updateTaskStatisticsWorkerUsage(workerUsage
, message
)
572 this.updateRunTimeWorkerUsage(workerUsage
, message
)
573 this.updateEluWorkerUsage(workerUsage
, message
)
576 private updateTaskStatisticsWorkerUsage (
577 workerUsage
: WorkerUsage
,
578 message
: MessageValue
<Response
>
580 const workerTaskStatistics
= workerUsage
.tasks
581 --workerTaskStatistics
.executing
582 ++workerTaskStatistics
.executed
583 if (message
.taskError
!= null) {
584 ++workerTaskStatistics
.failed
588 private updateRunTimeWorkerUsage (
589 workerUsage
: WorkerUsage
,
590 message
: MessageValue
<Response
>
593 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
596 workerUsage
.runTime
.aggregate
+= message
.taskPerformance
?.runTime
?? 0
598 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
600 workerUsage
.tasks
.executed
!== 0
602 workerUsage
.runTime
.average
=
603 workerUsage
.runTime
.aggregate
/
604 (workerUsage
.tasks
.executed
- workerUsage
.tasks
.failed
)
607 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
609 message
.taskPerformance
?.runTime
!= null
611 workerUsage
.runTime
.history
.push(message
.taskPerformance
.runTime
)
612 workerUsage
.runTime
.median
= median(workerUsage
.runTime
.history
)
617 private updateWaitTimeWorkerUsage (
618 workerUsage
: WorkerUsage
,
621 const timestamp
= performance
.now()
622 const taskWaitTime
= timestamp
- (task
.timestamp
?? timestamp
)
624 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().waitTime
627 workerUsage
.waitTime
.aggregate
+= taskWaitTime
?? 0
629 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
631 workerUsage
.tasks
.executed
!== 0
633 workerUsage
.waitTime
.average
=
634 workerUsage
.waitTime
.aggregate
/
635 (workerUsage
.tasks
.executed
- workerUsage
.tasks
.failed
)
638 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
642 workerUsage
.waitTime
.history
.push(taskWaitTime
)
643 workerUsage
.waitTime
.median
= median(workerUsage
.waitTime
.history
)
648 private updateEluWorkerUsage (
649 workerUsage
: WorkerUsage
,
650 message
: MessageValue
<Response
>
653 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
656 if (workerUsage
.elu
!= null && message
.taskPerformance
?.elu
!= null) {
657 workerUsage
.elu
.idle
.aggregate
+= message
.taskPerformance
.elu
.idle
658 workerUsage
.elu
.active
.aggregate
+= message
.taskPerformance
.elu
.active
659 workerUsage
.elu
.utilization
=
660 (workerUsage
.elu
.utilization
+
661 message
.taskPerformance
.elu
.utilization
) /
663 } else if (message
.taskPerformance
?.elu
!= null) {
664 workerUsage
.elu
.idle
.aggregate
= message
.taskPerformance
.elu
.idle
665 workerUsage
.elu
.active
.aggregate
= message
.taskPerformance
.elu
.active
666 workerUsage
.elu
.utilization
= message
.taskPerformance
.elu
.utilization
669 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
671 workerUsage
.tasks
.executed
!== 0
673 const executedTasks
=
674 workerUsage
.tasks
.executed
- workerUsage
.tasks
.failed
675 workerUsage
.elu
.idle
.average
=
676 workerUsage
.elu
.idle
.aggregate
/ executedTasks
677 workerUsage
.elu
.active
.average
=
678 workerUsage
.elu
.active
.aggregate
/ executedTasks
681 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
683 message
.taskPerformance
?.elu
!= null
685 workerUsage
.elu
.idle
.history
.push(message
.taskPerformance
.elu
.idle
)
686 workerUsage
.elu
.active
.history
.push(message
.taskPerformance
.elu
.active
)
687 workerUsage
.elu
.idle
.median
= median(workerUsage
.elu
.idle
.history
)
688 workerUsage
.elu
.active
.median
= median(workerUsage
.elu
.active
.history
)
694 * Chooses a worker node for the next task.
696 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
698 * @returns The worker node key
700 private chooseWorkerNode (): number {
701 if (this.shallCreateDynamicWorker()) {
702 const worker
= this.createAndSetupDynamicWorker()
704 this.workerChoiceStrategyContext
.getStrategyPolicy().useDynamicWorker
706 return this.getWorkerNodeKey(worker
)
709 return this.workerChoiceStrategyContext
.execute()
713 * Conditions for dynamic worker creation.
715 * @returns Whether to create a dynamic worker or not.
717 private shallCreateDynamicWorker (): boolean {
718 return this.type === PoolTypes
.dynamic
&& !this.full
&& this.internalBusy()
722 * Sends a message to the given worker.
724 * @param worker - The worker which should receive the message.
725 * @param message - The message.
727 protected abstract sendToWorker (
729 message
: MessageValue
<Data
>
733 * Registers a listener callback on the given worker.
735 * @param worker - The worker which should register a listener.
736 * @param listener - The message listener callback.
738 private registerWorkerMessageListener
<Message
extends Data
| Response
>(
740 listener
: (message
: MessageValue
<Message
>) => void
742 worker
.on('message', listener
as MessageHandler
<Worker
>)
746 * Creates a new worker.
748 * @returns Newly created worker.
750 protected abstract createWorker (): Worker
753 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
756 * @param worker - The newly created worker.
758 protected afterWorkerSetup (worker
: Worker
): void {
759 // Listen to worker messages.
760 this.registerWorkerMessageListener(worker
, this.workerListener())
764 * Creates a new worker and sets it up completely in the pool worker nodes.
766 * @returns New, completely set up worker.
768 protected createAndSetupWorker (): Worker
{
769 const worker
= this.createWorker()
771 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
772 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
773 worker
.on('error', error
=> {
774 if (this.emitter
!= null) {
775 this.emitter
.emit(PoolEvents
.error
, error
)
777 if (this.opts
.enableTasksQueue
=== true) {
778 const workerNodeKey
= this.getWorkerNodeKey(worker
)
779 while (this.tasksQueueSize(workerNodeKey
) > 0) {
780 let targetWorkerNodeKey
: number = workerNodeKey
781 let minQueuedTasks
= Infinity
782 for (const [workerNodeId
, workerNode
] of this.workerNodes
.entries()) {
784 workerNodeId
!== workerNodeKey
&&
785 workerNode
.usage
.tasks
.queued
=== 0
787 targetWorkerNodeKey
= workerNodeId
791 workerNodeId
!== workerNodeKey
&&
792 workerNode
.usage
.tasks
.queued
< minQueuedTasks
794 minQueuedTasks
= workerNode
.usage
.tasks
.queued
795 targetWorkerNodeKey
= workerNodeId
800 this.dequeueTask(workerNodeKey
) as Task
<Data
>
804 if (this.opts
.restartWorkerOnError
=== true) {
805 this.createAndSetupWorker()
808 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
809 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
810 worker
.once('exit', () => {
811 this.removeWorkerNode(worker
)
814 this.pushWorkerNode(worker
)
816 this.setWorkerStatistics(worker
)
818 this.afterWorkerSetup(worker
)
824 * Creates a new dynamic worker and sets it up completely in the pool worker nodes.
826 * @returns New, completely set up dynamic worker.
828 protected createAndSetupDynamicWorker (): Worker
{
829 const worker
= this.createAndSetupWorker()
830 this.registerWorkerMessageListener(worker
, message
=> {
831 const workerNodeKey
= this.getWorkerNodeKey(worker
)
833 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
834 (message
.kill
!= null &&
835 ((this.opts
.enableTasksQueue
=== false &&
836 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
=== 0) ||
837 (this.opts
.enableTasksQueue
=== true &&
838 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
=== 0 &&
839 this.tasksQueueSize(workerNodeKey
) === 0)))
841 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
842 void (this.destroyWorker(worker
) as Promise
<void>)
849 * This function is the listener registered for each worker message.
851 * @returns The listener function to execute when a message is received from a worker.
853 protected workerListener (): (message
: MessageValue
<Response
>) => void {
855 if (message
.workerId
!= null && message
.started
!= null) {
856 // Worker started message received
857 this.handleWorkerStartedMessage(message
)
858 } else if (message
.id
!= null) {
859 // Task execution response received
860 this.handleTaskExecutionResponse(message
)
865 private handleWorkerStartedMessage (message
: MessageValue
<Response
>): void {
866 // Worker started message received
867 const worker
= this.getWorkerById(message
.workerId
as number)
868 if (worker
!= null) {
869 this.workerNodes
[this.getWorkerNodeKey(worker
)].info
.started
=
870 message
.started
as boolean
873 `Worker started message received from unknown worker '${
874 message.workerId as number
880 private handleTaskExecutionResponse (message
: MessageValue
<Response
>): void {
881 const promiseResponse
= this.promiseResponseMap
.get(message
.id
as string)
882 if (promiseResponse
!= null) {
883 if (message
.taskError
!= null) {
884 if (this.emitter
!= null) {
885 this.emitter
.emit(PoolEvents
.taskError
, message
.taskError
)
887 promiseResponse
.reject(message
.taskError
.message
)
889 promiseResponse
.resolve(message
.data
as Response
)
891 this.afterTaskExecutionHook(promiseResponse
.worker
, message
)
892 this.promiseResponseMap
.delete(message
.id
as string)
893 const workerNodeKey
= this.getWorkerNodeKey(promiseResponse
.worker
)
895 this.opts
.enableTasksQueue
=== true &&
896 this.tasksQueueSize(workerNodeKey
) > 0
900 this.dequeueTask(workerNodeKey
) as Task
<Data
>
903 this.workerChoiceStrategyContext
.update(workerNodeKey
)
907 private checkAndEmitEvents (): void {
908 if (this.emitter
!= null) {
910 this.emitter
?.emit(PoolEvents
.busy
, this.info
)
912 if (this.type === PoolTypes
.dynamic
&& this.full
) {
913 this.emitter
?.emit(PoolEvents
.full
, this.info
)
919 * Sets the given worker node its tasks usage in the pool.
921 * @param workerNode - The worker node.
922 * @param workerUsage - The worker usage.
924 private setWorkerNodeTasksUsage (
925 workerNode
: WorkerNode
<Worker
, Data
>,
926 workerUsage
: WorkerUsage
928 workerNode
.usage
= workerUsage
932 * Pushes the given worker in the pool worker nodes.
934 * @param worker - The worker.
935 * @returns The worker nodes length.
937 private pushWorkerNode (worker
: Worker
): number {
938 this.workerNodes
.push({
940 info
: { id
: this.getWorkerId(worker
), started
: true },
941 usage
: this.getWorkerUsage(),
942 tasksQueue
: new Queue
<Task
<Data
>>()
944 const workerNodeKey
= this.getWorkerNodeKey(worker
)
945 this.setWorkerNodeTasksUsage(
946 this.workerNodes
[workerNodeKey
],
947 this.getWorkerUsage(workerNodeKey
)
949 return this.workerNodes
.length
953 * Gets the worker id.
955 * @param worker - The worker.
956 * @returns The worker id.
958 private getWorkerId (worker
: Worker
): number | undefined {
959 if (this.worker
=== WorkerTypes
.thread
) {
960 return worker
.threadId
961 } else if (this.worker
=== WorkerTypes
.cluster
) {
967 // * Sets the given worker in the pool worker nodes.
969 // * @param workerNodeKey - The worker node key.
970 // * @param worker - The worker.
971 // * @param workerInfo - The worker info.
972 // * @param workerUsage - The worker usage.
973 // * @param tasksQueue - The worker task queue.
975 // private setWorkerNode (
976 // workerNodeKey: number,
978 // workerInfo: WorkerInfo,
979 // workerUsage: WorkerUsage,
980 // tasksQueue: Queue<Task<Data>>
982 // this.workerNodes[workerNodeKey] = {
985 // usage: workerUsage,
991 * Removes the given worker from the pool worker nodes.
993 * @param worker - The worker.
995 private removeWorkerNode (worker
: Worker
): void {
996 const workerNodeKey
= this.getWorkerNodeKey(worker
)
997 if (workerNodeKey
!== -1) {
998 this.workerNodes
.splice(workerNodeKey
, 1)
999 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
1003 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
1004 this.beforeTaskExecutionHook(workerNodeKey
, task
)
1005 this.sendToWorker(this.workerNodes
[workerNodeKey
].worker
, task
)
1008 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
1009 return this.workerNodes
[workerNodeKey
].tasksQueue
.enqueue(task
)
1012 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
1013 return this.workerNodes
[workerNodeKey
].tasksQueue
.dequeue()
1016 private tasksQueueSize (workerNodeKey
: number): number {
1017 return this.workerNodes
[workerNodeKey
].tasksQueue
.size
1020 private tasksMaxQueueSize (workerNodeKey
: number): number {
1021 return this.workerNodes
[workerNodeKey
].tasksQueue
.maxSize
1024 private flushTasksQueue (workerNodeKey
: number): void {
1025 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1028 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1031 this.workerNodes
[workerNodeKey
].tasksQueue
.clear()
1034 private flushTasksQueues (): void {
1035 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
1036 this.flushTasksQueue(workerNodeKey
)
1040 private setWorkerStatistics (worker
: Worker
): void {
1041 this.sendToWorker(worker
, {
1044 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1046 elu
: this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1052 private getWorkerUsage (workerNodeKey
?: number): WorkerUsage
{
1053 const getTasksQueueSize
= (workerNodeKey
?: number): number => {
1054 return workerNodeKey
!= null ? this.tasksQueueSize(workerNodeKey
) : 0
1056 const getTasksMaxQueueSize
= (workerNodeKey
?: number): number => {
1057 return workerNodeKey
!= null ? this.tasksMaxQueueSize(workerNodeKey
) : 0
1063 get
queued (): number {
1064 return getTasksQueueSize(workerNodeKey
)
1066 get
maxQueued (): number {
1067 return getTasksMaxQueueSize(workerNodeKey
)
1075 history
: new CircularArray()
1081 history
: new CircularArray()
1088 history
: new CircularArray()
1094 history
: new CircularArray()