1 import { randomUUID
} from
'node:crypto'
2 import { performance
} from
'node:perf_hooks'
3 import { existsSync
} from
'node:fs'
4 import { type TransferListItem
} from
'node:worker_threads'
7 PromiseResponseWrapper
,
9 } from
'../utility-types'
12 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
,
21 updateMeasurementStatistics
23 import { KillBehaviors
} from
'../worker/worker-options'
32 type TasksQueueOptions
42 type MeasurementStatisticsRequirements
,
44 WorkerChoiceStrategies
,
45 type WorkerChoiceStrategy
,
46 type WorkerChoiceStrategyOptions
47 } from
'./selection-strategies/selection-strategies-types'
48 import { WorkerChoiceStrategyContext
} from
'./selection-strategies/worker-choice-strategy-context'
49 import { version
} from
'./version'
50 import { WorkerNode
} from
'./worker-node'
53 * Base class that implements some shared logic for all poolifier pools.
55 * @typeParam Worker - Type of worker which manages this pool.
56 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
57 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
59 export abstract class AbstractPool
<
60 Worker
extends IWorker
,
63 > implements IPool
<Worker
, Data
, Response
> {
65 public readonly workerNodes
: Array<IWorkerNode
<Worker
, Data
>> = []
68 public readonly emitter
?: PoolEmitter
71 * The task execution response promise map.
73 * - `key`: The message id of each submitted task.
74 * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks.
76 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
78 protected promiseResponseMap
: Map
<string, PromiseResponseWrapper
<Response
>> =
79 new Map
<string, PromiseResponseWrapper
<Response
>>()
82 * Worker choice strategy context referencing a worker choice algorithm implementation.
84 protected workerChoiceStrategyContext
: WorkerChoiceStrategyContext
<
91 * Dynamic pool maximum size property placeholder.
93 protected readonly max
?: number
96 * Whether the pool is starting or not.
98 private readonly starting
: boolean
100 * Whether the pool is started or not.
102 private started
: boolean
104 * The start timestamp of the pool.
106 private readonly startTimestamp
109 * Constructs a new poolifier pool.
111 * @param numberOfWorkers - Number of workers that this pool should manage.
112 * @param filePath - Path to the worker file.
113 * @param opts - Options for the pool.
116 protected readonly numberOfWorkers
: number,
117 protected readonly filePath
: string,
118 protected readonly opts
: PoolOptions
<Worker
>
120 if (!this.isMain()) {
122 'Cannot start a pool from a worker with the same type as the pool'
125 this.checkNumberOfWorkers(this.numberOfWorkers
)
126 this.checkFilePath(this.filePath
)
127 this.checkPoolOptions(this.opts
)
129 this.chooseWorkerNode
= this.chooseWorkerNode
.bind(this)
130 this.executeTask
= this.executeTask
.bind(this)
131 this.enqueueTask
= this.enqueueTask
.bind(this)
133 if (this.opts
.enableEvents
=== true) {
134 this.emitter
= new PoolEmitter()
136 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext
<
142 this.opts
.workerChoiceStrategy
,
143 this.opts
.workerChoiceStrategyOptions
150 this.starting
= false
153 this.startTimestamp
= performance
.now()
156 private checkFilePath (filePath
: string): void {
159 typeof filePath
!== 'string' ||
160 (typeof filePath
=== 'string' && filePath
.trim().length
=== 0)
162 throw new Error('Please specify a file with a worker implementation')
164 if (!existsSync(filePath
)) {
165 throw new Error(`Cannot find the worker file '${filePath}'`)
169 private checkNumberOfWorkers (numberOfWorkers
: number): void {
170 if (numberOfWorkers
== null) {
172 'Cannot instantiate a pool without specifying the number of workers'
174 } else if (!Number.isSafeInteger(numberOfWorkers
)) {
176 'Cannot instantiate a pool with a non safe integer number of workers'
178 } else if (numberOfWorkers
< 0) {
179 throw new RangeError(
180 'Cannot instantiate a pool with a negative number of workers'
182 } else if (this.type === PoolTypes
.fixed
&& numberOfWorkers
=== 0) {
183 throw new RangeError('Cannot instantiate a fixed pool with zero worker')
187 protected checkDynamicPoolSize (min
: number, max
: number): void {
188 if (this.type === PoolTypes
.dynamic
) {
191 'Cannot instantiate a dynamic pool without specifying the maximum pool size'
193 } else if (!Number.isSafeInteger(max
)) {
195 'Cannot instantiate a dynamic pool with a non safe integer maximum pool size'
197 } else if (min
> max
) {
198 throw new RangeError(
199 'Cannot instantiate a dynamic pool with a maximum pool size inferior to the minimum pool size'
201 } else if (max
=== 0) {
202 throw new RangeError(
203 'Cannot instantiate a dynamic pool with a maximum pool size equal to zero'
205 } else if (min
=== max
) {
206 throw new RangeError(
207 'Cannot instantiate a dynamic pool with a minimum pool size equal to the maximum pool size. Use a fixed pool instead'
213 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
214 if (isPlainObject(opts
)) {
215 this.opts
.workerChoiceStrategy
=
216 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
217 this.checkValidWorkerChoiceStrategy(this.opts
.workerChoiceStrategy
)
218 this.opts
.workerChoiceStrategyOptions
= {
219 ...DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
,
220 ...opts
.workerChoiceStrategyOptions
222 this.checkValidWorkerChoiceStrategyOptions(
223 this.opts
.workerChoiceStrategyOptions
225 this.opts
.restartWorkerOnError
= opts
.restartWorkerOnError
?? true
226 this.opts
.enableEvents
= opts
.enableEvents
?? true
227 this.opts
.enableTasksQueue
= opts
.enableTasksQueue
?? false
228 if (this.opts
.enableTasksQueue
) {
229 this.checkValidTasksQueueOptions(
230 opts
.tasksQueueOptions
as TasksQueueOptions
232 this.opts
.tasksQueueOptions
= this.buildTasksQueueOptions(
233 opts
.tasksQueueOptions
as TasksQueueOptions
237 throw new TypeError('Invalid pool options: must be a plain object')
241 private checkValidWorkerChoiceStrategy (
242 workerChoiceStrategy
: WorkerChoiceStrategy
244 if (!Object.values(WorkerChoiceStrategies
).includes(workerChoiceStrategy
)) {
246 `Invalid worker choice strategy '${workerChoiceStrategy}'`
251 private checkValidWorkerChoiceStrategyOptions (
252 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
254 if (!isPlainObject(workerChoiceStrategyOptions
)) {
256 'Invalid worker choice strategy options: must be a plain object'
260 workerChoiceStrategyOptions
.retries
!= null &&
261 !Number.isSafeInteger(workerChoiceStrategyOptions
.retries
)
264 'Invalid worker choice strategy options: retries must be an integer'
268 workerChoiceStrategyOptions
.retries
!= null &&
269 workerChoiceStrategyOptions
.retries
< 0
271 throw new RangeError(
272 `Invalid worker choice strategy options: retries '${workerChoiceStrategyOptions.retries}' must be greater or equal than zero`
276 workerChoiceStrategyOptions
.weights
!= null &&
277 Object.keys(workerChoiceStrategyOptions
.weights
).length
!== this.maxSize
280 'Invalid worker choice strategy options: must have a weight for each worker node'
284 workerChoiceStrategyOptions
.measurement
!= null &&
285 !Object.values(Measurements
).includes(
286 workerChoiceStrategyOptions
.measurement
290 `Invalid worker choice strategy options: invalid measurement '${workerChoiceStrategyOptions.measurement}'`
295 private checkValidTasksQueueOptions (
296 tasksQueueOptions
: TasksQueueOptions
298 if (tasksQueueOptions
!= null && !isPlainObject(tasksQueueOptions
)) {
299 throw new TypeError('Invalid tasks queue options: must be a plain object')
302 tasksQueueOptions
?.concurrency
!= null &&
303 !Number.isSafeInteger(tasksQueueOptions
?.concurrency
)
306 'Invalid worker node tasks concurrency: must be an integer'
310 tasksQueueOptions
?.concurrency
!= null &&
311 tasksQueueOptions
?.concurrency
<= 0
313 throw new RangeError(
314 `Invalid worker node tasks concurrency: ${tasksQueueOptions?.concurrency} is a negative integer or zero`
317 if (tasksQueueOptions
?.queueMaxSize
!= null) {
319 'Invalid tasks queue options: queueMaxSize is deprecated, please use size instead'
323 tasksQueueOptions
?.size
!= null &&
324 !Number.isSafeInteger(tasksQueueOptions
?.size
)
327 'Invalid worker node tasks queue size: must be an integer'
330 if (tasksQueueOptions
?.size
!= null && tasksQueueOptions
?.size
<= 0) {
331 throw new RangeError(
332 `Invalid worker node tasks queue size: ${tasksQueueOptions?.size} is a negative integer or zero`
337 private startPool (): void {
339 this.workerNodes
.reduce(
340 (accumulator
, workerNode
) =>
341 !workerNode
.info
.dynamic
? accumulator
+ 1 : accumulator
,
343 ) < this.numberOfWorkers
345 this.createAndSetupWorkerNode()
350 public get
info (): PoolInfo
{
356 strategy
: this.opts
.workerChoiceStrategy
as WorkerChoiceStrategy
,
357 minSize
: this.minSize
,
358 maxSize
: this.maxSize
,
359 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
360 .runTime
.aggregate
&&
361 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
362 .waitTime
.aggregate
&& { utilization
: round(this.utilization
) }),
363 workerNodes
: this.workerNodes
.length
,
364 idleWorkerNodes
: this.workerNodes
.reduce(
365 (accumulator
, workerNode
) =>
366 workerNode
.usage
.tasks
.executing
=== 0
371 busyWorkerNodes
: this.workerNodes
.reduce(
372 (accumulator
, workerNode
) =>
373 workerNode
.usage
.tasks
.executing
> 0 ? accumulator
+ 1 : accumulator
,
376 executedTasks
: this.workerNodes
.reduce(
377 (accumulator
, workerNode
) =>
378 accumulator
+ workerNode
.usage
.tasks
.executed
,
381 executingTasks
: this.workerNodes
.reduce(
382 (accumulator
, workerNode
) =>
383 accumulator
+ workerNode
.usage
.tasks
.executing
,
386 ...(this.opts
.enableTasksQueue
=== true && {
387 queuedTasks
: this.workerNodes
.reduce(
388 (accumulator
, workerNode
) =>
389 accumulator
+ workerNode
.usage
.tasks
.queued
,
393 ...(this.opts
.enableTasksQueue
=== true && {
394 maxQueuedTasks
: this.workerNodes
.reduce(
395 (accumulator
, workerNode
) =>
396 accumulator
+ (workerNode
.usage
.tasks
?.maxQueued
?? 0),
400 ...(this.opts
.enableTasksQueue
=== true && {
401 backPressure
: this.hasBackPressure()
403 ...(this.opts
.enableTasksQueue
=== true && {
404 stolenTasks
: this.workerNodes
.reduce(
405 (accumulator
, workerNode
) =>
406 accumulator
+ workerNode
.usage
.tasks
.stolen
,
410 failedTasks
: this.workerNodes
.reduce(
411 (accumulator
, workerNode
) =>
412 accumulator
+ workerNode
.usage
.tasks
.failed
,
415 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
416 .runTime
.aggregate
&& {
420 ...this.workerNodes
.map(
421 (workerNode
) => workerNode
.usage
.runTime
?.minimum
?? Infinity
427 ...this.workerNodes
.map(
428 (workerNode
) => workerNode
.usage
.runTime
?.maximum
?? -Infinity
432 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
433 .runTime
.average
&& {
436 this.workerNodes
.reduce
<number[]>(
437 (accumulator
, workerNode
) =>
438 accumulator
.concat(workerNode
.usage
.runTime
.history
),
444 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
448 this.workerNodes
.reduce
<number[]>(
449 (accumulator
, workerNode
) =>
450 accumulator
.concat(workerNode
.usage
.runTime
.history
),
458 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
459 .waitTime
.aggregate
&& {
463 ...this.workerNodes
.map(
464 (workerNode
) => workerNode
.usage
.waitTime
?.minimum
?? Infinity
470 ...this.workerNodes
.map(
471 (workerNode
) => workerNode
.usage
.waitTime
?.maximum
?? -Infinity
475 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
476 .waitTime
.average
&& {
479 this.workerNodes
.reduce
<number[]>(
480 (accumulator
, workerNode
) =>
481 accumulator
.concat(workerNode
.usage
.waitTime
.history
),
487 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
488 .waitTime
.median
&& {
491 this.workerNodes
.reduce
<number[]>(
492 (accumulator
, workerNode
) =>
493 accumulator
.concat(workerNode
.usage
.waitTime
.history
),
505 * The pool readiness boolean status.
507 private get
ready (): boolean {
509 this.workerNodes
.reduce(
510 (accumulator
, workerNode
) =>
511 !workerNode
.info
.dynamic
&& workerNode
.info
.ready
520 * The approximate pool utilization.
522 * @returns The pool utilization.
524 private get
utilization (): number {
525 const poolTimeCapacity
=
526 (performance
.now() - this.startTimestamp
) * this.maxSize
527 const totalTasksRunTime
= this.workerNodes
.reduce(
528 (accumulator
, workerNode
) =>
529 accumulator
+ (workerNode
.usage
.runTime
?.aggregate
?? 0),
532 const totalTasksWaitTime
= this.workerNodes
.reduce(
533 (accumulator
, workerNode
) =>
534 accumulator
+ (workerNode
.usage
.waitTime
?.aggregate
?? 0),
537 return (totalTasksRunTime
+ totalTasksWaitTime
) / poolTimeCapacity
543 * If it is `'dynamic'`, it provides the `max` property.
545 protected abstract get
type (): PoolType
550 protected abstract get
worker (): WorkerType
553 * The pool minimum size.
555 protected get
minSize (): number {
556 return this.numberOfWorkers
560 * The pool maximum size.
562 protected get
maxSize (): number {
563 return this.max
?? this.numberOfWorkers
567 * Checks if the worker id sent in the received message from a worker is valid.
569 * @param message - The received message.
570 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the worker id is invalid.
572 private checkMessageWorkerId (message
: MessageValue
<Response
>): void {
573 if (message
.workerId
== null) {
574 throw new Error('Worker message received without worker id')
576 message
.workerId
!= null &&
577 this.getWorkerNodeKeyByWorkerId(message
.workerId
) === -1
580 `Worker message received from unknown worker '${message.workerId}'`
586 * Gets the given worker its worker node key.
588 * @param worker - The worker.
589 * @returns The worker node key if found in the pool worker nodes, `-1` otherwise.
591 private getWorkerNodeKeyByWorker (worker
: Worker
): number {
592 return this.workerNodes
.findIndex(
593 (workerNode
) => workerNode
.worker
=== worker
598 * Gets the worker node key given its worker id.
600 * @param workerId - The worker id.
601 * @returns The worker node key if the worker id is found in the pool worker nodes, `-1` otherwise.
603 private getWorkerNodeKeyByWorkerId (workerId
: number): number {
604 return this.workerNodes
.findIndex(
605 (workerNode
) => workerNode
.info
.id
=== workerId
610 public setWorkerChoiceStrategy (
611 workerChoiceStrategy
: WorkerChoiceStrategy
,
612 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
614 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
615 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
616 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
617 this.opts
.workerChoiceStrategy
619 if (workerChoiceStrategyOptions
!= null) {
620 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
622 for (const [workerNodeKey
, workerNode
] of this.workerNodes
.entries()) {
623 workerNode
.resetUsage()
624 this.sendStatisticsMessageToWorker(workerNodeKey
)
629 public setWorkerChoiceStrategyOptions (
630 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
632 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
633 this.opts
.workerChoiceStrategyOptions
= {
634 ...DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
,
635 ...workerChoiceStrategyOptions
637 this.workerChoiceStrategyContext
.setOptions(
638 this.opts
.workerChoiceStrategyOptions
643 public enableTasksQueue (
645 tasksQueueOptions
?: TasksQueueOptions
647 if (this.opts
.enableTasksQueue
=== true && !enable
) {
648 this.flushTasksQueues()
650 this.opts
.enableTasksQueue
= enable
651 this.setTasksQueueOptions(tasksQueueOptions
as TasksQueueOptions
)
655 public setTasksQueueOptions (tasksQueueOptions
: TasksQueueOptions
): void {
656 if (this.opts
.enableTasksQueue
=== true) {
657 this.checkValidTasksQueueOptions(tasksQueueOptions
)
658 this.opts
.tasksQueueOptions
=
659 this.buildTasksQueueOptions(tasksQueueOptions
)
660 this.setTasksQueueSize(this.opts
.tasksQueueOptions
.size
as number)
661 } else if (this.opts
.tasksQueueOptions
!= null) {
662 delete this.opts
.tasksQueueOptions
666 private setTasksQueueSize (size
: number): void {
667 for (const workerNode
of this.workerNodes
) {
668 workerNode
.tasksQueueBackPressureSize
= size
672 private buildTasksQueueOptions (
673 tasksQueueOptions
: TasksQueueOptions
674 ): TasksQueueOptions
{
677 size
: Math.pow(this.maxSize
, 2),
685 * Whether the pool is full or not.
687 * The pool filling boolean status.
689 protected get
full (): boolean {
690 return this.workerNodes
.length
>= this.maxSize
694 * Whether the pool is busy or not.
696 * The pool busyness boolean status.
698 protected abstract get
busy (): boolean
701 * Whether worker nodes are executing concurrently their tasks quota or not.
703 * @returns Worker nodes busyness boolean status.
705 protected internalBusy (): boolean {
706 if (this.opts
.enableTasksQueue
=== true) {
708 this.workerNodes
.findIndex(
710 workerNode
.info
.ready
&&
711 workerNode
.usage
.tasks
.executing
<
712 (this.opts
.tasksQueueOptions
?.concurrency
as number)
717 this.workerNodes
.findIndex(
719 workerNode
.info
.ready
&& workerNode
.usage
.tasks
.executing
=== 0
726 public listTaskFunctions (): string[] {
727 for (const workerNode
of this.workerNodes
) {
729 Array.isArray(workerNode
.info
.taskFunctions
) &&
730 workerNode
.info
.taskFunctions
.length
> 0
732 return workerNode
.info
.taskFunctions
738 private shallExecuteTask (workerNodeKey
: number): boolean {
740 this.tasksQueueSize(workerNodeKey
) === 0 &&
741 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
<
742 (this.opts
.tasksQueueOptions
?.concurrency
as number)
747 public async execute (
750 transferList
?: TransferListItem
[]
751 ): Promise
<Response
> {
752 return await new Promise
<Response
>((resolve
, reject
) => {
754 reject(new Error('Cannot execute a task on destroyed pool'))
757 if (name
!= null && typeof name
!== 'string') {
758 reject(new TypeError('name argument must be a string'))
763 typeof name
=== 'string' &&
764 name
.trim().length
=== 0
766 reject(new TypeError('name argument must not be an empty string'))
769 if (transferList
!= null && !Array.isArray(transferList
)) {
770 reject(new TypeError('transferList argument must be an array'))
773 const timestamp
= performance
.now()
774 const workerNodeKey
= this.chooseWorkerNode()
775 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
776 const task
: Task
<Data
> = {
777 name
: name
?? DEFAULT_TASK_NAME
,
778 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
779 data
: data
?? ({} as Data
),
782 workerId
: workerInfo
.id
as number,
785 this.promiseResponseMap
.set(task
.taskId
as string, {
791 this.opts
.enableTasksQueue
=== false ||
792 (this.opts
.enableTasksQueue
=== true &&
793 this.shallExecuteTask(workerNodeKey
))
795 this.executeTask(workerNodeKey
, task
)
797 this.enqueueTask(workerNodeKey
, task
)
803 public async destroy (): Promise
<void> {
805 this.workerNodes
.map(async (_
, workerNodeKey
) => {
806 await this.destroyWorkerNode(workerNodeKey
)
809 this.emitter
?.emit(PoolEvents
.destroy
, this.info
)
813 protected async sendKillMessageToWorker (
814 workerNodeKey
: number,
817 await new Promise
<void>((resolve
, reject
) => {
818 this.registerWorkerMessageListener(workerNodeKey
, (message
) => {
819 if (message
.kill
=== 'success') {
821 } else if (message
.kill
=== 'failure') {
822 reject(new Error(`Worker ${workerId} kill message handling failed`))
825 this.sendToWorker(workerNodeKey
, { kill
: true, workerId
})
830 * Terminates the worker node given its worker node key.
832 * @param workerNodeKey - The worker node key.
834 protected abstract destroyWorkerNode (workerNodeKey
: number): Promise
<void>
837 * Setup hook to execute code before worker nodes are created in the abstract constructor.
842 protected setupHook (): void {
843 /* Intentionally empty */
847 * Should return whether the worker is the main worker or not.
849 protected abstract isMain (): boolean
852 * Hook executed before the worker task execution.
855 * @param workerNodeKey - The worker node key.
856 * @param task - The task to execute.
858 protected beforeTaskExecutionHook (
859 workerNodeKey
: number,
862 if (this.workerNodes
[workerNodeKey
]?.usage
!= null) {
863 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
864 ++workerUsage
.tasks
.executing
865 this.updateWaitTimeWorkerUsage(workerUsage
, task
)
868 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
869 this.workerNodes
[workerNodeKey
].getTaskFunctionWorkerUsage(
873 const taskFunctionWorkerUsage
= this.workerNodes
[
875 ].getTaskFunctionWorkerUsage(task
.name
as string) as WorkerUsage
876 ++taskFunctionWorkerUsage
.tasks
.executing
877 this.updateWaitTimeWorkerUsage(taskFunctionWorkerUsage
, task
)
882 * Hook executed after the worker task execution.
885 * @param workerNodeKey - The worker node key.
886 * @param message - The received message.
888 protected afterTaskExecutionHook (
889 workerNodeKey
: number,
890 message
: MessageValue
<Response
>
892 if (this.workerNodes
[workerNodeKey
]?.usage
!= null) {
893 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
894 this.updateTaskStatisticsWorkerUsage(workerUsage
, message
)
895 this.updateRunTimeWorkerUsage(workerUsage
, message
)
896 this.updateEluWorkerUsage(workerUsage
, message
)
899 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
900 this.workerNodes
[workerNodeKey
].getTaskFunctionWorkerUsage(
901 message
.taskPerformance
?.name
as string
904 const taskFunctionWorkerUsage
= this.workerNodes
[
906 ].getTaskFunctionWorkerUsage(
907 message
.taskPerformance
?.name
as string
909 this.updateTaskStatisticsWorkerUsage(taskFunctionWorkerUsage
, message
)
910 this.updateRunTimeWorkerUsage(taskFunctionWorkerUsage
, message
)
911 this.updateEluWorkerUsage(taskFunctionWorkerUsage
, message
)
916 * Whether the worker node shall update its task function worker usage or not.
918 * @param workerNodeKey - The worker node key.
919 * @returns `true` if the worker node shall update its task function worker usage, `false` otherwise.
921 private shallUpdateTaskFunctionWorkerUsage (workerNodeKey
: number): boolean {
922 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
924 workerInfo
!= null &&
925 Array.isArray(workerInfo
.taskFunctions
) &&
926 workerInfo
.taskFunctions
.length
> 2
930 private updateTaskStatisticsWorkerUsage (
931 workerUsage
: WorkerUsage
,
932 message
: MessageValue
<Response
>
934 const workerTaskStatistics
= workerUsage
.tasks
936 workerTaskStatistics
.executing
!= null &&
937 workerTaskStatistics
.executing
> 0
939 --workerTaskStatistics
.executing
941 if (message
.taskError
== null) {
942 ++workerTaskStatistics
.executed
944 ++workerTaskStatistics
.failed
948 private updateRunTimeWorkerUsage (
949 workerUsage
: WorkerUsage
,
950 message
: MessageValue
<Response
>
952 if (message
.taskError
!= null) {
955 updateMeasurementStatistics(
957 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
,
958 message
.taskPerformance
?.runTime
?? 0
962 private updateWaitTimeWorkerUsage (
963 workerUsage
: WorkerUsage
,
966 const timestamp
= performance
.now()
967 const taskWaitTime
= timestamp
- (task
.timestamp
?? timestamp
)
968 updateMeasurementStatistics(
969 workerUsage
.waitTime
,
970 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().waitTime
,
975 private updateEluWorkerUsage (
976 workerUsage
: WorkerUsage
,
977 message
: MessageValue
<Response
>
979 if (message
.taskError
!= null) {
982 const eluTaskStatisticsRequirements
: MeasurementStatisticsRequirements
=
983 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
984 updateMeasurementStatistics(
985 workerUsage
.elu
.active
,
986 eluTaskStatisticsRequirements
,
987 message
.taskPerformance
?.elu
?.active
?? 0
989 updateMeasurementStatistics(
990 workerUsage
.elu
.idle
,
991 eluTaskStatisticsRequirements
,
992 message
.taskPerformance
?.elu
?.idle
?? 0
994 if (eluTaskStatisticsRequirements
.aggregate
) {
995 if (message
.taskPerformance
?.elu
!= null) {
996 if (workerUsage
.elu
.utilization
!= null) {
997 workerUsage
.elu
.utilization
=
998 (workerUsage
.elu
.utilization
+
999 message
.taskPerformance
.elu
.utilization
) /
1002 workerUsage
.elu
.utilization
= message
.taskPerformance
.elu
.utilization
1009 * Chooses a worker node for the next task.
1011 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
1013 * @returns The chosen worker node key
1015 private chooseWorkerNode (): number {
1016 if (this.shallCreateDynamicWorker()) {
1017 const workerNodeKey
= this.createAndSetupDynamicWorkerNode()
1019 this.workerChoiceStrategyContext
.getStrategyPolicy().dynamicWorkerUsage
1021 return workerNodeKey
1024 return this.workerChoiceStrategyContext
.execute()
1028 * Conditions for dynamic worker creation.
1030 * @returns Whether to create a dynamic worker or not.
1032 private shallCreateDynamicWorker (): boolean {
1033 return this.type === PoolTypes
.dynamic
&& !this.full
&& this.internalBusy()
1037 * Sends a message to worker given its worker node key.
1039 * @param workerNodeKey - The worker node key.
1040 * @param message - The message.
1041 * @param transferList - The optional array of transferable objects.
1043 protected abstract sendToWorker (
1044 workerNodeKey
: number,
1045 message
: MessageValue
<Data
>,
1046 transferList
?: TransferListItem
[]
1050 * Creates a new worker.
1052 * @returns Newly created worker.
1054 protected abstract createWorker (): Worker
1057 * Creates a new, completely set up worker node.
1059 * @returns New, completely set up worker node key.
1061 protected createAndSetupWorkerNode (): number {
1062 const worker
= this.createWorker()
1064 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
1065 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
1066 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
1067 worker
.on('error', (error
) => {
1068 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
1069 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
1070 workerInfo
.ready
= false
1071 this.workerNodes
[workerNodeKey
].closeChannel()
1072 this.emitter
?.emit(PoolEvents
.error
, error
)
1074 this.opts
.restartWorkerOnError
=== true &&
1078 if (workerInfo
.dynamic
) {
1079 this.createAndSetupDynamicWorkerNode()
1081 this.createAndSetupWorkerNode()
1084 if (this.opts
.enableTasksQueue
=== true) {
1085 this.redistributeQueuedTasks(workerNodeKey
)
1088 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
1089 worker
.once('exit', () => {
1090 this.removeWorkerNode(worker
)
1093 const workerNodeKey
= this.addWorkerNode(worker
)
1095 this.afterWorkerNodeSetup(workerNodeKey
)
1097 return workerNodeKey
1101 * Creates a new, completely set up dynamic worker node.
1103 * @returns New, completely set up dynamic worker node key.
1105 protected createAndSetupDynamicWorkerNode (): number {
1106 const workerNodeKey
= this.createAndSetupWorkerNode()
1107 this.registerWorkerMessageListener(workerNodeKey
, (message
) => {
1108 const localWorkerNodeKey
= this.getWorkerNodeKeyByWorkerId(
1111 const workerUsage
= this.workerNodes
[localWorkerNodeKey
].usage
1112 // Kill message received from worker
1114 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
1115 (isKillBehavior(KillBehaviors
.SOFT
, message
.kill
) &&
1116 ((this.opts
.enableTasksQueue
=== false &&
1117 workerUsage
.tasks
.executing
=== 0) ||
1118 (this.opts
.enableTasksQueue
=== true &&
1119 workerUsage
.tasks
.executing
=== 0 &&
1120 this.tasksQueueSize(localWorkerNodeKey
) === 0)))
1122 this.destroyWorkerNode(localWorkerNodeKey
).catch((error
) => {
1123 this.emitter
?.emit(PoolEvents
.error
, error
)
1127 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
1128 this.sendToWorker(workerNodeKey
, {
1130 workerId
: workerInfo
.id
as number
1132 workerInfo
.dynamic
= true
1134 this.workerChoiceStrategyContext
.getStrategyPolicy().dynamicWorkerReady
||
1135 this.workerChoiceStrategyContext
.getStrategyPolicy().dynamicWorkerUsage
1137 workerInfo
.ready
= true
1139 this.checkAndEmitDynamicWorkerCreationEvents()
1140 return workerNodeKey
1144 * Registers a listener callback on the worker given its worker node key.
1146 * @param workerNodeKey - The worker node key.
1147 * @param listener - The message listener callback.
1149 protected abstract registerWorkerMessageListener
<
1150 Message
extends Data
| Response
1152 workerNodeKey
: number,
1153 listener
: (message
: MessageValue
<Message
>) => void
1157 * Method hooked up after a worker node has been newly created.
1158 * Can be overridden.
1160 * @param workerNodeKey - The newly created worker node key.
1162 protected afterWorkerNodeSetup (workerNodeKey
: number): void {
1163 // Listen to worker messages.
1164 this.registerWorkerMessageListener(workerNodeKey
, this.workerListener())
1165 // Send the startup message to worker.
1166 this.sendStartupMessageToWorker(workerNodeKey
)
1167 // Send the statistics message to worker.
1168 this.sendStatisticsMessageToWorker(workerNodeKey
)
1169 if (this.opts
.enableTasksQueue
=== true) {
1170 this.workerNodes
[workerNodeKey
].onEmptyQueue
=
1171 this.taskStealingOnEmptyQueue
.bind(this)
1172 this.workerNodes
[workerNodeKey
].onBackPressure
=
1173 this.tasksStealingOnBackPressure
.bind(this)
1178 * Sends the startup message to worker given its worker node key.
1180 * @param workerNodeKey - The worker node key.
1182 protected abstract sendStartupMessageToWorker (workerNodeKey
: number): void
1185 * Sends the statistics message to worker given its worker node key.
1187 * @param workerNodeKey - The worker node key.
1189 private sendStatisticsMessageToWorker (workerNodeKey
: number): void {
1190 this.sendToWorker(workerNodeKey
, {
1193 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1195 elu
: this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1198 workerId
: this.getWorkerInfo(workerNodeKey
).id
as number
1202 private redistributeQueuedTasks (workerNodeKey
: number): void {
1203 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1204 const destinationWorkerNodeKey
= this.workerNodes
.reduce(
1205 (minWorkerNodeKey
, workerNode
, workerNodeKey
, workerNodes
) => {
1206 return workerNode
.info
.ready
&&
1207 workerNode
.usage
.tasks
.queued
<
1208 workerNodes
[minWorkerNodeKey
].usage
.tasks
.queued
1214 const destinationWorkerNode
= this.workerNodes
[destinationWorkerNodeKey
]
1216 ...(this.dequeueTask(workerNodeKey
) as Task
<Data
>),
1217 workerId
: destinationWorkerNode
.info
.id
as number
1219 if (this.shallExecuteTask(destinationWorkerNodeKey
)) {
1220 this.executeTask(destinationWorkerNodeKey
, task
)
1222 this.enqueueTask(destinationWorkerNodeKey
, task
)
1227 private updateTaskStolenStatisticsWorkerUsage (
1228 workerNodeKey
: number,
1231 const workerNode
= this.workerNodes
[workerNodeKey
]
1232 if (workerNode
?.usage
!= null) {
1233 ++workerNode
.usage
.tasks
.stolen
1236 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
1237 workerNode
.getTaskFunctionWorkerUsage(taskName
) != null
1239 const taskFunctionWorkerUsage
= workerNode
.getTaskFunctionWorkerUsage(
1242 ++taskFunctionWorkerUsage
.tasks
.stolen
1246 private taskStealingOnEmptyQueue (workerId
: number): void {
1247 const destinationWorkerNodeKey
= this.getWorkerNodeKeyByWorkerId(workerId
)
1248 const destinationWorkerNode
= this.workerNodes
[destinationWorkerNodeKey
]
1249 const workerNodes
= this.workerNodes
1252 (workerNodeA
, workerNodeB
) =>
1253 workerNodeB
.usage
.tasks
.queued
- workerNodeA
.usage
.tasks
.queued
1255 const sourceWorkerNode
= workerNodes
.find(
1257 workerNode
.info
.ready
&&
1258 workerNode
.info
.id
!== workerId
&&
1259 workerNode
.usage
.tasks
.queued
> 0
1261 if (sourceWorkerNode
!= null) {
1263 ...(sourceWorkerNode
.popTask() as Task
<Data
>),
1264 workerId
: destinationWorkerNode
.info
.id
as number
1266 if (this.shallExecuteTask(destinationWorkerNodeKey
)) {
1267 this.executeTask(destinationWorkerNodeKey
, task
)
1269 this.enqueueTask(destinationWorkerNodeKey
, task
)
1271 this.updateTaskStolenStatisticsWorkerUsage(
1272 destinationWorkerNodeKey
,
1278 private tasksStealingOnBackPressure (workerId
: number): void {
1279 const sizeOffset
= 1
1280 if ((this.opts
.tasksQueueOptions
?.size
as number) <= sizeOffset
) {
1283 const sourceWorkerNode
=
1284 this.workerNodes
[this.getWorkerNodeKeyByWorkerId(workerId
)]
1285 const workerNodes
= this.workerNodes
1288 (workerNodeA
, workerNodeB
) =>
1289 workerNodeA
.usage
.tasks
.queued
- workerNodeB
.usage
.tasks
.queued
1291 for (const [workerNodeKey
, workerNode
] of workerNodes
.entries()) {
1293 sourceWorkerNode
.usage
.tasks
.queued
> 0 &&
1294 workerNode
.info
.ready
&&
1295 workerNode
.info
.id
!== workerId
&&
1296 workerNode
.usage
.tasks
.queued
<
1297 (this.opts
.tasksQueueOptions
?.size
as number) - sizeOffset
1300 ...(sourceWorkerNode
.popTask() as Task
<Data
>),
1301 workerId
: workerNode
.info
.id
as number
1303 if (this.shallExecuteTask(workerNodeKey
)) {
1304 this.executeTask(workerNodeKey
, task
)
1306 this.enqueueTask(workerNodeKey
, task
)
1308 this.updateTaskStolenStatisticsWorkerUsage(
1317 * This method is the listener registered for each worker message.
1319 * @returns The listener function to execute when a message is received from a worker.
1321 protected workerListener (): (message
: MessageValue
<Response
>) => void {
1322 return (message
) => {
1323 this.checkMessageWorkerId(message
)
1324 if (message
.ready
!= null && message
.taskFunctions
!= null) {
1325 // Worker ready response received from worker
1326 this.handleWorkerReadyResponse(message
)
1327 } else if (message
.taskId
!= null) {
1328 // Task execution response received from worker
1329 this.handleTaskExecutionResponse(message
)
1330 } else if (message
.taskFunctions
!= null) {
1331 // Task functions message received from worker
1333 this.getWorkerNodeKeyByWorkerId(message
.workerId
)
1334 ).taskFunctions
= message
.taskFunctions
1339 private handleWorkerReadyResponse (message
: MessageValue
<Response
>): void {
1340 if (message
.ready
=== false) {
1341 throw new Error(`Worker ${message.workerId} failed to initialize`)
1343 const workerInfo
= this.getWorkerInfo(
1344 this.getWorkerNodeKeyByWorkerId(message
.workerId
)
1346 workerInfo
.ready
= message
.ready
as boolean
1347 workerInfo
.taskFunctions
= message
.taskFunctions
1348 if (this.emitter
!= null && this.ready
) {
1349 this.emitter
.emit(PoolEvents
.ready
, this.info
)
1353 private handleTaskExecutionResponse (message
: MessageValue
<Response
>): void {
1354 const { taskId
, taskError
, data
} = message
1355 const promiseResponse
= this.promiseResponseMap
.get(taskId
as string)
1356 if (promiseResponse
!= null) {
1357 if (taskError
!= null) {
1358 this.emitter
?.emit(PoolEvents
.taskError
, taskError
)
1359 promiseResponse
.reject(taskError
.message
)
1361 promiseResponse
.resolve(data
as Response
)
1363 const workerNodeKey
= promiseResponse
.workerNodeKey
1364 this.afterTaskExecutionHook(workerNodeKey
, message
)
1365 this.workerChoiceStrategyContext
.update(workerNodeKey
)
1366 this.promiseResponseMap
.delete(taskId
as string)
1368 this.opts
.enableTasksQueue
=== true &&
1369 this.tasksQueueSize(workerNodeKey
) > 0 &&
1370 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
<
1371 (this.opts
.tasksQueueOptions
?.concurrency
as number)
1375 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1381 private checkAndEmitTaskExecutionEvents (): void {
1383 this.emitter
?.emit(PoolEvents
.busy
, this.info
)
1387 private checkAndEmitTaskQueuingEvents (): void {
1388 if (this.hasBackPressure()) {
1389 this.emitter
?.emit(PoolEvents
.backPressure
, this.info
)
1393 private checkAndEmitDynamicWorkerCreationEvents (): void {
1394 if (this.type === PoolTypes
.dynamic
) {
1396 this.emitter
?.emit(PoolEvents
.full
, this.info
)
1402 * Gets the worker information given its worker node key.
1404 * @param workerNodeKey - The worker node key.
1405 * @returns The worker information.
1407 protected getWorkerInfo (workerNodeKey
: number): WorkerInfo
{
1408 return this.workerNodes
[workerNodeKey
].info
1412 * Adds the given worker in the pool worker nodes.
1414 * @param worker - The worker.
1415 * @returns The added worker node key.
1416 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the added worker node is not found.
1418 private addWorkerNode (worker
: Worker
): number {
1419 const workerNode
= new WorkerNode
<Worker
, Data
>(
1421 this.opts
.tasksQueueOptions
?.size
?? Math.pow(this.maxSize
, 2)
1423 // Flag the worker node as ready at pool startup.
1424 if (this.starting
) {
1425 workerNode
.info
.ready
= true
1427 this.workerNodes
.push(workerNode
)
1428 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
1429 if (workerNodeKey
=== -1) {
1430 throw new Error('Worker added not found in worker nodes')
1432 return workerNodeKey
1436 * Removes the given worker from the pool worker nodes.
1438 * @param worker - The worker.
1440 private removeWorkerNode (worker
: Worker
): void {
1441 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
1442 if (workerNodeKey
!== -1) {
1443 this.workerNodes
.splice(workerNodeKey
, 1)
1444 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
1449 public hasWorkerNodeBackPressure (workerNodeKey
: number): boolean {
1451 this.opts
.enableTasksQueue
=== true &&
1452 this.workerNodes
[workerNodeKey
].hasBackPressure()
1456 private hasBackPressure (): boolean {
1458 this.opts
.enableTasksQueue
=== true &&
1459 this.workerNodes
.findIndex(
1460 (workerNode
) => !workerNode
.hasBackPressure()
1466 * Executes the given task on the worker given its worker node key.
1468 * @param workerNodeKey - The worker node key.
1469 * @param task - The task to execute.
1471 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
1472 this.beforeTaskExecutionHook(workerNodeKey
, task
)
1473 this.sendToWorker(workerNodeKey
, task
, task
.transferList
)
1474 this.checkAndEmitTaskExecutionEvents()
1477 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
1478 const tasksQueueSize
= this.workerNodes
[workerNodeKey
].enqueueTask(task
)
1479 this.checkAndEmitTaskQueuingEvents()
1480 return tasksQueueSize
1483 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
1484 return this.workerNodes
[workerNodeKey
].dequeueTask()
1487 private tasksQueueSize (workerNodeKey
: number): number {
1488 return this.workerNodes
[workerNodeKey
].tasksQueueSize()
1491 protected flushTasksQueue (workerNodeKey
: number): void {
1492 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1495 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1498 this.workerNodes
[workerNodeKey
].clearTasksQueue()
1501 private flushTasksQueues (): void {
1502 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
1503 this.flushTasksQueue(workerNodeKey
)