1 import { randomUUID
} from
'node:crypto'
2 import { performance
} from
'node:perf_hooks'
3 import { existsSync
} from
'node:fs'
4 import { type TransferListItem
} from
'node:worker_threads'
7 PromiseResponseWrapper
,
9 } from
'../utility-types'
12 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
,
21 updateMeasurementStatistics
23 import { KillBehaviors
} from
'../worker/worker-options'
24 import type { TaskFunction
} from
'../worker/task-functions'
33 type TasksQueueOptions
43 type MeasurementStatisticsRequirements
,
45 WorkerChoiceStrategies
,
46 type WorkerChoiceStrategy
,
47 type WorkerChoiceStrategyOptions
48 } from
'./selection-strategies/selection-strategies-types'
49 import { WorkerChoiceStrategyContext
} from
'./selection-strategies/worker-choice-strategy-context'
50 import { version
} from
'./version'
51 import { WorkerNode
} from
'./worker-node'
54 * Base class that implements some shared logic for all poolifier pools.
56 * @typeParam Worker - Type of worker which manages this pool.
57 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
58 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
60 export abstract class AbstractPool
<
61 Worker
extends IWorker
,
64 > implements IPool
<Worker
, Data
, Response
> {
66 public readonly workerNodes
: Array<IWorkerNode
<Worker
, Data
>> = []
69 public readonly emitter
?: PoolEmitter
72 * The task execution response promise map.
74 * - `key`: The message id of each submitted task.
75 * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks.
77 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
79 protected promiseResponseMap
: Map
<string, PromiseResponseWrapper
<Response
>> =
80 new Map
<string, PromiseResponseWrapper
<Response
>>()
83 * Worker choice strategy context referencing a worker choice algorithm implementation.
85 protected workerChoiceStrategyContext
: WorkerChoiceStrategyContext
<
92 * Dynamic pool maximum size property placeholder.
94 protected readonly max
?: number
97 * Whether the pool is starting or not.
99 private readonly starting
: boolean
101 * Whether the pool is started or not.
103 private started
: boolean
105 * The start timestamp of the pool.
107 private readonly startTimestamp
110 * Constructs a new poolifier pool.
112 * @param numberOfWorkers - Number of workers that this pool should manage.
113 * @param filePath - Path to the worker file.
114 * @param opts - Options for the pool.
117 protected readonly numberOfWorkers
: number,
118 protected readonly filePath
: string,
119 protected readonly opts
: PoolOptions
<Worker
>
121 if (!this.isMain()) {
123 'Cannot start a pool from a worker with the same type as the pool'
126 this.checkNumberOfWorkers(this.numberOfWorkers
)
127 this.checkFilePath(this.filePath
)
128 this.checkPoolOptions(this.opts
)
130 this.chooseWorkerNode
= this.chooseWorkerNode
.bind(this)
131 this.executeTask
= this.executeTask
.bind(this)
132 this.enqueueTask
= this.enqueueTask
.bind(this)
134 if (this.opts
.enableEvents
=== true) {
135 this.emitter
= new PoolEmitter()
137 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext
<
143 this.opts
.workerChoiceStrategy
,
144 this.opts
.workerChoiceStrategyOptions
151 this.starting
= false
154 this.startTimestamp
= performance
.now()
157 private checkFilePath (filePath
: string): void {
160 typeof filePath
!== 'string' ||
161 (typeof filePath
=== 'string' && filePath
.trim().length
=== 0)
163 throw new Error('Please specify a file with a worker implementation')
165 if (!existsSync(filePath
)) {
166 throw new Error(`Cannot find the worker file '${filePath}'`)
170 private checkNumberOfWorkers (numberOfWorkers
: number): void {
171 if (numberOfWorkers
== null) {
173 'Cannot instantiate a pool without specifying the number of workers'
175 } else if (!Number.isSafeInteger(numberOfWorkers
)) {
177 'Cannot instantiate a pool with a non safe integer number of workers'
179 } else if (numberOfWorkers
< 0) {
180 throw new RangeError(
181 'Cannot instantiate a pool with a negative number of workers'
183 } else if (this.type === PoolTypes
.fixed
&& numberOfWorkers
=== 0) {
184 throw new RangeError('Cannot instantiate a fixed pool with zero worker')
188 protected checkDynamicPoolSize (min
: number, max
: number): void {
189 if (this.type === PoolTypes
.dynamic
) {
192 'Cannot instantiate a dynamic pool without specifying the maximum pool size'
194 } else if (!Number.isSafeInteger(max
)) {
196 'Cannot instantiate a dynamic pool with a non safe integer maximum pool size'
198 } else if (min
> max
) {
199 throw new RangeError(
200 'Cannot instantiate a dynamic pool with a maximum pool size inferior to the minimum pool size'
202 } else if (max
=== 0) {
203 throw new RangeError(
204 'Cannot instantiate a dynamic pool with a maximum pool size equal to zero'
206 } else if (min
=== max
) {
207 throw new RangeError(
208 'Cannot instantiate a dynamic pool with a minimum pool size equal to the maximum pool size. Use a fixed pool instead'
214 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
215 if (isPlainObject(opts
)) {
216 this.opts
.workerChoiceStrategy
=
217 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
218 this.checkValidWorkerChoiceStrategy(this.opts
.workerChoiceStrategy
)
219 this.opts
.workerChoiceStrategyOptions
= {
220 ...DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
,
221 ...opts
.workerChoiceStrategyOptions
223 this.checkValidWorkerChoiceStrategyOptions(
224 this.opts
.workerChoiceStrategyOptions
226 this.opts
.restartWorkerOnError
= opts
.restartWorkerOnError
?? true
227 this.opts
.enableEvents
= opts
.enableEvents
?? true
228 this.opts
.enableTasksQueue
= opts
.enableTasksQueue
?? false
229 if (this.opts
.enableTasksQueue
) {
230 this.checkValidTasksQueueOptions(
231 opts
.tasksQueueOptions
as TasksQueueOptions
233 this.opts
.tasksQueueOptions
= this.buildTasksQueueOptions(
234 opts
.tasksQueueOptions
as TasksQueueOptions
238 throw new TypeError('Invalid pool options: must be a plain object')
242 private checkValidWorkerChoiceStrategy (
243 workerChoiceStrategy
: WorkerChoiceStrategy
245 if (!Object.values(WorkerChoiceStrategies
).includes(workerChoiceStrategy
)) {
247 `Invalid worker choice strategy '${workerChoiceStrategy}'`
252 private checkValidWorkerChoiceStrategyOptions (
253 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
255 if (!isPlainObject(workerChoiceStrategyOptions
)) {
257 'Invalid worker choice strategy options: must be a plain object'
261 workerChoiceStrategyOptions
.retries
!= null &&
262 !Number.isSafeInteger(workerChoiceStrategyOptions
.retries
)
265 'Invalid worker choice strategy options: retries must be an integer'
269 workerChoiceStrategyOptions
.retries
!= null &&
270 workerChoiceStrategyOptions
.retries
< 0
272 throw new RangeError(
273 `Invalid worker choice strategy options: retries '${workerChoiceStrategyOptions.retries}' must be greater or equal than zero`
277 workerChoiceStrategyOptions
.weights
!= null &&
278 Object.keys(workerChoiceStrategyOptions
.weights
).length
!== this.maxSize
281 'Invalid worker choice strategy options: must have a weight for each worker node'
285 workerChoiceStrategyOptions
.measurement
!= null &&
286 !Object.values(Measurements
).includes(
287 workerChoiceStrategyOptions
.measurement
291 `Invalid worker choice strategy options: invalid measurement '${workerChoiceStrategyOptions.measurement}'`
296 private checkValidTasksQueueOptions (
297 tasksQueueOptions
: TasksQueueOptions
299 if (tasksQueueOptions
!= null && !isPlainObject(tasksQueueOptions
)) {
300 throw new TypeError('Invalid tasks queue options: must be a plain object')
303 tasksQueueOptions
?.concurrency
!= null &&
304 !Number.isSafeInteger(tasksQueueOptions
?.concurrency
)
307 'Invalid worker node tasks concurrency: must be an integer'
311 tasksQueueOptions
?.concurrency
!= null &&
312 tasksQueueOptions
?.concurrency
<= 0
314 throw new RangeError(
315 `Invalid worker node tasks concurrency: ${tasksQueueOptions?.concurrency} is a negative integer or zero`
318 if (tasksQueueOptions
?.queueMaxSize
!= null) {
320 'Invalid tasks queue options: queueMaxSize is deprecated, please use size instead'
324 tasksQueueOptions
?.size
!= null &&
325 !Number.isSafeInteger(tasksQueueOptions
?.size
)
328 'Invalid worker node tasks queue size: must be an integer'
331 if (tasksQueueOptions
?.size
!= null && tasksQueueOptions
?.size
<= 0) {
332 throw new RangeError(
333 `Invalid worker node tasks queue size: ${tasksQueueOptions?.size} is a negative integer or zero`
338 private startPool (): void {
340 this.workerNodes
.reduce(
341 (accumulator
, workerNode
) =>
342 !workerNode
.info
.dynamic
? accumulator
+ 1 : accumulator
,
344 ) < this.numberOfWorkers
346 this.createAndSetupWorkerNode()
351 public get
info (): PoolInfo
{
357 strategy
: this.opts
.workerChoiceStrategy
as WorkerChoiceStrategy
,
358 minSize
: this.minSize
,
359 maxSize
: this.maxSize
,
360 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
361 .runTime
.aggregate
&&
362 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
363 .waitTime
.aggregate
&& { utilization
: round(this.utilization
) }),
364 workerNodes
: this.workerNodes
.length
,
365 idleWorkerNodes
: this.workerNodes
.reduce(
366 (accumulator
, workerNode
) =>
367 workerNode
.usage
.tasks
.executing
=== 0
372 busyWorkerNodes
: this.workerNodes
.reduce(
373 (accumulator
, workerNode
) =>
374 workerNode
.usage
.tasks
.executing
> 0 ? accumulator
+ 1 : accumulator
,
377 executedTasks
: this.workerNodes
.reduce(
378 (accumulator
, workerNode
) =>
379 accumulator
+ workerNode
.usage
.tasks
.executed
,
382 executingTasks
: this.workerNodes
.reduce(
383 (accumulator
, workerNode
) =>
384 accumulator
+ workerNode
.usage
.tasks
.executing
,
387 ...(this.opts
.enableTasksQueue
=== true && {
388 queuedTasks
: this.workerNodes
.reduce(
389 (accumulator
, workerNode
) =>
390 accumulator
+ workerNode
.usage
.tasks
.queued
,
394 ...(this.opts
.enableTasksQueue
=== true && {
395 maxQueuedTasks
: this.workerNodes
.reduce(
396 (accumulator
, workerNode
) =>
397 accumulator
+ (workerNode
.usage
.tasks
?.maxQueued
?? 0),
401 ...(this.opts
.enableTasksQueue
=== true && {
402 backPressure
: this.hasBackPressure()
404 ...(this.opts
.enableTasksQueue
=== true && {
405 stolenTasks
: this.workerNodes
.reduce(
406 (accumulator
, workerNode
) =>
407 accumulator
+ workerNode
.usage
.tasks
.stolen
,
411 failedTasks
: this.workerNodes
.reduce(
412 (accumulator
, workerNode
) =>
413 accumulator
+ workerNode
.usage
.tasks
.failed
,
416 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
417 .runTime
.aggregate
&& {
421 ...this.workerNodes
.map(
422 workerNode
=> workerNode
.usage
.runTime
?.minimum
?? Infinity
428 ...this.workerNodes
.map(
429 workerNode
=> workerNode
.usage
.runTime
?.maximum
?? -Infinity
433 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
434 .runTime
.average
&& {
437 this.workerNodes
.reduce
<number[]>(
438 (accumulator
, workerNode
) =>
439 accumulator
.concat(workerNode
.usage
.runTime
.history
),
445 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
449 this.workerNodes
.reduce
<number[]>(
450 (accumulator
, workerNode
) =>
451 accumulator
.concat(workerNode
.usage
.runTime
.history
),
459 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
460 .waitTime
.aggregate
&& {
464 ...this.workerNodes
.map(
465 workerNode
=> workerNode
.usage
.waitTime
?.minimum
?? Infinity
471 ...this.workerNodes
.map(
472 workerNode
=> workerNode
.usage
.waitTime
?.maximum
?? -Infinity
476 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
477 .waitTime
.average
&& {
480 this.workerNodes
.reduce
<number[]>(
481 (accumulator
, workerNode
) =>
482 accumulator
.concat(workerNode
.usage
.waitTime
.history
),
488 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
489 .waitTime
.median
&& {
492 this.workerNodes
.reduce
<number[]>(
493 (accumulator
, workerNode
) =>
494 accumulator
.concat(workerNode
.usage
.waitTime
.history
),
506 * The pool readiness boolean status.
508 private get
ready (): boolean {
510 this.workerNodes
.reduce(
511 (accumulator
, workerNode
) =>
512 !workerNode
.info
.dynamic
&& workerNode
.info
.ready
521 * The approximate pool utilization.
523 * @returns The pool utilization.
525 private get
utilization (): number {
526 const poolTimeCapacity
=
527 (performance
.now() - this.startTimestamp
) * this.maxSize
528 const totalTasksRunTime
= this.workerNodes
.reduce(
529 (accumulator
, workerNode
) =>
530 accumulator
+ (workerNode
.usage
.runTime
?.aggregate
?? 0),
533 const totalTasksWaitTime
= this.workerNodes
.reduce(
534 (accumulator
, workerNode
) =>
535 accumulator
+ (workerNode
.usage
.waitTime
?.aggregate
?? 0),
538 return (totalTasksRunTime
+ totalTasksWaitTime
) / poolTimeCapacity
544 * If it is `'dynamic'`, it provides the `max` property.
546 protected abstract get
type (): PoolType
551 protected abstract get
worker (): WorkerType
554 * The pool minimum size.
556 protected get
minSize (): number {
557 return this.numberOfWorkers
561 * The pool maximum size.
563 protected get
maxSize (): number {
564 return this.max
?? this.numberOfWorkers
568 * Checks if the worker id sent in the received message from a worker is valid.
570 * @param message - The received message.
571 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the worker id is invalid.
573 private checkMessageWorkerId (message
: MessageValue
<Response
>): void {
574 if (message
.workerId
== null) {
575 throw new Error('Worker message received without worker id')
577 message
.workerId
!= null &&
578 this.getWorkerNodeKeyByWorkerId(message
.workerId
) === -1
581 `Worker message received from unknown worker '${message.workerId}'`
587 * Gets the given worker its worker node key.
589 * @param worker - The worker.
590 * @returns The worker node key if found in the pool worker nodes, `-1` otherwise.
592 private getWorkerNodeKeyByWorker (worker
: Worker
): number {
593 return this.workerNodes
.findIndex(
594 workerNode
=> workerNode
.worker
=== worker
599 * Gets the worker node key given its worker id.
601 * @param workerId - The worker id.
602 * @returns The worker node key if the worker id is found in the pool worker nodes, `-1` otherwise.
604 private getWorkerNodeKeyByWorkerId (workerId
: number): number {
605 return this.workerNodes
.findIndex(
606 workerNode
=> workerNode
.info
.id
=== workerId
611 public setWorkerChoiceStrategy (
612 workerChoiceStrategy
: WorkerChoiceStrategy
,
613 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
615 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
616 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
617 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
618 this.opts
.workerChoiceStrategy
620 if (workerChoiceStrategyOptions
!= null) {
621 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
623 for (const [workerNodeKey
, workerNode
] of this.workerNodes
.entries()) {
624 workerNode
.resetUsage()
625 this.sendStatisticsMessageToWorker(workerNodeKey
)
630 public setWorkerChoiceStrategyOptions (
631 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
633 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
634 this.opts
.workerChoiceStrategyOptions
= {
635 ...DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
,
636 ...workerChoiceStrategyOptions
638 this.workerChoiceStrategyContext
.setOptions(
639 this.opts
.workerChoiceStrategyOptions
644 public enableTasksQueue (
646 tasksQueueOptions
?: TasksQueueOptions
648 if (this.opts
.enableTasksQueue
=== true && !enable
) {
649 this.flushTasksQueues()
651 this.opts
.enableTasksQueue
= enable
652 this.setTasksQueueOptions(tasksQueueOptions
as TasksQueueOptions
)
656 public setTasksQueueOptions (tasksQueueOptions
: TasksQueueOptions
): void {
657 if (this.opts
.enableTasksQueue
=== true) {
658 this.checkValidTasksQueueOptions(tasksQueueOptions
)
659 this.opts
.tasksQueueOptions
=
660 this.buildTasksQueueOptions(tasksQueueOptions
)
661 this.setTasksQueueSize(this.opts
.tasksQueueOptions
.size
as number)
662 } else if (this.opts
.tasksQueueOptions
!= null) {
663 delete this.opts
.tasksQueueOptions
667 private setTasksQueueSize (size
: number): void {
668 for (const workerNode
of this.workerNodes
) {
669 workerNode
.tasksQueueBackPressureSize
= size
673 private buildTasksQueueOptions (
674 tasksQueueOptions
: TasksQueueOptions
675 ): TasksQueueOptions
{
678 size
: Math.pow(this.maxSize
, 2),
686 * Whether the pool is full or not.
688 * The pool filling boolean status.
690 protected get
full (): boolean {
691 return this.workerNodes
.length
>= this.maxSize
695 * Whether the pool is busy or not.
697 * The pool busyness boolean status.
699 protected abstract get
busy (): boolean
702 * Whether worker nodes are executing concurrently their tasks quota or not.
704 * @returns Worker nodes busyness boolean status.
706 protected internalBusy (): boolean {
707 if (this.opts
.enableTasksQueue
=== true) {
709 this.workerNodes
.findIndex(
711 workerNode
.info
.ready
&&
712 workerNode
.usage
.tasks
.executing
<
713 (this.opts
.tasksQueueOptions
?.concurrency
as number)
718 this.workerNodes
.findIndex(
720 workerNode
.info
.ready
&& workerNode
.usage
.tasks
.executing
=== 0
726 private sendToWorkers (message
: Omit
<MessageValue
<Data
>, 'workerId'>): number {
727 let messagesCount
= 0
728 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
729 this.sendToWorker(workerNodeKey
, {
731 workerId
: this.getWorkerInfo(workerNodeKey
).id
as number
739 public hasTaskFunction (name
: string): boolean {
741 taskFunctionOperation
: 'has',
742 taskFunctionName
: name
748 public addTaskFunction (name
: string, taskFunction
: TaskFunction
): boolean {
750 taskFunctionOperation
: 'add',
751 taskFunctionName
: name
,
752 taskFunction
: taskFunction
.toString()
758 public removeTaskFunction (name
: string): boolean {
760 taskFunctionOperation
: 'remove',
761 taskFunctionName
: name
767 public listTaskFunctionNames (): string[] {
768 for (const workerNode
of this.workerNodes
) {
770 Array.isArray(workerNode
.info
.taskFunctionNames
) &&
771 workerNode
.info
.taskFunctionNames
.length
> 0
773 return workerNode
.info
.taskFunctionNames
780 public setDefaultTaskFunction (name
: string): boolean {
782 taskFunctionOperation
: 'default',
783 taskFunctionName
: name
788 private shallExecuteTask (workerNodeKey
: number): boolean {
790 this.tasksQueueSize(workerNodeKey
) === 0 &&
791 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
<
792 (this.opts
.tasksQueueOptions
?.concurrency
as number)
797 public async execute (
800 transferList
?: TransferListItem
[]
801 ): Promise
<Response
> {
802 return await new Promise
<Response
>((resolve
, reject
) => {
804 reject(new Error('Cannot execute a task on destroyed pool'))
807 if (name
!= null && typeof name
!== 'string') {
808 reject(new TypeError('name argument must be a string'))
813 typeof name
=== 'string' &&
814 name
.trim().length
=== 0
816 reject(new TypeError('name argument must not be an empty string'))
819 if (transferList
!= null && !Array.isArray(transferList
)) {
820 reject(new TypeError('transferList argument must be an array'))
823 const timestamp
= performance
.now()
824 const workerNodeKey
= this.chooseWorkerNode()
825 const task
: Task
<Data
> = {
826 name
: name
?? DEFAULT_TASK_NAME
,
827 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
828 data
: data
?? ({} as Data
),
831 workerId
: this.getWorkerInfo(workerNodeKey
).id
as number,
834 this.promiseResponseMap
.set(task
.taskId
as string, {
840 this.opts
.enableTasksQueue
=== false ||
841 (this.opts
.enableTasksQueue
=== true &&
842 this.shallExecuteTask(workerNodeKey
))
844 this.executeTask(workerNodeKey
, task
)
846 this.enqueueTask(workerNodeKey
, task
)
852 public async destroy (): Promise
<void> {
854 this.workerNodes
.map(async (_
, workerNodeKey
) => {
855 await this.destroyWorkerNode(workerNodeKey
)
858 this.emitter
?.emit(PoolEvents
.destroy
, this.info
)
862 protected async sendKillMessageToWorker (
863 workerNodeKey
: number,
866 await new Promise
<void>((resolve
, reject
) => {
867 this.registerWorkerMessageListener(workerNodeKey
, message
=> {
868 if (message
.kill
=== 'success') {
870 } else if (message
.kill
=== 'failure') {
871 reject(new Error(`Worker ${workerId} kill message handling failed`))
874 this.sendToWorker(workerNodeKey
, { kill
: true, workerId
})
879 * Terminates the worker node given its worker node key.
881 * @param workerNodeKey - The worker node key.
883 protected abstract destroyWorkerNode (workerNodeKey
: number): Promise
<void>
886 * Setup hook to execute code before worker nodes are created in the abstract constructor.
891 protected setupHook (): void {
892 /* Intentionally empty */
896 * Should return whether the worker is the main worker or not.
898 protected abstract isMain (): boolean
901 * Hook executed before the worker task execution.
904 * @param workerNodeKey - The worker node key.
905 * @param task - The task to execute.
907 protected beforeTaskExecutionHook (
908 workerNodeKey
: number,
911 if (this.workerNodes
[workerNodeKey
]?.usage
!= null) {
912 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
913 ++workerUsage
.tasks
.executing
914 this.updateWaitTimeWorkerUsage(workerUsage
, task
)
917 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
918 this.workerNodes
[workerNodeKey
].getTaskFunctionWorkerUsage(
922 const taskFunctionWorkerUsage
= this.workerNodes
[
924 ].getTaskFunctionWorkerUsage(task
.name
as string) as WorkerUsage
925 ++taskFunctionWorkerUsage
.tasks
.executing
926 this.updateWaitTimeWorkerUsage(taskFunctionWorkerUsage
, task
)
931 * Hook executed after the worker task execution.
934 * @param workerNodeKey - The worker node key.
935 * @param message - The received message.
937 protected afterTaskExecutionHook (
938 workerNodeKey
: number,
939 message
: MessageValue
<Response
>
941 if (this.workerNodes
[workerNodeKey
]?.usage
!= null) {
942 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
943 this.updateTaskStatisticsWorkerUsage(workerUsage
, message
)
944 this.updateRunTimeWorkerUsage(workerUsage
, message
)
945 this.updateEluWorkerUsage(workerUsage
, message
)
948 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
949 this.workerNodes
[workerNodeKey
].getTaskFunctionWorkerUsage(
950 message
.taskPerformance
?.name
as string
953 const taskFunctionWorkerUsage
= this.workerNodes
[
955 ].getTaskFunctionWorkerUsage(
956 message
.taskPerformance
?.name
as string
958 this.updateTaskStatisticsWorkerUsage(taskFunctionWorkerUsage
, message
)
959 this.updateRunTimeWorkerUsage(taskFunctionWorkerUsage
, message
)
960 this.updateEluWorkerUsage(taskFunctionWorkerUsage
, message
)
965 * Whether the worker node shall update its task function worker usage or not.
967 * @param workerNodeKey - The worker node key.
968 * @returns `true` if the worker node shall update its task function worker usage, `false` otherwise.
970 private shallUpdateTaskFunctionWorkerUsage (workerNodeKey
: number): boolean {
971 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
973 workerInfo
!= null &&
974 Array.isArray(workerInfo
.taskFunctionNames
) &&
975 workerInfo
.taskFunctionNames
.length
> 2
979 private updateTaskStatisticsWorkerUsage (
980 workerUsage
: WorkerUsage
,
981 message
: MessageValue
<Response
>
983 const workerTaskStatistics
= workerUsage
.tasks
985 workerTaskStatistics
.executing
!= null &&
986 workerTaskStatistics
.executing
> 0
988 --workerTaskStatistics
.executing
990 if (message
.workerError
== null) {
991 ++workerTaskStatistics
.executed
993 ++workerTaskStatistics
.failed
997 private updateRunTimeWorkerUsage (
998 workerUsage
: WorkerUsage
,
999 message
: MessageValue
<Response
>
1001 if (message
.workerError
!= null) {
1004 updateMeasurementStatistics(
1005 workerUsage
.runTime
,
1006 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
,
1007 message
.taskPerformance
?.runTime
?? 0
1011 private updateWaitTimeWorkerUsage (
1012 workerUsage
: WorkerUsage
,
1015 const timestamp
= performance
.now()
1016 const taskWaitTime
= timestamp
- (task
.timestamp
?? timestamp
)
1017 updateMeasurementStatistics(
1018 workerUsage
.waitTime
,
1019 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().waitTime
,
1024 private updateEluWorkerUsage (
1025 workerUsage
: WorkerUsage
,
1026 message
: MessageValue
<Response
>
1028 if (message
.workerError
!= null) {
1031 const eluTaskStatisticsRequirements
: MeasurementStatisticsRequirements
=
1032 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
1033 updateMeasurementStatistics(
1034 workerUsage
.elu
.active
,
1035 eluTaskStatisticsRequirements
,
1036 message
.taskPerformance
?.elu
?.active
?? 0
1038 updateMeasurementStatistics(
1039 workerUsage
.elu
.idle
,
1040 eluTaskStatisticsRequirements
,
1041 message
.taskPerformance
?.elu
?.idle
?? 0
1043 if (eluTaskStatisticsRequirements
.aggregate
) {
1044 if (message
.taskPerformance
?.elu
!= null) {
1045 if (workerUsage
.elu
.utilization
!= null) {
1046 workerUsage
.elu
.utilization
=
1047 (workerUsage
.elu
.utilization
+
1048 message
.taskPerformance
.elu
.utilization
) /
1051 workerUsage
.elu
.utilization
= message
.taskPerformance
.elu
.utilization
1058 * Chooses a worker node for the next task.
1060 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
1062 * @returns The chosen worker node key
1064 private chooseWorkerNode (): number {
1065 if (this.shallCreateDynamicWorker()) {
1066 const workerNodeKey
= this.createAndSetupDynamicWorkerNode()
1068 this.workerChoiceStrategyContext
.getStrategyPolicy().dynamicWorkerUsage
1070 return workerNodeKey
1073 return this.workerChoiceStrategyContext
.execute()
1077 * Conditions for dynamic worker creation.
1079 * @returns Whether to create a dynamic worker or not.
1081 private shallCreateDynamicWorker (): boolean {
1082 return this.type === PoolTypes
.dynamic
&& !this.full
&& this.internalBusy()
1086 * Sends a message to worker given its worker node key.
1088 * @param workerNodeKey - The worker node key.
1089 * @param message - The message.
1090 * @param transferList - The optional array of transferable objects.
1092 protected abstract sendToWorker (
1093 workerNodeKey
: number,
1094 message
: MessageValue
<Data
>,
1095 transferList
?: TransferListItem
[]
1099 * Creates a new worker.
1101 * @returns Newly created worker.
1103 protected abstract createWorker (): Worker
1106 * Creates a new, completely set up worker node.
1108 * @returns New, completely set up worker node key.
1110 protected createAndSetupWorkerNode (): number {
1111 const worker
= this.createWorker()
1113 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
1114 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
1115 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
1116 worker
.on('error', error
=> {
1117 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
1118 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
1119 workerInfo
.ready
= false
1120 this.workerNodes
[workerNodeKey
].closeChannel()
1121 this.emitter
?.emit(PoolEvents
.error
, error
)
1123 this.opts
.restartWorkerOnError
=== true &&
1127 if (workerInfo
.dynamic
) {
1128 this.createAndSetupDynamicWorkerNode()
1130 this.createAndSetupWorkerNode()
1133 if (this.opts
.enableTasksQueue
=== true) {
1134 this.redistributeQueuedTasks(workerNodeKey
)
1137 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
1138 worker
.once('exit', () => {
1139 this.removeWorkerNode(worker
)
1142 const workerNodeKey
= this.addWorkerNode(worker
)
1144 this.afterWorkerNodeSetup(workerNodeKey
)
1146 return workerNodeKey
1150 * Creates a new, completely set up dynamic worker node.
1152 * @returns New, completely set up dynamic worker node key.
1154 protected createAndSetupDynamicWorkerNode (): number {
1155 const workerNodeKey
= this.createAndSetupWorkerNode()
1156 this.registerWorkerMessageListener(workerNodeKey
, message
=> {
1157 const localWorkerNodeKey
= this.getWorkerNodeKeyByWorkerId(
1160 const workerUsage
= this.workerNodes
[localWorkerNodeKey
].usage
1161 // Kill message received from worker
1163 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
1164 (isKillBehavior(KillBehaviors
.SOFT
, message
.kill
) &&
1165 ((this.opts
.enableTasksQueue
=== false &&
1166 workerUsage
.tasks
.executing
=== 0) ||
1167 (this.opts
.enableTasksQueue
=== true &&
1168 workerUsage
.tasks
.executing
=== 0 &&
1169 this.tasksQueueSize(localWorkerNodeKey
) === 0)))
1171 this.destroyWorkerNode(localWorkerNodeKey
).catch(error
=> {
1172 this.emitter
?.emit(PoolEvents
.error
, error
)
1176 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
1177 this.sendToWorker(workerNodeKey
, {
1179 workerId
: workerInfo
.id
as number
1181 workerInfo
.dynamic
= true
1183 this.workerChoiceStrategyContext
.getStrategyPolicy().dynamicWorkerReady
||
1184 this.workerChoiceStrategyContext
.getStrategyPolicy().dynamicWorkerUsage
1186 workerInfo
.ready
= true
1188 this.checkAndEmitDynamicWorkerCreationEvents()
1189 return workerNodeKey
1193 * Registers a listener callback on the worker given its worker node key.
1195 * @param workerNodeKey - The worker node key.
1196 * @param listener - The message listener callback.
1198 protected abstract registerWorkerMessageListener
<
1199 Message
extends Data
| Response
1201 workerNodeKey
: number,
1202 listener
: (message
: MessageValue
<Message
>) => void
1206 * Method hooked up after a worker node has been newly created.
1207 * Can be overridden.
1209 * @param workerNodeKey - The newly created worker node key.
1211 protected afterWorkerNodeSetup (workerNodeKey
: number): void {
1212 // Listen to worker messages.
1213 this.registerWorkerMessageListener(workerNodeKey
, this.workerListener())
1214 // Send the startup message to worker.
1215 this.sendStartupMessageToWorker(workerNodeKey
)
1216 // Send the statistics message to worker.
1217 this.sendStatisticsMessageToWorker(workerNodeKey
)
1218 if (this.opts
.enableTasksQueue
=== true) {
1219 this.workerNodes
[workerNodeKey
].onEmptyQueue
=
1220 this.taskStealingOnEmptyQueue
.bind(this)
1221 this.workerNodes
[workerNodeKey
].onBackPressure
=
1222 this.tasksStealingOnBackPressure
.bind(this)
1227 * Sends the startup message to worker given its worker node key.
1229 * @param workerNodeKey - The worker node key.
1231 protected abstract sendStartupMessageToWorker (workerNodeKey
: number): void
1234 * Sends the statistics message to worker given its worker node key.
1236 * @param workerNodeKey - The worker node key.
1238 private sendStatisticsMessageToWorker (workerNodeKey
: number): void {
1239 this.sendToWorker(workerNodeKey
, {
1242 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1244 elu
: this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1247 workerId
: this.getWorkerInfo(workerNodeKey
).id
as number
1251 private redistributeQueuedTasks (workerNodeKey
: number): void {
1252 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1253 const destinationWorkerNodeKey
= this.workerNodes
.reduce(
1254 (minWorkerNodeKey
, workerNode
, workerNodeKey
, workerNodes
) => {
1255 return workerNode
.info
.ready
&&
1256 workerNode
.usage
.tasks
.queued
<
1257 workerNodes
[minWorkerNodeKey
].usage
.tasks
.queued
1263 const destinationWorkerNode
= this.workerNodes
[destinationWorkerNodeKey
]
1265 ...(this.dequeueTask(workerNodeKey
) as Task
<Data
>),
1266 workerId
: destinationWorkerNode
.info
.id
as number
1268 if (this.shallExecuteTask(destinationWorkerNodeKey
)) {
1269 this.executeTask(destinationWorkerNodeKey
, task
)
1271 this.enqueueTask(destinationWorkerNodeKey
, task
)
1276 private updateTaskStolenStatisticsWorkerUsage (
1277 workerNodeKey
: number,
1280 const workerNode
= this.workerNodes
[workerNodeKey
]
1281 if (workerNode
?.usage
!= null) {
1282 ++workerNode
.usage
.tasks
.stolen
1285 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
1286 workerNode
.getTaskFunctionWorkerUsage(taskName
) != null
1288 const taskFunctionWorkerUsage
= workerNode
.getTaskFunctionWorkerUsage(
1291 ++taskFunctionWorkerUsage
.tasks
.stolen
1295 private taskStealingOnEmptyQueue (workerId
: number): void {
1296 const destinationWorkerNodeKey
= this.getWorkerNodeKeyByWorkerId(workerId
)
1297 const destinationWorkerNode
= this.workerNodes
[destinationWorkerNodeKey
]
1298 const workerNodes
= this.workerNodes
1301 (workerNodeA
, workerNodeB
) =>
1302 workerNodeB
.usage
.tasks
.queued
- workerNodeA
.usage
.tasks
.queued
1304 const sourceWorkerNode
= workerNodes
.find(
1306 workerNode
.info
.ready
&&
1307 workerNode
.info
.id
!== workerId
&&
1308 workerNode
.usage
.tasks
.queued
> 0
1310 if (sourceWorkerNode
!= null) {
1312 ...(sourceWorkerNode
.popTask() as Task
<Data
>),
1313 workerId
: destinationWorkerNode
.info
.id
as number
1315 if (this.shallExecuteTask(destinationWorkerNodeKey
)) {
1316 this.executeTask(destinationWorkerNodeKey
, task
)
1318 this.enqueueTask(destinationWorkerNodeKey
, task
)
1320 this.updateTaskStolenStatisticsWorkerUsage(
1321 destinationWorkerNodeKey
,
1327 private tasksStealingOnBackPressure (workerId
: number): void {
1328 const sizeOffset
= 1
1329 if ((this.opts
.tasksQueueOptions
?.size
as number) <= sizeOffset
) {
1332 const sourceWorkerNode
=
1333 this.workerNodes
[this.getWorkerNodeKeyByWorkerId(workerId
)]
1334 const workerNodes
= this.workerNodes
1337 (workerNodeA
, workerNodeB
) =>
1338 workerNodeA
.usage
.tasks
.queued
- workerNodeB
.usage
.tasks
.queued
1340 for (const [workerNodeKey
, workerNode
] of workerNodes
.entries()) {
1342 sourceWorkerNode
.usage
.tasks
.queued
> 0 &&
1343 workerNode
.info
.ready
&&
1344 workerNode
.info
.id
!== workerId
&&
1345 workerNode
.usage
.tasks
.queued
<
1346 (this.opts
.tasksQueueOptions
?.size
as number) - sizeOffset
1349 ...(sourceWorkerNode
.popTask() as Task
<Data
>),
1350 workerId
: workerNode
.info
.id
as number
1352 if (this.shallExecuteTask(workerNodeKey
)) {
1353 this.executeTask(workerNodeKey
, task
)
1355 this.enqueueTask(workerNodeKey
, task
)
1357 this.updateTaskStolenStatisticsWorkerUsage(
1366 * This method is the listener registered for each worker message.
1368 * @returns The listener function to execute when a message is received from a worker.
1370 protected workerListener (): (message
: MessageValue
<Response
>) => void {
1372 this.checkMessageWorkerId(message
)
1373 if (message
.ready
!= null && message
.taskFunctionNames
!= null) {
1374 // Worker ready response received from worker
1375 this.handleWorkerReadyResponse(message
)
1376 } else if (message
.taskId
!= null) {
1377 // Task execution response received from worker
1378 this.handleTaskExecutionResponse(message
)
1379 } else if (message
.taskFunctionNames
!= null) {
1380 // Task function names message received from worker
1382 this.getWorkerNodeKeyByWorkerId(message
.workerId
)
1383 ).taskFunctionNames
= message
.taskFunctionNames
1384 } else if (message
.taskFunctionOperation
!= null) {
1385 // Task function operation response received from worker
1390 private handleWorkerReadyResponse (message
: MessageValue
<Response
>): void {
1391 if (message
.ready
=== false) {
1392 throw new Error(`Worker ${message.workerId} failed to initialize`)
1394 const workerInfo
= this.getWorkerInfo(
1395 this.getWorkerNodeKeyByWorkerId(message
.workerId
)
1397 workerInfo
.ready
= message
.ready
as boolean
1398 workerInfo
.taskFunctionNames
= message
.taskFunctionNames
1399 if (this.emitter
!= null && this.ready
) {
1400 this.emitter
.emit(PoolEvents
.ready
, this.info
)
1404 private handleTaskExecutionResponse (message
: MessageValue
<Response
>): void {
1405 const { taskId
, workerError
, data
} = message
1406 const promiseResponse
= this.promiseResponseMap
.get(taskId
as string)
1407 if (promiseResponse
!= null) {
1408 if (workerError
!= null) {
1409 this.emitter
?.emit(PoolEvents
.taskError
, workerError
)
1410 promiseResponse
.reject(workerError
.message
)
1412 promiseResponse
.resolve(data
as Response
)
1414 const workerNodeKey
= promiseResponse
.workerNodeKey
1415 this.afterTaskExecutionHook(workerNodeKey
, message
)
1416 this.workerChoiceStrategyContext
.update(workerNodeKey
)
1417 this.promiseResponseMap
.delete(taskId
as string)
1419 this.opts
.enableTasksQueue
=== true &&
1420 this.tasksQueueSize(workerNodeKey
) > 0 &&
1421 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
<
1422 (this.opts
.tasksQueueOptions
?.concurrency
as number)
1426 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1432 private checkAndEmitTaskExecutionEvents (): void {
1434 this.emitter
?.emit(PoolEvents
.busy
, this.info
)
1438 private checkAndEmitTaskQueuingEvents (): void {
1439 if (this.hasBackPressure()) {
1440 this.emitter
?.emit(PoolEvents
.backPressure
, this.info
)
1444 private checkAndEmitDynamicWorkerCreationEvents (): void {
1445 if (this.type === PoolTypes
.dynamic
) {
1447 this.emitter
?.emit(PoolEvents
.full
, this.info
)
1453 * Gets the worker information given its worker node key.
1455 * @param workerNodeKey - The worker node key.
1456 * @returns The worker information.
1458 protected getWorkerInfo (workerNodeKey
: number): WorkerInfo
{
1459 return this.workerNodes
[workerNodeKey
].info
1463 * Adds the given worker in the pool worker nodes.
1465 * @param worker - The worker.
1466 * @returns The added worker node key.
1467 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the added worker node is not found.
1469 private addWorkerNode (worker
: Worker
): number {
1470 const workerNode
= new WorkerNode
<Worker
, Data
>(
1472 this.opts
.tasksQueueOptions
?.size
?? Math.pow(this.maxSize
, 2)
1474 // Flag the worker node as ready at pool startup.
1475 if (this.starting
) {
1476 workerNode
.info
.ready
= true
1478 this.workerNodes
.push(workerNode
)
1479 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
1480 if (workerNodeKey
=== -1) {
1481 throw new Error('Worker added not found in worker nodes')
1483 return workerNodeKey
1487 * Removes the given worker from the pool worker nodes.
1489 * @param worker - The worker.
1491 private removeWorkerNode (worker
: Worker
): void {
1492 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
1493 if (workerNodeKey
!== -1) {
1494 this.workerNodes
.splice(workerNodeKey
, 1)
1495 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
1500 public hasWorkerNodeBackPressure (workerNodeKey
: number): boolean {
1502 this.opts
.enableTasksQueue
=== true &&
1503 this.workerNodes
[workerNodeKey
].hasBackPressure()
1507 private hasBackPressure (): boolean {
1509 this.opts
.enableTasksQueue
=== true &&
1510 this.workerNodes
.findIndex(
1511 workerNode
=> !workerNode
.hasBackPressure()
1517 * Executes the given task on the worker given its worker node key.
1519 * @param workerNodeKey - The worker node key.
1520 * @param task - The task to execute.
1522 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
1523 this.beforeTaskExecutionHook(workerNodeKey
, task
)
1524 this.sendToWorker(workerNodeKey
, task
, task
.transferList
)
1525 this.checkAndEmitTaskExecutionEvents()
1528 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
1529 const tasksQueueSize
= this.workerNodes
[workerNodeKey
].enqueueTask(task
)
1530 this.checkAndEmitTaskQueuingEvents()
1531 return tasksQueueSize
1534 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
1535 return this.workerNodes
[workerNodeKey
].dequeueTask()
1538 private tasksQueueSize (workerNodeKey
: number): number {
1539 return this.workerNodes
[workerNodeKey
].tasksQueueSize()
1542 protected flushTasksQueue (workerNodeKey
: number): void {
1543 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1546 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1549 this.workerNodes
[workerNodeKey
].clearTasksQueue()
1552 private flushTasksQueues (): void {
1553 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
1554 this.flushTasksQueue(workerNodeKey
)