1 import { AsyncResource
} from
'node:async_hooks'
2 import { randomUUID
} from
'node:crypto'
3 import { EventEmitterAsyncResource
} from
'node:events'
4 import { performance
} from
'node:perf_hooks'
5 import type { TransferListItem
} from
'node:worker_threads'
9 PromiseResponseWrapper
,
11 TaskFunctionProperties
12 } from
'../utility-types.js'
15 buildTaskFunctionProperties
,
30 } from
'../worker/task-functions.js'
31 import { KillBehaviors
} from
'../worker/worker-options.js'
39 type TasksQueueOptions
43 WorkerChoiceStrategies
,
44 type WorkerChoiceStrategy
,
45 type WorkerChoiceStrategyOptions
46 } from
'./selection-strategies/selection-strategies-types.js'
47 import { WorkerChoiceStrategiesContext
} from
'./selection-strategies/worker-choice-strategies-context.js'
51 checkValidTasksQueueOptions
,
52 checkValidWorkerChoiceStrategy
,
53 getDefaultTasksQueueOptions
,
55 updateRunTimeWorkerUsage
,
56 updateTaskStatisticsWorkerUsage
,
57 updateWaitTimeWorkerUsage
,
60 import { version
} from
'./version.js'
65 WorkerNodeEventDetail
,
68 import { WorkerNode
} from
'./worker-node.js'
71 * Base class that implements some shared logic for all poolifier pools.
73 * @typeParam Worker - Type of worker which manages this pool.
74 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
75 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
77 export abstract class AbstractPool
<
78 Worker
extends IWorker
,
81 > implements IPool
<Worker
, Data
, Response
> {
83 public readonly workerNodes
: Array<IWorkerNode
<Worker
, Data
>> = []
86 public emitter
?: EventEmitterAsyncResource
89 * The task execution response promise map:
90 * - `key`: The message id of each submitted task.
91 * - `value`: An object that contains task's worker node key, execution response promise resolve and reject callbacks, async resource.
93 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
95 protected promiseResponseMap
: Map
<
96 `${string}-${string}-${string}-${string}-${string}`,
97 PromiseResponseWrapper
<Response
>
99 `${string}-${string}-${string}-${string}-${string}`,
100 PromiseResponseWrapper
<Response
>
104 * Worker choice strategies context referencing worker choice algorithms implementation.
106 protected workerChoiceStrategiesContext
?: WorkerChoiceStrategiesContext
<
113 * The task functions added at runtime map:
114 * - `key`: The task function name.
115 * - `value`: The task function object.
117 private readonly taskFunctions
: Map
<
119 TaskFunctionObject
<Data
, Response
>
123 * Whether the pool is started or not.
125 private started
: boolean
127 * Whether the pool is starting or not.
129 private starting
: boolean
131 * Whether the pool is destroying or not.
133 private destroying
: boolean
135 * Whether the minimum number of workers is starting or not.
137 private startingMinimumNumberOfWorkers
: boolean
139 * Whether the pool ready event has been emitted or not.
141 private readyEventEmitted
: boolean
143 * The start timestamp of the pool.
145 private startTimestamp
?: number
148 * Constructs a new poolifier pool.
150 * @param minimumNumberOfWorkers - Minimum number of workers that this pool manages.
151 * @param filePath - Path to the worker file.
152 * @param opts - Options for the pool.
153 * @param maximumNumberOfWorkers - Maximum number of workers that this pool manages.
156 protected readonly minimumNumberOfWorkers
: number,
157 protected readonly filePath
: string,
158 protected readonly opts
: PoolOptions
<Worker
>,
159 protected readonly maximumNumberOfWorkers
?: number
161 if (!this.isMain()) {
163 'Cannot start a pool from a worker with the same type as the pool'
167 checkFilePath(this.filePath
)
168 this.checkMinimumNumberOfWorkers(this.minimumNumberOfWorkers
)
169 this.checkPoolOptions(this.opts
)
171 this.chooseWorkerNode
= this.chooseWorkerNode
.bind(this)
172 this.executeTask
= this.executeTask
.bind(this)
173 this.enqueueTask
= this.enqueueTask
.bind(this)
175 if (this.opts
.enableEvents
=== true) {
176 this.initEventEmitter()
178 this.workerChoiceStrategiesContext
= new WorkerChoiceStrategiesContext
<
184 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
185 [this.opts
.workerChoiceStrategy
!],
186 this.opts
.workerChoiceStrategyOptions
191 this.taskFunctions
= new Map
<string, TaskFunctionObject
<Data
, Response
>>()
194 this.starting
= false
195 this.destroying
= false
196 this.readyEventEmitted
= false
197 this.startingMinimumNumberOfWorkers
= false
198 if (this.opts
.startWorkers
=== true) {
203 private checkPoolType (): void {
204 if (this.type === PoolTypes
.fixed
&& this.maximumNumberOfWorkers
!= null) {
206 'Cannot instantiate a fixed pool with a maximum number of workers specified at initialization'
211 private checkMinimumNumberOfWorkers (
212 minimumNumberOfWorkers
: number | undefined
214 if (minimumNumberOfWorkers
== null) {
216 'Cannot instantiate a pool without specifying the number of workers'
218 } else if (!Number.isSafeInteger(minimumNumberOfWorkers
)) {
220 'Cannot instantiate a pool with a non safe integer number of workers'
222 } else if (minimumNumberOfWorkers
< 0) {
223 throw new RangeError(
224 'Cannot instantiate a pool with a negative number of workers'
226 } else if (this.type === PoolTypes
.fixed
&& minimumNumberOfWorkers
=== 0) {
227 throw new RangeError('Cannot instantiate a fixed pool with zero worker')
231 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
232 if (isPlainObject(opts
)) {
233 this.opts
.startWorkers
= opts
.startWorkers
?? true
234 checkValidWorkerChoiceStrategy(opts
.workerChoiceStrategy
)
235 this.opts
.workerChoiceStrategy
=
236 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
237 this.checkValidWorkerChoiceStrategyOptions(
238 opts
.workerChoiceStrategyOptions
240 if (opts
.workerChoiceStrategyOptions
!= null) {
241 this.opts
.workerChoiceStrategyOptions
= opts
.workerChoiceStrategyOptions
243 this.opts
.restartWorkerOnError
= opts
.restartWorkerOnError
?? true
244 this.opts
.enableEvents
= opts
.enableEvents
?? true
245 this.opts
.enableTasksQueue
= opts
.enableTasksQueue
?? false
246 if (this.opts
.enableTasksQueue
) {
247 checkValidTasksQueueOptions(opts
.tasksQueueOptions
)
248 this.opts
.tasksQueueOptions
= this.buildTasksQueueOptions(
249 opts
.tasksQueueOptions
253 throw new TypeError('Invalid pool options: must be a plain object')
257 private checkValidWorkerChoiceStrategyOptions (
258 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
| undefined
261 workerChoiceStrategyOptions
!= null &&
262 !isPlainObject(workerChoiceStrategyOptions
)
265 'Invalid worker choice strategy options: must be a plain object'
269 workerChoiceStrategyOptions
?.weights
!= null &&
270 Object.keys(workerChoiceStrategyOptions
.weights
).length
!==
271 (this.maximumNumberOfWorkers
?? this.minimumNumberOfWorkers
)
274 'Invalid worker choice strategy options: must have a weight for each worker node'
278 workerChoiceStrategyOptions
?.measurement
!= null &&
279 !Object.values(Measurements
).includes(
280 workerChoiceStrategyOptions
.measurement
284 `Invalid worker choice strategy options: invalid measurement '${workerChoiceStrategyOptions.measurement}'`
289 private initEventEmitter (): void {
290 this.emitter
= new EventEmitterAsyncResource({
291 name
: `poolifier:${this.type}-${this.worker}-pool`
296 public get
info (): PoolInfo
{
301 started
: this.started
,
303 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
304 defaultStrategy
: this.opts
.workerChoiceStrategy
!,
305 strategyRetries
: this.workerChoiceStrategiesContext
?.retriesCount
?? 0,
306 minSize
: this.minimumNumberOfWorkers
,
307 maxSize
: this.maximumNumberOfWorkers
?? this.minimumNumberOfWorkers
,
308 ...(this.workerChoiceStrategiesContext
?.getTaskStatisticsRequirements()
309 .runTime
.aggregate
=== true &&
310 this.workerChoiceStrategiesContext
.getTaskStatisticsRequirements()
311 .waitTime
.aggregate
&& {
312 utilization
: round(this.utilization
)
314 workerNodes
: this.workerNodes
.length
,
315 idleWorkerNodes
: this.workerNodes
.reduce(
316 (accumulator
, workerNode
) =>
317 workerNode
.usage
.tasks
.executing
=== 0
322 ...(this.opts
.enableTasksQueue
=== true && {
323 stealingWorkerNodes
: this.workerNodes
.reduce(
324 (accumulator
, workerNode
) =>
325 workerNode
.info
.stealing
? accumulator
+ 1 : accumulator
,
329 busyWorkerNodes
: this.workerNodes
.reduce(
330 (accumulator
, _
, workerNodeKey
) =>
331 this.isWorkerNodeBusy(workerNodeKey
) ? accumulator
+ 1 : accumulator
,
334 executedTasks
: this.workerNodes
.reduce(
335 (accumulator
, workerNode
) =>
336 accumulator
+ workerNode
.usage
.tasks
.executed
,
339 executingTasks
: this.workerNodes
.reduce(
340 (accumulator
, workerNode
) =>
341 accumulator
+ workerNode
.usage
.tasks
.executing
,
344 ...(this.opts
.enableTasksQueue
=== true && {
345 queuedTasks
: this.workerNodes
.reduce(
346 (accumulator
, workerNode
) =>
347 accumulator
+ workerNode
.usage
.tasks
.queued
,
351 ...(this.opts
.enableTasksQueue
=== true && {
352 maxQueuedTasks
: this.workerNodes
.reduce(
353 (accumulator
, workerNode
) =>
354 accumulator
+ (workerNode
.usage
.tasks
.maxQueued
?? 0),
358 ...(this.opts
.enableTasksQueue
=== true && {
359 backPressure
: this.hasBackPressure()
361 ...(this.opts
.enableTasksQueue
=== true && {
362 stolenTasks
: this.workerNodes
.reduce(
363 (accumulator
, workerNode
) =>
364 accumulator
+ workerNode
.usage
.tasks
.stolen
,
368 failedTasks
: this.workerNodes
.reduce(
369 (accumulator
, workerNode
) =>
370 accumulator
+ workerNode
.usage
.tasks
.failed
,
373 ...(this.workerChoiceStrategiesContext
?.getTaskStatisticsRequirements()
374 .runTime
.aggregate
=== true && {
378 ...this.workerNodes
.map(
380 workerNode
.usage
.runTime
.minimum
?? Number.POSITIVE_INFINITY
386 ...this.workerNodes
.map(
388 workerNode
.usage
.runTime
.maximum
?? Number.NEGATIVE_INFINITY
392 ...(this.workerChoiceStrategiesContext
.getTaskStatisticsRequirements()
393 .runTime
.average
&& {
396 this.workerNodes
.reduce
<number[]>(
397 (accumulator
, workerNode
) =>
399 workerNode
.usage
.runTime
.history
.toArray()
406 ...(this.workerChoiceStrategiesContext
.getTaskStatisticsRequirements()
410 this.workerNodes
.reduce
<number[]>(
411 (accumulator
, workerNode
) =>
413 workerNode
.usage
.runTime
.history
.toArray()
422 ...(this.workerChoiceStrategiesContext
?.getTaskStatisticsRequirements()
423 .waitTime
.aggregate
=== true && {
427 ...this.workerNodes
.map(
429 workerNode
.usage
.waitTime
.minimum
?? Number.POSITIVE_INFINITY
435 ...this.workerNodes
.map(
437 workerNode
.usage
.waitTime
.maximum
?? Number.NEGATIVE_INFINITY
441 ...(this.workerChoiceStrategiesContext
.getTaskStatisticsRequirements()
442 .waitTime
.average
&& {
445 this.workerNodes
.reduce
<number[]>(
446 (accumulator
, workerNode
) =>
448 workerNode
.usage
.waitTime
.history
.toArray()
455 ...(this.workerChoiceStrategiesContext
.getTaskStatisticsRequirements()
456 .waitTime
.median
&& {
459 this.workerNodes
.reduce
<number[]>(
460 (accumulator
, workerNode
) =>
462 workerNode
.usage
.waitTime
.history
.toArray()
471 ...(this.workerChoiceStrategiesContext
?.getTaskStatisticsRequirements()
472 .elu
.aggregate
=== true && {
477 ...this.workerNodes
.map(
479 workerNode
.usage
.elu
.idle
.minimum
??
480 Number.POSITIVE_INFINITY
486 ...this.workerNodes
.map(
488 workerNode
.usage
.elu
.idle
.maximum
??
489 Number.NEGATIVE_INFINITY
493 ...(this.workerChoiceStrategiesContext
.getTaskStatisticsRequirements()
497 this.workerNodes
.reduce
<number[]>(
498 (accumulator
, workerNode
) =>
500 workerNode
.usage
.elu
.idle
.history
.toArray()
507 ...(this.workerChoiceStrategiesContext
.getTaskStatisticsRequirements()
511 this.workerNodes
.reduce
<number[]>(
512 (accumulator
, workerNode
) =>
514 workerNode
.usage
.elu
.idle
.history
.toArray()
525 ...this.workerNodes
.map(
527 workerNode
.usage
.elu
.active
.minimum
??
528 Number.POSITIVE_INFINITY
534 ...this.workerNodes
.map(
536 workerNode
.usage
.elu
.active
.maximum
??
537 Number.NEGATIVE_INFINITY
541 ...(this.workerChoiceStrategiesContext
.getTaskStatisticsRequirements()
545 this.workerNodes
.reduce
<number[]>(
546 (accumulator
, workerNode
) =>
548 workerNode
.usage
.elu
.active
.history
.toArray()
555 ...(this.workerChoiceStrategiesContext
.getTaskStatisticsRequirements()
559 this.workerNodes
.reduce
<number[]>(
560 (accumulator
, workerNode
) =>
562 workerNode
.usage
.elu
.active
.history
.toArray()
573 this.workerNodes
.map(
574 workerNode
=> workerNode
.usage
.elu
.utilization
?? 0
580 this.workerNodes
.map(
581 workerNode
=> workerNode
.usage
.elu
.utilization
?? 0
592 * The pool readiness boolean status.
594 private get
ready (): boolean {
599 this.workerNodes
.reduce(
600 (accumulator
, workerNode
) =>
601 !workerNode
.info
.dynamic
&& workerNode
.info
.ready
605 ) >= this.minimumNumberOfWorkers
610 * The pool emptiness boolean status.
612 protected get
empty (): boolean {
613 return this.minimumNumberOfWorkers
=== 0 && this.workerNodes
.length
=== 0
617 * The approximate pool utilization.
619 * @returns The pool utilization.
621 private get
utilization (): number {
622 if (this.startTimestamp
== null) {
625 const poolTimeCapacity
=
626 (performance
.now() - this.startTimestamp
) *
627 (this.maximumNumberOfWorkers
?? this.minimumNumberOfWorkers
)
628 const totalTasksRunTime
= this.workerNodes
.reduce(
629 (accumulator
, workerNode
) =>
630 accumulator
+ (workerNode
.usage
.runTime
.aggregate
?? 0),
633 const totalTasksWaitTime
= this.workerNodes
.reduce(
634 (accumulator
, workerNode
) =>
635 accumulator
+ (workerNode
.usage
.waitTime
.aggregate
?? 0),
638 return (totalTasksRunTime
+ totalTasksWaitTime
) / poolTimeCapacity
644 * If it is `'dynamic'`, it provides the `max` property.
646 protected abstract get
type (): PoolType
651 protected abstract get
worker (): WorkerType
654 * Checks if the worker id sent in the received message from a worker is valid.
656 * @param message - The received message.
657 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the worker id is invalid.
659 private checkMessageWorkerId (message
: MessageValue
<Data
| Response
>): void {
660 if (message
.workerId
== null) {
661 throw new Error('Worker message received without worker id')
662 } else if (this.getWorkerNodeKeyByWorkerId(message
.workerId
) === -1) {
664 `Worker message received from unknown worker '${message.workerId}'`
670 * Gets the worker node key given its worker id.
672 * @param workerId - The worker id.
673 * @returns The worker node key if the worker id is found in the pool worker nodes, `-1` otherwise.
675 private getWorkerNodeKeyByWorkerId (workerId
: number | undefined): number {
676 return this.workerNodes
.findIndex(
677 workerNode
=> workerNode
.info
.id
=== workerId
682 public setWorkerChoiceStrategy (
683 workerChoiceStrategy
: WorkerChoiceStrategy
,
684 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
686 let requireSync
= false
687 checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
688 if (workerChoiceStrategyOptions
!= null) {
689 requireSync
= !this.setWorkerChoiceStrategyOptions(
690 workerChoiceStrategyOptions
693 if (workerChoiceStrategy
!== this.opts
.workerChoiceStrategy
) {
694 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
695 this.workerChoiceStrategiesContext
?.setDefaultWorkerChoiceStrategy(
696 this.opts
.workerChoiceStrategy
,
697 this.opts
.workerChoiceStrategyOptions
702 this.workerChoiceStrategiesContext
?.syncWorkerChoiceStrategies(
703 this.getWorkerChoiceStrategies(),
704 this.opts
.workerChoiceStrategyOptions
706 for (const workerNodeKey
of this.workerNodes
.keys()) {
707 this.sendStatisticsMessageToWorker(workerNodeKey
)
713 public setWorkerChoiceStrategyOptions (
714 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
| undefined
716 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
717 if (workerChoiceStrategyOptions
!= null) {
718 this.opts
.workerChoiceStrategyOptions
= workerChoiceStrategyOptions
719 this.workerChoiceStrategiesContext
?.setOptions(
720 this.opts
.workerChoiceStrategyOptions
722 this.workerChoiceStrategiesContext
?.syncWorkerChoiceStrategies(
723 this.getWorkerChoiceStrategies(),
724 this.opts
.workerChoiceStrategyOptions
726 for (const workerNodeKey
of this.workerNodes
.keys()) {
727 this.sendStatisticsMessageToWorker(workerNodeKey
)
735 public enableTasksQueue (
737 tasksQueueOptions
?: TasksQueueOptions
739 if (this.opts
.enableTasksQueue
=== true && !enable
) {
740 this.unsetTaskStealing()
741 this.unsetTasksStealingOnBackPressure()
742 this.flushTasksQueues()
744 this.opts
.enableTasksQueue
= enable
745 this.setTasksQueueOptions(tasksQueueOptions
)
749 public setTasksQueueOptions (
750 tasksQueueOptions
: TasksQueueOptions
| undefined
752 if (this.opts
.enableTasksQueue
=== true) {
753 checkValidTasksQueueOptions(tasksQueueOptions
)
754 this.opts
.tasksQueueOptions
=
755 this.buildTasksQueueOptions(tasksQueueOptions
)
756 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
757 this.setTasksQueueSize(this.opts
.tasksQueueOptions
.size
!)
758 if (this.opts
.tasksQueueOptions
.taskStealing
=== true) {
759 this.unsetTaskStealing()
760 this.setTaskStealing()
762 this.unsetTaskStealing()
764 if (this.opts
.tasksQueueOptions
.tasksStealingOnBackPressure
=== true) {
765 this.unsetTasksStealingOnBackPressure()
766 this.setTasksStealingOnBackPressure()
768 this.unsetTasksStealingOnBackPressure()
770 } else if (this.opts
.tasksQueueOptions
!= null) {
771 delete this.opts
.tasksQueueOptions
775 private buildTasksQueueOptions (
776 tasksQueueOptions
: TasksQueueOptions
| undefined
777 ): TasksQueueOptions
{
779 ...getDefaultTasksQueueOptions(
780 this.maximumNumberOfWorkers
?? this.minimumNumberOfWorkers
786 private setTasksQueueSize (size
: number): void {
787 for (const workerNode
of this.workerNodes
) {
788 workerNode
.tasksQueueBackPressureSize
= size
792 private setTaskStealing (): void {
793 for (const workerNodeKey
of this.workerNodes
.keys()) {
794 this.workerNodes
[workerNodeKey
].on('idle', this.handleWorkerNodeIdleEvent
)
798 private unsetTaskStealing (): void {
799 for (const workerNodeKey
of this.workerNodes
.keys()) {
800 this.workerNodes
[workerNodeKey
].off(
802 this.handleWorkerNodeIdleEvent
807 private setTasksStealingOnBackPressure (): void {
808 for (const workerNodeKey
of this.workerNodes
.keys()) {
809 this.workerNodes
[workerNodeKey
].on(
811 this.handleWorkerNodeBackPressureEvent
816 private unsetTasksStealingOnBackPressure (): void {
817 for (const workerNodeKey
of this.workerNodes
.keys()) {
818 this.workerNodes
[workerNodeKey
].off(
820 this.handleWorkerNodeBackPressureEvent
826 * Whether the pool is full or not.
828 * The pool filling boolean status.
830 protected get
full (): boolean {
832 this.workerNodes
.length
>=
833 (this.maximumNumberOfWorkers
?? this.minimumNumberOfWorkers
)
838 * Whether the pool is busy or not.
840 * The pool busyness boolean status.
842 protected abstract get
busy (): boolean
845 * Whether worker nodes are executing concurrently their tasks quota or not.
847 * @returns Worker nodes busyness boolean status.
849 protected internalBusy (): boolean {
850 if (this.opts
.enableTasksQueue
=== true) {
852 this.workerNodes
.findIndex(
854 workerNode
.info
.ready
&&
855 workerNode
.usage
.tasks
.executing
<
856 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
857 this.opts
.tasksQueueOptions
!.concurrency
!
862 this.workerNodes
.findIndex(
864 workerNode
.info
.ready
&& workerNode
.usage
.tasks
.executing
=== 0
869 private isWorkerNodeBusy (workerNodeKey
: number): boolean {
870 if (this.opts
.enableTasksQueue
=== true) {
872 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
>=
873 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
874 this.opts
.tasksQueueOptions
!.concurrency
!
877 return this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
> 0
880 private async sendTaskFunctionOperationToWorker (
881 workerNodeKey
: number,
882 message
: MessageValue
<Data
>
883 ): Promise
<boolean> {
884 return await new Promise
<boolean>((resolve
, reject
) => {
885 const taskFunctionOperationListener
= (
886 message
: MessageValue
<Response
>
888 this.checkMessageWorkerId(message
)
889 const workerId
= this.getWorkerInfo(workerNodeKey
)?.id
891 message
.taskFunctionOperationStatus
!= null &&
892 message
.workerId
=== workerId
894 if (message
.taskFunctionOperationStatus
) {
899 `Task function operation '${message.taskFunctionOperation}' failed on worker ${message.workerId} with error: '${message.workerError?.message}'`
903 this.deregisterWorkerMessageListener(
904 this.getWorkerNodeKeyByWorkerId(message
.workerId
),
905 taskFunctionOperationListener
909 this.registerWorkerMessageListener(
911 taskFunctionOperationListener
913 this.sendToWorker(workerNodeKey
, message
)
917 private async sendTaskFunctionOperationToWorkers (
918 message
: MessageValue
<Data
>
919 ): Promise
<boolean> {
920 return await new Promise
<boolean>((resolve
, reject
) => {
921 const responsesReceived
= new Array<MessageValue
<Response
>>()
922 const taskFunctionOperationsListener
= (
923 message
: MessageValue
<Response
>
925 this.checkMessageWorkerId(message
)
926 if (message
.taskFunctionOperationStatus
!= null) {
927 responsesReceived
.push(message
)
928 if (responsesReceived
.length
=== this.workerNodes
.length
) {
930 responsesReceived
.every(
931 message
=> message
.taskFunctionOperationStatus
=== true
936 responsesReceived
.some(
937 message
=> message
.taskFunctionOperationStatus
=== false
940 const errorResponse
= responsesReceived
.find(
941 response
=> response
.taskFunctionOperationStatus
=== false
945 `Task function operation '${
946 message.taskFunctionOperation as string
947 }' failed on worker ${errorResponse?.workerId} with error: '${
948 errorResponse?.workerError?.message
953 this.deregisterWorkerMessageListener(
954 this.getWorkerNodeKeyByWorkerId(message
.workerId
),
955 taskFunctionOperationsListener
960 for (const workerNodeKey
of this.workerNodes
.keys()) {
961 this.registerWorkerMessageListener(
963 taskFunctionOperationsListener
965 this.sendToWorker(workerNodeKey
, message
)
971 public hasTaskFunction (name
: string): boolean {
972 return this.listTaskFunctionsProperties().some(
973 taskFunctionProperties
=> taskFunctionProperties
.name
=== name
978 public async addTaskFunction (
980 fn
: TaskFunction
<Data
, Response
> | TaskFunctionObject
<Data
, Response
>
981 ): Promise
<boolean> {
982 if (typeof name
!== 'string') {
983 throw new TypeError('name argument must be a string')
985 if (typeof name
=== 'string' && name
.trim().length
=== 0) {
986 throw new TypeError('name argument must not be an empty string')
988 if (typeof fn
=== 'function') {
989 fn
= { taskFunction
: fn
} satisfies TaskFunctionObject
<Data
, Response
>
991 if (typeof fn
.taskFunction
!== 'function') {
992 throw new TypeError('taskFunction property must be a function')
994 checkValidPriority(fn
.priority
)
995 checkValidWorkerChoiceStrategy(fn
.strategy
)
996 const opResult
= await this.sendTaskFunctionOperationToWorkers({
997 taskFunctionOperation
: 'add',
998 taskFunctionProperties
: buildTaskFunctionProperties(name
, fn
),
999 taskFunction
: fn
.taskFunction
.toString()
1001 this.taskFunctions
.set(name
, fn
)
1002 this.workerChoiceStrategiesContext
?.syncWorkerChoiceStrategies(
1003 this.getWorkerChoiceStrategies()
1005 for (const workerNodeKey
of this.workerNodes
.keys()) {
1006 this.sendStatisticsMessageToWorker(workerNodeKey
)
1012 public async removeTaskFunction (name
: string): Promise
<boolean> {
1013 if (!this.taskFunctions
.has(name
)) {
1015 'Cannot remove a task function not handled on the pool side'
1018 const opResult
= await this.sendTaskFunctionOperationToWorkers({
1019 taskFunctionOperation
: 'remove',
1020 taskFunctionProperties
: buildTaskFunctionProperties(
1022 this.taskFunctions
.get(name
)
1025 for (const workerNode
of this.workerNodes
) {
1026 workerNode
.deleteTaskFunctionWorkerUsage(name
)
1028 this.taskFunctions
.delete(name
)
1029 this.workerChoiceStrategiesContext
?.syncWorkerChoiceStrategies(
1030 this.getWorkerChoiceStrategies()
1032 for (const workerNodeKey
of this.workerNodes
.keys()) {
1033 this.sendStatisticsMessageToWorker(workerNodeKey
)
1039 public listTaskFunctionsProperties (): TaskFunctionProperties
[] {
1040 for (const workerNode
of this.workerNodes
) {
1042 Array.isArray(workerNode
.info
.taskFunctionsProperties
) &&
1043 workerNode
.info
.taskFunctionsProperties
.length
> 0
1045 return workerNode
.info
.taskFunctionsProperties
1052 * Gets task function worker choice strategy, if any.
1054 * @param name - The task function name.
1055 * @returns The task function worker choice strategy if the task function worker choice strategy is defined, `undefined` otherwise.
1057 private readonly getTaskFunctionWorkerChoiceStrategy
= (
1059 ): WorkerChoiceStrategy
| undefined => {
1060 name
= name
?? DEFAULT_TASK_NAME
1061 const taskFunctionsProperties
= this.listTaskFunctionsProperties()
1062 if (name
=== DEFAULT_TASK_NAME
) {
1063 name
= taskFunctionsProperties
[1]?.name
1065 return taskFunctionsProperties
.find(
1066 (taskFunctionProperties
: TaskFunctionProperties
) =>
1067 taskFunctionProperties
.name
=== name
1072 * Gets worker node task function worker choice strategy, if any.
1074 * @param workerNodeKey - The worker node key.
1075 * @param name - The task function name.
1076 * @returns The worker node task function worker choice strategy if the worker node task function worker choice strategy is defined, `undefined` otherwise.
1078 private readonly getWorkerNodeTaskFunctionWorkerChoiceStrategy
= (
1079 workerNodeKey
: number,
1081 ): WorkerChoiceStrategy
| undefined => {
1082 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
1083 if (workerInfo
== null) {
1086 name
= name
?? DEFAULT_TASK_NAME
1087 if (name
=== DEFAULT_TASK_NAME
) {
1088 name
= workerInfo
.taskFunctionsProperties
?.[1]?.name
1090 return workerInfo
.taskFunctionsProperties
?.find(
1091 (taskFunctionProperties
: TaskFunctionProperties
) =>
1092 taskFunctionProperties
.name
=== name
1097 * Gets worker node task function priority, if any.
1099 * @param workerNodeKey - The worker node key.
1100 * @param name - The task function name.
1101 * @returns The worker node task function priority if the worker node task function priority is defined, `undefined` otherwise.
1103 private readonly getWorkerNodeTaskFunctionPriority
= (
1104 workerNodeKey
: number,
1106 ): number | undefined => {
1107 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
1108 if (workerInfo
== null) {
1111 name
= name
?? DEFAULT_TASK_NAME
1112 if (name
=== DEFAULT_TASK_NAME
) {
1113 name
= workerInfo
.taskFunctionsProperties
?.[1]?.name
1115 return workerInfo
.taskFunctionsProperties
?.find(
1116 (taskFunctionProperties
: TaskFunctionProperties
) =>
1117 taskFunctionProperties
.name
=== name
1122 * Gets the worker choice strategies registered in this pool.
1124 * @returns The worker choice strategies.
1126 private readonly getWorkerChoiceStrategies
=
1127 (): Set
<WorkerChoiceStrategy
> => {
1129 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1130 this.opts
.workerChoiceStrategy
!,
1131 ...(this.listTaskFunctionsProperties()
1133 (taskFunctionProperties
: TaskFunctionProperties
) =>
1134 taskFunctionProperties
.strategy
1137 (strategy
: WorkerChoiceStrategy
| undefined) => strategy
!= null
1138 ) as WorkerChoiceStrategy
[])
1143 public async setDefaultTaskFunction (name
: string): Promise
<boolean> {
1144 return await this.sendTaskFunctionOperationToWorkers({
1145 taskFunctionOperation
: 'default',
1146 taskFunctionProperties
: buildTaskFunctionProperties(
1148 this.taskFunctions
.get(name
)
1153 private shallExecuteTask (workerNodeKey
: number): boolean {
1155 this.tasksQueueSize(workerNodeKey
) === 0 &&
1156 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
<
1157 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1158 this.opts
.tasksQueueOptions
!.concurrency
!
1163 public async execute (
1166 transferList
?: readonly TransferListItem
[]
1167 ): Promise
<Response
> {
1168 return await new Promise
<Response
>((resolve
, reject
) => {
1169 if (!this.started
) {
1170 reject(new Error('Cannot execute a task on not started pool'))
1173 if (this.destroying
) {
1174 reject(new Error('Cannot execute a task on destroying pool'))
1177 if (name
!= null && typeof name
!== 'string') {
1178 reject(new TypeError('name argument must be a string'))
1183 typeof name
=== 'string' &&
1184 name
.trim().length
=== 0
1186 reject(new TypeError('name argument must not be an empty string'))
1189 if (transferList
!= null && !Array.isArray(transferList
)) {
1190 reject(new TypeError('transferList argument must be an array'))
1193 const timestamp
= performance
.now()
1194 const workerNodeKey
= this.chooseWorkerNode(name
)
1195 const task
: Task
<Data
> = {
1196 name
: name
?? DEFAULT_TASK_NAME
,
1197 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
1198 data
: data
?? ({} as Data
),
1199 priority
: this.getWorkerNodeTaskFunctionPriority(workerNodeKey
, name
),
1200 strategy
: this.getWorkerNodeTaskFunctionWorkerChoiceStrategy(
1206 taskId
: randomUUID()
1208 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1209 this.promiseResponseMap
.set(task
.taskId
!, {
1213 ...(this.emitter
!= null && {
1214 asyncResource
: new AsyncResource('poolifier:task', {
1215 triggerAsyncId
: this.emitter
.asyncId
,
1216 requireManualDestroy
: true
1221 this.opts
.enableTasksQueue
=== false ||
1222 (this.opts
.enableTasksQueue
=== true &&
1223 this.shallExecuteTask(workerNodeKey
))
1225 this.executeTask(workerNodeKey
, task
)
1227 this.enqueueTask(workerNodeKey
, task
)
1233 * Starts the minimum number of workers.
1235 private startMinimumNumberOfWorkers (initWorkerNodeUsage
= false): void {
1236 this.startingMinimumNumberOfWorkers
= true
1238 this.workerNodes
.reduce(
1239 (accumulator
, workerNode
) =>
1240 !workerNode
.info
.dynamic
? accumulator
+ 1 : accumulator
,
1242 ) < this.minimumNumberOfWorkers
1244 const workerNodeKey
= this.createAndSetupWorkerNode()
1245 initWorkerNodeUsage
&&
1246 this.initWorkerNodeUsage(this.workerNodes
[workerNodeKey
])
1248 this.startingMinimumNumberOfWorkers
= false
1252 public start (): void {
1254 throw new Error('Cannot start an already started pool')
1256 if (this.starting
) {
1257 throw new Error('Cannot start an already starting pool')
1259 if (this.destroying
) {
1260 throw new Error('Cannot start a destroying pool')
1262 this.starting
= true
1263 this.startMinimumNumberOfWorkers()
1264 this.startTimestamp
= performance
.now()
1265 this.starting
= false
1270 public async destroy (): Promise
<void> {
1271 if (!this.started
) {
1272 throw new Error('Cannot destroy an already destroyed pool')
1274 if (this.starting
) {
1275 throw new Error('Cannot destroy an starting pool')
1277 if (this.destroying
) {
1278 throw new Error('Cannot destroy an already destroying pool')
1280 this.destroying
= true
1282 this.workerNodes
.map(async (_
, workerNodeKey
) => {
1283 await this.destroyWorkerNode(workerNodeKey
)
1286 this.emitter
?.emit(PoolEvents
.destroy
, this.info
)
1287 this.emitter
?.emitDestroy()
1288 this.readyEventEmitted
= false
1289 delete this.startTimestamp
1290 this.destroying
= false
1291 this.started
= false
1294 private async sendKillMessageToWorker (workerNodeKey
: number): Promise
<void> {
1295 await new Promise
<void>((resolve
, reject
) => {
1296 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1297 if (this.workerNodes
[workerNodeKey
] == null) {
1301 const killMessageListener
= (message
: MessageValue
<Response
>): void => {
1302 this.checkMessageWorkerId(message
)
1303 if (message
.kill
=== 'success') {
1305 } else if (message
.kill
=== 'failure') {
1308 `Kill message handling failed on worker ${message.workerId}`
1313 // FIXME: should be registered only once
1314 this.registerWorkerMessageListener(workerNodeKey
, killMessageListener
)
1315 this.sendToWorker(workerNodeKey
, { kill
: true })
1320 * Terminates the worker node given its worker node key.
1322 * @param workerNodeKey - The worker node key.
1324 protected async destroyWorkerNode (workerNodeKey
: number): Promise
<void> {
1325 this.flagWorkerNodeAsNotReady(workerNodeKey
)
1326 const flushedTasks
= this.flushTasksQueue(workerNodeKey
)
1327 const workerNode
= this.workerNodes
[workerNodeKey
]
1328 await waitWorkerNodeEvents(
1332 this.opts
.tasksQueueOptions
?.tasksFinishedTimeout
??
1333 getDefaultTasksQueueOptions(
1334 this.maximumNumberOfWorkers
?? this.minimumNumberOfWorkers
1335 ).tasksFinishedTimeout
1337 await this.sendKillMessageToWorker(workerNodeKey
)
1338 await workerNode
.terminate()
1342 * Setup hook to execute code before worker nodes are created in the abstract constructor.
1343 * Can be overridden.
1347 protected setupHook (): void {
1348 /* Intentionally empty */
1352 * Returns whether the worker is the main worker or not.
1354 * @returns `true` if the worker is the main worker, `false` otherwise.
1356 protected abstract isMain (): boolean
1359 * Hook executed before the worker task execution.
1360 * Can be overridden.
1362 * @param workerNodeKey - The worker node key.
1363 * @param task - The task to execute.
1365 protected beforeTaskExecutionHook (
1366 workerNodeKey
: number,
1369 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1370 if (this.workerNodes
[workerNodeKey
]?.usage
!= null) {
1371 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
1372 ++workerUsage
.tasks
.executing
1373 updateWaitTimeWorkerUsage(
1374 this.workerChoiceStrategiesContext
,
1380 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
1381 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1382 this.workerNodes
[workerNodeKey
].getTaskFunctionWorkerUsage(task
.name
!) !=
1385 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1386 const taskFunctionWorkerUsage
= this.workerNodes
[
1388 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1389 ].getTaskFunctionWorkerUsage(task
.name
!)!
1390 ++taskFunctionWorkerUsage
.tasks
.executing
1391 updateWaitTimeWorkerUsage(
1392 this.workerChoiceStrategiesContext
,
1393 taskFunctionWorkerUsage
,
1400 * Hook executed after the worker task execution.
1401 * Can be overridden.
1403 * @param workerNodeKey - The worker node key.
1404 * @param message - The received message.
1406 protected afterTaskExecutionHook (
1407 workerNodeKey
: number,
1408 message
: MessageValue
<Response
>
1410 let needWorkerChoiceStrategiesUpdate
= false
1411 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1412 if (this.workerNodes
[workerNodeKey
]?.usage
!= null) {
1413 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
1414 updateTaskStatisticsWorkerUsage(workerUsage
, message
)
1415 updateRunTimeWorkerUsage(
1416 this.workerChoiceStrategiesContext
,
1420 updateEluWorkerUsage(
1421 this.workerChoiceStrategiesContext
,
1425 needWorkerChoiceStrategiesUpdate
= true
1428 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
1429 this.workerNodes
[workerNodeKey
].getTaskFunctionWorkerUsage(
1430 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1431 message
.taskPerformance
!.name
1434 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1435 const taskFunctionWorkerUsage
= this.workerNodes
[
1437 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1438 ].getTaskFunctionWorkerUsage(message
.taskPerformance
!.name
)!
1439 updateTaskStatisticsWorkerUsage(taskFunctionWorkerUsage
, message
)
1440 updateRunTimeWorkerUsage(
1441 this.workerChoiceStrategiesContext
,
1442 taskFunctionWorkerUsage
,
1445 updateEluWorkerUsage(
1446 this.workerChoiceStrategiesContext
,
1447 taskFunctionWorkerUsage
,
1450 needWorkerChoiceStrategiesUpdate
= true
1452 if (needWorkerChoiceStrategiesUpdate
) {
1453 this.workerChoiceStrategiesContext
?.update(workerNodeKey
)
1458 * Whether the worker node shall update its task function worker usage or not.
1460 * @param workerNodeKey - The worker node key.
1461 * @returns `true` if the worker node shall update its task function worker usage, `false` otherwise.
1463 private shallUpdateTaskFunctionWorkerUsage (workerNodeKey
: number): boolean {
1464 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
1466 workerInfo
!= null &&
1467 Array.isArray(workerInfo
.taskFunctionsProperties
) &&
1468 workerInfo
.taskFunctionsProperties
.length
> 2
1473 * Chooses a worker node for the next task.
1475 * @param name - The task function name.
1476 * @returns The chosen worker node key.
1478 private chooseWorkerNode (name
?: string): number {
1479 if (this.shallCreateDynamicWorker()) {
1480 const workerNodeKey
= this.createAndSetupDynamicWorkerNode()
1482 this.workerChoiceStrategiesContext
?.getPolicy().dynamicWorkerUsage
===
1485 return workerNodeKey
1488 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1489 return this.workerChoiceStrategiesContext
!.execute(
1490 this.getTaskFunctionWorkerChoiceStrategy(name
)
1495 * Conditions for dynamic worker creation.
1497 * @returns Whether to create a dynamic worker or not.
1499 protected abstract shallCreateDynamicWorker (): boolean
1502 * Sends a message to worker given its worker node key.
1504 * @param workerNodeKey - The worker node key.
1505 * @param message - The message.
1506 * @param transferList - The optional array of transferable objects.
1508 protected abstract sendToWorker (
1509 workerNodeKey
: number,
1510 message
: MessageValue
<Data
>,
1511 transferList
?: readonly TransferListItem
[]
1515 * Initializes the worker node usage with sensible default values gathered during runtime.
1517 * @param workerNode - The worker node.
1519 private initWorkerNodeUsage (workerNode
: IWorkerNode
<Worker
, Data
>): void {
1521 this.workerChoiceStrategiesContext
?.getTaskStatisticsRequirements()
1522 .runTime
.aggregate
=== true
1524 workerNode
.usage
.runTime
.aggregate
= min(
1525 ...this.workerNodes
.map(
1527 workerNode
.usage
.runTime
.aggregate
?? Number.POSITIVE_INFINITY
1532 this.workerChoiceStrategiesContext
?.getTaskStatisticsRequirements()
1533 .waitTime
.aggregate
=== true
1535 workerNode
.usage
.waitTime
.aggregate
= min(
1536 ...this.workerNodes
.map(
1538 workerNode
.usage
.waitTime
.aggregate
?? Number.POSITIVE_INFINITY
1543 this.workerChoiceStrategiesContext
?.getTaskStatisticsRequirements().elu
1546 workerNode
.usage
.elu
.active
.aggregate
= min(
1547 ...this.workerNodes
.map(
1549 workerNode
.usage
.elu
.active
.aggregate
?? Number.POSITIVE_INFINITY
1556 * Creates a new, completely set up worker node.
1558 * @returns New, completely set up worker node key.
1560 protected createAndSetupWorkerNode (): number {
1561 const workerNode
= this.createWorkerNode()
1562 workerNode
.registerWorkerEventHandler(
1564 this.opts
.onlineHandler
?? EMPTY_FUNCTION
1566 workerNode
.registerWorkerEventHandler(
1568 this.opts
.messageHandler
?? EMPTY_FUNCTION
1570 workerNode
.registerWorkerEventHandler(
1572 this.opts
.errorHandler
?? EMPTY_FUNCTION
1574 workerNode
.registerOnceWorkerEventHandler('error', (error
: Error) => {
1575 workerNode
.info
.ready
= false
1576 this.emitter
?.emit(PoolEvents
.error
, error
)
1580 this.opts
.restartWorkerOnError
=== true
1582 if (workerNode
.info
.dynamic
) {
1583 this.createAndSetupDynamicWorkerNode()
1584 } else if (!this.startingMinimumNumberOfWorkers
) {
1585 this.startMinimumNumberOfWorkers(true)
1591 this.opts
.enableTasksQueue
=== true
1593 this.redistributeQueuedTasks(this.workerNodes
.indexOf(workerNode
))
1595 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1596 workerNode
?.terminate().catch((error
: unknown
) => {
1597 this.emitter
?.emit(PoolEvents
.error
, error
)
1600 workerNode
.registerWorkerEventHandler(
1602 this.opts
.exitHandler
?? EMPTY_FUNCTION
1604 workerNode
.registerOnceWorkerEventHandler('exit', () => {
1605 this.removeWorkerNode(workerNode
)
1608 !this.startingMinimumNumberOfWorkers
&&
1611 this.startMinimumNumberOfWorkers(true)
1614 const workerNodeKey
= this.addWorkerNode(workerNode
)
1615 this.afterWorkerNodeSetup(workerNodeKey
)
1616 return workerNodeKey
1620 * Creates a new, completely set up dynamic worker node.
1622 * @returns New, completely set up dynamic worker node key.
1624 protected createAndSetupDynamicWorkerNode (): number {
1625 const workerNodeKey
= this.createAndSetupWorkerNode()
1626 this.registerWorkerMessageListener(workerNodeKey
, message
=> {
1627 this.checkMessageWorkerId(message
)
1628 const localWorkerNodeKey
= this.getWorkerNodeKeyByWorkerId(
1631 const workerInfo
= this.getWorkerInfo(localWorkerNodeKey
)
1632 const workerUsage
= this.workerNodes
[localWorkerNodeKey
]?.usage
1633 // Kill message received from worker
1635 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
1636 (isKillBehavior(KillBehaviors
.SOFT
, message
.kill
) &&
1637 ((this.opts
.enableTasksQueue
=== false &&
1638 workerUsage
.tasks
.executing
=== 0) ||
1639 (this.opts
.enableTasksQueue
=== true &&
1640 workerInfo
!= null &&
1641 !workerInfo
.stealing
&&
1642 workerUsage
.tasks
.executing
=== 0 &&
1643 this.tasksQueueSize(localWorkerNodeKey
) === 0)))
1645 // Flag the worker node as not ready immediately
1646 this.flagWorkerNodeAsNotReady(localWorkerNodeKey
)
1647 this.destroyWorkerNode(localWorkerNodeKey
).catch((error
: unknown
) => {
1648 this.emitter
?.emit(PoolEvents
.error
, error
)
1652 this.sendToWorker(workerNodeKey
, {
1655 if (this.taskFunctions
.size
> 0) {
1656 for (const [taskFunctionName
, taskFunctionObject
] of this.taskFunctions
) {
1657 this.sendTaskFunctionOperationToWorker(workerNodeKey
, {
1658 taskFunctionOperation
: 'add',
1659 taskFunctionProperties
: buildTaskFunctionProperties(
1663 taskFunction
: taskFunctionObject
.taskFunction
.toString()
1664 }).catch((error
: unknown
) => {
1665 this.emitter
?.emit(PoolEvents
.error
, error
)
1669 const workerNode
= this.workerNodes
[workerNodeKey
]
1670 workerNode
.info
.dynamic
= true
1672 this.workerChoiceStrategiesContext
?.getPolicy().dynamicWorkerReady
===
1674 this.workerChoiceStrategiesContext
?.getPolicy().dynamicWorkerUsage
===
1677 workerNode
.info
.ready
= true
1679 this.initWorkerNodeUsage(workerNode
)
1680 this.checkAndEmitDynamicWorkerCreationEvents()
1681 return workerNodeKey
1685 * Registers a listener callback on the worker given its worker node key.
1687 * @param workerNodeKey - The worker node key.
1688 * @param listener - The message listener callback.
1690 protected abstract registerWorkerMessageListener
<
1691 Message
extends Data
| Response
1693 workerNodeKey
: number,
1694 listener
: (message
: MessageValue
<Message
>) => void
1698 * Registers once a listener callback on the worker given its worker node key.
1700 * @param workerNodeKey - The worker node key.
1701 * @param listener - The message listener callback.
1703 protected abstract registerOnceWorkerMessageListener
<
1704 Message
extends Data
| Response
1706 workerNodeKey
: number,
1707 listener
: (message
: MessageValue
<Message
>) => void
1711 * Deregisters a listener callback on the worker given its worker node key.
1713 * @param workerNodeKey - The worker node key.
1714 * @param listener - The message listener callback.
1716 protected abstract deregisterWorkerMessageListener
<
1717 Message
extends Data
| Response
1719 workerNodeKey
: number,
1720 listener
: (message
: MessageValue
<Message
>) => void
1724 * Method hooked up after a worker node has been newly created.
1725 * Can be overridden.
1727 * @param workerNodeKey - The newly created worker node key.
1729 protected afterWorkerNodeSetup (workerNodeKey
: number): void {
1730 // Listen to worker messages.
1731 this.registerWorkerMessageListener(
1733 this.workerMessageListener
1735 // Send the startup message to worker.
1736 this.sendStartupMessageToWorker(workerNodeKey
)
1737 // Send the statistics message to worker.
1738 this.sendStatisticsMessageToWorker(workerNodeKey
)
1739 if (this.opts
.enableTasksQueue
=== true) {
1740 if (this.opts
.tasksQueueOptions
?.taskStealing
=== true) {
1741 this.workerNodes
[workerNodeKey
].on(
1743 this.handleWorkerNodeIdleEvent
1746 if (this.opts
.tasksQueueOptions
?.tasksStealingOnBackPressure
=== true) {
1747 this.workerNodes
[workerNodeKey
].on(
1749 this.handleWorkerNodeBackPressureEvent
1756 * Sends the startup message to worker given its worker node key.
1758 * @param workerNodeKey - The worker node key.
1760 protected abstract sendStartupMessageToWorker (workerNodeKey
: number): void
1763 * Sends the statistics message to worker given its worker node key.
1765 * @param workerNodeKey - The worker node key.
1767 private sendStatisticsMessageToWorker (workerNodeKey
: number): void {
1768 this.sendToWorker(workerNodeKey
, {
1771 this.workerChoiceStrategiesContext
?.getTaskStatisticsRequirements()
1772 .runTime
.aggregate
?? false,
1774 this.workerChoiceStrategiesContext
?.getTaskStatisticsRequirements()
1775 .elu
.aggregate
?? false
1780 private cannotStealTask (): boolean {
1781 return this.workerNodes
.length
<= 1 || this.info
.queuedTasks
=== 0
1784 private handleTask (workerNodeKey
: number, task
: Task
<Data
>): void {
1785 if (this.shallExecuteTask(workerNodeKey
)) {
1786 this.executeTask(workerNodeKey
, task
)
1788 this.enqueueTask(workerNodeKey
, task
)
1792 private redistributeQueuedTasks (sourceWorkerNodeKey
: number): void {
1793 if (sourceWorkerNodeKey
=== -1 || this.cannotStealTask()) {
1796 while (this.tasksQueueSize(sourceWorkerNodeKey
) > 0) {
1797 const destinationWorkerNodeKey
= this.workerNodes
.reduce(
1798 (minWorkerNodeKey
, workerNode
, workerNodeKey
, workerNodes
) => {
1799 return sourceWorkerNodeKey
!== workerNodeKey
&&
1800 workerNode
.info
.ready
&&
1801 workerNode
.usage
.tasks
.queued
<
1802 workerNodes
[minWorkerNodeKey
].usage
.tasks
.queued
1809 destinationWorkerNodeKey
,
1810 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1811 this.dequeueTask(sourceWorkerNodeKey
)!
1816 private updateTaskStolenStatisticsWorkerUsage (
1817 workerNodeKey
: number,
1820 const workerNode
= this.workerNodes
[workerNodeKey
]
1821 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1822 if (workerNode
?.usage
!= null) {
1823 ++workerNode
.usage
.tasks
.stolen
1826 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
1827 workerNode
.getTaskFunctionWorkerUsage(taskName
) != null
1829 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1830 ++workerNode
.getTaskFunctionWorkerUsage(taskName
)!.tasks
.stolen
1834 private updateTaskSequentiallyStolenStatisticsWorkerUsage (
1835 workerNodeKey
: number,
1837 previousTaskName
?: string
1839 const workerNode
= this.workerNodes
[workerNodeKey
]
1840 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1841 if (workerNode
?.usage
!= null) {
1842 ++workerNode
.usage
.tasks
.sequentiallyStolen
1845 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
1846 workerNode
.getTaskFunctionWorkerUsage(taskName
) != null
1848 const taskFunctionWorkerUsage
=
1849 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1850 workerNode
.getTaskFunctionWorkerUsage(taskName
)!
1852 taskFunctionWorkerUsage
.tasks
.sequentiallyStolen
=== 0 ||
1853 (previousTaskName
!= null &&
1854 previousTaskName
=== taskName
&&
1855 taskFunctionWorkerUsage
.tasks
.sequentiallyStolen
> 0)
1857 ++taskFunctionWorkerUsage
.tasks
.sequentiallyStolen
1858 } else if (taskFunctionWorkerUsage
.tasks
.sequentiallyStolen
> 0) {
1859 taskFunctionWorkerUsage
.tasks
.sequentiallyStolen
= 0
1864 private resetTaskSequentiallyStolenStatisticsWorkerUsage (
1865 workerNodeKey
: number,
1868 const workerNode
= this.workerNodes
[workerNodeKey
]
1869 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1870 if (workerNode
?.usage
!= null) {
1871 workerNode
.usage
.tasks
.sequentiallyStolen
= 0
1874 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
1875 workerNode
.getTaskFunctionWorkerUsage(taskName
) != null
1877 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1878 workerNode
.getTaskFunctionWorkerUsage(
1880 )!.tasks
.sequentiallyStolen
= 0
1884 private readonly handleWorkerNodeIdleEvent
= (
1885 eventDetail
: WorkerNodeEventDetail
,
1886 previousStolenTask
?: Task
<Data
>
1888 const { workerNodeKey
} = eventDetail
1889 if (workerNodeKey
== null) {
1891 "WorkerNode event detail 'workerNodeKey' property must be defined"
1894 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
1895 if (workerInfo
== null) {
1897 `Worker node with key '${workerNodeKey}' not found in pool`
1901 this.cannotStealTask() ||
1902 (this.info
.stealingWorkerNodes
?? 0) >
1903 Math.floor(this.workerNodes
.length
/ 2)
1905 if (previousStolenTask
!= null) {
1906 workerInfo
.stealing
= false
1907 this.resetTaskSequentiallyStolenStatisticsWorkerUsage(
1909 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1910 previousStolenTask
.name
!
1915 const workerNodeTasksUsage
= this.workerNodes
[workerNodeKey
].usage
.tasks
1917 previousStolenTask
!= null &&
1918 (workerNodeTasksUsage
.executing
> 0 ||
1919 this.tasksQueueSize(workerNodeKey
) > 0)
1921 workerInfo
.stealing
= false
1922 this.resetTaskSequentiallyStolenStatisticsWorkerUsage(
1924 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1925 previousStolenTask
.name
!
1929 workerInfo
.stealing
= true
1930 const stolenTask
= this.workerNodeStealTask(workerNodeKey
)
1931 if (stolenTask
!= null) {
1932 this.updateTaskSequentiallyStolenStatisticsWorkerUsage(
1934 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1936 previousStolenTask
?.name
1939 sleep(exponentialDelay(workerNodeTasksUsage
.sequentiallyStolen
))
1941 this.handleWorkerNodeIdleEvent(eventDetail
, stolenTask
)
1944 .catch((error
: unknown
) => {
1945 this.emitter
?.emit(PoolEvents
.error
, error
)
1949 private readonly workerNodeStealTask
= (
1950 workerNodeKey
: number
1951 ): Task
<Data
> | undefined => {
1952 const workerNodes
= this.workerNodes
1955 (workerNodeA
, workerNodeB
) =>
1956 workerNodeB
.usage
.tasks
.queued
- workerNodeA
.usage
.tasks
.queued
1958 const sourceWorkerNode
= workerNodes
.find(
1959 (sourceWorkerNode
, sourceWorkerNodeKey
) =>
1960 sourceWorkerNode
.info
.ready
&&
1961 !sourceWorkerNode
.info
.stealing
&&
1962 sourceWorkerNodeKey
!== workerNodeKey
&&
1963 sourceWorkerNode
.usage
.tasks
.queued
> 0
1965 if (sourceWorkerNode
!= null) {
1966 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1967 const task
= sourceWorkerNode
.dequeueLastPrioritizedTask()!
1968 this.handleTask(workerNodeKey
, task
)
1969 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1970 this.updateTaskStolenStatisticsWorkerUsage(workerNodeKey
, task
.name
!)
1975 private readonly handleWorkerNodeBackPressureEvent
= (
1976 eventDetail
: WorkerNodeEventDetail
1979 this.cannotStealTask() ||
1980 this.hasBackPressure() ||
1981 (this.info
.stealingWorkerNodes
?? 0) >
1982 Math.floor(this.workerNodes
.length
/ 2)
1986 const sizeOffset
= 1
1987 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1988 if (this.opts
.tasksQueueOptions
!.size
! <= sizeOffset
) {
1991 const { workerId
} = eventDetail
1992 const sourceWorkerNode
=
1993 this.workerNodes
[this.getWorkerNodeKeyByWorkerId(workerId
)]
1994 const workerNodes
= this.workerNodes
1997 (workerNodeA
, workerNodeB
) =>
1998 workerNodeA
.usage
.tasks
.queued
- workerNodeB
.usage
.tasks
.queued
2000 for (const [workerNodeKey
, workerNode
] of workerNodes
.entries()) {
2002 sourceWorkerNode
.usage
.tasks
.queued
> 0 &&
2003 workerNode
.info
.ready
&&
2004 !workerNode
.info
.stealing
&&
2005 workerNode
.info
.id
!== workerId
&&
2006 workerNode
.usage
.tasks
.queued
<
2007 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2008 this.opts
.tasksQueueOptions
!.size
! - sizeOffset
2010 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
2011 if (workerInfo
== null) {
2013 `Worker node with key '${workerNodeKey}' not found in pool`
2016 workerInfo
.stealing
= true
2017 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2018 const task
= sourceWorkerNode
.dequeueLastPrioritizedTask()!
2019 this.handleTask(workerNodeKey
, task
)
2020 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2021 this.updateTaskStolenStatisticsWorkerUsage(workerNodeKey
, task
.name
!)
2022 workerInfo
.stealing
= false
2028 * This method is the message listener registered on each worker.
2030 protected readonly workerMessageListener
= (
2031 message
: MessageValue
<Response
>
2033 this.checkMessageWorkerId(message
)
2034 const { workerId
, ready
, taskId
, taskFunctionsProperties
} = message
2035 if (ready
!= null && taskFunctionsProperties
!= null) {
2036 // Worker ready response received from worker
2037 this.handleWorkerReadyResponse(message
)
2038 } else if (taskFunctionsProperties
!= null) {
2039 // Task function properties message received from worker
2040 const workerNodeKey
= this.getWorkerNodeKeyByWorkerId(workerId
)
2041 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
2042 if (workerInfo
!= null) {
2043 workerInfo
.taskFunctionsProperties
= taskFunctionsProperties
2044 this.sendStatisticsMessageToWorker(workerNodeKey
)
2046 } else if (taskId
!= null) {
2047 // Task execution response received from worker
2048 this.handleTaskExecutionResponse(message
)
2052 private checkAndEmitReadyEvent (): void {
2053 if (!this.readyEventEmitted
&& this.ready
) {
2054 this.emitter
?.emit(PoolEvents
.ready
, this.info
)
2055 this.readyEventEmitted
= true
2059 private handleWorkerReadyResponse (message
: MessageValue
<Response
>): void {
2060 const { workerId
, ready
, taskFunctionsProperties
} = message
2061 if (ready
== null || !ready
) {
2062 throw new Error(`Worker ${workerId} failed to initialize`)
2064 const workerNodeKey
= this.getWorkerNodeKeyByWorkerId(workerId
)
2065 const workerNode
= this.workerNodes
[workerNodeKey
]
2066 workerNode
.info
.ready
= ready
2067 workerNode
.info
.taskFunctionsProperties
= taskFunctionsProperties
2068 this.sendStatisticsMessageToWorker(workerNodeKey
)
2069 this.checkAndEmitReadyEvent()
2072 private handleTaskExecutionResponse (message
: MessageValue
<Response
>): void {
2073 const { workerId
, taskId
, workerError
, data
} = message
2074 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2075 const promiseResponse
= this.promiseResponseMap
.get(taskId
!)
2076 if (promiseResponse
!= null) {
2077 const { resolve
, reject
, workerNodeKey
, asyncResource
} = promiseResponse
2078 const workerNode
= this.workerNodes
[workerNodeKey
]
2079 if (workerError
!= null) {
2080 this.emitter
?.emit(PoolEvents
.taskError
, workerError
)
2081 asyncResource
!= null
2082 ? asyncResource
.runInAsyncScope(
2087 : reject(workerError
.message
)
2089 asyncResource
!= null
2090 ? asyncResource
.runInAsyncScope(resolve
, this.emitter
, data
)
2091 : resolve(data
as Response
)
2093 asyncResource
?.emitDestroy()
2094 this.afterTaskExecutionHook(workerNodeKey
, message
)
2095 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2096 this.promiseResponseMap
.delete(taskId
!)
2097 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
2098 workerNode
?.emit('taskFinished', taskId
)
2100 this.opts
.enableTasksQueue
=== true &&
2102 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
2105 const workerNodeTasksUsage
= workerNode
.usage
.tasks
2107 this.tasksQueueSize(workerNodeKey
) > 0 &&
2108 workerNodeTasksUsage
.executing
<
2109 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2110 this.opts
.tasksQueueOptions
!.concurrency
!
2112 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2113 this.executeTask(workerNodeKey
, this.dequeueTask(workerNodeKey
)!)
2116 workerNodeTasksUsage
.executing
=== 0 &&
2117 this.tasksQueueSize(workerNodeKey
) === 0 &&
2118 workerNodeTasksUsage
.sequentiallyStolen
=== 0
2120 workerNode
.emit('idle', {
2129 private checkAndEmitTaskExecutionEvents (): void {
2131 this.emitter
?.emit(PoolEvents
.busy
, this.info
)
2135 private checkAndEmitTaskQueuingEvents (): void {
2136 if (this.hasBackPressure()) {
2137 this.emitter
?.emit(PoolEvents
.backPressure
, this.info
)
2142 * Emits dynamic worker creation events.
2144 protected abstract checkAndEmitDynamicWorkerCreationEvents (): void
2147 * Gets the worker information given its worker node key.
2149 * @param workerNodeKey - The worker node key.
2150 * @returns The worker information.
2152 protected getWorkerInfo (workerNodeKey
: number): WorkerInfo
| undefined {
2153 return this.workerNodes
[workerNodeKey
]?.info
2157 * Creates a worker node.
2159 * @returns The created worker node.
2161 private createWorkerNode (): IWorkerNode
<Worker
, Data
> {
2162 const workerNode
= new WorkerNode
<Worker
, Data
>(
2167 workerOptions
: this.opts
.workerOptions
,
2168 tasksQueueBackPressureSize
:
2169 this.opts
.tasksQueueOptions
?.size
??
2170 getDefaultTasksQueueOptions(
2171 this.maximumNumberOfWorkers
?? this.minimumNumberOfWorkers
2173 tasksQueueBucketSize
:
2174 (this.maximumNumberOfWorkers
?? this.minimumNumberOfWorkers
) * 2
2177 // Flag the worker node as ready at pool startup.
2178 if (this.starting
) {
2179 workerNode
.info
.ready
= true
2185 * Adds the given worker node in the pool worker nodes.
2187 * @param workerNode - The worker node.
2188 * @returns The added worker node key.
2189 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the added worker node is not found.
2191 private addWorkerNode (workerNode
: IWorkerNode
<Worker
, Data
>): number {
2192 this.workerNodes
.push(workerNode
)
2193 const workerNodeKey
= this.workerNodes
.indexOf(workerNode
)
2194 if (workerNodeKey
=== -1) {
2195 throw new Error('Worker added not found in worker nodes')
2197 return workerNodeKey
2200 private checkAndEmitEmptyEvent (): void {
2202 this.emitter
?.emit(PoolEvents
.empty
, this.info
)
2203 this.readyEventEmitted
= false
2208 * Removes the worker node from the pool worker nodes.
2210 * @param workerNode - The worker node.
2212 private removeWorkerNode (workerNode
: IWorkerNode
<Worker
, Data
>): void {
2213 const workerNodeKey
= this.workerNodes
.indexOf(workerNode
)
2214 if (workerNodeKey
!== -1) {
2215 this.workerNodes
.splice(workerNodeKey
, 1)
2216 this.workerChoiceStrategiesContext
?.remove(workerNodeKey
)
2218 this.checkAndEmitEmptyEvent()
2221 protected flagWorkerNodeAsNotReady (workerNodeKey
: number): void {
2222 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
2223 if (workerInfo
!= null) {
2224 workerInfo
.ready
= false
2228 private hasBackPressure (): boolean {
2230 this.opts
.enableTasksQueue
=== true &&
2231 this.workerNodes
.findIndex(
2232 workerNode
=> !workerNode
.hasBackPressure()
2238 * Executes the given task on the worker given its worker node key.
2240 * @param workerNodeKey - The worker node key.
2241 * @param task - The task to execute.
2243 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
2244 this.beforeTaskExecutionHook(workerNodeKey
, task
)
2245 this.sendToWorker(workerNodeKey
, task
, task
.transferList
)
2246 this.checkAndEmitTaskExecutionEvents()
2249 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
2250 const tasksQueueSize
= this.workerNodes
[workerNodeKey
].enqueueTask(task
)
2251 this.checkAndEmitTaskQueuingEvents()
2252 return tasksQueueSize
2255 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
2256 return this.workerNodes
[workerNodeKey
].dequeueTask()
2259 private tasksQueueSize (workerNodeKey
: number): number {
2260 return this.workerNodes
[workerNodeKey
].tasksQueueSize()
2263 protected flushTasksQueue (workerNodeKey
: number): number {
2264 let flushedTasks
= 0
2265 while (this.tasksQueueSize(workerNodeKey
) > 0) {
2266 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2267 this.executeTask(workerNodeKey
, this.dequeueTask(workerNodeKey
)!)
2270 this.workerNodes
[workerNodeKey
].clearTasksQueue()
2274 private flushTasksQueues (): void {
2275 for (const workerNodeKey
of this.workerNodes
.keys()) {
2276 this.flushTasksQueue(workerNodeKey
)