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 ...(this.opts
.enableTasksQueue
=== true && {
409 stolenTasks
: this.workerNodes
.reduce(
410 (accumulator
, workerNode
) =>
411 accumulator
+ workerNode
.usage
.tasks
.stolen
,
415 failedTasks
: this.workerNodes
.reduce(
416 (accumulator
, workerNode
) =>
417 accumulator
+ workerNode
.usage
.tasks
.failed
,
420 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
421 .runTime
.aggregate
&& {
425 ...this.workerNodes
.map(
426 (workerNode
) => workerNode
.usage
.runTime
?.minimum
?? Infinity
432 ...this.workerNodes
.map(
433 (workerNode
) => workerNode
.usage
.runTime
?.maximum
?? -Infinity
437 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
438 .runTime
.average
&& {
441 this.workerNodes
.reduce
<number[]>(
442 (accumulator
, workerNode
) =>
443 accumulator
.concat(workerNode
.usage
.runTime
.history
),
449 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
453 this.workerNodes
.reduce
<number[]>(
454 (accumulator
, workerNode
) =>
455 accumulator
.concat(workerNode
.usage
.runTime
.history
),
463 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
464 .waitTime
.aggregate
&& {
468 ...this.workerNodes
.map(
469 (workerNode
) => workerNode
.usage
.waitTime
?.minimum
?? Infinity
475 ...this.workerNodes
.map(
476 (workerNode
) => workerNode
.usage
.waitTime
?.maximum
?? -Infinity
480 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
481 .waitTime
.average
&& {
484 this.workerNodes
.reduce
<number[]>(
485 (accumulator
, workerNode
) =>
486 accumulator
.concat(workerNode
.usage
.waitTime
.history
),
492 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
493 .waitTime
.median
&& {
496 this.workerNodes
.reduce
<number[]>(
497 (accumulator
, workerNode
) =>
498 accumulator
.concat(workerNode
.usage
.waitTime
.history
),
510 * The pool readiness boolean status.
512 private get
ready (): boolean {
514 this.workerNodes
.reduce(
515 (accumulator
, workerNode
) =>
516 !workerNode
.info
.dynamic
&& workerNode
.info
.ready
525 * The approximate pool utilization.
527 * @returns The pool utilization.
529 private get
utilization (): number {
530 const poolTimeCapacity
=
531 (performance
.now() - this.startTimestamp
) * this.maxSize
532 const totalTasksRunTime
= this.workerNodes
.reduce(
533 (accumulator
, workerNode
) =>
534 accumulator
+ (workerNode
.usage
.runTime
?.aggregate
?? 0),
537 const totalTasksWaitTime
= this.workerNodes
.reduce(
538 (accumulator
, workerNode
) =>
539 accumulator
+ (workerNode
.usage
.waitTime
?.aggregate
?? 0),
542 return (totalTasksRunTime
+ totalTasksWaitTime
) / poolTimeCapacity
548 * If it is `'dynamic'`, it provides the `max` property.
550 protected abstract get
type (): PoolType
555 protected abstract get
worker (): WorkerType
558 * The pool minimum size.
560 protected get
minSize (): number {
561 return this.numberOfWorkers
565 * The pool maximum size.
567 protected get
maxSize (): number {
568 return this.max
?? this.numberOfWorkers
572 * Checks if the worker id sent in the received message from a worker is valid.
574 * @param message - The received message.
575 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the worker id is invalid.
577 private checkMessageWorkerId (message
: MessageValue
<Response
>): void {
578 if (message
.workerId
== null) {
579 throw new Error('Worker message received without worker id')
581 message
.workerId
!= null &&
582 this.getWorkerNodeKeyByWorkerId(message
.workerId
) === -1
585 `Worker message received from unknown worker '${message.workerId}'`
591 * Gets the given worker its worker node key.
593 * @param worker - The worker.
594 * @returns The worker node key if found in the pool worker nodes, `-1` otherwise.
596 private getWorkerNodeKeyByWorker (worker
: Worker
): number {
597 return this.workerNodes
.findIndex(
598 (workerNode
) => workerNode
.worker
=== worker
603 * Gets the worker node key given its worker id.
605 * @param workerId - The worker id.
606 * @returns The worker node key if the worker id is found in the pool worker nodes, `-1` otherwise.
608 private getWorkerNodeKeyByWorkerId (workerId
: number): number {
609 return this.workerNodes
.findIndex(
610 (workerNode
) => workerNode
.info
.id
=== workerId
615 public setWorkerChoiceStrategy (
616 workerChoiceStrategy
: WorkerChoiceStrategy
,
617 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
619 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
620 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
621 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
622 this.opts
.workerChoiceStrategy
624 if (workerChoiceStrategyOptions
!= null) {
625 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
627 for (const [workerNodeKey
, workerNode
] of this.workerNodes
.entries()) {
628 workerNode
.resetUsage()
629 this.sendStatisticsMessageToWorker(workerNodeKey
)
634 public setWorkerChoiceStrategyOptions (
635 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
637 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
638 this.opts
.workerChoiceStrategyOptions
= {
639 ...DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
,
640 ...workerChoiceStrategyOptions
642 this.workerChoiceStrategyContext
.setOptions(
643 this.opts
.workerChoiceStrategyOptions
648 public enableTasksQueue (
650 tasksQueueOptions
?: TasksQueueOptions
652 if (this.opts
.enableTasksQueue
=== true && !enable
) {
653 this.flushTasksQueues()
655 this.opts
.enableTasksQueue
= enable
656 this.setTasksQueueOptions(tasksQueueOptions
as TasksQueueOptions
)
660 public setTasksQueueOptions (tasksQueueOptions
: TasksQueueOptions
): void {
661 if (this.opts
.enableTasksQueue
=== true) {
662 this.checkValidTasksQueueOptions(tasksQueueOptions
)
663 this.opts
.tasksQueueOptions
=
664 this.buildTasksQueueOptions(tasksQueueOptions
)
665 this.setTasksQueueMaxSize(this.opts
.tasksQueueOptions
.size
as number)
666 } else if (this.opts
.tasksQueueOptions
!= null) {
667 delete this.opts
.tasksQueueOptions
671 private setTasksQueueMaxSize (size
: number): void {
672 for (const workerNode
of this.workerNodes
) {
673 workerNode
.tasksQueueBackPressureSize
= size
677 private buildTasksQueueOptions (
678 tasksQueueOptions
: TasksQueueOptions
679 ): TasksQueueOptions
{
682 size
: Math.pow(this.maxSize
, 2),
690 * Whether the pool is full or not.
692 * The pool filling boolean status.
694 protected get
full (): boolean {
695 return this.workerNodes
.length
>= this.maxSize
699 * Whether the pool is busy or not.
701 * The pool busyness boolean status.
703 protected abstract get
busy (): boolean
706 * Whether worker nodes are executing concurrently their tasks quota or not.
708 * @returns Worker nodes busyness boolean status.
710 protected internalBusy (): boolean {
711 if (this.opts
.enableTasksQueue
=== true) {
713 this.workerNodes
.findIndex(
715 workerNode
.info
.ready
&&
716 workerNode
.usage
.tasks
.executing
<
717 (this.opts
.tasksQueueOptions
?.concurrency
as number)
722 this.workerNodes
.findIndex(
724 workerNode
.info
.ready
&& workerNode
.usage
.tasks
.executing
=== 0
731 public listTaskFunctions (): string[] {
732 for (const workerNode
of this.workerNodes
) {
734 Array.isArray(workerNode
.info
.taskFunctions
) &&
735 workerNode
.info
.taskFunctions
.length
> 0
737 return workerNode
.info
.taskFunctions
744 public async execute (
747 transferList
?: TransferListItem
[]
748 ): Promise
<Response
> {
749 return await new Promise
<Response
>((resolve
, reject
) => {
751 reject(new Error('Cannot execute a task on destroyed pool'))
753 if (name
!= null && typeof name
!== 'string') {
754 reject(new TypeError('name argument must be a string'))
758 typeof name
=== 'string' &&
759 name
.trim().length
=== 0
761 reject(new TypeError('name argument must not be an empty string'))
763 if (transferList
!= null && !Array.isArray(transferList
)) {
764 reject(new TypeError('transferList argument must be an array'))
766 const timestamp
= performance
.now()
767 const workerNodeKey
= this.chooseWorkerNode()
768 const workerInfo
= this.getWorkerInfo(workerNodeKey
) as WorkerInfo
771 Array.isArray(workerInfo
.taskFunctions
) &&
772 !workerInfo
.taskFunctions
.includes(name
)
775 new Error(`Task function '${name}' is not registered in the pool`)
778 const task
: Task
<Data
> = {
779 name
: name
?? DEFAULT_TASK_NAME
,
780 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
781 data
: data
?? ({} as Data
),
784 workerId
: workerInfo
.id
as number,
787 this.promiseResponseMap
.set(task
.taskId
as string, {
793 this.opts
.enableTasksQueue
=== false ||
794 (this.opts
.enableTasksQueue
=== true &&
795 this.tasksQueueSize(workerNodeKey
) === 0 &&
796 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
<
797 (this.opts
.tasksQueueOptions
?.concurrency
as number))
799 this.executeTask(workerNodeKey
, task
)
801 this.enqueueTask(workerNodeKey
, task
)
807 public async destroy (): Promise
<void> {
809 this.workerNodes
.map(async (_
, workerNodeKey
) => {
810 await this.destroyWorkerNode(workerNodeKey
)
813 this.emitter
?.emit(PoolEvents
.destroy
, this.info
)
817 protected async sendKillMessageToWorker (
818 workerNodeKey
: number,
821 await new Promise
<void>((resolve
, reject
) => {
822 this.registerWorkerMessageListener(workerNodeKey
, (message
) => {
823 if (message
.kill
=== 'success') {
825 } else if (message
.kill
=== 'failure') {
826 reject(new Error(`Worker ${workerId} kill message handling failed`))
829 this.sendToWorker(workerNodeKey
, { kill
: true, workerId
})
834 * Terminates the worker node given its worker node key.
836 * @param workerNodeKey - The worker node key.
838 protected abstract destroyWorkerNode (workerNodeKey
: number): Promise
<void>
841 * Setup hook to execute code before worker nodes are created in the abstract constructor.
846 protected setupHook (): void {
847 /** Intentionally empty */
851 * Should return whether the worker is the main worker or not.
853 protected abstract isMain (): boolean
856 * Hook executed before the worker task execution.
859 * @param workerNodeKey - The worker node key.
860 * @param task - The task to execute.
862 protected beforeTaskExecutionHook (
863 workerNodeKey
: number,
866 if (this.workerNodes
[workerNodeKey
]?.usage
!= null) {
867 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
868 ++workerUsage
.tasks
.executing
869 this.updateWaitTimeWorkerUsage(workerUsage
, task
)
872 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
873 this.workerNodes
[workerNodeKey
].getTaskFunctionWorkerUsage(
877 const taskFunctionWorkerUsage
= this.workerNodes
[
879 ].getTaskFunctionWorkerUsage(task
.name
as string) as WorkerUsage
880 ++taskFunctionWorkerUsage
.tasks
.executing
881 this.updateWaitTimeWorkerUsage(taskFunctionWorkerUsage
, task
)
886 * Hook executed after the worker task execution.
889 * @param workerNodeKey - The worker node key.
890 * @param message - The received message.
892 protected afterTaskExecutionHook (
893 workerNodeKey
: number,
894 message
: MessageValue
<Response
>
896 if (this.workerNodes
[workerNodeKey
]?.usage
!= null) {
897 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
898 this.updateTaskStatisticsWorkerUsage(workerUsage
, message
)
899 this.updateRunTimeWorkerUsage(workerUsage
, message
)
900 this.updateEluWorkerUsage(workerUsage
, message
)
903 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
904 this.workerNodes
[workerNodeKey
].getTaskFunctionWorkerUsage(
905 message
.taskPerformance
?.name
as string
908 const taskFunctionWorkerUsage
= this.workerNodes
[
910 ].getTaskFunctionWorkerUsage(
911 message
.taskPerformance
?.name
as string
913 this.updateTaskStatisticsWorkerUsage(taskFunctionWorkerUsage
, message
)
914 this.updateRunTimeWorkerUsage(taskFunctionWorkerUsage
, message
)
915 this.updateEluWorkerUsage(taskFunctionWorkerUsage
, message
)
920 * Whether the worker node shall update its task function worker usage or not.
922 * @param workerNodeKey - The worker node key.
923 * @returns `true` if the worker node shall update its task function worker usage, `false` otherwise.
925 private shallUpdateTaskFunctionWorkerUsage (workerNodeKey
: number): boolean {
926 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
928 workerInfo
!= null &&
929 Array.isArray(workerInfo
.taskFunctions
) &&
930 workerInfo
.taskFunctions
.length
> 2
934 private updateTaskStatisticsWorkerUsage (
935 workerUsage
: WorkerUsage
,
936 message
: MessageValue
<Response
>
938 const workerTaskStatistics
= workerUsage
.tasks
940 workerTaskStatistics
.executing
!= null &&
941 workerTaskStatistics
.executing
> 0
943 --workerTaskStatistics
.executing
945 if (message
.taskError
== null) {
946 ++workerTaskStatistics
.executed
948 ++workerTaskStatistics
.failed
952 private updateRunTimeWorkerUsage (
953 workerUsage
: WorkerUsage
,
954 message
: MessageValue
<Response
>
956 if (message
.taskError
!= null) {
959 updateMeasurementStatistics(
961 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
,
962 message
.taskPerformance
?.runTime
?? 0
966 private updateWaitTimeWorkerUsage (
967 workerUsage
: WorkerUsage
,
970 const timestamp
= performance
.now()
971 const taskWaitTime
= timestamp
- (task
.timestamp
?? timestamp
)
972 updateMeasurementStatistics(
973 workerUsage
.waitTime
,
974 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().waitTime
,
979 private updateEluWorkerUsage (
980 workerUsage
: WorkerUsage
,
981 message
: MessageValue
<Response
>
983 if (message
.taskError
!= null) {
986 const eluTaskStatisticsRequirements
: MeasurementStatisticsRequirements
=
987 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
988 updateMeasurementStatistics(
989 workerUsage
.elu
.active
,
990 eluTaskStatisticsRequirements
,
991 message
.taskPerformance
?.elu
?.active
?? 0
993 updateMeasurementStatistics(
994 workerUsage
.elu
.idle
,
995 eluTaskStatisticsRequirements
,
996 message
.taskPerformance
?.elu
?.idle
?? 0
998 if (eluTaskStatisticsRequirements
.aggregate
) {
999 if (message
.taskPerformance
?.elu
!= null) {
1000 if (workerUsage
.elu
.utilization
!= null) {
1001 workerUsage
.elu
.utilization
=
1002 (workerUsage
.elu
.utilization
+
1003 message
.taskPerformance
.elu
.utilization
) /
1006 workerUsage
.elu
.utilization
= message
.taskPerformance
.elu
.utilization
1013 * Chooses a worker node for the next task.
1015 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
1017 * @returns The chosen worker node key
1019 private chooseWorkerNode (): number {
1020 if (this.shallCreateDynamicWorker()) {
1021 const workerNodeKey
= this.createAndSetupDynamicWorkerNode()
1023 this.workerChoiceStrategyContext
.getStrategyPolicy().dynamicWorkerUsage
1025 return workerNodeKey
1028 return this.workerChoiceStrategyContext
.execute()
1032 * Conditions for dynamic worker creation.
1034 * @returns Whether to create a dynamic worker or not.
1036 private shallCreateDynamicWorker (): boolean {
1037 return this.type === PoolTypes
.dynamic
&& !this.full
&& this.internalBusy()
1041 * Sends a message to worker given its worker node key.
1043 * @param workerNodeKey - The worker node key.
1044 * @param message - The message.
1045 * @param transferList - The optional array of transferable objects.
1047 protected abstract sendToWorker (
1048 workerNodeKey
: number,
1049 message
: MessageValue
<Data
>,
1050 transferList
?: TransferListItem
[]
1054 * Creates a new worker.
1056 * @returns Newly created worker.
1058 protected abstract createWorker (): Worker
1061 * Creates a new, completely set up worker node.
1063 * @returns New, completely set up worker node key.
1065 protected createAndSetupWorkerNode (): number {
1066 const worker
= this.createWorker()
1068 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
1069 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
1070 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
1071 worker
.on('error', (error
) => {
1072 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
1073 const workerInfo
= this.getWorkerInfo(workerNodeKey
) as WorkerInfo
1074 workerInfo
.ready
= false
1075 this.workerNodes
[workerNodeKey
].closeChannel()
1076 this.emitter
?.emit(PoolEvents
.error
, error
)
1078 this.opts
.restartWorkerOnError
=== true &&
1082 if (workerInfo
.dynamic
) {
1083 this.createAndSetupDynamicWorkerNode()
1085 this.createAndSetupWorkerNode()
1088 if (this.opts
.enableTasksQueue
=== true) {
1089 this.redistributeQueuedTasks(workerNodeKey
)
1092 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
1093 worker
.once('exit', () => {
1094 this.removeWorkerNode(worker
)
1097 const workerNodeKey
= this.addWorkerNode(worker
)
1099 this.afterWorkerNodeSetup(workerNodeKey
)
1101 return workerNodeKey
1105 * Creates a new, completely set up dynamic worker node.
1107 * @returns New, completely set up dynamic worker node key.
1109 protected createAndSetupDynamicWorkerNode (): number {
1110 const workerNodeKey
= this.createAndSetupWorkerNode()
1111 this.registerWorkerMessageListener(workerNodeKey
, (message
) => {
1112 const localWorkerNodeKey
= this.getWorkerNodeKeyByWorkerId(
1115 const workerUsage
= this.workerNodes
[localWorkerNodeKey
].usage
1116 // Kill message received from worker
1118 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
1119 (isKillBehavior(KillBehaviors
.SOFT
, message
.kill
) &&
1120 ((this.opts
.enableTasksQueue
=== false &&
1121 workerUsage
.tasks
.executing
=== 0) ||
1122 (this.opts
.enableTasksQueue
=== true &&
1123 workerUsage
.tasks
.executing
=== 0 &&
1124 this.tasksQueueSize(localWorkerNodeKey
) === 0)))
1126 this.destroyWorkerNode(localWorkerNodeKey
).catch((error
) => {
1127 this.emitter
?.emit(PoolEvents
.error
, error
)
1131 const workerInfo
= this.getWorkerInfo(workerNodeKey
) as WorkerInfo
1132 this.sendToWorker(workerNodeKey
, {
1134 workerId
: workerInfo
.id
as number
1136 workerInfo
.dynamic
= true
1138 this.workerChoiceStrategyContext
.getStrategyPolicy().dynamicWorkerReady
||
1139 this.workerChoiceStrategyContext
.getStrategyPolicy().dynamicWorkerUsage
1141 workerInfo
.ready
= true
1143 this.checkAndEmitDynamicWorkerCreationEvents()
1144 return workerNodeKey
1148 * Registers a listener callback on the worker given its worker node key.
1150 * @param workerNodeKey - The worker node key.
1151 * @param listener - The message listener callback.
1153 protected abstract registerWorkerMessageListener
<
1154 Message
extends Data
| Response
1156 workerNodeKey
: number,
1157 listener
: (message
: MessageValue
<Message
>) => void
1161 * Method hooked up after a worker node has been newly created.
1162 * Can be overridden.
1164 * @param workerNodeKey - The newly created worker node key.
1166 protected afterWorkerNodeSetup (workerNodeKey
: number): void {
1167 // Listen to worker messages.
1168 this.registerWorkerMessageListener(workerNodeKey
, this.workerListener())
1169 // Send the startup message to worker.
1170 this.sendStartupMessageToWorker(workerNodeKey
)
1171 // Send the statistics message to worker.
1172 this.sendStatisticsMessageToWorker(workerNodeKey
)
1173 if (this.opts
.enableTasksQueue
=== true) {
1174 this.workerNodes
[workerNodeKey
].onEmptyQueue
=
1175 this.taskStealingOnEmptyQueue
.bind(this)
1176 this.workerNodes
[workerNodeKey
].onBackPressure
=
1177 this.tasksStealingOnBackPressure
.bind(this)
1182 * Sends the startup message to worker given its worker node key.
1184 * @param workerNodeKey - The worker node key.
1186 protected abstract sendStartupMessageToWorker (workerNodeKey
: number): void
1189 * Sends the statistics message to worker given its worker node key.
1191 * @param workerNodeKey - The worker node key.
1193 private sendStatisticsMessageToWorker (workerNodeKey
: number): void {
1194 this.sendToWorker(workerNodeKey
, {
1197 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1199 elu
: this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1202 workerId
: (this.getWorkerInfo(workerNodeKey
) as WorkerInfo
).id
as number
1206 private redistributeQueuedTasks (workerNodeKey
: number): void {
1207 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1208 let destinationWorkerNodeKey
!: number
1209 let minQueuedTasks
= Infinity
1210 for (const [workerNodeId
, workerNode
] of this.workerNodes
.entries()) {
1211 if (workerNode
.info
.ready
&& workerNodeId
!== workerNodeKey
) {
1212 if (workerNode
.usage
.tasks
.queued
=== 0) {
1213 destinationWorkerNodeKey
= workerNodeId
1216 if (workerNode
.usage
.tasks
.queued
< minQueuedTasks
) {
1217 minQueuedTasks
= workerNode
.usage
.tasks
.queued
1218 destinationWorkerNodeKey
= workerNodeId
1222 if (destinationWorkerNodeKey
!= null) {
1223 const destinationWorkerNode
= this.workerNodes
[destinationWorkerNodeKey
]
1225 ...(this.dequeueTask(workerNodeKey
) as Task
<Data
>),
1226 workerId
: destinationWorkerNode
.info
.id
as number
1229 this.tasksQueueSize(destinationWorkerNodeKey
) === 0 &&
1230 destinationWorkerNode
.usage
.tasks
.executing
<
1231 (this.opts
.tasksQueueOptions
?.concurrency
as number)
1233 this.executeTask(destinationWorkerNodeKey
, task
)
1235 this.enqueueTask(destinationWorkerNodeKey
, task
)
1241 private taskStealingOnEmptyQueue (workerId
: number): void {
1242 const destinationWorkerNodeKey
= this.getWorkerNodeKeyByWorkerId(workerId
)
1243 const destinationWorkerNode
= this.workerNodes
[destinationWorkerNodeKey
]
1244 const workerNodes
= this.workerNodes
1247 (workerNodeA
, workerNodeB
) =>
1248 workerNodeB
.usage
.tasks
.queued
- workerNodeA
.usage
.tasks
.queued
1250 for (const sourceWorkerNode
of workerNodes
) {
1251 if (sourceWorkerNode
.usage
.tasks
.queued
=== 0) {
1255 sourceWorkerNode
.info
.ready
&&
1256 sourceWorkerNode
.info
.id
!== workerId
&&
1257 sourceWorkerNode
.usage
.tasks
.queued
> 0
1260 ...(sourceWorkerNode
.popTask() as Task
<Data
>),
1261 workerId
: destinationWorkerNode
.info
.id
as number
1264 this.tasksQueueSize(destinationWorkerNodeKey
) === 0 &&
1265 destinationWorkerNode
.usage
.tasks
.executing
<
1266 (this.opts
.tasksQueueOptions
?.concurrency
as number)
1268 this.executeTask(destinationWorkerNodeKey
, task
)
1270 this.enqueueTask(destinationWorkerNodeKey
, task
)
1272 ++destinationWorkerNode
.usage
.tasks
.stolen
1273 if (this.shallUpdateTaskFunctionWorkerUsage(destinationWorkerNodeKey
)) {
1274 const taskFunctionWorkerUsage
=
1275 destinationWorkerNode
.getTaskFunctionWorkerUsage(
1278 ++taskFunctionWorkerUsage
.tasks
.stolen
1285 private tasksStealingOnBackPressure (workerId
: number): void {
1286 const sourceWorkerNode
=
1287 this.workerNodes
[this.getWorkerNodeKeyByWorkerId(workerId
)]
1288 const workerNodes
= this.workerNodes
1291 (workerNodeA
, workerNodeB
) =>
1292 workerNodeA
.usage
.tasks
.queued
- workerNodeB
.usage
.tasks
.queued
1294 for (const [workerNodeKey
, workerNode
] of workerNodes
.entries()) {
1296 sourceWorkerNode
.usage
.tasks
.queued
> 0 &&
1297 workerNode
.info
.ready
&&
1298 workerNode
.info
.id
!== workerId
&&
1299 workerNode
.usage
.tasks
.queued
<
1300 (this.opts
.tasksQueueOptions
?.size
as number) - 1
1303 ...(sourceWorkerNode
.popTask() as Task
<Data
>),
1304 workerId
: workerNode
.info
.id
as number
1307 this.tasksQueueSize(workerNodeKey
) === 0 &&
1308 workerNode
.usage
.tasks
.executing
<
1309 (this.opts
.tasksQueueOptions
?.concurrency
as number)
1311 this.executeTask(workerNodeKey
, task
)
1313 this.enqueueTask(workerNodeKey
, task
)
1315 ++workerNode
.usage
.tasks
.stolen
1316 if (this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
)) {
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
)