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
,
10 } from
'../utility-types'
13 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
,
20 updateMeasurementStatistics
22 import { KillBehaviors
} from
'../worker/worker-options'
31 type TasksQueueOptions
41 type MeasurementStatisticsRequirements
,
43 WorkerChoiceStrategies
,
44 type WorkerChoiceStrategy
,
45 type WorkerChoiceStrategyOptions
46 } from
'./selection-strategies/selection-strategies-types'
47 import { WorkerChoiceStrategyContext
} from
'./selection-strategies/worker-choice-strategy-context'
48 import { version
} from
'./version'
49 import { WorkerNode
} from
'./worker-node'
52 * Base class that implements some shared logic for all poolifier pools.
54 * @typeParam Worker - Type of worker which manages this pool.
55 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
56 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
58 export abstract class AbstractPool
<
59 Worker
extends IWorker
,
62 > implements IPool
<Worker
, Data
, Response
> {
64 public readonly workerNodes
: Array<IWorkerNode
<Worker
, Data
>> = []
67 public readonly emitter
?: PoolEmitter
70 * The task execution response promise map.
72 * - `key`: The message id of each submitted task.
73 * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks.
75 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
77 protected promiseResponseMap
: Map
<string, PromiseResponseWrapper
<Response
>> =
78 new Map
<string, PromiseResponseWrapper
<Response
>>()
81 * Worker choice strategy context referencing a worker choice algorithm implementation.
83 protected workerChoiceStrategyContext
: WorkerChoiceStrategyContext
<
90 * Dynamic pool maximum size property placeholder.
92 protected readonly max
?: number
95 * Whether the pool is starting or not.
97 private readonly starting
: boolean
99 * Whether the pool is started or not.
101 private started
: boolean
103 * The start timestamp of the pool.
105 private readonly startTimestamp
108 * Constructs a new poolifier pool.
110 * @param numberOfWorkers - Number of workers that this pool should manage.
111 * @param filePath - Path to the worker file.
112 * @param opts - Options for the pool.
115 protected readonly numberOfWorkers
: number,
116 protected readonly filePath
: string,
117 protected readonly opts
: PoolOptions
<Worker
>
119 if (!this.isMain()) {
121 'Cannot start a pool from a worker with the same type as the pool'
124 this.checkNumberOfWorkers(this.numberOfWorkers
)
125 this.checkFilePath(this.filePath
)
126 this.checkPoolOptions(this.opts
)
128 this.chooseWorkerNode
= this.chooseWorkerNode
.bind(this)
129 this.executeTask
= this.executeTask
.bind(this)
130 this.enqueueTask
= this.enqueueTask
.bind(this)
132 if (this.opts
.enableEvents
=== true) {
133 this.emitter
= new PoolEmitter()
135 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext
<
141 this.opts
.workerChoiceStrategy
,
142 this.opts
.workerChoiceStrategyOptions
149 this.starting
= false
152 this.startTimestamp
= performance
.now()
155 private checkFilePath (filePath
: string): void {
158 typeof filePath
!== 'string' ||
159 (typeof filePath
=== 'string' && filePath
.trim().length
=== 0)
161 throw new Error('Please specify a file with a worker implementation')
163 if (!existsSync(filePath
)) {
164 throw new Error(`Cannot find the worker file '${filePath}'`)
168 private checkNumberOfWorkers (numberOfWorkers
: number): void {
169 if (numberOfWorkers
== null) {
171 'Cannot instantiate a pool without specifying the number of workers'
173 } else if (!Number.isSafeInteger(numberOfWorkers
)) {
175 'Cannot instantiate a pool with a non safe integer number of workers'
177 } else if (numberOfWorkers
< 0) {
178 throw new RangeError(
179 'Cannot instantiate a pool with a negative number of workers'
181 } else if (this.type === PoolTypes
.fixed
&& numberOfWorkers
=== 0) {
182 throw new RangeError('Cannot instantiate a fixed pool with zero worker')
186 protected checkDynamicPoolSize (min
: number, max
: number): void {
187 if (this.type === PoolTypes
.dynamic
) {
190 'Cannot instantiate a dynamic pool without specifying the maximum pool size'
192 } else if (!Number.isSafeInteger(max
)) {
194 'Cannot instantiate a dynamic pool with a non safe integer maximum pool size'
196 } else if (min
> max
) {
197 throw new RangeError(
198 'Cannot instantiate a dynamic pool with a maximum pool size inferior to the minimum pool size'
200 } else if (max
=== 0) {
201 throw new RangeError(
202 'Cannot instantiate a dynamic pool with a maximum pool size equal to zero'
204 } else if (min
=== max
) {
205 throw new RangeError(
206 'Cannot instantiate a dynamic pool with a minimum pool size equal to the maximum pool size. Use a fixed pool instead'
212 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
213 if (isPlainObject(opts
)) {
214 this.opts
.workerChoiceStrategy
=
215 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
216 this.checkValidWorkerChoiceStrategy(this.opts
.workerChoiceStrategy
)
217 this.opts
.workerChoiceStrategyOptions
= {
218 ...DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
,
219 ...opts
.workerChoiceStrategyOptions
221 this.checkValidWorkerChoiceStrategyOptions(
222 this.opts
.workerChoiceStrategyOptions
224 this.opts
.restartWorkerOnError
= opts
.restartWorkerOnError
?? true
225 this.opts
.enableEvents
= opts
.enableEvents
?? true
226 this.opts
.enableTasksQueue
= opts
.enableTasksQueue
?? false
227 if (this.opts
.enableTasksQueue
) {
228 this.checkValidTasksQueueOptions(
229 opts
.tasksQueueOptions
as TasksQueueOptions
231 this.opts
.tasksQueueOptions
= this.buildTasksQueueOptions(
232 opts
.tasksQueueOptions
as TasksQueueOptions
236 throw new TypeError('Invalid pool options: must be a plain object')
240 private checkValidWorkerChoiceStrategy (
241 workerChoiceStrategy
: WorkerChoiceStrategy
243 if (!Object.values(WorkerChoiceStrategies
).includes(workerChoiceStrategy
)) {
245 `Invalid worker choice strategy '${workerChoiceStrategy}'`
250 private checkValidWorkerChoiceStrategyOptions (
251 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
253 if (!isPlainObject(workerChoiceStrategyOptions
)) {
255 'Invalid worker choice strategy options: must be a plain object'
259 workerChoiceStrategyOptions
.choiceRetries
!= null &&
260 !Number.isSafeInteger(workerChoiceStrategyOptions
.choiceRetries
)
263 'Invalid worker choice strategy options: choice retries must be an integer'
267 workerChoiceStrategyOptions
.choiceRetries
!= null &&
268 workerChoiceStrategyOptions
.choiceRetries
<= 0
270 throw new RangeError(
271 `Invalid worker choice strategy options: choice retries '${workerChoiceStrategyOptions.choiceRetries}' must be greater than zero`
275 workerChoiceStrategyOptions
.weights
!= null &&
276 Object.keys(workerChoiceStrategyOptions
.weights
).length
!== this.maxSize
279 'Invalid worker choice strategy options: must have a weight for each worker node'
283 workerChoiceStrategyOptions
.measurement
!= null &&
284 !Object.values(Measurements
).includes(
285 workerChoiceStrategyOptions
.measurement
289 `Invalid worker choice strategy options: invalid measurement '${workerChoiceStrategyOptions.measurement}'`
294 private checkValidTasksQueueOptions (
295 tasksQueueOptions
: Writable
<TasksQueueOptions
>
297 if (tasksQueueOptions
!= null && !isPlainObject(tasksQueueOptions
)) {
298 throw new TypeError('Invalid tasks queue options: must be a plain object')
301 tasksQueueOptions
?.concurrency
!= null &&
302 !Number.isSafeInteger(tasksQueueOptions
.concurrency
)
305 'Invalid worker node tasks concurrency: must be an integer'
309 tasksQueueOptions
?.concurrency
!= null &&
310 tasksQueueOptions
.concurrency
<= 0
312 throw new RangeError(
313 `Invalid worker node tasks concurrency: ${tasksQueueOptions.concurrency} is a negative integer or zero`
317 tasksQueueOptions
?.queueMaxSize
!= null &&
318 tasksQueueOptions
?.size
!= null
321 'Invalid tasks queue options: cannot specify both queueMaxSize and size'
324 if (tasksQueueOptions
?.queueMaxSize
!= null) {
325 tasksQueueOptions
.size
= tasksQueueOptions
.queueMaxSize
328 tasksQueueOptions
?.size
!= null &&
329 !Number.isSafeInteger(tasksQueueOptions
.size
)
332 'Invalid worker node tasks queue max size: must be an integer'
335 if (tasksQueueOptions
?.size
!= null && tasksQueueOptions
.size
<= 0) {
336 throw new RangeError(
337 `Invalid worker node tasks queue max size: ${tasksQueueOptions.size} is a negative integer or zero`
342 private startPool (): void {
344 this.workerNodes
.reduce(
345 (accumulator
, workerNode
) =>
346 !workerNode
.info
.dynamic
? accumulator
+ 1 : accumulator
,
348 ) < this.numberOfWorkers
350 this.createAndSetupWorkerNode()
355 public get
info (): PoolInfo
{
361 strategy
: this.opts
.workerChoiceStrategy
as WorkerChoiceStrategy
,
362 minSize
: this.minSize
,
363 maxSize
: this.maxSize
,
364 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
365 .runTime
.aggregate
&&
366 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
367 .waitTime
.aggregate
&& { utilization
: round(this.utilization
) }),
368 workerNodes
: this.workerNodes
.length
,
369 idleWorkerNodes
: this.workerNodes
.reduce(
370 (accumulator
, workerNode
) =>
371 workerNode
.usage
.tasks
.executing
=== 0
376 busyWorkerNodes
: this.workerNodes
.reduce(
377 (accumulator
, workerNode
) =>
378 workerNode
.usage
.tasks
.executing
> 0 ? accumulator
+ 1 : accumulator
,
381 executedTasks
: this.workerNodes
.reduce(
382 (accumulator
, workerNode
) =>
383 accumulator
+ workerNode
.usage
.tasks
.executed
,
386 executingTasks
: this.workerNodes
.reduce(
387 (accumulator
, workerNode
) =>
388 accumulator
+ workerNode
.usage
.tasks
.executing
,
391 ...(this.opts
.enableTasksQueue
=== true && {
392 queuedTasks
: this.workerNodes
.reduce(
393 (accumulator
, workerNode
) =>
394 accumulator
+ workerNode
.usage
.tasks
.queued
,
398 ...(this.opts
.enableTasksQueue
=== true && {
399 maxQueuedTasks
: this.workerNodes
.reduce(
400 (accumulator
, workerNode
) =>
401 accumulator
+ (workerNode
.usage
.tasks
?.maxQueued
?? 0),
405 ...(this.opts
.enableTasksQueue
=== true && {
406 backPressure
: this.hasBackPressure()
408 failedTasks
: this.workerNodes
.reduce(
409 (accumulator
, workerNode
) =>
410 accumulator
+ workerNode
.usage
.tasks
.failed
,
413 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
414 .runTime
.aggregate
&& {
418 ...this.workerNodes
.map(
419 (workerNode
) => workerNode
.usage
.runTime
?.minimum
?? Infinity
425 ...this.workerNodes
.map(
426 (workerNode
) => workerNode
.usage
.runTime
?.maximum
?? -Infinity
432 this.workerNodes
.reduce
<number[]>(
433 (accumulator
, workerNode
) =>
434 accumulator
.concat(workerNode
.usage
.runTime
.history
),
439 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
443 this.workerNodes
.map(
444 (workerNode
) => workerNode
.usage
.runTime
?.median
?? 0
451 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
452 .waitTime
.aggregate
&& {
456 ...this.workerNodes
.map(
457 (workerNode
) => workerNode
.usage
.waitTime
?.minimum
?? Infinity
463 ...this.workerNodes
.map(
464 (workerNode
) => workerNode
.usage
.waitTime
?.maximum
?? -Infinity
470 this.workerNodes
.reduce
<number[]>(
471 (accumulator
, workerNode
) =>
472 accumulator
.concat(workerNode
.usage
.waitTime
.history
),
477 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
478 .waitTime
.median
&& {
481 this.workerNodes
.map(
482 (workerNode
) => workerNode
.usage
.waitTime
?.median
?? 0
493 * The pool readiness boolean status.
495 private get
ready (): boolean {
497 this.workerNodes
.reduce(
498 (accumulator
, workerNode
) =>
499 !workerNode
.info
.dynamic
&& workerNode
.info
.ready
508 * The approximate pool utilization.
510 * @returns The pool utilization.
512 private get
utilization (): number {
513 const poolTimeCapacity
=
514 (performance
.now() - this.startTimestamp
) * this.maxSize
515 const totalTasksRunTime
= this.workerNodes
.reduce(
516 (accumulator
, workerNode
) =>
517 accumulator
+ (workerNode
.usage
.runTime
?.aggregate
?? 0),
520 const totalTasksWaitTime
= this.workerNodes
.reduce(
521 (accumulator
, workerNode
) =>
522 accumulator
+ (workerNode
.usage
.waitTime
?.aggregate
?? 0),
525 return (totalTasksRunTime
+ totalTasksWaitTime
) / poolTimeCapacity
531 * If it is `'dynamic'`, it provides the `max` property.
533 protected abstract get
type (): PoolType
538 protected abstract get
worker (): WorkerType
541 * The pool minimum size.
543 protected get
minSize (): number {
544 return this.numberOfWorkers
548 * The pool maximum size.
550 protected get
maxSize (): number {
551 return this.max
?? this.numberOfWorkers
555 * Checks if the worker id sent in the received message from a worker is valid.
557 * @param message - The received message.
558 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the worker id is invalid.
560 private checkMessageWorkerId (message
: MessageValue
<Response
>): void {
561 if (message
.workerId
== null) {
562 throw new Error('Worker message received without worker id')
564 message
.workerId
!= null &&
565 this.getWorkerNodeKeyByWorkerId(message
.workerId
) === -1
568 `Worker message received from unknown worker '${message.workerId}'`
574 * Gets the given worker its worker node key.
576 * @param worker - The worker.
577 * @returns The worker node key if found in the pool worker nodes, `-1` otherwise.
579 private getWorkerNodeKeyByWorker (worker
: Worker
): number {
580 return this.workerNodes
.findIndex(
581 (workerNode
) => workerNode
.worker
=== worker
586 * Gets the worker node key given its worker id.
588 * @param workerId - The worker id.
589 * @returns The worker node key if the worker id is found in the pool worker nodes, `-1` otherwise.
591 private getWorkerNodeKeyByWorkerId (workerId
: number): number {
592 return this.workerNodes
.findIndex(
593 (workerNode
) => workerNode
.info
.id
=== workerId
598 public setWorkerChoiceStrategy (
599 workerChoiceStrategy
: WorkerChoiceStrategy
,
600 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
602 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
603 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
604 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
605 this.opts
.workerChoiceStrategy
607 if (workerChoiceStrategyOptions
!= null) {
608 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
610 for (const [workerNodeKey
, workerNode
] of this.workerNodes
.entries()) {
611 workerNode
.resetUsage()
612 this.sendStatisticsMessageToWorker(workerNodeKey
)
617 public setWorkerChoiceStrategyOptions (
618 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
620 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
621 this.opts
.workerChoiceStrategyOptions
= {
622 ...DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
,
623 ...workerChoiceStrategyOptions
625 this.workerChoiceStrategyContext
.setOptions(
626 this.opts
.workerChoiceStrategyOptions
631 public enableTasksQueue (
633 tasksQueueOptions
?: TasksQueueOptions
635 if (this.opts
.enableTasksQueue
=== true && !enable
) {
636 this.flushTasksQueues()
638 this.opts
.enableTasksQueue
= enable
639 this.setTasksQueueOptions(tasksQueueOptions
as TasksQueueOptions
)
643 public setTasksQueueOptions (tasksQueueOptions
: TasksQueueOptions
): void {
644 if (this.opts
.enableTasksQueue
=== true) {
645 this.checkValidTasksQueueOptions(tasksQueueOptions
)
646 this.opts
.tasksQueueOptions
=
647 this.buildTasksQueueOptions(tasksQueueOptions
)
648 this.setTasksQueueMaxSize(this.opts
.tasksQueueOptions
.size
as number)
649 } else if (this.opts
.tasksQueueOptions
!= null) {
650 delete this.opts
.tasksQueueOptions
654 private setTasksQueueMaxSize (size
: number): void {
655 for (const workerNode
of this.workerNodes
) {
656 workerNode
.tasksQueueBackPressureSize
= size
660 private buildTasksQueueOptions (
661 tasksQueueOptions
: TasksQueueOptions
662 ): TasksQueueOptions
{
665 size
: Math.pow(this.maxSize
, 2),
673 * Whether the pool is full or not.
675 * The pool filling boolean status.
677 protected get
full (): boolean {
678 return this.workerNodes
.length
>= this.maxSize
682 * Whether the pool is busy or not.
684 * The pool busyness boolean status.
686 protected abstract get
busy (): boolean
689 * Whether worker nodes are executing concurrently their tasks quota or not.
691 * @returns Worker nodes busyness boolean status.
693 protected internalBusy (): boolean {
694 if (this.opts
.enableTasksQueue
=== true) {
696 this.workerNodes
.findIndex(
698 workerNode
.info
.ready
&&
699 workerNode
.usage
.tasks
.executing
<
700 (this.opts
.tasksQueueOptions
?.concurrency
as number)
705 this.workerNodes
.findIndex(
707 workerNode
.info
.ready
&& workerNode
.usage
.tasks
.executing
=== 0
714 public listTaskFunctions (): string[] {
715 for (const workerNode
of this.workerNodes
) {
717 Array.isArray(workerNode
.info
.taskFunctions
) &&
718 workerNode
.info
.taskFunctions
.length
> 0
720 return workerNode
.info
.taskFunctions
727 public async execute (
730 transferList
?: TransferListItem
[]
731 ): Promise
<Response
> {
732 return await new Promise
<Response
>((resolve
, reject
) => {
734 reject(new Error('Cannot execute a task on destroyed pool'))
736 if (name
!= null && typeof name
!== 'string') {
737 reject(new TypeError('name argument must be a string'))
741 typeof name
=== 'string' &&
742 name
.trim().length
=== 0
744 reject(new TypeError('name argument must not be an empty string'))
746 if (transferList
!= null && !Array.isArray(transferList
)) {
747 reject(new TypeError('transferList argument must be an array'))
749 const timestamp
= performance
.now()
750 const workerNodeKey
= this.chooseWorkerNode()
751 const workerInfo
= this.getWorkerInfo(workerNodeKey
) as WorkerInfo
754 Array.isArray(workerInfo
.taskFunctions
) &&
755 !workerInfo
.taskFunctions
.includes(name
)
758 new Error(`Task function '${name}' is not registered in the pool`)
761 const task
: Task
<Data
> = {
762 name
: name
?? DEFAULT_TASK_NAME
,
763 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
764 data
: data
?? ({} as Data
),
767 workerId
: workerInfo
.id
as number,
770 this.promiseResponseMap
.set(task
.taskId
as string, {
776 this.opts
.enableTasksQueue
=== false ||
777 (this.opts
.enableTasksQueue
=== true &&
778 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
<
779 (this.opts
.tasksQueueOptions
?.concurrency
as number))
781 this.executeTask(workerNodeKey
, task
)
783 this.enqueueTask(workerNodeKey
, task
)
789 public async destroy (): Promise
<void> {
791 this.workerNodes
.map(async (_
, workerNodeKey
) => {
792 await this.destroyWorkerNode(workerNodeKey
)
795 this.emitter
?.emit(PoolEvents
.destroy
, this.info
)
799 protected async sendKillMessageToWorker (
800 workerNodeKey
: number,
803 await new Promise
<void>((resolve
, reject
) => {
804 this.registerWorkerMessageListener(workerNodeKey
, (message
) => {
805 if (message
.kill
=== 'success') {
807 } else if (message
.kill
=== 'failure') {
808 reject(new Error(`Worker ${workerId} kill message handling failed`))
811 this.sendToWorker(workerNodeKey
, { kill
: true, workerId
})
816 * Terminates the worker node given its worker node key.
818 * @param workerNodeKey - The worker node key.
820 protected abstract destroyWorkerNode (workerNodeKey
: number): Promise
<void>
823 * Setup hook to execute code before worker nodes are created in the abstract constructor.
828 protected setupHook (): void {
829 // Intentionally empty
833 * Should return whether the worker is the main worker or not.
835 protected abstract isMain (): boolean
838 * Hook executed before the worker task execution.
841 * @param workerNodeKey - The worker node key.
842 * @param task - The task to execute.
844 protected beforeTaskExecutionHook (
845 workerNodeKey
: number,
848 if (this.workerNodes
[workerNodeKey
]?.usage
!= null) {
849 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
850 ++workerUsage
.tasks
.executing
851 this.updateWaitTimeWorkerUsage(workerUsage
, task
)
854 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
855 this.workerNodes
[workerNodeKey
].getTaskFunctionWorkerUsage(
859 const taskFunctionWorkerUsage
= this.workerNodes
[
861 ].getTaskFunctionWorkerUsage(task
.name
as string) as WorkerUsage
862 ++taskFunctionWorkerUsage
.tasks
.executing
863 this.updateWaitTimeWorkerUsage(taskFunctionWorkerUsage
, task
)
868 * Hook executed after the worker task execution.
871 * @param workerNodeKey - The worker node key.
872 * @param message - The received message.
874 protected afterTaskExecutionHook (
875 workerNodeKey
: number,
876 message
: MessageValue
<Response
>
878 if (this.workerNodes
[workerNodeKey
]?.usage
!= null) {
879 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
880 this.updateTaskStatisticsWorkerUsage(workerUsage
, message
)
881 this.updateRunTimeWorkerUsage(workerUsage
, message
)
882 this.updateEluWorkerUsage(workerUsage
, message
)
885 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
886 this.workerNodes
[workerNodeKey
].getTaskFunctionWorkerUsage(
887 message
.taskPerformance
?.name
as string
890 const taskFunctionWorkerUsage
= this.workerNodes
[
892 ].getTaskFunctionWorkerUsage(
893 message
.taskPerformance
?.name
as string
895 this.updateTaskStatisticsWorkerUsage(taskFunctionWorkerUsage
, message
)
896 this.updateRunTimeWorkerUsage(taskFunctionWorkerUsage
, message
)
897 this.updateEluWorkerUsage(taskFunctionWorkerUsage
, message
)
902 * Whether the worker node shall update its task function worker usage or not.
904 * @param workerNodeKey - The worker node key.
905 * @returns `true` if the worker node shall update its task function worker usage, `false` otherwise.
907 private shallUpdateTaskFunctionWorkerUsage (workerNodeKey
: number): boolean {
908 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
910 workerInfo
!= null &&
911 Array.isArray(workerInfo
.taskFunctions
) &&
912 workerInfo
.taskFunctions
.length
> 2
916 private updateTaskStatisticsWorkerUsage (
917 workerUsage
: WorkerUsage
,
918 message
: MessageValue
<Response
>
920 const workerTaskStatistics
= workerUsage
.tasks
922 workerTaskStatistics
.executing
!= null &&
923 workerTaskStatistics
.executing
> 0
925 --workerTaskStatistics
.executing
927 if (message
.taskError
== null) {
928 ++workerTaskStatistics
.executed
930 ++workerTaskStatistics
.failed
934 private updateRunTimeWorkerUsage (
935 workerUsage
: WorkerUsage
,
936 message
: MessageValue
<Response
>
938 if (message
.taskError
!= null) {
941 updateMeasurementStatistics(
943 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
,
944 message
.taskPerformance
?.runTime
?? 0
948 private updateWaitTimeWorkerUsage (
949 workerUsage
: WorkerUsage
,
952 const timestamp
= performance
.now()
953 const taskWaitTime
= timestamp
- (task
.timestamp
?? timestamp
)
954 updateMeasurementStatistics(
955 workerUsage
.waitTime
,
956 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().waitTime
,
961 private updateEluWorkerUsage (
962 workerUsage
: WorkerUsage
,
963 message
: MessageValue
<Response
>
965 if (message
.taskError
!= null) {
968 const eluTaskStatisticsRequirements
: MeasurementStatisticsRequirements
=
969 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
970 updateMeasurementStatistics(
971 workerUsage
.elu
.active
,
972 eluTaskStatisticsRequirements
,
973 message
.taskPerformance
?.elu
?.active
?? 0
975 updateMeasurementStatistics(
976 workerUsage
.elu
.idle
,
977 eluTaskStatisticsRequirements
,
978 message
.taskPerformance
?.elu
?.idle
?? 0
980 if (eluTaskStatisticsRequirements
.aggregate
) {
981 if (message
.taskPerformance
?.elu
!= null) {
982 if (workerUsage
.elu
.utilization
!= null) {
983 workerUsage
.elu
.utilization
=
984 (workerUsage
.elu
.utilization
+
985 message
.taskPerformance
.elu
.utilization
) /
988 workerUsage
.elu
.utilization
= message
.taskPerformance
.elu
.utilization
995 * Chooses a worker node for the next task.
997 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
999 * @returns The chosen worker node key
1001 private chooseWorkerNode (): number {
1002 if (this.shallCreateDynamicWorker()) {
1003 const workerNodeKey
= this.createAndSetupDynamicWorkerNode()
1005 this.workerChoiceStrategyContext
.getStrategyPolicy().dynamicWorkerUsage
1007 return workerNodeKey
1010 return this.workerChoiceStrategyContext
.execute()
1014 * Conditions for dynamic worker creation.
1016 * @returns Whether to create a dynamic worker or not.
1018 private shallCreateDynamicWorker (): boolean {
1019 return this.type === PoolTypes
.dynamic
&& !this.full
&& this.internalBusy()
1023 * Sends a message to worker given its worker node key.
1025 * @param workerNodeKey - The worker node key.
1026 * @param message - The message.
1027 * @param transferList - The optional array of transferable objects.
1029 protected abstract sendToWorker (
1030 workerNodeKey
: number,
1031 message
: MessageValue
<Data
>,
1032 transferList
?: TransferListItem
[]
1036 * Creates a new worker.
1038 * @returns Newly created worker.
1040 protected abstract createWorker (): Worker
1043 * Creates a new, completely set up worker node.
1045 * @returns New, completely set up worker node key.
1047 protected createAndSetupWorkerNode (): number {
1048 const worker
= this.createWorker()
1050 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
1051 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
1052 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
1053 worker
.on('error', (error
) => {
1054 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
1055 const workerInfo
= this.getWorkerInfo(workerNodeKey
) as WorkerInfo
1056 workerInfo
.ready
= false
1057 this.workerNodes
[workerNodeKey
].closeChannel()
1058 this.emitter
?.emit(PoolEvents
.error
, error
)
1060 this.opts
.restartWorkerOnError
=== true &&
1064 if (workerInfo
.dynamic
) {
1065 this.createAndSetupDynamicWorkerNode()
1067 this.createAndSetupWorkerNode()
1070 if (this.opts
.enableTasksQueue
=== true) {
1071 this.redistributeQueuedTasks(workerNodeKey
)
1074 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
1075 worker
.once('exit', () => {
1076 this.removeWorkerNode(worker
)
1079 const workerNodeKey
= this.addWorkerNode(worker
)
1081 this.afterWorkerNodeSetup(workerNodeKey
)
1083 return workerNodeKey
1087 * Creates a new, completely set up dynamic worker node.
1089 * @returns New, completely set up dynamic worker node key.
1091 protected createAndSetupDynamicWorkerNode (): number {
1092 const workerNodeKey
= this.createAndSetupWorkerNode()
1093 this.registerWorkerMessageListener(workerNodeKey
, (message
) => {
1094 const localWorkerNodeKey
= this.getWorkerNodeKeyByWorkerId(
1097 const workerUsage
= this.workerNodes
[localWorkerNodeKey
].usage
1098 // Kill message received from worker
1100 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
1101 (isKillBehavior(KillBehaviors
.SOFT
, message
.kill
) &&
1102 ((this.opts
.enableTasksQueue
=== false &&
1103 workerUsage
.tasks
.executing
=== 0) ||
1104 (this.opts
.enableTasksQueue
=== true &&
1105 workerUsage
.tasks
.executing
=== 0 &&
1106 this.tasksQueueSize(localWorkerNodeKey
) === 0)))
1108 this.destroyWorkerNode(localWorkerNodeKey
).catch((error
) => {
1109 this.emitter
?.emit(PoolEvents
.error
, error
)
1113 const workerInfo
= this.getWorkerInfo(workerNodeKey
) as WorkerInfo
1114 this.sendToWorker(workerNodeKey
, {
1116 workerId
: workerInfo
.id
as number
1118 workerInfo
.dynamic
= true
1120 this.workerChoiceStrategyContext
.getStrategyPolicy().dynamicWorkerReady
||
1121 this.workerChoiceStrategyContext
.getStrategyPolicy().dynamicWorkerUsage
1123 workerInfo
.ready
= true
1125 this.checkAndEmitDynamicWorkerCreationEvents()
1126 return workerNodeKey
1130 * Registers a listener callback on the worker given its worker node key.
1132 * @param workerNodeKey - The worker node key.
1133 * @param listener - The message listener callback.
1135 protected abstract registerWorkerMessageListener
<
1136 Message
extends Data
| Response
1138 workerNodeKey
: number,
1139 listener
: (message
: MessageValue
<Message
>) => void
1143 * Method hooked up after a worker node has been newly created.
1144 * Can be overridden.
1146 * @param workerNodeKey - The newly created worker node key.
1148 protected afterWorkerNodeSetup (workerNodeKey
: number): void {
1149 // Listen to worker messages.
1150 this.registerWorkerMessageListener(workerNodeKey
, this.workerListener())
1151 // Send the startup message to worker.
1152 this.sendStartupMessageToWorker(workerNodeKey
)
1153 // Send the statistics message to worker.
1154 this.sendStatisticsMessageToWorker(workerNodeKey
)
1155 if (this.opts
.enableTasksQueue
=== true) {
1156 this.workerNodes
[workerNodeKey
].onEmptyQueue
=
1157 this.taskStealingOnEmptyQueue
.bind(this)
1158 this.workerNodes
[workerNodeKey
].onBackPressure
=
1159 this.tasksStealingOnBackPressure
.bind(this)
1164 * Sends the startup message to worker given its worker node key.
1166 * @param workerNodeKey - The worker node key.
1168 protected abstract sendStartupMessageToWorker (workerNodeKey
: number): void
1171 * Sends the statistics message to worker given its worker node key.
1173 * @param workerNodeKey - The worker node key.
1175 private sendStatisticsMessageToWorker (workerNodeKey
: number): void {
1176 this.sendToWorker(workerNodeKey
, {
1179 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1181 elu
: this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1184 workerId
: (this.getWorkerInfo(workerNodeKey
) as WorkerInfo
).id
as number
1188 private redistributeQueuedTasks (workerNodeKey
: number): void {
1189 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1190 let destinationWorkerNodeKey
!: number
1191 let minQueuedTasks
= Infinity
1192 let executeTask
= false
1193 for (const [workerNodeId
, workerNode
] of this.workerNodes
.entries()) {
1194 if (workerNode
.info
.ready
&& workerNodeId
!== workerNodeKey
) {
1196 workerNode
.usage
.tasks
.executing
<
1197 (this.opts
.tasksQueueOptions
?.concurrency
as number)
1201 if (workerNode
.usage
.tasks
.queued
=== 0) {
1202 destinationWorkerNodeKey
= workerNodeId
1205 if (workerNode
.usage
.tasks
.queued
< minQueuedTasks
) {
1206 minQueuedTasks
= workerNode
.usage
.tasks
.queued
1207 destinationWorkerNodeKey
= workerNodeId
1211 if (destinationWorkerNodeKey
!= null) {
1213 ...(this.dequeueTask(workerNodeKey
) as Task
<Data
>),
1214 workerId
: (this.getWorkerInfo(destinationWorkerNodeKey
) as WorkerInfo
)
1218 this.executeTask(destinationWorkerNodeKey
, task
)
1220 this.enqueueTask(destinationWorkerNodeKey
, task
)
1226 private taskStealingOnEmptyQueue (workerId
: number): void {
1227 const destinationWorkerNodeKey
= this.getWorkerNodeKeyByWorkerId(workerId
)
1228 const destinationWorkerNode
= this.workerNodes
[destinationWorkerNodeKey
]
1229 const workerNodes
= this.workerNodes
1232 (workerNodeA
, workerNodeB
) =>
1233 workerNodeB
.usage
.tasks
.queued
- workerNodeA
.usage
.tasks
.queued
1235 for (const sourceWorkerNode
of workerNodes
) {
1236 if (sourceWorkerNode
.usage
.tasks
.queued
=== 0) {
1240 sourceWorkerNode
.info
.ready
&&
1241 sourceWorkerNode
.info
.id
!== workerId
&&
1242 sourceWorkerNode
.usage
.tasks
.queued
> 0
1245 ...(sourceWorkerNode
.popTask() as Task
<Data
>),
1246 workerId
: destinationWorkerNode
.info
.id
as number
1249 destinationWorkerNode
.usage
.tasks
.executing
<
1250 (this.opts
.tasksQueueOptions
?.concurrency
as number)
1252 this.executeTask(destinationWorkerNodeKey
, task
)
1254 this.enqueueTask(destinationWorkerNodeKey
, task
)
1261 private tasksStealingOnBackPressure (workerId
: number): void {
1262 const sourceWorkerNode
=
1263 this.workerNodes
[this.getWorkerNodeKeyByWorkerId(workerId
)]
1264 const workerNodes
= this.workerNodes
1267 (workerNodeA
, workerNodeB
) =>
1268 workerNodeA
.usage
.tasks
.queued
- workerNodeB
.usage
.tasks
.queued
1270 for (const [workerNodeKey
, workerNode
] of workerNodes
.entries()) {
1272 sourceWorkerNode
.usage
.tasks
.queued
> 0 &&
1273 workerNode
.info
.ready
&&
1274 workerNode
.info
.id
!== workerId
&&
1275 workerNode
.usage
.tasks
.queued
<
1276 (this.opts
.tasksQueueOptions
?.size
as number) - 1
1279 ...(sourceWorkerNode
.popTask() as Task
<Data
>),
1280 workerId
: workerNode
.info
.id
as number
1283 workerNode
.usage
.tasks
.executing
<
1284 (this.opts
.tasksQueueOptions
?.concurrency
as number)
1286 this.executeTask(workerNodeKey
, task
)
1288 this.enqueueTask(workerNodeKey
, task
)
1295 * This method is the listener registered for each worker message.
1297 * @returns The listener function to execute when a message is received from a worker.
1299 protected workerListener (): (message
: MessageValue
<Response
>) => void {
1300 return (message
) => {
1301 this.checkMessageWorkerId(message
)
1302 if (message
.ready
!= null && message
.taskFunctions
!= null) {
1303 // Worker ready response received from worker
1304 this.handleWorkerReadyResponse(message
)
1305 } else if (message
.taskId
!= null) {
1306 // Task execution response received from worker
1307 this.handleTaskExecutionResponse(message
)
1308 } else if (message
.taskFunctions
!= null) {
1309 // Task functions message received from worker
1312 this.getWorkerNodeKeyByWorkerId(message
.workerId
)
1314 ).taskFunctions
= message
.taskFunctions
1319 private handleWorkerReadyResponse (message
: MessageValue
<Response
>): void {
1320 if (message
.ready
=== false) {
1321 throw new Error(`Worker ${message.workerId} failed to initialize`)
1323 const workerInfo
= this.getWorkerInfo(
1324 this.getWorkerNodeKeyByWorkerId(message
.workerId
)
1326 workerInfo
.ready
= message
.ready
as boolean
1327 workerInfo
.taskFunctions
= message
.taskFunctions
1328 if (this.emitter
!= null && this.ready
) {
1329 this.emitter
.emit(PoolEvents
.ready
, this.info
)
1333 private handleTaskExecutionResponse (message
: MessageValue
<Response
>): void {
1334 const { taskId
, taskError
, data
} = message
1335 const promiseResponse
= this.promiseResponseMap
.get(taskId
as string)
1336 if (promiseResponse
!= null) {
1337 if (taskError
!= null) {
1338 this.emitter
?.emit(PoolEvents
.taskError
, taskError
)
1339 promiseResponse
.reject(taskError
.message
)
1341 promiseResponse
.resolve(data
as Response
)
1343 const workerNodeKey
= promiseResponse
.workerNodeKey
1344 this.afterTaskExecutionHook(workerNodeKey
, message
)
1345 this.promiseResponseMap
.delete(taskId
as string)
1347 this.opts
.enableTasksQueue
=== true &&
1348 this.tasksQueueSize(workerNodeKey
) > 0 &&
1349 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
<
1350 (this.opts
.tasksQueueOptions
?.concurrency
as number)
1354 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1357 this.workerChoiceStrategyContext
.update(workerNodeKey
)
1361 private checkAndEmitTaskExecutionEvents (): void {
1363 this.emitter
?.emit(PoolEvents
.busy
, this.info
)
1367 private checkAndEmitTaskQueuingEvents (): void {
1368 if (this.hasBackPressure()) {
1369 this.emitter
?.emit(PoolEvents
.backPressure
, this.info
)
1373 private checkAndEmitDynamicWorkerCreationEvents (): void {
1374 if (this.type === PoolTypes
.dynamic
) {
1376 this.emitter
?.emit(PoolEvents
.full
, this.info
)
1382 * Gets the worker information given its worker node key.
1384 * @param workerNodeKey - The worker node key.
1385 * @returns The worker information.
1387 protected getWorkerInfo (workerNodeKey
: number): WorkerInfo
| undefined {
1388 return this.workerNodes
[workerNodeKey
]?.info
1392 * Adds the given worker in the pool worker nodes.
1394 * @param worker - The worker.
1395 * @returns The added worker node key.
1396 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the added worker node is not found.
1398 private addWorkerNode (worker
: Worker
): number {
1399 const workerNode
= new WorkerNode
<Worker
, Data
>(
1402 this.opts
.tasksQueueOptions
?.size
?? Math.pow(this.maxSize
, 2)
1404 // Flag the worker node as ready at pool startup.
1405 if (this.starting
) {
1406 workerNode
.info
.ready
= true
1408 this.workerNodes
.push(workerNode
)
1409 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
1410 if (workerNodeKey
=== -1) {
1411 throw new Error('Worker node added not found')
1413 return workerNodeKey
1417 * Removes the given worker from the pool worker nodes.
1419 * @param worker - The worker.
1421 private removeWorkerNode (worker
: Worker
): void {
1422 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
1423 if (workerNodeKey
!== -1) {
1424 this.workerNodes
.splice(workerNodeKey
, 1)
1425 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
1430 public hasWorkerNodeBackPressure (workerNodeKey
: number): boolean {
1432 this.opts
.enableTasksQueue
=== true &&
1433 this.workerNodes
[workerNodeKey
].hasBackPressure()
1437 private hasBackPressure (): boolean {
1439 this.opts
.enableTasksQueue
=== true &&
1440 this.workerNodes
.findIndex(
1441 (workerNode
) => !workerNode
.hasBackPressure()
1447 * Executes the given task on the worker given its worker node key.
1449 * @param workerNodeKey - The worker node key.
1450 * @param task - The task to execute.
1452 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
1453 this.beforeTaskExecutionHook(workerNodeKey
, task
)
1454 this.sendToWorker(workerNodeKey
, task
, task
.transferList
)
1455 this.checkAndEmitTaskExecutionEvents()
1458 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
1459 const tasksQueueSize
= this.workerNodes
[workerNodeKey
].enqueueTask(task
)
1460 this.checkAndEmitTaskQueuingEvents()
1461 return tasksQueueSize
1464 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
1465 return this.workerNodes
[workerNodeKey
].dequeueTask()
1468 private tasksQueueSize (workerNodeKey
: number): number {
1469 return this.workerNodes
[workerNodeKey
].tasksQueueSize()
1472 protected flushTasksQueue (workerNodeKey
: number): void {
1473 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1476 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1479 this.workerNodes
[workerNodeKey
].clearTasksQueue()
1482 private flushTasksQueues (): void {
1483 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
1484 this.flushTasksQueue(workerNodeKey
)