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 task
: Task
<Data
> = {
776 name
: name
?? DEFAULT_TASK_NAME
,
777 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
778 data
: data
?? ({} as Data
),
781 workerId
: this.getWorkerInfo(workerNodeKey
).id
as number,
784 this.promiseResponseMap
.set(task
.taskId
as string, {
790 this.opts
.enableTasksQueue
=== false ||
791 (this.opts
.enableTasksQueue
=== true &&
792 this.shallExecuteTask(workerNodeKey
))
794 this.executeTask(workerNodeKey
, task
)
796 this.enqueueTask(workerNodeKey
, task
)
802 public async destroy (): Promise
<void> {
804 this.workerNodes
.map(async (_
, workerNodeKey
) => {
805 await this.destroyWorkerNode(workerNodeKey
)
808 this.emitter
?.emit(PoolEvents
.destroy
, this.info
)
812 protected async sendKillMessageToWorker (
813 workerNodeKey
: number,
816 await new Promise
<void>((resolve
, reject
) => {
817 this.registerWorkerMessageListener(workerNodeKey
, message
=> {
818 if (message
.kill
=== 'success') {
820 } else if (message
.kill
=== 'failure') {
821 reject(new Error(`Worker ${workerId} kill message handling failed`))
824 this.sendToWorker(workerNodeKey
, { kill
: true, workerId
})
829 * Terminates the worker node given its worker node key.
831 * @param workerNodeKey - The worker node key.
833 protected abstract destroyWorkerNode (workerNodeKey
: number): Promise
<void>
836 * Setup hook to execute code before worker nodes are created in the abstract constructor.
841 protected setupHook (): void {
842 /* Intentionally empty */
846 * Should return whether the worker is the main worker or not.
848 protected abstract isMain (): boolean
851 * Hook executed before the worker task execution.
854 * @param workerNodeKey - The worker node key.
855 * @param task - The task to execute.
857 protected beforeTaskExecutionHook (
858 workerNodeKey
: number,
861 if (this.workerNodes
[workerNodeKey
]?.usage
!= null) {
862 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
863 ++workerUsage
.tasks
.executing
864 this.updateWaitTimeWorkerUsage(workerUsage
, task
)
867 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
868 this.workerNodes
[workerNodeKey
].getTaskFunctionWorkerUsage(
872 const taskFunctionWorkerUsage
= this.workerNodes
[
874 ].getTaskFunctionWorkerUsage(task
.name
as string) as WorkerUsage
875 ++taskFunctionWorkerUsage
.tasks
.executing
876 this.updateWaitTimeWorkerUsage(taskFunctionWorkerUsage
, task
)
881 * Hook executed after the worker task execution.
884 * @param workerNodeKey - The worker node key.
885 * @param message - The received message.
887 protected afterTaskExecutionHook (
888 workerNodeKey
: number,
889 message
: MessageValue
<Response
>
891 if (this.workerNodes
[workerNodeKey
]?.usage
!= null) {
892 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
893 this.updateTaskStatisticsWorkerUsage(workerUsage
, message
)
894 this.updateRunTimeWorkerUsage(workerUsage
, message
)
895 this.updateEluWorkerUsage(workerUsage
, message
)
898 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
899 this.workerNodes
[workerNodeKey
].getTaskFunctionWorkerUsage(
900 message
.taskPerformance
?.name
as string
903 const taskFunctionWorkerUsage
= this.workerNodes
[
905 ].getTaskFunctionWorkerUsage(
906 message
.taskPerformance
?.name
as string
908 this.updateTaskStatisticsWorkerUsage(taskFunctionWorkerUsage
, message
)
909 this.updateRunTimeWorkerUsage(taskFunctionWorkerUsage
, message
)
910 this.updateEluWorkerUsage(taskFunctionWorkerUsage
, message
)
915 * Whether the worker node shall update its task function worker usage or not.
917 * @param workerNodeKey - The worker node key.
918 * @returns `true` if the worker node shall update its task function worker usage, `false` otherwise.
920 private shallUpdateTaskFunctionWorkerUsage (workerNodeKey
: number): boolean {
921 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
923 workerInfo
!= null &&
924 Array.isArray(workerInfo
.taskFunctions
) &&
925 workerInfo
.taskFunctions
.length
> 2
929 private updateTaskStatisticsWorkerUsage (
930 workerUsage
: WorkerUsage
,
931 message
: MessageValue
<Response
>
933 const workerTaskStatistics
= workerUsage
.tasks
935 workerTaskStatistics
.executing
!= null &&
936 workerTaskStatistics
.executing
> 0
938 --workerTaskStatistics
.executing
940 if (message
.taskError
== null) {
941 ++workerTaskStatistics
.executed
943 ++workerTaskStatistics
.failed
947 private updateRunTimeWorkerUsage (
948 workerUsage
: WorkerUsage
,
949 message
: MessageValue
<Response
>
951 if (message
.taskError
!= null) {
954 updateMeasurementStatistics(
956 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
,
957 message
.taskPerformance
?.runTime
?? 0
961 private updateWaitTimeWorkerUsage (
962 workerUsage
: WorkerUsage
,
965 const timestamp
= performance
.now()
966 const taskWaitTime
= timestamp
- (task
.timestamp
?? timestamp
)
967 updateMeasurementStatistics(
968 workerUsage
.waitTime
,
969 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().waitTime
,
974 private updateEluWorkerUsage (
975 workerUsage
: WorkerUsage
,
976 message
: MessageValue
<Response
>
978 if (message
.taskError
!= null) {
981 const eluTaskStatisticsRequirements
: MeasurementStatisticsRequirements
=
982 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
983 updateMeasurementStatistics(
984 workerUsage
.elu
.active
,
985 eluTaskStatisticsRequirements
,
986 message
.taskPerformance
?.elu
?.active
?? 0
988 updateMeasurementStatistics(
989 workerUsage
.elu
.idle
,
990 eluTaskStatisticsRequirements
,
991 message
.taskPerformance
?.elu
?.idle
?? 0
993 if (eluTaskStatisticsRequirements
.aggregate
) {
994 if (message
.taskPerformance
?.elu
!= null) {
995 if (workerUsage
.elu
.utilization
!= null) {
996 workerUsage
.elu
.utilization
=
997 (workerUsage
.elu
.utilization
+
998 message
.taskPerformance
.elu
.utilization
) /
1001 workerUsage
.elu
.utilization
= message
.taskPerformance
.elu
.utilization
1008 * Chooses a worker node for the next task.
1010 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
1012 * @returns The chosen worker node key
1014 private chooseWorkerNode (): number {
1015 if (this.shallCreateDynamicWorker()) {
1016 const workerNodeKey
= this.createAndSetupDynamicWorkerNode()
1018 this.workerChoiceStrategyContext
.getStrategyPolicy().dynamicWorkerUsage
1020 return workerNodeKey
1023 return this.workerChoiceStrategyContext
.execute()
1027 * Conditions for dynamic worker creation.
1029 * @returns Whether to create a dynamic worker or not.
1031 private shallCreateDynamicWorker (): boolean {
1032 return this.type === PoolTypes
.dynamic
&& !this.full
&& this.internalBusy()
1036 * Sends a message to worker given its worker node key.
1038 * @param workerNodeKey - The worker node key.
1039 * @param message - The message.
1040 * @param transferList - The optional array of transferable objects.
1042 protected abstract sendToWorker (
1043 workerNodeKey
: number,
1044 message
: MessageValue
<Data
>,
1045 transferList
?: TransferListItem
[]
1049 * Creates a new worker.
1051 * @returns Newly created worker.
1053 protected abstract createWorker (): Worker
1056 * Creates a new, completely set up worker node.
1058 * @returns New, completely set up worker node key.
1060 protected createAndSetupWorkerNode (): number {
1061 const worker
= this.createWorker()
1063 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
1064 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
1065 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
1066 worker
.on('error', error
=> {
1067 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
1068 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
1069 workerInfo
.ready
= false
1070 this.workerNodes
[workerNodeKey
].closeChannel()
1071 this.emitter
?.emit(PoolEvents
.error
, error
)
1073 this.opts
.restartWorkerOnError
=== true &&
1077 if (workerInfo
.dynamic
) {
1078 this.createAndSetupDynamicWorkerNode()
1080 this.createAndSetupWorkerNode()
1083 if (this.opts
.enableTasksQueue
=== true) {
1084 this.redistributeQueuedTasks(workerNodeKey
)
1087 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
1088 worker
.once('exit', () => {
1089 this.removeWorkerNode(worker
)
1092 const workerNodeKey
= this.addWorkerNode(worker
)
1094 this.afterWorkerNodeSetup(workerNodeKey
)
1096 return workerNodeKey
1100 * Creates a new, completely set up dynamic worker node.
1102 * @returns New, completely set up dynamic worker node key.
1104 protected createAndSetupDynamicWorkerNode (): number {
1105 const workerNodeKey
= this.createAndSetupWorkerNode()
1106 this.registerWorkerMessageListener(workerNodeKey
, message
=> {
1107 const localWorkerNodeKey
= this.getWorkerNodeKeyByWorkerId(
1110 const workerUsage
= this.workerNodes
[localWorkerNodeKey
].usage
1111 // Kill message received from worker
1113 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
1114 (isKillBehavior(KillBehaviors
.SOFT
, message
.kill
) &&
1115 ((this.opts
.enableTasksQueue
=== false &&
1116 workerUsage
.tasks
.executing
=== 0) ||
1117 (this.opts
.enableTasksQueue
=== true &&
1118 workerUsage
.tasks
.executing
=== 0 &&
1119 this.tasksQueueSize(localWorkerNodeKey
) === 0)))
1121 this.destroyWorkerNode(localWorkerNodeKey
).catch(error
=> {
1122 this.emitter
?.emit(PoolEvents
.error
, error
)
1126 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
1127 this.sendToWorker(workerNodeKey
, {
1129 workerId
: workerInfo
.id
as number
1131 workerInfo
.dynamic
= true
1133 this.workerChoiceStrategyContext
.getStrategyPolicy().dynamicWorkerReady
||
1134 this.workerChoiceStrategyContext
.getStrategyPolicy().dynamicWorkerUsage
1136 workerInfo
.ready
= true
1138 this.checkAndEmitDynamicWorkerCreationEvents()
1139 return workerNodeKey
1143 * Registers a listener callback on the worker given its worker node key.
1145 * @param workerNodeKey - The worker node key.
1146 * @param listener - The message listener callback.
1148 protected abstract registerWorkerMessageListener
<
1149 Message
extends Data
| Response
1151 workerNodeKey
: number,
1152 listener
: (message
: MessageValue
<Message
>) => void
1156 * Method hooked up after a worker node has been newly created.
1157 * Can be overridden.
1159 * @param workerNodeKey - The newly created worker node key.
1161 protected afterWorkerNodeSetup (workerNodeKey
: number): void {
1162 // Listen to worker messages.
1163 this.registerWorkerMessageListener(workerNodeKey
, this.workerListener())
1164 // Send the startup message to worker.
1165 this.sendStartupMessageToWorker(workerNodeKey
)
1166 // Send the statistics message to worker.
1167 this.sendStatisticsMessageToWorker(workerNodeKey
)
1168 if (this.opts
.enableTasksQueue
=== true) {
1169 this.workerNodes
[workerNodeKey
].onEmptyQueue
=
1170 this.taskStealingOnEmptyQueue
.bind(this)
1171 this.workerNodes
[workerNodeKey
].onBackPressure
=
1172 this.tasksStealingOnBackPressure
.bind(this)
1177 * Sends the startup message to worker given its worker node key.
1179 * @param workerNodeKey - The worker node key.
1181 protected abstract sendStartupMessageToWorker (workerNodeKey
: number): void
1184 * Sends the statistics message to worker given its worker node key.
1186 * @param workerNodeKey - The worker node key.
1188 private sendStatisticsMessageToWorker (workerNodeKey
: number): void {
1189 this.sendToWorker(workerNodeKey
, {
1192 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1194 elu
: this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1197 workerId
: this.getWorkerInfo(workerNodeKey
).id
as number
1201 private redistributeQueuedTasks (workerNodeKey
: number): void {
1202 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1203 const destinationWorkerNodeKey
= this.workerNodes
.reduce(
1204 (minWorkerNodeKey
, workerNode
, workerNodeKey
, workerNodes
) => {
1205 return workerNode
.info
.ready
&&
1206 workerNode
.usage
.tasks
.queued
<
1207 workerNodes
[minWorkerNodeKey
].usage
.tasks
.queued
1213 const destinationWorkerNode
= this.workerNodes
[destinationWorkerNodeKey
]
1215 ...(this.dequeueTask(workerNodeKey
) as Task
<Data
>),
1216 workerId
: destinationWorkerNode
.info
.id
as number
1218 if (this.shallExecuteTask(destinationWorkerNodeKey
)) {
1219 this.executeTask(destinationWorkerNodeKey
, task
)
1221 this.enqueueTask(destinationWorkerNodeKey
, task
)
1226 private updateTaskStolenStatisticsWorkerUsage (
1227 workerNodeKey
: number,
1230 const workerNode
= this.workerNodes
[workerNodeKey
]
1231 if (workerNode
?.usage
!= null) {
1232 ++workerNode
.usage
.tasks
.stolen
1235 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
1236 workerNode
.getTaskFunctionWorkerUsage(taskName
) != null
1238 const taskFunctionWorkerUsage
= workerNode
.getTaskFunctionWorkerUsage(
1241 ++taskFunctionWorkerUsage
.tasks
.stolen
1245 private taskStealingOnEmptyQueue (workerId
: number): void {
1246 const destinationWorkerNodeKey
= this.getWorkerNodeKeyByWorkerId(workerId
)
1247 const destinationWorkerNode
= this.workerNodes
[destinationWorkerNodeKey
]
1248 const workerNodes
= this.workerNodes
1251 (workerNodeA
, workerNodeB
) =>
1252 workerNodeB
.usage
.tasks
.queued
- workerNodeA
.usage
.tasks
.queued
1254 const sourceWorkerNode
= workerNodes
.find(
1256 workerNode
.info
.ready
&&
1257 workerNode
.info
.id
!== workerId
&&
1258 workerNode
.usage
.tasks
.queued
> 0
1260 if (sourceWorkerNode
!= null) {
1262 ...(sourceWorkerNode
.popTask() as Task
<Data
>),
1263 workerId
: destinationWorkerNode
.info
.id
as number
1265 if (this.shallExecuteTask(destinationWorkerNodeKey
)) {
1266 this.executeTask(destinationWorkerNodeKey
, task
)
1268 this.enqueueTask(destinationWorkerNodeKey
, task
)
1270 this.updateTaskStolenStatisticsWorkerUsage(
1271 destinationWorkerNodeKey
,
1277 private tasksStealingOnBackPressure (workerId
: number): void {
1278 const sizeOffset
= 1
1279 if ((this.opts
.tasksQueueOptions
?.size
as number) <= sizeOffset
) {
1282 const sourceWorkerNode
=
1283 this.workerNodes
[this.getWorkerNodeKeyByWorkerId(workerId
)]
1284 const workerNodes
= this.workerNodes
1287 (workerNodeA
, workerNodeB
) =>
1288 workerNodeA
.usage
.tasks
.queued
- workerNodeB
.usage
.tasks
.queued
1290 for (const [workerNodeKey
, workerNode
] of workerNodes
.entries()) {
1292 sourceWorkerNode
.usage
.tasks
.queued
> 0 &&
1293 workerNode
.info
.ready
&&
1294 workerNode
.info
.id
!== workerId
&&
1295 workerNode
.usage
.tasks
.queued
<
1296 (this.opts
.tasksQueueOptions
?.size
as number) - sizeOffset
1299 ...(sourceWorkerNode
.popTask() as Task
<Data
>),
1300 workerId
: workerNode
.info
.id
as number
1302 if (this.shallExecuteTask(workerNodeKey
)) {
1303 this.executeTask(workerNodeKey
, task
)
1305 this.enqueueTask(workerNodeKey
, task
)
1307 this.updateTaskStolenStatisticsWorkerUsage(
1316 * This method is the listener registered for each worker message.
1318 * @returns The listener function to execute when a message is received from a worker.
1320 protected workerListener (): (message
: MessageValue
<Response
>) => void {
1322 this.checkMessageWorkerId(message
)
1323 if (message
.ready
!= null && message
.taskFunctions
!= null) {
1324 // Worker ready response received from worker
1325 this.handleWorkerReadyResponse(message
)
1326 } else if (message
.taskId
!= null) {
1327 // Task execution response received from worker
1328 this.handleTaskExecutionResponse(message
)
1329 } else if (message
.taskFunctions
!= null) {
1330 // Task functions message received from worker
1332 this.getWorkerNodeKeyByWorkerId(message
.workerId
)
1333 ).taskFunctions
= message
.taskFunctions
1338 private handleWorkerReadyResponse (message
: MessageValue
<Response
>): void {
1339 if (message
.ready
=== false) {
1340 throw new Error(`Worker ${message.workerId} failed to initialize`)
1342 const workerInfo
= this.getWorkerInfo(
1343 this.getWorkerNodeKeyByWorkerId(message
.workerId
)
1345 workerInfo
.ready
= message
.ready
as boolean
1346 workerInfo
.taskFunctions
= message
.taskFunctions
1347 if (this.emitter
!= null && this.ready
) {
1348 this.emitter
.emit(PoolEvents
.ready
, this.info
)
1352 private handleTaskExecutionResponse (message
: MessageValue
<Response
>): void {
1353 const { taskId
, taskError
, data
} = message
1354 const promiseResponse
= this.promiseResponseMap
.get(taskId
as string)
1355 if (promiseResponse
!= null) {
1356 if (taskError
!= null) {
1357 this.emitter
?.emit(PoolEvents
.taskError
, taskError
)
1358 promiseResponse
.reject(taskError
.message
)
1360 promiseResponse
.resolve(data
as Response
)
1362 const workerNodeKey
= promiseResponse
.workerNodeKey
1363 this.afterTaskExecutionHook(workerNodeKey
, message
)
1364 this.workerChoiceStrategyContext
.update(workerNodeKey
)
1365 this.promiseResponseMap
.delete(taskId
as string)
1367 this.opts
.enableTasksQueue
=== true &&
1368 this.tasksQueueSize(workerNodeKey
) > 0 &&
1369 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
<
1370 (this.opts
.tasksQueueOptions
?.concurrency
as number)
1374 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1380 private checkAndEmitTaskExecutionEvents (): void {
1382 this.emitter
?.emit(PoolEvents
.busy
, this.info
)
1386 private checkAndEmitTaskQueuingEvents (): void {
1387 if (this.hasBackPressure()) {
1388 this.emitter
?.emit(PoolEvents
.backPressure
, this.info
)
1392 private checkAndEmitDynamicWorkerCreationEvents (): void {
1393 if (this.type === PoolTypes
.dynamic
) {
1395 this.emitter
?.emit(PoolEvents
.full
, this.info
)
1401 * Gets the worker information given its worker node key.
1403 * @param workerNodeKey - The worker node key.
1404 * @returns The worker information.
1406 protected getWorkerInfo (workerNodeKey
: number): WorkerInfo
{
1407 return this.workerNodes
[workerNodeKey
].info
1411 * Adds the given worker in the pool worker nodes.
1413 * @param worker - The worker.
1414 * @returns The added worker node key.
1415 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the added worker node is not found.
1417 private addWorkerNode (worker
: Worker
): number {
1418 const workerNode
= new WorkerNode
<Worker
, Data
>(
1420 this.opts
.tasksQueueOptions
?.size
?? Math.pow(this.maxSize
, 2)
1422 // Flag the worker node as ready at pool startup.
1423 if (this.starting
) {
1424 workerNode
.info
.ready
= true
1426 this.workerNodes
.push(workerNode
)
1427 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
1428 if (workerNodeKey
=== -1) {
1429 throw new Error('Worker added not found in worker nodes')
1431 return workerNodeKey
1435 * Removes the given worker from the pool worker nodes.
1437 * @param worker - The worker.
1439 private removeWorkerNode (worker
: Worker
): void {
1440 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
1441 if (workerNodeKey
!== -1) {
1442 this.workerNodes
.splice(workerNodeKey
, 1)
1443 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
1448 public hasWorkerNodeBackPressure (workerNodeKey
: number): boolean {
1450 this.opts
.enableTasksQueue
=== true &&
1451 this.workerNodes
[workerNodeKey
].hasBackPressure()
1455 private hasBackPressure (): boolean {
1457 this.opts
.enableTasksQueue
=== true &&
1458 this.workerNodes
.findIndex(
1459 workerNode
=> !workerNode
.hasBackPressure()
1465 * Executes the given task on the worker given its worker node key.
1467 * @param workerNodeKey - The worker node key.
1468 * @param task - The task to execute.
1470 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
1471 this.beforeTaskExecutionHook(workerNodeKey
, task
)
1472 this.sendToWorker(workerNodeKey
, task
, task
.transferList
)
1473 this.checkAndEmitTaskExecutionEvents()
1476 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
1477 const tasksQueueSize
= this.workerNodes
[workerNodeKey
].enqueueTask(task
)
1478 this.checkAndEmitTaskQueuingEvents()
1479 return tasksQueueSize
1482 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
1483 return this.workerNodes
[workerNodeKey
].dequeueTask()
1486 private tasksQueueSize (workerNodeKey
: number): number {
1487 return this.workerNodes
[workerNodeKey
].tasksQueueSize()
1490 protected flushTasksQueue (workerNodeKey
: number): void {
1491 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1494 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1497 this.workerNodes
[workerNodeKey
].clearTasksQueue()
1500 private flushTasksQueues (): void {
1501 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
1502 this.flushTasksQueue(workerNodeKey
)