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
430 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
431 .runTime
.average
&& {
434 this.workerNodes
.reduce
<number[]>(
435 (accumulator
, workerNode
) =>
436 accumulator
.concat(workerNode
.usage
.runTime
.history
),
442 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
446 this.workerNodes
.reduce
<number[]>(
447 (accumulator
, workerNode
) =>
448 accumulator
.concat(workerNode
.usage
.runTime
.history
),
456 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
457 .waitTime
.aggregate
&& {
461 ...this.workerNodes
.map(
462 (workerNode
) => workerNode
.usage
.waitTime
?.minimum
?? Infinity
468 ...this.workerNodes
.map(
469 (workerNode
) => workerNode
.usage
.waitTime
?.maximum
?? -Infinity
473 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
474 .waitTime
.average
&& {
477 this.workerNodes
.reduce
<number[]>(
478 (accumulator
, workerNode
) =>
479 accumulator
.concat(workerNode
.usage
.waitTime
.history
),
485 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
486 .waitTime
.median
&& {
489 this.workerNodes
.reduce
<number[]>(
490 (accumulator
, workerNode
) =>
491 accumulator
.concat(workerNode
.usage
.waitTime
.history
),
503 * The pool readiness boolean status.
505 private get
ready (): boolean {
507 this.workerNodes
.reduce(
508 (accumulator
, workerNode
) =>
509 !workerNode
.info
.dynamic
&& workerNode
.info
.ready
518 * The approximate pool utilization.
520 * @returns The pool utilization.
522 private get
utilization (): number {
523 const poolTimeCapacity
=
524 (performance
.now() - this.startTimestamp
) * this.maxSize
525 const totalTasksRunTime
= this.workerNodes
.reduce(
526 (accumulator
, workerNode
) =>
527 accumulator
+ (workerNode
.usage
.runTime
?.aggregate
?? 0),
530 const totalTasksWaitTime
= this.workerNodes
.reduce(
531 (accumulator
, workerNode
) =>
532 accumulator
+ (workerNode
.usage
.waitTime
?.aggregate
?? 0),
535 return (totalTasksRunTime
+ totalTasksWaitTime
) / poolTimeCapacity
541 * If it is `'dynamic'`, it provides the `max` property.
543 protected abstract get
type (): PoolType
548 protected abstract get
worker (): WorkerType
551 * The pool minimum size.
553 protected get
minSize (): number {
554 return this.numberOfWorkers
558 * The pool maximum size.
560 protected get
maxSize (): number {
561 return this.max
?? this.numberOfWorkers
565 * Checks if the worker id sent in the received message from a worker is valid.
567 * @param message - The received message.
568 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the worker id is invalid.
570 private checkMessageWorkerId (message
: MessageValue
<Response
>): void {
571 if (message
.workerId
== null) {
572 throw new Error('Worker message received without worker id')
574 message
.workerId
!= null &&
575 this.getWorkerNodeKeyByWorkerId(message
.workerId
) === -1
578 `Worker message received from unknown worker '${message.workerId}'`
584 * Gets the given worker its worker node key.
586 * @param worker - The worker.
587 * @returns The worker node key if found in the pool worker nodes, `-1` otherwise.
589 private getWorkerNodeKeyByWorker (worker
: Worker
): number {
590 return this.workerNodes
.findIndex(
591 (workerNode
) => workerNode
.worker
=== worker
596 * Gets the worker node key given its worker id.
598 * @param workerId - The worker id.
599 * @returns The worker node key if the worker id is found in the pool worker nodes, `-1` otherwise.
601 private getWorkerNodeKeyByWorkerId (workerId
: number): number {
602 return this.workerNodes
.findIndex(
603 (workerNode
) => workerNode
.info
.id
=== workerId
608 public setWorkerChoiceStrategy (
609 workerChoiceStrategy
: WorkerChoiceStrategy
,
610 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
612 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
613 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
614 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
615 this.opts
.workerChoiceStrategy
617 if (workerChoiceStrategyOptions
!= null) {
618 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
620 for (const [workerNodeKey
, workerNode
] of this.workerNodes
.entries()) {
621 workerNode
.resetUsage()
622 this.sendStatisticsMessageToWorker(workerNodeKey
)
627 public setWorkerChoiceStrategyOptions (
628 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
630 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
631 this.opts
.workerChoiceStrategyOptions
= {
632 ...DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
,
633 ...workerChoiceStrategyOptions
635 this.workerChoiceStrategyContext
.setOptions(
636 this.opts
.workerChoiceStrategyOptions
641 public enableTasksQueue (
643 tasksQueueOptions
?: TasksQueueOptions
645 if (this.opts
.enableTasksQueue
=== true && !enable
) {
646 this.flushTasksQueues()
648 this.opts
.enableTasksQueue
= enable
649 this.setTasksQueueOptions(tasksQueueOptions
as TasksQueueOptions
)
653 public setTasksQueueOptions (tasksQueueOptions
: TasksQueueOptions
): void {
654 if (this.opts
.enableTasksQueue
=== true) {
655 this.checkValidTasksQueueOptions(tasksQueueOptions
)
656 this.opts
.tasksQueueOptions
=
657 this.buildTasksQueueOptions(tasksQueueOptions
)
658 this.setTasksQueueMaxSize(this.opts
.tasksQueueOptions
.size
as number)
659 } else if (this.opts
.tasksQueueOptions
!= null) {
660 delete this.opts
.tasksQueueOptions
664 private setTasksQueueMaxSize (size
: number): void {
665 for (const workerNode
of this.workerNodes
) {
666 workerNode
.tasksQueueBackPressureSize
= size
670 private buildTasksQueueOptions (
671 tasksQueueOptions
: TasksQueueOptions
672 ): TasksQueueOptions
{
675 size
: Math.pow(this.maxSize
, 2),
683 * Whether the pool is full or not.
685 * The pool filling boolean status.
687 protected get
full (): boolean {
688 return this.workerNodes
.length
>= this.maxSize
692 * Whether the pool is busy or not.
694 * The pool busyness boolean status.
696 protected abstract get
busy (): boolean
699 * Whether worker nodes are executing concurrently their tasks quota or not.
701 * @returns Worker nodes busyness boolean status.
703 protected internalBusy (): boolean {
704 if (this.opts
.enableTasksQueue
=== true) {
706 this.workerNodes
.findIndex(
708 workerNode
.info
.ready
&&
709 workerNode
.usage
.tasks
.executing
<
710 (this.opts
.tasksQueueOptions
?.concurrency
as number)
715 this.workerNodes
.findIndex(
717 workerNode
.info
.ready
&& workerNode
.usage
.tasks
.executing
=== 0
724 public listTaskFunctions (): string[] {
725 for (const workerNode
of this.workerNodes
) {
727 Array.isArray(workerNode
.info
.taskFunctions
) &&
728 workerNode
.info
.taskFunctions
.length
> 0
730 return workerNode
.info
.taskFunctions
737 public async execute (
740 transferList
?: TransferListItem
[]
741 ): Promise
<Response
> {
742 return await new Promise
<Response
>((resolve
, reject
) => {
744 reject(new Error('Cannot execute a task on destroyed pool'))
746 if (name
!= null && typeof name
!== 'string') {
747 reject(new TypeError('name argument must be a string'))
751 typeof name
=== 'string' &&
752 name
.trim().length
=== 0
754 reject(new TypeError('name argument must not be an empty string'))
756 if (transferList
!= null && !Array.isArray(transferList
)) {
757 reject(new TypeError('transferList argument must be an array'))
759 const timestamp
= performance
.now()
760 const workerNodeKey
= this.chooseWorkerNode()
761 const workerInfo
= this.getWorkerInfo(workerNodeKey
) as WorkerInfo
764 Array.isArray(workerInfo
.taskFunctions
) &&
765 !workerInfo
.taskFunctions
.includes(name
)
768 new Error(`Task function '${name}' is not registered in the pool`)
771 const task
: Task
<Data
> = {
772 name
: name
?? DEFAULT_TASK_NAME
,
773 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
774 data
: data
?? ({} as Data
),
777 workerId
: workerInfo
.id
as number,
780 this.promiseResponseMap
.set(task
.taskId
as string, {
786 this.opts
.enableTasksQueue
=== false ||
787 (this.opts
.enableTasksQueue
=== true &&
788 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
<
789 (this.opts
.tasksQueueOptions
?.concurrency
as number))
791 this.executeTask(workerNodeKey
, task
)
793 this.enqueueTask(workerNodeKey
, task
)
799 public async destroy (): Promise
<void> {
801 this.workerNodes
.map(async (_
, workerNodeKey
) => {
802 await this.destroyWorkerNode(workerNodeKey
)
805 this.emitter
?.emit(PoolEvents
.destroy
, this.info
)
809 protected async sendKillMessageToWorker (
810 workerNodeKey
: number,
813 await new Promise
<void>((resolve
, reject
) => {
814 this.registerWorkerMessageListener(workerNodeKey
, (message
) => {
815 if (message
.kill
=== 'success') {
817 } else if (message
.kill
=== 'failure') {
818 reject(new Error(`Worker ${workerId} kill message handling failed`))
821 this.sendToWorker(workerNodeKey
, { kill
: true, workerId
})
826 * Terminates the worker node given its worker node key.
828 * @param workerNodeKey - The worker node key.
830 protected abstract destroyWorkerNode (workerNodeKey
: number): Promise
<void>
833 * Setup hook to execute code before worker nodes are created in the abstract constructor.
838 protected setupHook (): void {
839 // Intentionally empty
843 * Should return whether the worker is the main worker or not.
845 protected abstract isMain (): boolean
848 * Hook executed before the worker task execution.
851 * @param workerNodeKey - The worker node key.
852 * @param task - The task to execute.
854 protected beforeTaskExecutionHook (
855 workerNodeKey
: number,
858 if (this.workerNodes
[workerNodeKey
]?.usage
!= null) {
859 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
860 ++workerUsage
.tasks
.executing
861 this.updateWaitTimeWorkerUsage(workerUsage
, task
)
864 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
865 this.workerNodes
[workerNodeKey
].getTaskFunctionWorkerUsage(
869 const taskFunctionWorkerUsage
= this.workerNodes
[
871 ].getTaskFunctionWorkerUsage(task
.name
as string) as WorkerUsage
872 ++taskFunctionWorkerUsage
.tasks
.executing
873 this.updateWaitTimeWorkerUsage(taskFunctionWorkerUsage
, task
)
878 * Hook executed after the worker task execution.
881 * @param workerNodeKey - The worker node key.
882 * @param message - The received message.
884 protected afterTaskExecutionHook (
885 workerNodeKey
: number,
886 message
: MessageValue
<Response
>
888 if (this.workerNodes
[workerNodeKey
]?.usage
!= null) {
889 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
890 this.updateTaskStatisticsWorkerUsage(workerUsage
, message
)
891 this.updateRunTimeWorkerUsage(workerUsage
, message
)
892 this.updateEluWorkerUsage(workerUsage
, message
)
895 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
896 this.workerNodes
[workerNodeKey
].getTaskFunctionWorkerUsage(
897 message
.taskPerformance
?.name
as string
900 const taskFunctionWorkerUsage
= this.workerNodes
[
902 ].getTaskFunctionWorkerUsage(
903 message
.taskPerformance
?.name
as string
905 this.updateTaskStatisticsWorkerUsage(taskFunctionWorkerUsage
, message
)
906 this.updateRunTimeWorkerUsage(taskFunctionWorkerUsage
, message
)
907 this.updateEluWorkerUsage(taskFunctionWorkerUsage
, message
)
912 * Whether the worker node shall update its task function worker usage or not.
914 * @param workerNodeKey - The worker node key.
915 * @returns `true` if the worker node shall update its task function worker usage, `false` otherwise.
917 private shallUpdateTaskFunctionWorkerUsage (workerNodeKey
: number): boolean {
918 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
920 workerInfo
!= null &&
921 Array.isArray(workerInfo
.taskFunctions
) &&
922 workerInfo
.taskFunctions
.length
> 2
926 private updateTaskStatisticsWorkerUsage (
927 workerUsage
: WorkerUsage
,
928 message
: MessageValue
<Response
>
930 const workerTaskStatistics
= workerUsage
.tasks
932 workerTaskStatistics
.executing
!= null &&
933 workerTaskStatistics
.executing
> 0
935 --workerTaskStatistics
.executing
937 if (message
.taskError
== null) {
938 ++workerTaskStatistics
.executed
940 ++workerTaskStatistics
.failed
944 private updateRunTimeWorkerUsage (
945 workerUsage
: WorkerUsage
,
946 message
: MessageValue
<Response
>
948 if (message
.taskError
!= null) {
951 updateMeasurementStatistics(
953 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
,
954 message
.taskPerformance
?.runTime
?? 0
958 private updateWaitTimeWorkerUsage (
959 workerUsage
: WorkerUsage
,
962 const timestamp
= performance
.now()
963 const taskWaitTime
= timestamp
- (task
.timestamp
?? timestamp
)
964 updateMeasurementStatistics(
965 workerUsage
.waitTime
,
966 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().waitTime
,
971 private updateEluWorkerUsage (
972 workerUsage
: WorkerUsage
,
973 message
: MessageValue
<Response
>
975 if (message
.taskError
!= null) {
978 const eluTaskStatisticsRequirements
: MeasurementStatisticsRequirements
=
979 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
980 updateMeasurementStatistics(
981 workerUsage
.elu
.active
,
982 eluTaskStatisticsRequirements
,
983 message
.taskPerformance
?.elu
?.active
?? 0
985 updateMeasurementStatistics(
986 workerUsage
.elu
.idle
,
987 eluTaskStatisticsRequirements
,
988 message
.taskPerformance
?.elu
?.idle
?? 0
990 if (eluTaskStatisticsRequirements
.aggregate
) {
991 if (message
.taskPerformance
?.elu
!= null) {
992 if (workerUsage
.elu
.utilization
!= null) {
993 workerUsage
.elu
.utilization
=
994 (workerUsage
.elu
.utilization
+
995 message
.taskPerformance
.elu
.utilization
) /
998 workerUsage
.elu
.utilization
= message
.taskPerformance
.elu
.utilization
1005 * Chooses a worker node for the next task.
1007 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
1009 * @returns The chosen worker node key
1011 private chooseWorkerNode (): number {
1012 if (this.shallCreateDynamicWorker()) {
1013 const workerNodeKey
= this.createAndSetupDynamicWorkerNode()
1015 this.workerChoiceStrategyContext
.getStrategyPolicy().dynamicWorkerUsage
1017 return workerNodeKey
1020 return this.workerChoiceStrategyContext
.execute()
1024 * Conditions for dynamic worker creation.
1026 * @returns Whether to create a dynamic worker or not.
1028 private shallCreateDynamicWorker (): boolean {
1029 return this.type === PoolTypes
.dynamic
&& !this.full
&& this.internalBusy()
1033 * Sends a message to worker given its worker node key.
1035 * @param workerNodeKey - The worker node key.
1036 * @param message - The message.
1037 * @param transferList - The optional array of transferable objects.
1039 protected abstract sendToWorker (
1040 workerNodeKey
: number,
1041 message
: MessageValue
<Data
>,
1042 transferList
?: TransferListItem
[]
1046 * Creates a new worker.
1048 * @returns Newly created worker.
1050 protected abstract createWorker (): Worker
1053 * Creates a new, completely set up worker node.
1055 * @returns New, completely set up worker node key.
1057 protected createAndSetupWorkerNode (): number {
1058 const worker
= this.createWorker()
1060 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
1061 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
1062 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
1063 worker
.on('error', (error
) => {
1064 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
1065 const workerInfo
= this.getWorkerInfo(workerNodeKey
) as WorkerInfo
1066 workerInfo
.ready
= false
1067 this.workerNodes
[workerNodeKey
].closeChannel()
1068 this.emitter
?.emit(PoolEvents
.error
, error
)
1070 this.opts
.restartWorkerOnError
=== true &&
1074 if (workerInfo
.dynamic
) {
1075 this.createAndSetupDynamicWorkerNode()
1077 this.createAndSetupWorkerNode()
1080 if (this.opts
.enableTasksQueue
=== true) {
1081 this.redistributeQueuedTasks(workerNodeKey
)
1084 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
1085 worker
.once('exit', () => {
1086 this.removeWorkerNode(worker
)
1089 const workerNodeKey
= this.addWorkerNode(worker
)
1091 this.afterWorkerNodeSetup(workerNodeKey
)
1093 return workerNodeKey
1097 * Creates a new, completely set up dynamic worker node.
1099 * @returns New, completely set up dynamic worker node key.
1101 protected createAndSetupDynamicWorkerNode (): number {
1102 const workerNodeKey
= this.createAndSetupWorkerNode()
1103 this.registerWorkerMessageListener(workerNodeKey
, (message
) => {
1104 const localWorkerNodeKey
= this.getWorkerNodeKeyByWorkerId(
1107 const workerUsage
= this.workerNodes
[localWorkerNodeKey
].usage
1108 // Kill message received from worker
1110 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
1111 (isKillBehavior(KillBehaviors
.SOFT
, message
.kill
) &&
1112 ((this.opts
.enableTasksQueue
=== false &&
1113 workerUsage
.tasks
.executing
=== 0) ||
1114 (this.opts
.enableTasksQueue
=== true &&
1115 workerUsage
.tasks
.executing
=== 0 &&
1116 this.tasksQueueSize(localWorkerNodeKey
) === 0)))
1118 this.destroyWorkerNode(localWorkerNodeKey
).catch((error
) => {
1119 this.emitter
?.emit(PoolEvents
.error
, error
)
1123 const workerInfo
= this.getWorkerInfo(workerNodeKey
) as WorkerInfo
1124 this.sendToWorker(workerNodeKey
, {
1126 workerId
: workerInfo
.id
as number
1128 workerInfo
.dynamic
= true
1130 this.workerChoiceStrategyContext
.getStrategyPolicy().dynamicWorkerReady
||
1131 this.workerChoiceStrategyContext
.getStrategyPolicy().dynamicWorkerUsage
1133 workerInfo
.ready
= true
1135 this.checkAndEmitDynamicWorkerCreationEvents()
1136 return workerNodeKey
1140 * Registers a listener callback on the worker given its worker node key.
1142 * @param workerNodeKey - The worker node key.
1143 * @param listener - The message listener callback.
1145 protected abstract registerWorkerMessageListener
<
1146 Message
extends Data
| Response
1148 workerNodeKey
: number,
1149 listener
: (message
: MessageValue
<Message
>) => void
1153 * Method hooked up after a worker node has been newly created.
1154 * Can be overridden.
1156 * @param workerNodeKey - The newly created worker node key.
1158 protected afterWorkerNodeSetup (workerNodeKey
: number): void {
1159 // Listen to worker messages.
1160 this.registerWorkerMessageListener(workerNodeKey
, this.workerListener())
1161 // Send the startup message to worker.
1162 this.sendStartupMessageToWorker(workerNodeKey
)
1163 // Send the statistics message to worker.
1164 this.sendStatisticsMessageToWorker(workerNodeKey
)
1165 if (this.opts
.enableTasksQueue
=== true) {
1166 this.workerNodes
[workerNodeKey
].onEmptyQueue
=
1167 this.taskStealingOnEmptyQueue
.bind(this)
1168 this.workerNodes
[workerNodeKey
].onBackPressure
=
1169 this.tasksStealingOnBackPressure
.bind(this)
1174 * Sends the startup message to worker given its worker node key.
1176 * @param workerNodeKey - The worker node key.
1178 protected abstract sendStartupMessageToWorker (workerNodeKey
: number): void
1181 * Sends the statistics message to worker given its worker node key.
1183 * @param workerNodeKey - The worker node key.
1185 private sendStatisticsMessageToWorker (workerNodeKey
: number): void {
1186 this.sendToWorker(workerNodeKey
, {
1189 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1191 elu
: this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1194 workerId
: (this.getWorkerInfo(workerNodeKey
) as WorkerInfo
).id
as number
1198 private redistributeQueuedTasks (workerNodeKey
: number): void {
1199 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1200 let destinationWorkerNodeKey
!: number
1201 let minQueuedTasks
= Infinity
1202 let executeTask
= false
1203 for (const [workerNodeId
, workerNode
] of this.workerNodes
.entries()) {
1204 if (workerNode
.info
.ready
&& workerNodeId
!== workerNodeKey
) {
1206 workerNode
.usage
.tasks
.executing
<
1207 (this.opts
.tasksQueueOptions
?.concurrency
as number)
1211 if (workerNode
.usage
.tasks
.queued
=== 0) {
1212 destinationWorkerNodeKey
= workerNodeId
1215 if (workerNode
.usage
.tasks
.queued
< minQueuedTasks
) {
1216 minQueuedTasks
= workerNode
.usage
.tasks
.queued
1217 destinationWorkerNodeKey
= workerNodeId
1221 if (destinationWorkerNodeKey
!= null) {
1223 ...(this.dequeueTask(workerNodeKey
) as Task
<Data
>),
1224 workerId
: (this.getWorkerInfo(destinationWorkerNodeKey
) as WorkerInfo
)
1228 this.executeTask(destinationWorkerNodeKey
, task
)
1230 this.enqueueTask(destinationWorkerNodeKey
, task
)
1236 private taskStealingOnEmptyQueue (workerId
: number): void {
1237 const destinationWorkerNodeKey
= this.getWorkerNodeKeyByWorkerId(workerId
)
1238 const destinationWorkerNode
= this.workerNodes
[destinationWorkerNodeKey
]
1239 const workerNodes
= this.workerNodes
1242 (workerNodeA
, workerNodeB
) =>
1243 workerNodeB
.usage
.tasks
.queued
- workerNodeA
.usage
.tasks
.queued
1245 for (const sourceWorkerNode
of workerNodes
) {
1246 if (sourceWorkerNode
.usage
.tasks
.queued
=== 0) {
1250 sourceWorkerNode
.info
.ready
&&
1251 sourceWorkerNode
.info
.id
!== workerId
&&
1252 sourceWorkerNode
.usage
.tasks
.queued
> 0
1255 ...(sourceWorkerNode
.popTask() as Task
<Data
>),
1256 workerId
: destinationWorkerNode
.info
.id
as number
1259 destinationWorkerNode
.usage
.tasks
.executing
<
1260 (this.opts
.tasksQueueOptions
?.concurrency
as number)
1262 this.executeTask(destinationWorkerNodeKey
, task
)
1264 this.enqueueTask(destinationWorkerNodeKey
, task
)
1271 private tasksStealingOnBackPressure (workerId
: number): void {
1272 const sourceWorkerNode
=
1273 this.workerNodes
[this.getWorkerNodeKeyByWorkerId(workerId
)]
1274 const workerNodes
= this.workerNodes
1277 (workerNodeA
, workerNodeB
) =>
1278 workerNodeA
.usage
.tasks
.queued
- workerNodeB
.usage
.tasks
.queued
1280 for (const [workerNodeKey
, workerNode
] of workerNodes
.entries()) {
1282 sourceWorkerNode
.usage
.tasks
.queued
> 0 &&
1283 workerNode
.info
.ready
&&
1284 workerNode
.info
.id
!== workerId
&&
1285 workerNode
.usage
.tasks
.queued
<
1286 (this.opts
.tasksQueueOptions
?.size
as number) - 1
1289 ...(sourceWorkerNode
.popTask() as Task
<Data
>),
1290 workerId
: workerNode
.info
.id
as number
1293 workerNode
.usage
.tasks
.executing
<
1294 (this.opts
.tasksQueueOptions
?.concurrency
as number)
1296 this.executeTask(workerNodeKey
, task
)
1298 this.enqueueTask(workerNodeKey
, task
)
1305 * This method is the listener registered for each worker message.
1307 * @returns The listener function to execute when a message is received from a worker.
1309 protected workerListener (): (message
: MessageValue
<Response
>) => void {
1310 return (message
) => {
1311 this.checkMessageWorkerId(message
)
1312 if (message
.ready
!= null && message
.taskFunctions
!= null) {
1313 // Worker ready response received from worker
1314 this.handleWorkerReadyResponse(message
)
1315 } else if (message
.taskId
!= null) {
1316 // Task execution response received from worker
1317 this.handleTaskExecutionResponse(message
)
1318 } else if (message
.taskFunctions
!= null) {
1319 // Task functions message received from worker
1322 this.getWorkerNodeKeyByWorkerId(message
.workerId
)
1324 ).taskFunctions
= message
.taskFunctions
1329 private handleWorkerReadyResponse (message
: MessageValue
<Response
>): void {
1330 if (message
.ready
=== false) {
1331 throw new Error(`Worker ${message.workerId} failed to initialize`)
1333 const workerInfo
= this.getWorkerInfo(
1334 this.getWorkerNodeKeyByWorkerId(message
.workerId
)
1336 workerInfo
.ready
= message
.ready
as boolean
1337 workerInfo
.taskFunctions
= message
.taskFunctions
1338 if (this.emitter
!= null && this.ready
) {
1339 this.emitter
.emit(PoolEvents
.ready
, this.info
)
1343 private handleTaskExecutionResponse (message
: MessageValue
<Response
>): void {
1344 const { taskId
, taskError
, data
} = message
1345 const promiseResponse
= this.promiseResponseMap
.get(taskId
as string)
1346 if (promiseResponse
!= null) {
1347 if (taskError
!= null) {
1348 this.emitter
?.emit(PoolEvents
.taskError
, taskError
)
1349 promiseResponse
.reject(taskError
.message
)
1351 promiseResponse
.resolve(data
as Response
)
1353 const workerNodeKey
= promiseResponse
.workerNodeKey
1354 this.afterTaskExecutionHook(workerNodeKey
, message
)
1355 this.promiseResponseMap
.delete(taskId
as string)
1357 this.opts
.enableTasksQueue
=== true &&
1358 this.tasksQueueSize(workerNodeKey
) > 0 &&
1359 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
<
1360 (this.opts
.tasksQueueOptions
?.concurrency
as number)
1364 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1367 this.workerChoiceStrategyContext
.update(workerNodeKey
)
1371 private checkAndEmitTaskExecutionEvents (): void {
1373 this.emitter
?.emit(PoolEvents
.busy
, this.info
)
1377 private checkAndEmitTaskQueuingEvents (): void {
1378 if (this.hasBackPressure()) {
1379 this.emitter
?.emit(PoolEvents
.backPressure
, this.info
)
1383 private checkAndEmitDynamicWorkerCreationEvents (): void {
1384 if (this.type === PoolTypes
.dynamic
) {
1386 this.emitter
?.emit(PoolEvents
.full
, this.info
)
1392 * Gets the worker information given its worker node key.
1394 * @param workerNodeKey - The worker node key.
1395 * @returns The worker information.
1397 protected getWorkerInfo (workerNodeKey
: number): WorkerInfo
| undefined {
1398 return this.workerNodes
[workerNodeKey
]?.info
1402 * Adds the given worker in the pool worker nodes.
1404 * @param worker - The worker.
1405 * @returns The added worker node key.
1406 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the added worker node is not found.
1408 private addWorkerNode (worker
: Worker
): number {
1409 const workerNode
= new WorkerNode
<Worker
, Data
>(
1412 this.opts
.tasksQueueOptions
?.size
?? Math.pow(this.maxSize
, 2)
1414 // Flag the worker node as ready at pool startup.
1415 if (this.starting
) {
1416 workerNode
.info
.ready
= true
1418 this.workerNodes
.push(workerNode
)
1419 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
1420 if (workerNodeKey
=== -1) {
1421 throw new Error('Worker node added not found')
1423 return workerNodeKey
1427 * Removes the given worker from the pool worker nodes.
1429 * @param worker - The worker.
1431 private removeWorkerNode (worker
: Worker
): void {
1432 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
1433 if (workerNodeKey
!== -1) {
1434 this.workerNodes
.splice(workerNodeKey
, 1)
1435 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
1440 public hasWorkerNodeBackPressure (workerNodeKey
: number): boolean {
1442 this.opts
.enableTasksQueue
=== true &&
1443 this.workerNodes
[workerNodeKey
].hasBackPressure()
1447 private hasBackPressure (): boolean {
1449 this.opts
.enableTasksQueue
=== true &&
1450 this.workerNodes
.findIndex(
1451 (workerNode
) => !workerNode
.hasBackPressure()
1457 * Executes the given task on the worker given its worker node key.
1459 * @param workerNodeKey - The worker node key.
1460 * @param task - The task to execute.
1462 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
1463 this.beforeTaskExecutionHook(workerNodeKey
, task
)
1464 this.sendToWorker(workerNodeKey
, task
, task
.transferList
)
1465 this.checkAndEmitTaskExecutionEvents()
1468 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
1469 const tasksQueueSize
= this.workerNodes
[workerNodeKey
].enqueueTask(task
)
1470 this.checkAndEmitTaskQueuingEvents()
1471 return tasksQueueSize
1474 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
1475 return this.workerNodes
[workerNodeKey
].dequeueTask()
1478 private tasksQueueSize (workerNodeKey
: number): number {
1479 return this.workerNodes
[workerNodeKey
].tasksQueueSize()
1482 protected flushTasksQueue (workerNodeKey
: number): void {
1483 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1486 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1489 this.workerNodes
[workerNodeKey
].clearTasksQueue()
1492 private flushTasksQueues (): void {
1493 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
1494 this.flushTasksQueue(workerNodeKey
)