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 or equal 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`
316 if (tasksQueueOptions
?.queueMaxSize
!= null) {
318 'Invalid tasks queue options: queueMaxSize is deprecated, please use size instead'
322 tasksQueueOptions
?.size
!= null &&
323 !Number.isSafeInteger(tasksQueueOptions
.size
)
326 'Invalid worker node tasks queue size: must be an integer'
329 if (tasksQueueOptions
?.size
!= null && tasksQueueOptions
.size
<= 0) {
330 throw new RangeError(
331 `Invalid worker node tasks queue size: ${tasksQueueOptions.size} is a negative integer or zero`
336 private startPool (): void {
338 this.workerNodes
.reduce(
339 (accumulator
, workerNode
) =>
340 !workerNode
.info
.dynamic
? accumulator
+ 1 : accumulator
,
342 ) < this.numberOfWorkers
344 this.createAndSetupWorkerNode()
349 public get
info (): PoolInfo
{
355 strategy
: this.opts
.workerChoiceStrategy
as WorkerChoiceStrategy
,
356 minSize
: this.minSize
,
357 maxSize
: this.maxSize
,
358 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
359 .runTime
.aggregate
&&
360 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
361 .waitTime
.aggregate
&& { utilization
: round(this.utilization
) }),
362 workerNodes
: this.workerNodes
.length
,
363 idleWorkerNodes
: this.workerNodes
.reduce(
364 (accumulator
, workerNode
) =>
365 workerNode
.usage
.tasks
.executing
=== 0
370 busyWorkerNodes
: this.workerNodes
.reduce(
371 (accumulator
, workerNode
) =>
372 workerNode
.usage
.tasks
.executing
> 0 ? accumulator
+ 1 : accumulator
,
375 executedTasks
: this.workerNodes
.reduce(
376 (accumulator
, workerNode
) =>
377 accumulator
+ workerNode
.usage
.tasks
.executed
,
380 executingTasks
: this.workerNodes
.reduce(
381 (accumulator
, workerNode
) =>
382 accumulator
+ workerNode
.usage
.tasks
.executing
,
385 ...(this.opts
.enableTasksQueue
=== true && {
386 queuedTasks
: this.workerNodes
.reduce(
387 (accumulator
, workerNode
) =>
388 accumulator
+ workerNode
.usage
.tasks
.queued
,
392 ...(this.opts
.enableTasksQueue
=== true && {
393 maxQueuedTasks
: this.workerNodes
.reduce(
394 (accumulator
, workerNode
) =>
395 accumulator
+ (workerNode
.usage
.tasks
?.maxQueued
?? 0),
399 ...(this.opts
.enableTasksQueue
=== true && {
400 backPressure
: this.hasBackPressure()
402 ...(this.opts
.enableTasksQueue
=== true && {
403 stolenTasks
: this.workerNodes
.reduce(
404 (accumulator
, workerNode
) =>
405 accumulator
+ workerNode
.usage
.tasks
.stolen
,
409 failedTasks
: this.workerNodes
.reduce(
410 (accumulator
, workerNode
) =>
411 accumulator
+ workerNode
.usage
.tasks
.failed
,
414 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
415 .runTime
.aggregate
&& {
419 ...this.workerNodes
.map(
420 (workerNode
) => workerNode
.usage
.runTime
?.minimum
?? Infinity
426 ...this.workerNodes
.map(
427 (workerNode
) => workerNode
.usage
.runTime
?.maximum
?? -Infinity
431 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
432 .runTime
.average
&& {
435 this.workerNodes
.reduce
<number[]>(
436 (accumulator
, workerNode
) =>
437 accumulator
.concat(workerNode
.usage
.runTime
.history
),
443 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
447 this.workerNodes
.reduce
<number[]>(
448 (accumulator
, workerNode
) =>
449 accumulator
.concat(workerNode
.usage
.runTime
.history
),
457 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
458 .waitTime
.aggregate
&& {
462 ...this.workerNodes
.map(
463 (workerNode
) => workerNode
.usage
.waitTime
?.minimum
?? Infinity
469 ...this.workerNodes
.map(
470 (workerNode
) => workerNode
.usage
.waitTime
?.maximum
?? -Infinity
474 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
475 .waitTime
.average
&& {
478 this.workerNodes
.reduce
<number[]>(
479 (accumulator
, workerNode
) =>
480 accumulator
.concat(workerNode
.usage
.waitTime
.history
),
486 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
487 .waitTime
.median
&& {
490 this.workerNodes
.reduce
<number[]>(
491 (accumulator
, workerNode
) =>
492 accumulator
.concat(workerNode
.usage
.waitTime
.history
),
504 * The pool readiness boolean status.
506 private get
ready (): boolean {
508 this.workerNodes
.reduce(
509 (accumulator
, workerNode
) =>
510 !workerNode
.info
.dynamic
&& workerNode
.info
.ready
519 * The approximate pool utilization.
521 * @returns The pool utilization.
523 private get
utilization (): number {
524 const poolTimeCapacity
=
525 (performance
.now() - this.startTimestamp
) * this.maxSize
526 const totalTasksRunTime
= this.workerNodes
.reduce(
527 (accumulator
, workerNode
) =>
528 accumulator
+ (workerNode
.usage
.runTime
?.aggregate
?? 0),
531 const totalTasksWaitTime
= this.workerNodes
.reduce(
532 (accumulator
, workerNode
) =>
533 accumulator
+ (workerNode
.usage
.waitTime
?.aggregate
?? 0),
536 return (totalTasksRunTime
+ totalTasksWaitTime
) / poolTimeCapacity
542 * If it is `'dynamic'`, it provides the `max` property.
544 protected abstract get
type (): PoolType
549 protected abstract get
worker (): WorkerType
552 * The pool minimum size.
554 protected get
minSize (): number {
555 return this.numberOfWorkers
559 * The pool maximum size.
561 protected get
maxSize (): number {
562 return this.max
?? this.numberOfWorkers
566 * Checks if the worker id sent in the received message from a worker is valid.
568 * @param message - The received message.
569 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the worker id is invalid.
571 private checkMessageWorkerId (message
: MessageValue
<Response
>): void {
572 if (message
.workerId
== null) {
573 throw new Error('Worker message received without worker id')
575 message
.workerId
!= null &&
576 this.getWorkerNodeKeyByWorkerId(message
.workerId
) === -1
579 `Worker message received from unknown worker '${message.workerId}'`
585 * Gets the given worker its worker node key.
587 * @param worker - The worker.
588 * @returns The worker node key if found in the pool worker nodes, `-1` otherwise.
590 private getWorkerNodeKeyByWorker (worker
: Worker
): number {
591 return this.workerNodes
.findIndex(
592 (workerNode
) => workerNode
.worker
=== worker
597 * Gets the worker node key given its worker id.
599 * @param workerId - The worker id.
600 * @returns The worker node key if the worker id is found in the pool worker nodes, `-1` otherwise.
602 private getWorkerNodeKeyByWorkerId (workerId
: number): number {
603 return this.workerNodes
.findIndex(
604 (workerNode
) => workerNode
.info
.id
=== workerId
609 public setWorkerChoiceStrategy (
610 workerChoiceStrategy
: WorkerChoiceStrategy
,
611 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
613 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
614 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
615 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
616 this.opts
.workerChoiceStrategy
618 if (workerChoiceStrategyOptions
!= null) {
619 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
621 for (const [workerNodeKey
, workerNode
] of this.workerNodes
.entries()) {
622 workerNode
.resetUsage()
623 this.sendStatisticsMessageToWorker(workerNodeKey
)
628 public setWorkerChoiceStrategyOptions (
629 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
631 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
632 this.opts
.workerChoiceStrategyOptions
= {
633 ...DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
,
634 ...workerChoiceStrategyOptions
636 this.workerChoiceStrategyContext
.setOptions(
637 this.opts
.workerChoiceStrategyOptions
642 public enableTasksQueue (
644 tasksQueueOptions
?: TasksQueueOptions
646 if (this.opts
.enableTasksQueue
=== true && !enable
) {
647 this.flushTasksQueues()
649 this.opts
.enableTasksQueue
= enable
650 this.setTasksQueueOptions(tasksQueueOptions
as TasksQueueOptions
)
654 public setTasksQueueOptions (tasksQueueOptions
: TasksQueueOptions
): void {
655 if (this.opts
.enableTasksQueue
=== true) {
656 this.checkValidTasksQueueOptions(tasksQueueOptions
)
657 this.opts
.tasksQueueOptions
=
658 this.buildTasksQueueOptions(tasksQueueOptions
)
659 this.setTasksQueueMaxSize(this.opts
.tasksQueueOptions
.size
as number)
660 } else if (this.opts
.tasksQueueOptions
!= null) {
661 delete this.opts
.tasksQueueOptions
665 private setTasksQueueMaxSize (size
: number): void {
666 for (const workerNode
of this.workerNodes
) {
667 workerNode
.tasksQueueBackPressureSize
= size
671 private buildTasksQueueOptions (
672 tasksQueueOptions
: TasksQueueOptions
673 ): TasksQueueOptions
{
676 size
: Math.pow(this.maxSize
, 2),
684 * Whether the pool is full or not.
686 * The pool filling boolean status.
688 protected get
full (): boolean {
689 return this.workerNodes
.length
>= this.maxSize
693 * Whether the pool is busy or not.
695 * The pool busyness boolean status.
697 protected abstract get
busy (): boolean
700 * Whether worker nodes are executing concurrently their tasks quota or not.
702 * @returns Worker nodes busyness boolean status.
704 protected internalBusy (): boolean {
705 if (this.opts
.enableTasksQueue
=== true) {
707 this.workerNodes
.findIndex(
709 workerNode
.info
.ready
&&
710 workerNode
.usage
.tasks
.executing
<
711 (this.opts
.tasksQueueOptions
?.concurrency
as number)
716 this.workerNodes
.findIndex(
718 workerNode
.info
.ready
&& workerNode
.usage
.tasks
.executing
=== 0
725 public listTaskFunctions (): string[] {
726 for (const workerNode
of this.workerNodes
) {
728 Array.isArray(workerNode
.info
.taskFunctions
) &&
729 workerNode
.info
.taskFunctions
.length
> 0
731 return workerNode
.info
.taskFunctions
738 public async execute (
741 transferList
?: TransferListItem
[]
742 ): Promise
<Response
> {
743 return await new Promise
<Response
>((resolve
, reject
) => {
745 reject(new Error('Cannot execute a task on destroyed pool'))
748 if (name
!= null && typeof name
!== 'string') {
749 reject(new TypeError('name argument must be a string'))
754 typeof name
=== 'string' &&
755 name
.trim().length
=== 0
757 reject(new TypeError('name argument must not be an empty string'))
760 if (transferList
!= null && !Array.isArray(transferList
)) {
761 reject(new TypeError('transferList argument must be an array'))
764 const timestamp
= performance
.now()
765 const workerNodeKey
= this.chooseWorkerNode()
766 const workerInfo
= this.getWorkerInfo(workerNodeKey
) as WorkerInfo
767 const task
: Task
<Data
> = {
768 name
: name
?? DEFAULT_TASK_NAME
,
769 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
770 data
: data
?? ({} as Data
),
773 workerId
: workerInfo
.id
as number,
776 this.promiseResponseMap
.set(task
.taskId
as string, {
782 this.opts
.enableTasksQueue
=== false ||
783 (this.opts
.enableTasksQueue
=== true &&
784 this.tasksQueueSize(workerNodeKey
) === 0 &&
785 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
<
786 (this.opts
.tasksQueueOptions
?.concurrency
as number))
788 this.executeTask(workerNodeKey
, task
)
790 this.enqueueTask(workerNodeKey
, task
)
796 public async destroy (): Promise
<void> {
798 this.workerNodes
.map(async (_
, workerNodeKey
) => {
799 await this.destroyWorkerNode(workerNodeKey
)
802 this.emitter
?.emit(PoolEvents
.destroy
, this.info
)
806 protected async sendKillMessageToWorker (
807 workerNodeKey
: number,
810 await new Promise
<void>((resolve
, reject
) => {
811 this.registerWorkerMessageListener(workerNodeKey
, (message
) => {
812 if (message
.kill
=== 'success') {
814 } else if (message
.kill
=== 'failure') {
815 reject(new Error(`Worker ${workerId} kill message handling failed`))
818 this.sendToWorker(workerNodeKey
, { kill
: true, workerId
})
823 * Terminates the worker node given its worker node key.
825 * @param workerNodeKey - The worker node key.
827 protected abstract destroyWorkerNode (workerNodeKey
: number): Promise
<void>
830 * Setup hook to execute code before worker nodes are created in the abstract constructor.
835 protected setupHook (): void {
836 /** Intentionally empty */
840 * Should return whether the worker is the main worker or not.
842 protected abstract isMain (): boolean
845 * Hook executed before the worker task execution.
848 * @param workerNodeKey - The worker node key.
849 * @param task - The task to execute.
851 protected beforeTaskExecutionHook (
852 workerNodeKey
: number,
855 if (this.workerNodes
[workerNodeKey
]?.usage
!= null) {
856 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
857 ++workerUsage
.tasks
.executing
858 this.updateWaitTimeWorkerUsage(workerUsage
, task
)
861 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
862 this.workerNodes
[workerNodeKey
].getTaskFunctionWorkerUsage(
866 const taskFunctionWorkerUsage
= this.workerNodes
[
868 ].getTaskFunctionWorkerUsage(task
.name
as string) as WorkerUsage
869 ++taskFunctionWorkerUsage
.tasks
.executing
870 this.updateWaitTimeWorkerUsage(taskFunctionWorkerUsage
, task
)
875 * Hook executed after the worker task execution.
878 * @param workerNodeKey - The worker node key.
879 * @param message - The received message.
881 protected afterTaskExecutionHook (
882 workerNodeKey
: number,
883 message
: MessageValue
<Response
>
885 if (this.workerNodes
[workerNodeKey
]?.usage
!= null) {
886 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
887 this.updateTaskStatisticsWorkerUsage(workerUsage
, message
)
888 this.updateRunTimeWorkerUsage(workerUsage
, message
)
889 this.updateEluWorkerUsage(workerUsage
, message
)
892 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
893 this.workerNodes
[workerNodeKey
].getTaskFunctionWorkerUsage(
894 message
.taskPerformance
?.name
as string
897 const taskFunctionWorkerUsage
= this.workerNodes
[
899 ].getTaskFunctionWorkerUsage(
900 message
.taskPerformance
?.name
as string
902 this.updateTaskStatisticsWorkerUsage(taskFunctionWorkerUsage
, message
)
903 this.updateRunTimeWorkerUsage(taskFunctionWorkerUsage
, message
)
904 this.updateEluWorkerUsage(taskFunctionWorkerUsage
, message
)
909 * Whether the worker node shall update its task function worker usage or not.
911 * @param workerNodeKey - The worker node key.
912 * @returns `true` if the worker node shall update its task function worker usage, `false` otherwise.
914 private shallUpdateTaskFunctionWorkerUsage (workerNodeKey
: number): boolean {
915 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
917 workerInfo
!= null &&
918 Array.isArray(workerInfo
.taskFunctions
) &&
919 workerInfo
.taskFunctions
.length
> 2
923 private updateTaskStatisticsWorkerUsage (
924 workerUsage
: WorkerUsage
,
925 message
: MessageValue
<Response
>
927 const workerTaskStatistics
= workerUsage
.tasks
929 workerTaskStatistics
.executing
!= null &&
930 workerTaskStatistics
.executing
> 0
932 --workerTaskStatistics
.executing
934 if (message
.taskError
== null) {
935 ++workerTaskStatistics
.executed
937 ++workerTaskStatistics
.failed
941 private updateRunTimeWorkerUsage (
942 workerUsage
: WorkerUsage
,
943 message
: MessageValue
<Response
>
945 if (message
.taskError
!= null) {
948 updateMeasurementStatistics(
950 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
,
951 message
.taskPerformance
?.runTime
?? 0
955 private updateWaitTimeWorkerUsage (
956 workerUsage
: WorkerUsage
,
959 const timestamp
= performance
.now()
960 const taskWaitTime
= timestamp
- (task
.timestamp
?? timestamp
)
961 updateMeasurementStatistics(
962 workerUsage
.waitTime
,
963 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().waitTime
,
968 private updateEluWorkerUsage (
969 workerUsage
: WorkerUsage
,
970 message
: MessageValue
<Response
>
972 if (message
.taskError
!= null) {
975 const eluTaskStatisticsRequirements
: MeasurementStatisticsRequirements
=
976 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
977 updateMeasurementStatistics(
978 workerUsage
.elu
.active
,
979 eluTaskStatisticsRequirements
,
980 message
.taskPerformance
?.elu
?.active
?? 0
982 updateMeasurementStatistics(
983 workerUsage
.elu
.idle
,
984 eluTaskStatisticsRequirements
,
985 message
.taskPerformance
?.elu
?.idle
?? 0
987 if (eluTaskStatisticsRequirements
.aggregate
) {
988 if (message
.taskPerformance
?.elu
!= null) {
989 if (workerUsage
.elu
.utilization
!= null) {
990 workerUsage
.elu
.utilization
=
991 (workerUsage
.elu
.utilization
+
992 message
.taskPerformance
.elu
.utilization
) /
995 workerUsage
.elu
.utilization
= message
.taskPerformance
.elu
.utilization
1002 * Chooses a worker node for the next task.
1004 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
1006 * @returns The chosen worker node key
1008 private chooseWorkerNode (): number {
1009 if (this.shallCreateDynamicWorker()) {
1010 const workerNodeKey
= this.createAndSetupDynamicWorkerNode()
1012 this.workerChoiceStrategyContext
.getStrategyPolicy().dynamicWorkerUsage
1014 return workerNodeKey
1017 return this.workerChoiceStrategyContext
.execute()
1021 * Conditions for dynamic worker creation.
1023 * @returns Whether to create a dynamic worker or not.
1025 private shallCreateDynamicWorker (): boolean {
1026 return this.type === PoolTypes
.dynamic
&& !this.full
&& this.internalBusy()
1030 * Sends a message to worker given its worker node key.
1032 * @param workerNodeKey - The worker node key.
1033 * @param message - The message.
1034 * @param transferList - The optional array of transferable objects.
1036 protected abstract sendToWorker (
1037 workerNodeKey
: number,
1038 message
: MessageValue
<Data
>,
1039 transferList
?: TransferListItem
[]
1043 * Creates a new worker.
1045 * @returns Newly created worker.
1047 protected abstract createWorker (): Worker
1050 * Creates a new, completely set up worker node.
1052 * @returns New, completely set up worker node key.
1054 protected createAndSetupWorkerNode (): number {
1055 const worker
= this.createWorker()
1057 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
1058 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
1059 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
1060 worker
.on('error', (error
) => {
1061 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
1062 const workerInfo
= this.getWorkerInfo(workerNodeKey
) as WorkerInfo
1063 workerInfo
.ready
= false
1064 this.workerNodes
[workerNodeKey
].closeChannel()
1065 this.emitter
?.emit(PoolEvents
.error
, error
)
1067 this.opts
.restartWorkerOnError
=== true &&
1071 if (workerInfo
.dynamic
) {
1072 this.createAndSetupDynamicWorkerNode()
1074 this.createAndSetupWorkerNode()
1077 if (this.opts
.enableTasksQueue
=== true) {
1078 this.redistributeQueuedTasks(workerNodeKey
)
1081 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
1082 worker
.once('exit', () => {
1083 this.removeWorkerNode(worker
)
1086 const workerNodeKey
= this.addWorkerNode(worker
)
1088 this.afterWorkerNodeSetup(workerNodeKey
)
1090 return workerNodeKey
1094 * Creates a new, completely set up dynamic worker node.
1096 * @returns New, completely set up dynamic worker node key.
1098 protected createAndSetupDynamicWorkerNode (): number {
1099 const workerNodeKey
= this.createAndSetupWorkerNode()
1100 this.registerWorkerMessageListener(workerNodeKey
, (message
) => {
1101 const localWorkerNodeKey
= this.getWorkerNodeKeyByWorkerId(
1104 const workerUsage
= this.workerNodes
[localWorkerNodeKey
].usage
1105 // Kill message received from worker
1107 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
1108 (isKillBehavior(KillBehaviors
.SOFT
, message
.kill
) &&
1109 ((this.opts
.enableTasksQueue
=== false &&
1110 workerUsage
.tasks
.executing
=== 0) ||
1111 (this.opts
.enableTasksQueue
=== true &&
1112 workerUsage
.tasks
.executing
=== 0 &&
1113 this.tasksQueueSize(localWorkerNodeKey
) === 0)))
1115 this.destroyWorkerNode(localWorkerNodeKey
).catch((error
) => {
1116 this.emitter
?.emit(PoolEvents
.error
, error
)
1120 const workerInfo
= this.getWorkerInfo(workerNodeKey
) as WorkerInfo
1121 this.sendToWorker(workerNodeKey
, {
1123 workerId
: workerInfo
.id
as number
1125 workerInfo
.dynamic
= true
1127 this.workerChoiceStrategyContext
.getStrategyPolicy().dynamicWorkerReady
||
1128 this.workerChoiceStrategyContext
.getStrategyPolicy().dynamicWorkerUsage
1130 workerInfo
.ready
= true
1132 this.checkAndEmitDynamicWorkerCreationEvents()
1133 return workerNodeKey
1137 * Registers a listener callback on the worker given its worker node key.
1139 * @param workerNodeKey - The worker node key.
1140 * @param listener - The message listener callback.
1142 protected abstract registerWorkerMessageListener
<
1143 Message
extends Data
| Response
1145 workerNodeKey
: number,
1146 listener
: (message
: MessageValue
<Message
>) => void
1150 * Method hooked up after a worker node has been newly created.
1151 * Can be overridden.
1153 * @param workerNodeKey - The newly created worker node key.
1155 protected afterWorkerNodeSetup (workerNodeKey
: number): void {
1156 // Listen to worker messages.
1157 this.registerWorkerMessageListener(workerNodeKey
, this.workerListener())
1158 // Send the startup message to worker.
1159 this.sendStartupMessageToWorker(workerNodeKey
)
1160 // Send the statistics message to worker.
1161 this.sendStatisticsMessageToWorker(workerNodeKey
)
1162 if (this.opts
.enableTasksQueue
=== true) {
1163 this.workerNodes
[workerNodeKey
].onEmptyQueue
=
1164 this.taskStealingOnEmptyQueue
.bind(this)
1165 this.workerNodes
[workerNodeKey
].onBackPressure
=
1166 this.tasksStealingOnBackPressure
.bind(this)
1171 * Sends the startup message to worker given its worker node key.
1173 * @param workerNodeKey - The worker node key.
1175 protected abstract sendStartupMessageToWorker (workerNodeKey
: number): void
1178 * Sends the statistics message to worker given its worker node key.
1180 * @param workerNodeKey - The worker node key.
1182 private sendStatisticsMessageToWorker (workerNodeKey
: number): void {
1183 this.sendToWorker(workerNodeKey
, {
1186 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1188 elu
: this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1191 workerId
: (this.getWorkerInfo(workerNodeKey
) as WorkerInfo
).id
as number
1195 private redistributeQueuedTasks (workerNodeKey
: number): void {
1196 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1197 let destinationWorkerNodeKey
!: number
1198 let minQueuedTasks
= Infinity
1199 for (const [workerNodeId
, workerNode
] of this.workerNodes
.entries()) {
1200 if (workerNode
.info
.ready
&& workerNodeId
!== workerNodeKey
) {
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) {
1212 const destinationWorkerNode
= this.workerNodes
[destinationWorkerNodeKey
]
1214 ...(this.dequeueTask(workerNodeKey
) as Task
<Data
>),
1215 workerId
: destinationWorkerNode
.info
.id
as number
1218 this.tasksQueueSize(destinationWorkerNodeKey
) === 0 &&
1219 destinationWorkerNode
.usage
.tasks
.executing
<
1220 (this.opts
.tasksQueueOptions
?.concurrency
as number)
1222 this.executeTask(destinationWorkerNodeKey
, task
)
1224 this.enqueueTask(destinationWorkerNodeKey
, task
)
1230 private taskStealingOnEmptyQueue (workerId
: number): void {
1231 const destinationWorkerNodeKey
= this.getWorkerNodeKeyByWorkerId(workerId
)
1232 const destinationWorkerNode
= this.workerNodes
[destinationWorkerNodeKey
]
1233 const workerNodes
= this.workerNodes
1236 (workerNodeA
, workerNodeB
) =>
1237 workerNodeB
.usage
.tasks
.queued
- workerNodeA
.usage
.tasks
.queued
1239 for (const sourceWorkerNode
of workerNodes
) {
1240 if (sourceWorkerNode
.usage
.tasks
.queued
=== 0) {
1244 sourceWorkerNode
.info
.ready
&&
1245 sourceWorkerNode
.info
.id
!== workerId
&&
1246 sourceWorkerNode
.usage
.tasks
.queued
> 0
1249 ...(sourceWorkerNode
.popTask() as Task
<Data
>),
1250 workerId
: destinationWorkerNode
.info
.id
as number
1253 this.tasksQueueSize(destinationWorkerNodeKey
) === 0 &&
1254 destinationWorkerNode
.usage
.tasks
.executing
<
1255 (this.opts
.tasksQueueOptions
?.concurrency
as number)
1257 this.executeTask(destinationWorkerNodeKey
, task
)
1259 this.enqueueTask(destinationWorkerNodeKey
, task
)
1261 if (destinationWorkerNode
?.usage
!= null) {
1262 ++destinationWorkerNode
.usage
.tasks
.stolen
1265 this.shallUpdateTaskFunctionWorkerUsage(destinationWorkerNodeKey
) &&
1266 destinationWorkerNode
.getTaskFunctionWorkerUsage(
1270 const taskFunctionWorkerUsage
=
1271 destinationWorkerNode
.getTaskFunctionWorkerUsage(
1274 ++taskFunctionWorkerUsage
.tasks
.stolen
1281 private tasksStealingOnBackPressure (workerId
: number): void {
1282 if ((this.opts
.tasksQueueOptions
?.size
as number) <= 1) {
1285 const sourceWorkerNode
=
1286 this.workerNodes
[this.getWorkerNodeKeyByWorkerId(workerId
)]
1287 const workerNodes
= this.workerNodes
1290 (workerNodeA
, workerNodeB
) =>
1291 workerNodeA
.usage
.tasks
.queued
- workerNodeB
.usage
.tasks
.queued
1293 for (const [workerNodeKey
, workerNode
] of workerNodes
.entries()) {
1295 sourceWorkerNode
.usage
.tasks
.queued
> 0 &&
1296 workerNode
.info
.ready
&&
1297 workerNode
.info
.id
!== workerId
&&
1298 workerNode
.usage
.tasks
.queued
<
1299 (this.opts
.tasksQueueOptions
?.size
as number) - 1
1302 ...(sourceWorkerNode
.popTask() as Task
<Data
>),
1303 workerId
: workerNode
.info
.id
as number
1305 if (this.tasksQueueSize(workerNodeKey
) === 0) {
1306 this.executeTask(workerNodeKey
, task
)
1308 this.enqueueTask(workerNodeKey
, task
)
1310 if (workerNode
?.usage
!= null) {
1311 ++workerNode
.usage
.tasks
.stolen
1314 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
1315 workerNode
.getTaskFunctionWorkerUsage(task
.name
as string) != null
1317 const taskFunctionWorkerUsage
= workerNode
.getTaskFunctionWorkerUsage(
1320 ++taskFunctionWorkerUsage
.tasks
.stolen
1327 * This method is the listener registered for each worker message.
1329 * @returns The listener function to execute when a message is received from a worker.
1331 protected workerListener (): (message
: MessageValue
<Response
>) => void {
1332 return (message
) => {
1333 this.checkMessageWorkerId(message
)
1334 if (message
.ready
!= null && message
.taskFunctions
!= null) {
1335 // Worker ready response received from worker
1336 this.handleWorkerReadyResponse(message
)
1337 } else if (message
.taskId
!= null) {
1338 // Task execution response received from worker
1339 this.handleTaskExecutionResponse(message
)
1340 } else if (message
.taskFunctions
!= null) {
1341 // Task functions message received from worker
1344 this.getWorkerNodeKeyByWorkerId(message
.workerId
)
1346 ).taskFunctions
= message
.taskFunctions
1351 private handleWorkerReadyResponse (message
: MessageValue
<Response
>): void {
1352 if (message
.ready
=== false) {
1353 throw new Error(`Worker ${message.workerId} failed to initialize`)
1355 const workerInfo
= this.getWorkerInfo(
1356 this.getWorkerNodeKeyByWorkerId(message
.workerId
)
1358 workerInfo
.ready
= message
.ready
as boolean
1359 workerInfo
.taskFunctions
= message
.taskFunctions
1360 if (this.emitter
!= null && this.ready
) {
1361 this.emitter
.emit(PoolEvents
.ready
, this.info
)
1365 private handleTaskExecutionResponse (message
: MessageValue
<Response
>): void {
1366 const { taskId
, taskError
, data
} = message
1367 const promiseResponse
= this.promiseResponseMap
.get(taskId
as string)
1368 if (promiseResponse
!= null) {
1369 if (taskError
!= null) {
1370 this.emitter
?.emit(PoolEvents
.taskError
, taskError
)
1371 promiseResponse
.reject(taskError
.message
)
1373 promiseResponse
.resolve(data
as Response
)
1375 const workerNodeKey
= promiseResponse
.workerNodeKey
1376 this.afterTaskExecutionHook(workerNodeKey
, message
)
1377 this.promiseResponseMap
.delete(taskId
as string)
1379 this.opts
.enableTasksQueue
=== true &&
1380 this.tasksQueueSize(workerNodeKey
) > 0 &&
1381 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
<
1382 (this.opts
.tasksQueueOptions
?.concurrency
as number)
1386 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1389 this.workerChoiceStrategyContext
.update(workerNodeKey
)
1393 private checkAndEmitTaskExecutionEvents (): void {
1395 this.emitter
?.emit(PoolEvents
.busy
, this.info
)
1399 private checkAndEmitTaskQueuingEvents (): void {
1400 if (this.hasBackPressure()) {
1401 this.emitter
?.emit(PoolEvents
.backPressure
, this.info
)
1405 private checkAndEmitDynamicWorkerCreationEvents (): void {
1406 if (this.type === PoolTypes
.dynamic
) {
1408 this.emitter
?.emit(PoolEvents
.full
, this.info
)
1414 * Gets the worker information given its worker node key.
1416 * @param workerNodeKey - The worker node key.
1417 * @returns The worker information.
1419 protected getWorkerInfo (workerNodeKey
: number): WorkerInfo
| undefined {
1420 return this.workerNodes
[workerNodeKey
]?.info
1424 * Adds the given worker in the pool worker nodes.
1426 * @param worker - The worker.
1427 * @returns The added worker node key.
1428 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the added worker node is not found.
1430 private addWorkerNode (worker
: Worker
): number {
1431 const workerNode
= new WorkerNode
<Worker
, Data
>(
1434 this.opts
.tasksQueueOptions
?.size
?? Math.pow(this.maxSize
, 2)
1436 // Flag the worker node as ready at pool startup.
1437 if (this.starting
) {
1438 workerNode
.info
.ready
= true
1440 this.workerNodes
.push(workerNode
)
1441 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
1442 if (workerNodeKey
=== -1) {
1443 throw new Error('Worker node added not found')
1445 return workerNodeKey
1449 * Removes the given worker from the pool worker nodes.
1451 * @param worker - The worker.
1453 private removeWorkerNode (worker
: Worker
): void {
1454 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
1455 if (workerNodeKey
!== -1) {
1456 this.workerNodes
.splice(workerNodeKey
, 1)
1457 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
1462 public hasWorkerNodeBackPressure (workerNodeKey
: number): boolean {
1464 this.opts
.enableTasksQueue
=== true &&
1465 this.workerNodes
[workerNodeKey
].hasBackPressure()
1469 private hasBackPressure (): boolean {
1471 this.opts
.enableTasksQueue
=== true &&
1472 this.workerNodes
.findIndex(
1473 (workerNode
) => !workerNode
.hasBackPressure()
1479 * Executes the given task on the worker given its worker node key.
1481 * @param workerNodeKey - The worker node key.
1482 * @param task - The task to execute.
1484 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
1485 this.beforeTaskExecutionHook(workerNodeKey
, task
)
1486 this.sendToWorker(workerNodeKey
, task
, task
.transferList
)
1487 this.checkAndEmitTaskExecutionEvents()
1490 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
1491 const tasksQueueSize
= this.workerNodes
[workerNodeKey
].enqueueTask(task
)
1492 this.checkAndEmitTaskQueuingEvents()
1493 return tasksQueueSize
1496 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
1497 return this.workerNodes
[workerNodeKey
].dequeueTask()
1500 private tasksQueueSize (workerNodeKey
: number): number {
1501 return this.workerNodes
[workerNodeKey
].tasksQueueSize()
1504 protected flushTasksQueue (workerNodeKey
: number): void {
1505 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1508 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1511 this.workerNodes
[workerNodeKey
].clearTasksQueue()
1514 private flushTasksQueues (): void {
1515 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
1516 this.flushTasksQueue(workerNodeKey
)