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'
7 import { defaultBucketSize
} from
'../priority-queue.js'
10 PromiseResponseWrapper
,
12 TaskFunctionProperties
,
13 } from
'../utility-types.js'
16 buildTaskFunctionProperties
,
31 } from
'../worker/task-functions.js'
32 import { KillBehaviors
} from
'../worker/worker-options.js'
40 type TasksQueueOptions
,
44 WorkerChoiceStrategies
,
45 type WorkerChoiceStrategy
,
46 type WorkerChoiceStrategyOptions
,
47 } from
'./selection-strategies/selection-strategies-types.js'
48 import { WorkerChoiceStrategiesContext
} from
'./selection-strategies/worker-choice-strategies-context.js'
52 checkValidTasksQueueOptions
,
53 checkValidWorkerChoiceStrategy
,
54 getDefaultTasksQueueOptions
,
56 updateRunTimeWorkerUsage
,
57 updateTaskStatisticsWorkerUsage
,
58 updateWaitTimeWorkerUsage
,
61 import { version
} from
'./version.js'
66 WorkerNodeEventDetail
,
69 import { WorkerNode
} from
'./worker-node.js'
72 * 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
: 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.
149 * @param minimumNumberOfWorkers - Minimum number of workers that this pool manages.
150 * @param filePath - Path to the worker file.
151 * @param opts - Options for the pool.
152 * @param maximumNumberOfWorkers - Maximum number of workers that this pool manages.
155 protected readonly minimumNumberOfWorkers
: number,
156 protected readonly filePath
: string,
157 protected readonly opts
: PoolOptions
<Worker
>,
158 protected readonly maximumNumberOfWorkers
?: number
160 if (!this.isMain()) {
162 'Cannot start a pool from a worker with the same type as the pool'
166 checkFilePath(this.filePath
)
167 this.checkMinimumNumberOfWorkers(this.minimumNumberOfWorkers
)
168 this.checkPoolOptions(this.opts
)
170 this.chooseWorkerNode
= this.chooseWorkerNode
.bind(this)
171 this.executeTask
= this.executeTask
.bind(this)
172 this.enqueueTask
= this.enqueueTask
.bind(this)
174 if (this.opts
.enableEvents
=== true) {
175 this.initEventEmitter()
177 this.workerChoiceStrategiesContext
= new WorkerChoiceStrategiesContext
<
183 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
184 [this.opts
.workerChoiceStrategy
!],
185 this.opts
.workerChoiceStrategyOptions
190 this.taskFunctions
= new Map
<string, TaskFunctionObject
<Data
, Response
>>()
193 this.starting
= false
194 this.destroying
= false
195 this.readyEventEmitted
= false
196 this.startingMinimumNumberOfWorkers
= false
197 if (this.opts
.startWorkers
=== true) {
202 private checkPoolType (): void {
203 if (this.type === PoolTypes
.fixed
&& this.maximumNumberOfWorkers
!= null) {
205 'Cannot instantiate a fixed pool with a maximum number of workers specified at initialization'
210 private checkMinimumNumberOfWorkers (
211 minimumNumberOfWorkers
: number | undefined
213 if (minimumNumberOfWorkers
== null) {
215 'Cannot instantiate a pool without specifying the number of workers'
217 } else if (!Number.isSafeInteger(minimumNumberOfWorkers
)) {
219 'Cannot instantiate a pool with a non safe integer number of workers'
221 } else if (minimumNumberOfWorkers
< 0) {
222 throw new RangeError(
223 'Cannot instantiate a pool with a negative number of workers'
225 } else if (this.type === PoolTypes
.fixed
&& minimumNumberOfWorkers
=== 0) {
226 throw new RangeError('Cannot instantiate a fixed pool with zero worker')
230 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
231 if (isPlainObject(opts
)) {
232 this.opts
.startWorkers
= opts
.startWorkers
?? true
233 checkValidWorkerChoiceStrategy(opts
.workerChoiceStrategy
)
234 this.opts
.workerChoiceStrategy
=
235 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
236 this.checkValidWorkerChoiceStrategyOptions(
237 opts
.workerChoiceStrategyOptions
239 if (opts
.workerChoiceStrategyOptions
!= null) {
240 this.opts
.workerChoiceStrategyOptions
= opts
.workerChoiceStrategyOptions
242 this.opts
.restartWorkerOnError
= opts
.restartWorkerOnError
?? true
243 this.opts
.enableEvents
= opts
.enableEvents
?? true
244 this.opts
.enableTasksQueue
= opts
.enableTasksQueue
?? false
245 if (this.opts
.enableTasksQueue
) {
246 checkValidTasksQueueOptions(opts
.tasksQueueOptions
)
247 this.opts
.tasksQueueOptions
= this.buildTasksQueueOptions(
248 opts
.tasksQueueOptions
252 throw new TypeError('Invalid pool options: must be a plain object')
256 private checkValidWorkerChoiceStrategyOptions (
257 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
| undefined
260 workerChoiceStrategyOptions
!= null &&
261 !isPlainObject(workerChoiceStrategyOptions
)
264 'Invalid worker choice strategy options: must be a plain object'
268 workerChoiceStrategyOptions
?.weights
!= null &&
269 Object.keys(workerChoiceStrategyOptions
.weights
).length
!==
270 (this.maximumNumberOfWorkers
?? this.minimumNumberOfWorkers
)
273 'Invalid worker choice strategy options: must have a weight for each worker node'
277 workerChoiceStrategyOptions
?.measurement
!= null &&
278 !Object.values(Measurements
).includes(
279 workerChoiceStrategyOptions
.measurement
283 `Invalid worker choice strategy options: invalid measurement '${workerChoiceStrategyOptions.measurement}'`
288 private initEventEmitter (): void {
289 this.emitter
= new EventEmitterAsyncResource({
290 name
: `poolifier:${this.type}-${this.worker}-pool`,
295 public get
info (): PoolInfo
{
300 started
: this.started
,
302 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
303 defaultStrategy
: this.opts
.workerChoiceStrategy
!,
304 strategyRetries
: this.workerChoiceStrategiesContext
?.retriesCount
?? 0,
305 minSize
: this.minimumNumberOfWorkers
,
306 maxSize
: this.maximumNumberOfWorkers
?? this.minimumNumberOfWorkers
,
307 ...(this.workerChoiceStrategiesContext
?.getTaskStatisticsRequirements()
308 .runTime
.aggregate
=== true &&
309 this.workerChoiceStrategiesContext
.getTaskStatisticsRequirements()
310 .waitTime
.aggregate
&& {
311 utilization
: round(this.utilization
),
313 workerNodes
: this.workerNodes
.length
,
314 idleWorkerNodes
: this.workerNodes
.reduce(
315 (accumulator
, workerNode
) =>
316 workerNode
.usage
.tasks
.executing
=== 0
321 ...(this.opts
.enableTasksQueue
=== true && {
322 stealingWorkerNodes
: this.workerNodes
.reduce(
323 (accumulator
, workerNode
) =>
324 workerNode
.info
.stealing
? accumulator
+ 1 : accumulator
,
328 busyWorkerNodes
: this.workerNodes
.reduce(
329 (accumulator
, _
, workerNodeKey
) =>
330 this.isWorkerNodeBusy(workerNodeKey
) ? accumulator
+ 1 : accumulator
,
333 executedTasks
: this.workerNodes
.reduce(
334 (accumulator
, workerNode
) =>
335 accumulator
+ workerNode
.usage
.tasks
.executed
,
338 executingTasks
: this.workerNodes
.reduce(
339 (accumulator
, workerNode
) =>
340 accumulator
+ workerNode
.usage
.tasks
.executing
,
343 ...(this.opts
.enableTasksQueue
=== true && {
344 queuedTasks
: this.workerNodes
.reduce(
345 (accumulator
, workerNode
) =>
346 accumulator
+ workerNode
.usage
.tasks
.queued
,
350 ...(this.opts
.enableTasksQueue
=== true && {
351 maxQueuedTasks
: this.workerNodes
.reduce(
352 (accumulator
, workerNode
) =>
353 accumulator
+ (workerNode
.usage
.tasks
.maxQueued
?? 0),
357 ...(this.opts
.enableTasksQueue
=== true && {
358 backPressure
: this.hasBackPressure(),
360 ...(this.opts
.enableTasksQueue
=== true && {
361 stolenTasks
: this.workerNodes
.reduce(
362 (accumulator
, workerNode
) =>
363 accumulator
+ workerNode
.usage
.tasks
.stolen
,
367 failedTasks
: this.workerNodes
.reduce(
368 (accumulator
, workerNode
) =>
369 accumulator
+ workerNode
.usage
.tasks
.failed
,
372 ...(this.workerChoiceStrategiesContext
?.getTaskStatisticsRequirements()
373 .runTime
.aggregate
=== true && {
377 ...this.workerNodes
.map(
379 workerNode
.usage
.runTime
.minimum
?? Number.POSITIVE_INFINITY
385 ...this.workerNodes
.map(
387 workerNode
.usage
.runTime
.maximum
?? Number.NEGATIVE_INFINITY
391 ...(this.workerChoiceStrategiesContext
.getTaskStatisticsRequirements()
392 .runTime
.average
&& {
395 this.workerNodes
.reduce
<number[]>(
396 (accumulator
, workerNode
) =>
398 workerNode
.usage
.runTime
.history
.toArray()
405 ...(this.workerChoiceStrategiesContext
.getTaskStatisticsRequirements()
409 this.workerNodes
.reduce
<number[]>(
410 (accumulator
, workerNode
) =>
412 workerNode
.usage
.runTime
.history
.toArray()
421 ...(this.workerChoiceStrategiesContext
?.getTaskStatisticsRequirements()
422 .waitTime
.aggregate
=== true && {
426 ...this.workerNodes
.map(
428 workerNode
.usage
.waitTime
.minimum
?? Number.POSITIVE_INFINITY
434 ...this.workerNodes
.map(
436 workerNode
.usage
.waitTime
.maximum
?? Number.NEGATIVE_INFINITY
440 ...(this.workerChoiceStrategiesContext
.getTaskStatisticsRequirements()
441 .waitTime
.average
&& {
444 this.workerNodes
.reduce
<number[]>(
445 (accumulator
, workerNode
) =>
447 workerNode
.usage
.waitTime
.history
.toArray()
454 ...(this.workerChoiceStrategiesContext
.getTaskStatisticsRequirements()
455 .waitTime
.median
&& {
458 this.workerNodes
.reduce
<number[]>(
459 (accumulator
, workerNode
) =>
461 workerNode
.usage
.waitTime
.history
.toArray()
470 ...(this.workerChoiceStrategiesContext
?.getTaskStatisticsRequirements()
471 .elu
.aggregate
=== true && {
476 ...this.workerNodes
.map(
478 workerNode
.usage
.elu
.idle
.minimum
??
479 Number.POSITIVE_INFINITY
485 ...this.workerNodes
.map(
487 workerNode
.usage
.elu
.idle
.maximum
??
488 Number.NEGATIVE_INFINITY
492 ...(this.workerChoiceStrategiesContext
.getTaskStatisticsRequirements()
496 this.workerNodes
.reduce
<number[]>(
497 (accumulator
, workerNode
) =>
499 workerNode
.usage
.elu
.idle
.history
.toArray()
506 ...(this.workerChoiceStrategiesContext
.getTaskStatisticsRequirements()
510 this.workerNodes
.reduce
<number[]>(
511 (accumulator
, workerNode
) =>
513 workerNode
.usage
.elu
.idle
.history
.toArray()
524 ...this.workerNodes
.map(
526 workerNode
.usage
.elu
.active
.minimum
??
527 Number.POSITIVE_INFINITY
533 ...this.workerNodes
.map(
535 workerNode
.usage
.elu
.active
.maximum
??
536 Number.NEGATIVE_INFINITY
540 ...(this.workerChoiceStrategiesContext
.getTaskStatisticsRequirements()
544 this.workerNodes
.reduce
<number[]>(
545 (accumulator
, workerNode
) =>
547 workerNode
.usage
.elu
.active
.history
.toArray()
554 ...(this.workerChoiceStrategiesContext
.getTaskStatisticsRequirements()
558 this.workerNodes
.reduce
<number[]>(
559 (accumulator
, workerNode
) =>
561 workerNode
.usage
.elu
.active
.history
.toArray()
572 this.workerNodes
.map(
573 workerNode
=> workerNode
.usage
.elu
.utilization
?? 0
579 this.workerNodes
.map(
580 workerNode
=> workerNode
.usage
.elu
.utilization
?? 0
591 * The pool readiness boolean status.
593 private get
ready (): boolean {
598 this.workerNodes
.reduce(
599 (accumulator
, workerNode
) =>
600 !workerNode
.info
.dynamic
&& workerNode
.info
.ready
604 ) >= this.minimumNumberOfWorkers
609 * The pool emptiness boolean status.
611 protected get
empty (): boolean {
612 return this.minimumNumberOfWorkers
=== 0 && this.workerNodes
.length
=== 0
616 * The approximate pool utilization.
617 * @returns The pool utilization.
619 private get
utilization (): number {
620 if (this.startTimestamp
== null) {
623 const poolTimeCapacity
=
624 (performance
.now() - this.startTimestamp
) *
625 (this.maximumNumberOfWorkers
?? this.minimumNumberOfWorkers
)
626 const totalTasksRunTime
= this.workerNodes
.reduce(
627 (accumulator
, workerNode
) =>
628 accumulator
+ (workerNode
.usage
.runTime
.aggregate
?? 0),
631 const totalTasksWaitTime
= this.workerNodes
.reduce(
632 (accumulator
, workerNode
) =>
633 accumulator
+ (workerNode
.usage
.waitTime
.aggregate
?? 0),
636 return (totalTasksRunTime
+ totalTasksWaitTime
) / poolTimeCapacity
642 * If it is `'dynamic'`, it provides the `max` property.
644 protected abstract get
type (): PoolType
649 protected abstract get
worker (): WorkerType
652 * Checks if the worker id sent in the received message from a worker is valid.
653 * @param message - The received message.
654 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the worker id is invalid.
656 private checkMessageWorkerId (message
: MessageValue
<Data
| Response
>): void {
657 if (message
.workerId
== null) {
658 throw new Error('Worker message received without worker id')
659 } else if (this.getWorkerNodeKeyByWorkerId(message
.workerId
) === -1) {
661 `Worker message received from unknown worker '${message.workerId}'`
667 * Gets the worker node key given its worker id.
668 * @param workerId - The worker id.
669 * @returns The worker node key if the worker id is found in the pool worker nodes, `-1` otherwise.
671 private getWorkerNodeKeyByWorkerId (workerId
: number | undefined): number {
672 return this.workerNodes
.findIndex(
673 workerNode
=> workerNode
.info
.id
=== workerId
678 public setWorkerChoiceStrategy (
679 workerChoiceStrategy
: WorkerChoiceStrategy
,
680 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
682 let requireSync
= false
683 checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
684 if (workerChoiceStrategyOptions
!= null) {
685 requireSync
= !this.setWorkerChoiceStrategyOptions(
686 workerChoiceStrategyOptions
689 if (workerChoiceStrategy
!== this.opts
.workerChoiceStrategy
) {
690 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
691 this.workerChoiceStrategiesContext
?.setDefaultWorkerChoiceStrategy(
692 this.opts
.workerChoiceStrategy
,
693 this.opts
.workerChoiceStrategyOptions
698 this.workerChoiceStrategiesContext
?.syncWorkerChoiceStrategies(
699 this.getWorkerChoiceStrategies(),
700 this.opts
.workerChoiceStrategyOptions
702 for (const workerNodeKey
of this.workerNodes
.keys()) {
703 this.sendStatisticsMessageToWorker(workerNodeKey
)
709 public setWorkerChoiceStrategyOptions (
710 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
| undefined
712 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
713 if (workerChoiceStrategyOptions
!= null) {
714 this.opts
.workerChoiceStrategyOptions
= workerChoiceStrategyOptions
715 this.workerChoiceStrategiesContext
?.setOptions(
716 this.opts
.workerChoiceStrategyOptions
718 this.workerChoiceStrategiesContext
?.syncWorkerChoiceStrategies(
719 this.getWorkerChoiceStrategies(),
720 this.opts
.workerChoiceStrategyOptions
722 for (const workerNodeKey
of this.workerNodes
.keys()) {
723 this.sendStatisticsMessageToWorker(workerNodeKey
)
731 public enableTasksQueue (
733 tasksQueueOptions
?: TasksQueueOptions
735 if (this.opts
.enableTasksQueue
=== true && !enable
) {
736 this.unsetTaskStealing()
737 this.unsetTasksStealingOnBackPressure()
738 this.flushTasksQueues()
740 this.opts
.enableTasksQueue
= enable
741 this.setTasksQueueOptions(tasksQueueOptions
)
745 public setTasksQueueOptions (
746 tasksQueueOptions
: TasksQueueOptions
| undefined
748 if (this.opts
.enableTasksQueue
=== true) {
749 checkValidTasksQueueOptions(tasksQueueOptions
)
750 this.opts
.tasksQueueOptions
=
751 this.buildTasksQueueOptions(tasksQueueOptions
)
752 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
753 this.setTasksQueueSize(this.opts
.tasksQueueOptions
.size
!)
754 if (this.opts
.tasksQueueOptions
.taskStealing
=== true) {
755 this.unsetTaskStealing()
756 this.setTaskStealing()
758 this.unsetTaskStealing()
760 if (this.opts
.tasksQueueOptions
.tasksStealingOnBackPressure
=== true) {
761 this.unsetTasksStealingOnBackPressure()
762 this.setTasksStealingOnBackPressure()
764 this.unsetTasksStealingOnBackPressure()
766 } else if (this.opts
.tasksQueueOptions
!= null) {
767 delete this.opts
.tasksQueueOptions
771 private buildTasksQueueOptions (
772 tasksQueueOptions
: TasksQueueOptions
| undefined
773 ): TasksQueueOptions
{
775 ...getDefaultTasksQueueOptions(
776 this.maximumNumberOfWorkers
?? this.minimumNumberOfWorkers
778 ...tasksQueueOptions
,
782 private setTasksQueueSize (size
: number): void {
783 for (const workerNode
of this.workerNodes
) {
784 workerNode
.tasksQueueBackPressureSize
= size
788 private setTaskStealing (): void {
789 for (const workerNodeKey
of this.workerNodes
.keys()) {
790 this.workerNodes
[workerNodeKey
].on('idle', this.handleWorkerNodeIdleEvent
)
794 private unsetTaskStealing (): void {
795 for (const workerNodeKey
of this.workerNodes
.keys()) {
796 this.workerNodes
[workerNodeKey
].off(
798 this.handleWorkerNodeIdleEvent
803 private setTasksStealingOnBackPressure (): void {
804 for (const workerNodeKey
of this.workerNodes
.keys()) {
805 this.workerNodes
[workerNodeKey
].on(
807 this.handleWorkerNodeBackPressureEvent
812 private unsetTasksStealingOnBackPressure (): void {
813 for (const workerNodeKey
of this.workerNodes
.keys()) {
814 this.workerNodes
[workerNodeKey
].off(
816 this.handleWorkerNodeBackPressureEvent
822 * Whether the pool is full or not.
824 * The pool filling boolean status.
826 protected get
full (): boolean {
828 this.workerNodes
.length
>=
829 (this.maximumNumberOfWorkers
?? this.minimumNumberOfWorkers
)
834 * Whether the pool is busy or not.
836 * The pool busyness boolean status.
838 protected abstract get
busy (): boolean
841 * Whether worker nodes are executing concurrently their tasks quota or not.
842 * @returns Worker nodes busyness boolean status.
844 protected internalBusy (): boolean {
845 if (this.opts
.enableTasksQueue
=== true) {
847 this.workerNodes
.findIndex(
849 workerNode
.info
.ready
&&
850 workerNode
.usage
.tasks
.executing
<
851 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
852 this.opts
.tasksQueueOptions
!.concurrency
!
857 this.workerNodes
.findIndex(
859 workerNode
.info
.ready
&& workerNode
.usage
.tasks
.executing
=== 0
864 private isWorkerNodeBusy (workerNodeKey
: number): boolean {
865 if (this.opts
.enableTasksQueue
=== true) {
867 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
>=
868 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
869 this.opts
.tasksQueueOptions
!.concurrency
!
872 return this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
> 0
875 private async sendTaskFunctionOperationToWorker (
876 workerNodeKey
: number,
877 message
: MessageValue
<Data
>
878 ): Promise
<boolean> {
879 return await new Promise
<boolean>((resolve
, reject
) => {
880 const taskFunctionOperationListener
= (
881 message
: MessageValue
<Response
>
883 this.checkMessageWorkerId(message
)
884 const workerId
= this.getWorkerInfo(workerNodeKey
)?.id
886 message
.taskFunctionOperationStatus
!= null &&
887 message
.workerId
=== workerId
889 if (message
.taskFunctionOperationStatus
) {
894 `Task function operation '${message.taskFunctionOperation}' failed on worker ${message.workerId} with error: '${message.workerError?.message}'`
898 this.deregisterWorkerMessageListener(
899 this.getWorkerNodeKeyByWorkerId(message
.workerId
),
900 taskFunctionOperationListener
904 this.registerWorkerMessageListener(
906 taskFunctionOperationListener
908 this.sendToWorker(workerNodeKey
, message
)
912 private async sendTaskFunctionOperationToWorkers (
913 message
: MessageValue
<Data
>
914 ): Promise
<boolean> {
915 return await new Promise
<boolean>((resolve
, reject
) => {
916 const responsesReceived
= new Array<MessageValue
<Response
>>()
917 const taskFunctionOperationsListener
= (
918 message
: MessageValue
<Response
>
920 this.checkMessageWorkerId(message
)
921 if (message
.taskFunctionOperationStatus
!= null) {
922 responsesReceived
.push(message
)
923 if (responsesReceived
.length
=== this.workerNodes
.length
) {
925 responsesReceived
.every(
926 message
=> message
.taskFunctionOperationStatus
=== true
931 responsesReceived
.some(
932 message
=> message
.taskFunctionOperationStatus
=== false
935 const errorResponse
= responsesReceived
.find(
936 response
=> response
.taskFunctionOperationStatus
=== false
940 `Task function operation '${
941 message.taskFunctionOperation as string
942 }' failed on worker ${errorResponse?.workerId} with error: '${
943 errorResponse?.workerError?.message
948 this.deregisterWorkerMessageListener(
949 this.getWorkerNodeKeyByWorkerId(message
.workerId
),
950 taskFunctionOperationsListener
955 for (const workerNodeKey
of this.workerNodes
.keys()) {
956 this.registerWorkerMessageListener(
958 taskFunctionOperationsListener
960 this.sendToWorker(workerNodeKey
, message
)
966 public hasTaskFunction (name
: string): boolean {
967 return this.listTaskFunctionsProperties().some(
968 taskFunctionProperties
=> taskFunctionProperties
.name
=== name
973 public async addTaskFunction (
975 fn
: TaskFunction
<Data
, Response
> | TaskFunctionObject
<Data
, Response
>
976 ): Promise
<boolean> {
977 if (typeof name
!== 'string') {
978 throw new TypeError('name argument must be a string')
980 if (typeof name
=== 'string' && name
.trim().length
=== 0) {
981 throw new TypeError('name argument must not be an empty string')
983 if (typeof fn
=== 'function') {
984 fn
= { taskFunction
: fn
} satisfies TaskFunctionObject
<Data
, Response
>
986 if (typeof fn
.taskFunction
!== 'function') {
987 throw new TypeError('taskFunction property must be a function')
989 checkValidPriority(fn
.priority
)
990 checkValidWorkerChoiceStrategy(fn
.strategy
)
991 const opResult
= await this.sendTaskFunctionOperationToWorkers({
992 taskFunctionOperation
: 'add',
993 taskFunctionProperties
: buildTaskFunctionProperties(name
, fn
),
994 taskFunction
: fn
.taskFunction
.toString(),
996 this.taskFunctions
.set(name
, fn
)
997 this.workerChoiceStrategiesContext
?.syncWorkerChoiceStrategies(
998 this.getWorkerChoiceStrategies()
1000 for (const workerNodeKey
of this.workerNodes
.keys()) {
1001 this.sendStatisticsMessageToWorker(workerNodeKey
)
1007 public async removeTaskFunction (name
: string): Promise
<boolean> {
1008 if (!this.taskFunctions
.has(name
)) {
1010 'Cannot remove a task function not handled on the pool side'
1013 const opResult
= await this.sendTaskFunctionOperationToWorkers({
1014 taskFunctionOperation
: 'remove',
1015 taskFunctionProperties
: buildTaskFunctionProperties(
1017 this.taskFunctions
.get(name
)
1020 for (const workerNode
of this.workerNodes
) {
1021 workerNode
.deleteTaskFunctionWorkerUsage(name
)
1023 this.taskFunctions
.delete(name
)
1024 this.workerChoiceStrategiesContext
?.syncWorkerChoiceStrategies(
1025 this.getWorkerChoiceStrategies()
1027 for (const workerNodeKey
of this.workerNodes
.keys()) {
1028 this.sendStatisticsMessageToWorker(workerNodeKey
)
1034 public listTaskFunctionsProperties (): TaskFunctionProperties
[] {
1035 for (const workerNode
of this.workerNodes
) {
1037 Array.isArray(workerNode
.info
.taskFunctionsProperties
) &&
1038 workerNode
.info
.taskFunctionsProperties
.length
> 0
1040 return workerNode
.info
.taskFunctionsProperties
1047 * Gets task function worker choice strategy, if any.
1048 * @param name - The task function name.
1049 * @returns The task function worker choice strategy if the task function worker choice strategy is defined, `undefined` otherwise.
1051 private readonly getTaskFunctionWorkerChoiceStrategy
= (
1053 ): WorkerChoiceStrategy
| undefined => {
1054 name
= name
?? DEFAULT_TASK_NAME
1055 const taskFunctionsProperties
= this.listTaskFunctionsProperties()
1056 if (name
=== DEFAULT_TASK_NAME
) {
1057 name
= taskFunctionsProperties
[1]?.name
1059 return taskFunctionsProperties
.find(
1060 (taskFunctionProperties
: TaskFunctionProperties
) =>
1061 taskFunctionProperties
.name
=== name
1066 * Gets worker node task function worker choice strategy, if any.
1067 * @param workerNodeKey - The worker node key.
1068 * @param name - The task function name.
1069 * @returns The worker node task function worker choice strategy if the worker node task function worker choice strategy is defined, `undefined` otherwise.
1071 private readonly getWorkerNodeTaskFunctionWorkerChoiceStrategy
= (
1072 workerNodeKey
: number,
1074 ): WorkerChoiceStrategy
| undefined => {
1075 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
1076 if (workerInfo
== null) {
1079 name
= name
?? DEFAULT_TASK_NAME
1080 if (name
=== DEFAULT_TASK_NAME
) {
1081 name
= workerInfo
.taskFunctionsProperties
?.[1]?.name
1083 return workerInfo
.taskFunctionsProperties
?.find(
1084 (taskFunctionProperties
: TaskFunctionProperties
) =>
1085 taskFunctionProperties
.name
=== name
1090 * Gets worker node task function priority, if any.
1091 * @param workerNodeKey - The worker node key.
1092 * @param name - The task function name.
1093 * @returns The worker node task function priority if the worker node task function priority is defined, `undefined` otherwise.
1095 private readonly getWorkerNodeTaskFunctionPriority
= (
1096 workerNodeKey
: number,
1098 ): number | undefined => {
1099 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
1100 if (workerInfo
== null) {
1103 name
= name
?? DEFAULT_TASK_NAME
1104 if (name
=== DEFAULT_TASK_NAME
) {
1105 name
= workerInfo
.taskFunctionsProperties
?.[1]?.name
1107 return workerInfo
.taskFunctionsProperties
?.find(
1108 (taskFunctionProperties
: TaskFunctionProperties
) =>
1109 taskFunctionProperties
.name
=== name
1114 * Gets the worker choice strategies registered in this pool.
1115 * @returns The worker choice strategies.
1117 private readonly getWorkerChoiceStrategies
=
1118 (): Set
<WorkerChoiceStrategy
> => {
1120 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1121 this.opts
.workerChoiceStrategy
!,
1122 ...(this.listTaskFunctionsProperties()
1124 (taskFunctionProperties
: TaskFunctionProperties
) =>
1125 taskFunctionProperties
.strategy
1128 (strategy
: WorkerChoiceStrategy
| undefined) => strategy
!= null
1129 ) as WorkerChoiceStrategy
[]),
1134 public async setDefaultTaskFunction (name
: string): Promise
<boolean> {
1135 return await this.sendTaskFunctionOperationToWorkers({
1136 taskFunctionOperation
: 'default',
1137 taskFunctionProperties
: buildTaskFunctionProperties(
1139 this.taskFunctions
.get(name
)
1144 private shallExecuteTask (workerNodeKey
: number): boolean {
1146 this.tasksQueueSize(workerNodeKey
) === 0 &&
1147 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
<
1148 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1149 this.opts
.tasksQueueOptions
!.concurrency
!
1154 public async execute (
1157 transferList
?: readonly TransferListItem
[]
1158 ): Promise
<Response
> {
1159 return await new Promise
<Response
>((resolve
, reject
) => {
1160 if (!this.started
) {
1161 reject(new Error('Cannot execute a task on not started pool'))
1164 if (this.destroying
) {
1165 reject(new Error('Cannot execute a task on destroying pool'))
1168 if (name
!= null && typeof name
!== 'string') {
1169 reject(new TypeError('name argument must be a string'))
1174 typeof name
=== 'string' &&
1175 name
.trim().length
=== 0
1177 reject(new TypeError('name argument must not be an empty string'))
1180 if (transferList
!= null && !Array.isArray(transferList
)) {
1181 reject(new TypeError('transferList argument must be an array'))
1184 const timestamp
= performance
.now()
1185 const workerNodeKey
= this.chooseWorkerNode(name
)
1186 const task
: Task
<Data
> = {
1187 name
: name
?? DEFAULT_TASK_NAME
,
1189 data
: data
?? ({} as Data
),
1190 priority
: this.getWorkerNodeTaskFunctionPriority(workerNodeKey
, name
),
1191 strategy
: this.getWorkerNodeTaskFunctionWorkerChoiceStrategy(
1197 taskId
: randomUUID(),
1199 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1200 this.promiseResponseMap
.set(task
.taskId
!, {
1204 ...(this.emitter
!= null && {
1205 asyncResource
: new AsyncResource('poolifier:task', {
1206 triggerAsyncId
: this.emitter
.asyncId
,
1207 requireManualDestroy
: true,
1212 this.opts
.enableTasksQueue
=== false ||
1213 (this.opts
.enableTasksQueue
=== true &&
1214 this.shallExecuteTask(workerNodeKey
))
1216 this.executeTask(workerNodeKey
, task
)
1218 this.enqueueTask(workerNodeKey
, task
)
1224 * Starts the minimum number of workers.
1225 * @param initWorkerNodeUsage
1227 private startMinimumNumberOfWorkers (initWorkerNodeUsage
= false): void {
1228 this.startingMinimumNumberOfWorkers
= true
1230 this.workerNodes
.reduce(
1231 (accumulator
, workerNode
) =>
1232 !workerNode
.info
.dynamic
? accumulator
+ 1 : accumulator
,
1234 ) < this.minimumNumberOfWorkers
1236 const workerNodeKey
= this.createAndSetupWorkerNode()
1237 initWorkerNodeUsage
&&
1238 this.initWorkerNodeUsage(this.workerNodes
[workerNodeKey
])
1240 this.startingMinimumNumberOfWorkers
= false
1244 public start (): void {
1246 throw new Error('Cannot start an already started pool')
1248 if (this.starting
) {
1249 throw new Error('Cannot start an already starting pool')
1251 if (this.destroying
) {
1252 throw new Error('Cannot start a destroying pool')
1254 this.starting
= true
1255 this.startMinimumNumberOfWorkers()
1256 this.startTimestamp
= performance
.now()
1257 this.starting
= false
1262 public async destroy (): Promise
<void> {
1263 if (!this.started
) {
1264 throw new Error('Cannot destroy an already destroyed pool')
1266 if (this.starting
) {
1267 throw new Error('Cannot destroy an starting pool')
1269 if (this.destroying
) {
1270 throw new Error('Cannot destroy an already destroying pool')
1272 this.destroying
= true
1274 this.workerNodes
.map(async (_
, workerNodeKey
) => {
1275 await this.destroyWorkerNode(workerNodeKey
)
1278 this.emitter
?.emit(PoolEvents
.destroy
, this.info
)
1279 this.emitter
?.emitDestroy()
1280 this.readyEventEmitted
= false
1281 delete this.startTimestamp
1282 this.destroying
= false
1283 this.started
= false
1286 private async sendKillMessageToWorker (workerNodeKey
: number): Promise
<void> {
1287 await new Promise
<void>((resolve
, reject
) => {
1288 if (this.workerNodes
[workerNodeKey
] == null) {
1292 const killMessageListener
= (message
: MessageValue
<Response
>): void => {
1293 this.checkMessageWorkerId(message
)
1294 if (message
.kill
=== 'success') {
1296 } else if (message
.kill
=== 'failure') {
1299 `Kill message handling failed on worker ${message.workerId}`
1304 // FIXME: should be registered only once
1305 this.registerWorkerMessageListener(workerNodeKey
, killMessageListener
)
1306 this.sendToWorker(workerNodeKey
, { kill
: true })
1311 * Terminates the worker node given its worker node key.
1312 * @param workerNodeKey - The worker node key.
1314 protected async destroyWorkerNode (workerNodeKey
: number): Promise
<void> {
1315 this.flagWorkerNodeAsNotReady(workerNodeKey
)
1316 const flushedTasks
= this.flushTasksQueue(workerNodeKey
)
1317 const workerNode
= this.workerNodes
[workerNodeKey
]
1318 await waitWorkerNodeEvents(
1322 this.opts
.tasksQueueOptions
?.tasksFinishedTimeout
??
1323 getDefaultTasksQueueOptions(
1324 this.maximumNumberOfWorkers
?? this.minimumNumberOfWorkers
1325 ).tasksFinishedTimeout
1327 await this.sendKillMessageToWorker(workerNodeKey
)
1328 await workerNode
.terminate()
1332 * Setup hook to execute code before worker nodes are created in the abstract constructor.
1333 * Can be overridden.
1335 protected setupHook (): void {
1336 /* Intentionally empty */
1340 * Returns whether the worker is the main worker or not.
1341 * @returns `true` if the worker is the main worker, `false` otherwise.
1343 protected abstract isMain (): boolean
1346 * Hook executed before the worker task execution.
1347 * Can be overridden.
1348 * @param workerNodeKey - The worker node key.
1349 * @param task - The task to execute.
1351 protected beforeTaskExecutionHook (
1352 workerNodeKey
: number,
1355 if (this.workerNodes
[workerNodeKey
]?.usage
!= null) {
1356 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
1357 ++workerUsage
.tasks
.executing
1358 updateWaitTimeWorkerUsage(
1359 this.workerChoiceStrategiesContext
,
1365 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
1366 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1367 this.workerNodes
[workerNodeKey
].getTaskFunctionWorkerUsage(task
.name
!) !=
1370 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1371 const taskFunctionWorkerUsage
= this.workerNodes
[
1373 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1374 ].getTaskFunctionWorkerUsage(task
.name
!)!
1375 ++taskFunctionWorkerUsage
.tasks
.executing
1376 updateWaitTimeWorkerUsage(
1377 this.workerChoiceStrategiesContext
,
1378 taskFunctionWorkerUsage
,
1385 * Hook executed after the worker task execution.
1386 * Can be overridden.
1387 * @param workerNodeKey - The worker node key.
1388 * @param message - The received message.
1390 protected afterTaskExecutionHook (
1391 workerNodeKey
: number,
1392 message
: MessageValue
<Response
>
1394 let needWorkerChoiceStrategiesUpdate
= false
1396 if (this.workerNodes
[workerNodeKey
]?.usage
!= null) {
1397 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
1398 updateTaskStatisticsWorkerUsage(workerUsage
, message
)
1399 updateRunTimeWorkerUsage(
1400 this.workerChoiceStrategiesContext
,
1404 updateEluWorkerUsage(
1405 this.workerChoiceStrategiesContext
,
1409 needWorkerChoiceStrategiesUpdate
= true
1412 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
1413 this.workerNodes
[workerNodeKey
].getTaskFunctionWorkerUsage(
1414 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1415 message
.taskPerformance
!.name
1418 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1419 const taskFunctionWorkerUsage
= this.workerNodes
[
1421 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1422 ].getTaskFunctionWorkerUsage(message
.taskPerformance
!.name
)!
1423 updateTaskStatisticsWorkerUsage(taskFunctionWorkerUsage
, message
)
1424 updateRunTimeWorkerUsage(
1425 this.workerChoiceStrategiesContext
,
1426 taskFunctionWorkerUsage
,
1429 updateEluWorkerUsage(
1430 this.workerChoiceStrategiesContext
,
1431 taskFunctionWorkerUsage
,
1434 needWorkerChoiceStrategiesUpdate
= true
1436 if (needWorkerChoiceStrategiesUpdate
) {
1437 this.workerChoiceStrategiesContext
?.update(workerNodeKey
)
1442 * Whether the worker node shall update its task function worker usage or not.
1443 * @param workerNodeKey - The worker node key.
1444 * @returns `true` if the worker node shall update its task function worker usage, `false` otherwise.
1446 private shallUpdateTaskFunctionWorkerUsage (workerNodeKey
: number): boolean {
1447 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
1449 workerInfo
!= null &&
1450 Array.isArray(workerInfo
.taskFunctionsProperties
) &&
1451 workerInfo
.taskFunctionsProperties
.length
> 2
1456 * Chooses a worker node for the next task.
1457 * @param name - The task function name.
1458 * @returns The chosen worker node key.
1460 private chooseWorkerNode (name
?: string): number {
1461 if (this.shallCreateDynamicWorker()) {
1462 const workerNodeKey
= this.createAndSetupDynamicWorkerNode()
1464 this.workerChoiceStrategiesContext
?.getPolicy().dynamicWorkerUsage
===
1467 return workerNodeKey
1470 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1471 return this.workerChoiceStrategiesContext
!.execute(
1472 this.getTaskFunctionWorkerChoiceStrategy(name
)
1477 * Conditions for dynamic worker creation.
1478 * @returns Whether to create a dynamic worker or not.
1480 protected abstract shallCreateDynamicWorker (): boolean
1483 * Sends a message to worker given its worker node key.
1484 * @param workerNodeKey - The worker node key.
1485 * @param message - The message.
1486 * @param transferList - The optional array of transferable objects.
1488 protected abstract sendToWorker (
1489 workerNodeKey
: number,
1490 message
: MessageValue
<Data
>,
1491 transferList
?: readonly TransferListItem
[]
1495 * Initializes the worker node usage with sensible default values gathered during runtime.
1496 * @param workerNode - The worker node.
1498 private initWorkerNodeUsage (workerNode
: IWorkerNode
<Worker
, Data
>): void {
1500 this.workerChoiceStrategiesContext
?.getTaskStatisticsRequirements()
1501 .runTime
.aggregate
=== true
1503 workerNode
.usage
.runTime
.aggregate
= min(
1504 ...this.workerNodes
.map(
1506 workerNode
.usage
.runTime
.aggregate
?? Number.POSITIVE_INFINITY
1511 this.workerChoiceStrategiesContext
?.getTaskStatisticsRequirements()
1512 .waitTime
.aggregate
=== true
1514 workerNode
.usage
.waitTime
.aggregate
= min(
1515 ...this.workerNodes
.map(
1517 workerNode
.usage
.waitTime
.aggregate
?? Number.POSITIVE_INFINITY
1522 this.workerChoiceStrategiesContext
?.getTaskStatisticsRequirements().elu
1525 workerNode
.usage
.elu
.active
.aggregate
= min(
1526 ...this.workerNodes
.map(
1528 workerNode
.usage
.elu
.active
.aggregate
?? Number.POSITIVE_INFINITY
1535 * Creates a new, completely set up worker node.
1536 * @returns New, completely set up worker node key.
1538 protected createAndSetupWorkerNode (): number {
1539 const workerNode
= this.createWorkerNode()
1540 workerNode
.registerWorkerEventHandler(
1542 this.opts
.onlineHandler
?? EMPTY_FUNCTION
1544 workerNode
.registerWorkerEventHandler(
1546 this.opts
.messageHandler
?? EMPTY_FUNCTION
1548 workerNode
.registerWorkerEventHandler(
1550 this.opts
.errorHandler
?? EMPTY_FUNCTION
1552 workerNode
.registerOnceWorkerEventHandler('error', (error
: Error) => {
1553 workerNode
.info
.ready
= false
1554 this.emitter
?.emit(PoolEvents
.error
, error
)
1558 this.opts
.restartWorkerOnError
=== true
1560 if (workerNode
.info
.dynamic
) {
1561 this.createAndSetupDynamicWorkerNode()
1562 } else if (!this.startingMinimumNumberOfWorkers
) {
1563 this.startMinimumNumberOfWorkers(true)
1569 this.opts
.enableTasksQueue
=== true
1571 this.redistributeQueuedTasks(this.workerNodes
.indexOf(workerNode
))
1574 workerNode
?.terminate().catch((error
: unknown
) => {
1575 this.emitter
?.emit(PoolEvents
.error
, error
)
1578 workerNode
.registerWorkerEventHandler(
1580 this.opts
.exitHandler
?? EMPTY_FUNCTION
1582 workerNode
.registerOnceWorkerEventHandler('exit', () => {
1583 this.removeWorkerNode(workerNode
)
1586 !this.startingMinimumNumberOfWorkers
&&
1589 this.startMinimumNumberOfWorkers(true)
1592 const workerNodeKey
= this.addWorkerNode(workerNode
)
1593 this.afterWorkerNodeSetup(workerNodeKey
)
1594 return workerNodeKey
1598 * Creates a new, completely set up dynamic worker node.
1599 * @returns New, completely set up dynamic worker node key.
1601 protected createAndSetupDynamicWorkerNode (): number {
1602 const workerNodeKey
= this.createAndSetupWorkerNode()
1603 this.registerWorkerMessageListener(workerNodeKey
, message
=> {
1604 this.checkMessageWorkerId(message
)
1605 const localWorkerNodeKey
= this.getWorkerNodeKeyByWorkerId(
1608 const workerInfo
= this.getWorkerInfo(localWorkerNodeKey
)
1609 const workerUsage
= this.workerNodes
[localWorkerNodeKey
]?.usage
1610 // Kill message received from worker
1612 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
1613 (isKillBehavior(KillBehaviors
.SOFT
, message
.kill
) &&
1614 ((this.opts
.enableTasksQueue
=== false &&
1615 workerUsage
.tasks
.executing
=== 0) ||
1616 (this.opts
.enableTasksQueue
=== true &&
1617 workerInfo
!= null &&
1618 !workerInfo
.stealing
&&
1619 workerUsage
.tasks
.executing
=== 0 &&
1620 this.tasksQueueSize(localWorkerNodeKey
) === 0)))
1622 // Flag the worker node as not ready immediately
1623 this.flagWorkerNodeAsNotReady(localWorkerNodeKey
)
1624 this.destroyWorkerNode(localWorkerNodeKey
).catch((error
: unknown
) => {
1625 this.emitter
?.emit(PoolEvents
.error
, error
)
1629 this.sendToWorker(workerNodeKey
, {
1632 if (this.taskFunctions
.size
> 0) {
1633 for (const [taskFunctionName
, taskFunctionObject
] of this.taskFunctions
) {
1634 this.sendTaskFunctionOperationToWorker(workerNodeKey
, {
1635 taskFunctionOperation
: 'add',
1636 taskFunctionProperties
: buildTaskFunctionProperties(
1640 taskFunction
: taskFunctionObject
.taskFunction
.toString(),
1641 }).catch((error
: unknown
) => {
1642 this.emitter
?.emit(PoolEvents
.error
, error
)
1646 const workerNode
= this.workerNodes
[workerNodeKey
]
1647 workerNode
.info
.dynamic
= true
1649 this.workerChoiceStrategiesContext
?.getPolicy().dynamicWorkerReady
===
1651 this.workerChoiceStrategiesContext
?.getPolicy().dynamicWorkerUsage
===
1654 workerNode
.info
.ready
= true
1656 this.initWorkerNodeUsage(workerNode
)
1657 this.checkAndEmitDynamicWorkerCreationEvents()
1658 return workerNodeKey
1662 * Registers a listener callback on the worker given its worker node key.
1663 * @param workerNodeKey - The worker node key.
1664 * @param listener - The message listener callback.
1666 protected abstract registerWorkerMessageListener
<
1667 Message
extends Data
| Response
1669 workerNodeKey
: number,
1670 listener
: (message
: MessageValue
<Message
>) => void
1674 * Registers once a listener callback on the worker given its worker node key.
1675 * @param workerNodeKey - The worker node key.
1676 * @param listener - The message listener callback.
1678 protected abstract registerOnceWorkerMessageListener
<
1679 Message
extends Data
| Response
1681 workerNodeKey
: number,
1682 listener
: (message
: MessageValue
<Message
>) => void
1686 * Deregisters 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 deregisterWorkerMessageListener
<
1691 Message
extends Data
| Response
1693 workerNodeKey
: number,
1694 listener
: (message
: MessageValue
<Message
>) => void
1698 * Method hooked up after a worker node has been newly created.
1699 * Can be overridden.
1700 * @param workerNodeKey - The newly created worker node key.
1702 protected afterWorkerNodeSetup (workerNodeKey
: number): void {
1703 // Listen to worker messages.
1704 this.registerWorkerMessageListener(
1706 this.workerMessageListener
1708 // Send the startup message to worker.
1709 this.sendStartupMessageToWorker(workerNodeKey
)
1710 // Send the statistics message to worker.
1711 this.sendStatisticsMessageToWorker(workerNodeKey
)
1712 if (this.opts
.enableTasksQueue
=== true) {
1713 if (this.opts
.tasksQueueOptions
?.taskStealing
=== true) {
1714 this.workerNodes
[workerNodeKey
].on(
1716 this.handleWorkerNodeIdleEvent
1719 if (this.opts
.tasksQueueOptions
?.tasksStealingOnBackPressure
=== true) {
1720 this.workerNodes
[workerNodeKey
].on(
1722 this.handleWorkerNodeBackPressureEvent
1729 * Sends the startup message to worker given its worker node key.
1730 * @param workerNodeKey - The worker node key.
1732 protected abstract sendStartupMessageToWorker (workerNodeKey
: number): void
1735 * Sends the statistics message to worker given its worker node key.
1736 * @param workerNodeKey - The worker node key.
1738 private sendStatisticsMessageToWorker (workerNodeKey
: number): void {
1739 this.sendToWorker(workerNodeKey
, {
1742 this.workerChoiceStrategiesContext
?.getTaskStatisticsRequirements()
1743 .runTime
.aggregate
?? false,
1745 this.workerChoiceStrategiesContext
?.getTaskStatisticsRequirements()
1746 .elu
.aggregate
?? false,
1751 private cannotStealTask (): boolean {
1752 return this.workerNodes
.length
<= 1 || this.info
.queuedTasks
=== 0
1755 private handleTask (workerNodeKey
: number, task
: Task
<Data
>): void {
1756 if (this.shallExecuteTask(workerNodeKey
)) {
1757 this.executeTask(workerNodeKey
, task
)
1759 this.enqueueTask(workerNodeKey
, task
)
1763 private redistributeQueuedTasks (sourceWorkerNodeKey
: number): void {
1764 if (sourceWorkerNodeKey
=== -1 || this.cannotStealTask()) {
1767 while (this.tasksQueueSize(sourceWorkerNodeKey
) > 0) {
1768 const destinationWorkerNodeKey
= this.workerNodes
.reduce(
1769 (minWorkerNodeKey
, workerNode
, workerNodeKey
, workerNodes
) => {
1770 return sourceWorkerNodeKey
!== workerNodeKey
&&
1771 workerNode
.info
.ready
&&
1772 workerNode
.usage
.tasks
.queued
<
1773 workerNodes
[minWorkerNodeKey
].usage
.tasks
.queued
1780 destinationWorkerNodeKey
,
1781 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1782 this.dequeueTask(sourceWorkerNodeKey
)!
1787 private updateTaskStolenStatisticsWorkerUsage (
1788 workerNodeKey
: number,
1791 const workerNode
= this.workerNodes
[workerNodeKey
]
1793 if (workerNode
?.usage
!= null) {
1794 ++workerNode
.usage
.tasks
.stolen
1797 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
1798 workerNode
.getTaskFunctionWorkerUsage(taskName
) != null
1800 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1801 ++workerNode
.getTaskFunctionWorkerUsage(taskName
)!.tasks
.stolen
1805 private updateTaskSequentiallyStolenStatisticsWorkerUsage (
1806 workerNodeKey
: number,
1808 previousTaskName
?: string
1810 const workerNode
= this.workerNodes
[workerNodeKey
]
1812 if (workerNode
?.usage
!= null) {
1813 ++workerNode
.usage
.tasks
.sequentiallyStolen
1816 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
1817 workerNode
.getTaskFunctionWorkerUsage(taskName
) != null
1819 const taskFunctionWorkerUsage
=
1820 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1821 workerNode
.getTaskFunctionWorkerUsage(taskName
)!
1823 taskFunctionWorkerUsage
.tasks
.sequentiallyStolen
=== 0 ||
1824 (previousTaskName
!= null &&
1825 previousTaskName
=== taskName
&&
1826 taskFunctionWorkerUsage
.tasks
.sequentiallyStolen
> 0)
1828 ++taskFunctionWorkerUsage
.tasks
.sequentiallyStolen
1829 } else if (taskFunctionWorkerUsage
.tasks
.sequentiallyStolen
> 0) {
1830 taskFunctionWorkerUsage
.tasks
.sequentiallyStolen
= 0
1835 private resetTaskSequentiallyStolenStatisticsWorkerUsage (
1836 workerNodeKey
: number,
1839 const workerNode
= this.workerNodes
[workerNodeKey
]
1841 if (workerNode
?.usage
!= null) {
1842 workerNode
.usage
.tasks
.sequentiallyStolen
= 0
1845 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
1846 workerNode
.getTaskFunctionWorkerUsage(taskName
) != null
1848 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1849 workerNode
.getTaskFunctionWorkerUsage(
1851 )!.tasks
.sequentiallyStolen
= 0
1855 private readonly handleWorkerNodeIdleEvent
= (
1856 eventDetail
: WorkerNodeEventDetail
,
1857 previousStolenTask
?: Task
<Data
>
1859 const { workerNodeKey
} = eventDetail
1860 if (workerNodeKey
== null) {
1862 "WorkerNode event detail 'workerNodeKey' property must be defined"
1865 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
1866 if (workerInfo
== null) {
1868 `Worker node with key '${workerNodeKey}' not found in pool`
1872 this.cannotStealTask() ||
1873 (this.info
.stealingWorkerNodes
?? 0) >
1874 Math.floor(this.workerNodes
.length
/ 2)
1876 if (previousStolenTask
!= null) {
1877 workerInfo
.stealing
= false
1878 this.resetTaskSequentiallyStolenStatisticsWorkerUsage(
1880 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1881 previousStolenTask
.name
!
1886 const workerNodeTasksUsage
= this.workerNodes
[workerNodeKey
].usage
.tasks
1888 previousStolenTask
!= null &&
1889 (workerNodeTasksUsage
.executing
> 0 ||
1890 this.tasksQueueSize(workerNodeKey
) > 0)
1892 workerInfo
.stealing
= false
1893 this.resetTaskSequentiallyStolenStatisticsWorkerUsage(
1895 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1896 previousStolenTask
.name
!
1900 workerInfo
.stealing
= true
1901 const stolenTask
= this.workerNodeStealTask(workerNodeKey
)
1902 if (stolenTask
!= null) {
1903 this.updateTaskSequentiallyStolenStatisticsWorkerUsage(
1905 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1907 previousStolenTask
?.name
1910 sleep(exponentialDelay(workerNodeTasksUsage
.sequentiallyStolen
))
1912 this.handleWorkerNodeIdleEvent(eventDetail
, stolenTask
)
1915 .catch((error
: unknown
) => {
1916 this.emitter
?.emit(PoolEvents
.error
, error
)
1920 private readonly workerNodeStealTask
= (
1921 workerNodeKey
: number
1922 ): Task
<Data
> | undefined => {
1923 const workerNodes
= this.workerNodes
1926 (workerNodeA
, workerNodeB
) =>
1927 workerNodeB
.usage
.tasks
.queued
- workerNodeA
.usage
.tasks
.queued
1929 const sourceWorkerNode
= workerNodes
.find(
1930 (sourceWorkerNode
, sourceWorkerNodeKey
) =>
1931 sourceWorkerNode
.info
.ready
&&
1932 !sourceWorkerNode
.info
.stealing
&&
1933 sourceWorkerNodeKey
!== workerNodeKey
&&
1934 sourceWorkerNode
.usage
.tasks
.queued
> 0
1936 if (sourceWorkerNode
!= null) {
1937 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1938 const task
= sourceWorkerNode
.dequeueLastPrioritizedTask()!
1939 this.handleTask(workerNodeKey
, task
)
1940 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1941 this.updateTaskStolenStatisticsWorkerUsage(workerNodeKey
, task
.name
!)
1946 private readonly handleWorkerNodeBackPressureEvent
= (
1947 eventDetail
: WorkerNodeEventDetail
1950 this.cannotStealTask() ||
1951 this.hasBackPressure() ||
1952 (this.info
.stealingWorkerNodes
?? 0) >
1953 Math.floor(this.workerNodes
.length
/ 2)
1957 const sizeOffset
= 1
1958 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1959 if (this.opts
.tasksQueueOptions
!.size
! <= sizeOffset
) {
1962 const { workerId
} = eventDetail
1963 const sourceWorkerNode
=
1964 this.workerNodes
[this.getWorkerNodeKeyByWorkerId(workerId
)]
1965 const workerNodes
= this.workerNodes
1968 (workerNodeA
, workerNodeB
) =>
1969 workerNodeA
.usage
.tasks
.queued
- workerNodeB
.usage
.tasks
.queued
1971 for (const [workerNodeKey
, workerNode
] of workerNodes
.entries()) {
1973 sourceWorkerNode
.usage
.tasks
.queued
> 0 &&
1974 workerNode
.info
.ready
&&
1975 !workerNode
.info
.stealing
&&
1976 workerNode
.info
.id
!== workerId
&&
1977 workerNode
.usage
.tasks
.queued
<
1978 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1979 this.opts
.tasksQueueOptions
!.size
! - sizeOffset
1981 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
1982 if (workerInfo
== null) {
1984 `Worker node with key '${workerNodeKey}' not found in pool`
1987 workerInfo
.stealing
= true
1988 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1989 const task
= sourceWorkerNode
.dequeueLastPrioritizedTask()!
1990 this.handleTask(workerNodeKey
, task
)
1991 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1992 this.updateTaskStolenStatisticsWorkerUsage(workerNodeKey
, task
.name
!)
1993 workerInfo
.stealing
= false
1998 private setTasksQueuePriority (workerNodeKey
: number): void {
1999 this.workerNodes
[workerNodeKey
].setTasksQueuePriority(
2000 this.getTasksQueuePriority()
2005 * This method is the message listener registered on each worker.
2008 protected readonly workerMessageListener
= (
2009 message
: MessageValue
<Response
>
2011 this.checkMessageWorkerId(message
)
2012 const { workerId
, ready
, taskId
, taskFunctionsProperties
} = message
2013 if (ready
!= null && taskFunctionsProperties
!= null) {
2014 // Worker ready response received from worker
2015 this.handleWorkerReadyResponse(message
)
2016 } else if (taskFunctionsProperties
!= null) {
2017 // Task function properties message received from worker
2018 const workerNodeKey
= this.getWorkerNodeKeyByWorkerId(workerId
)
2019 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
2020 if (workerInfo
!= null) {
2021 workerInfo
.taskFunctionsProperties
= taskFunctionsProperties
2022 this.sendStatisticsMessageToWorker(workerNodeKey
)
2023 this.setTasksQueuePriority(workerNodeKey
)
2025 } else if (taskId
!= null) {
2026 // Task execution response received from worker
2027 this.handleTaskExecutionResponse(message
)
2031 private checkAndEmitReadyEvent (): void {
2032 if (!this.readyEventEmitted
&& this.ready
) {
2033 this.emitter
?.emit(PoolEvents
.ready
, this.info
)
2034 this.readyEventEmitted
= true
2038 private handleWorkerReadyResponse (message
: MessageValue
<Response
>): void {
2039 const { workerId
, ready
, taskFunctionsProperties
} = message
2040 if (ready
== null || !ready
) {
2041 throw new Error(`Worker ${workerId} failed to initialize`)
2043 const workerNodeKey
= this.getWorkerNodeKeyByWorkerId(workerId
)
2044 const workerNode
= this.workerNodes
[workerNodeKey
]
2045 workerNode
.info
.ready
= ready
2046 workerNode
.info
.taskFunctionsProperties
= taskFunctionsProperties
2047 this.sendStatisticsMessageToWorker(workerNodeKey
)
2048 this.setTasksQueuePriority(workerNodeKey
)
2049 this.checkAndEmitReadyEvent()
2052 private handleTaskExecutionResponse (message
: MessageValue
<Response
>): void {
2053 const { workerId
, taskId
, workerError
, data
} = message
2054 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2055 const promiseResponse
= this.promiseResponseMap
.get(taskId
!)
2056 if (promiseResponse
!= null) {
2057 const { resolve
, reject
, workerNodeKey
, asyncResource
} = promiseResponse
2058 const workerNode
= this.workerNodes
[workerNodeKey
]
2059 if (workerError
!= null) {
2060 this.emitter
?.emit(PoolEvents
.taskError
, workerError
)
2061 asyncResource
!= null
2062 ? asyncResource
.runInAsyncScope(
2067 : reject(workerError
.message
)
2069 asyncResource
!= null
2070 ? asyncResource
.runInAsyncScope(resolve
, this.emitter
, data
)
2071 : resolve(data
as Response
)
2073 asyncResource
?.emitDestroy()
2074 this.afterTaskExecutionHook(workerNodeKey
, message
)
2075 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2076 this.promiseResponseMap
.delete(taskId
!)
2077 workerNode
?.emit('taskFinished', taskId
)
2079 this.opts
.enableTasksQueue
=== true &&
2083 const workerNodeTasksUsage
= workerNode
.usage
.tasks
2085 this.tasksQueueSize(workerNodeKey
) > 0 &&
2086 workerNodeTasksUsage
.executing
<
2087 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2088 this.opts
.tasksQueueOptions
!.concurrency
!
2090 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2091 this.executeTask(workerNodeKey
, this.dequeueTask(workerNodeKey
)!)
2094 workerNodeTasksUsage
.executing
=== 0 &&
2095 this.tasksQueueSize(workerNodeKey
) === 0 &&
2096 workerNodeTasksUsage
.sequentiallyStolen
=== 0
2098 workerNode
.emit('idle', {
2107 private checkAndEmitTaskExecutionEvents (): void {
2109 this.emitter
?.emit(PoolEvents
.busy
, this.info
)
2113 private checkAndEmitTaskQueuingEvents (): void {
2114 if (this.hasBackPressure()) {
2115 this.emitter
?.emit(PoolEvents
.backPressure
, this.info
)
2120 * Emits dynamic worker creation events.
2122 protected abstract checkAndEmitDynamicWorkerCreationEvents (): void
2125 * Gets the worker information given its worker node key.
2126 * @param workerNodeKey - The worker node key.
2127 * @returns The worker information.
2129 protected getWorkerInfo (workerNodeKey
: number): WorkerInfo
| undefined {
2130 return this.workerNodes
[workerNodeKey
]?.info
2133 private getTasksQueuePriority (): boolean {
2134 return this.listTaskFunctionsProperties().some(
2135 taskFunctionProperties
=> taskFunctionProperties
.priority
!= null
2140 * Creates a worker node.
2141 * @returns The created worker node.
2143 private createWorkerNode (): IWorkerNode
<Worker
, Data
> {
2144 const workerNode
= new WorkerNode
<Worker
, Data
>(
2149 workerOptions
: this.opts
.workerOptions
,
2150 tasksQueueBackPressureSize
:
2151 this.opts
.tasksQueueOptions
?.size
??
2152 getDefaultTasksQueueOptions(
2153 this.maximumNumberOfWorkers
?? this.minimumNumberOfWorkers
2155 tasksQueueBucketSize
: defaultBucketSize
,
2156 tasksQueuePriority
: this.getTasksQueuePriority(),
2159 // Flag the worker node as ready at pool startup.
2160 if (this.starting
) {
2161 workerNode
.info
.ready
= true
2167 * Adds the given worker node in the pool worker nodes.
2168 * @param workerNode - The worker node.
2169 * @returns The added worker node key.
2170 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the added worker node is not found.
2172 private addWorkerNode (workerNode
: IWorkerNode
<Worker
, Data
>): number {
2173 this.workerNodes
.push(workerNode
)
2174 const workerNodeKey
= this.workerNodes
.indexOf(workerNode
)
2175 if (workerNodeKey
=== -1) {
2176 throw new Error('Worker added not found in worker nodes')
2178 return workerNodeKey
2181 private checkAndEmitEmptyEvent (): void {
2183 this.emitter
?.emit(PoolEvents
.empty
, this.info
)
2184 this.readyEventEmitted
= false
2189 * Removes the worker node from the pool worker nodes.
2190 * @param workerNode - The worker node.
2192 private removeWorkerNode (workerNode
: IWorkerNode
<Worker
, Data
>): void {
2193 const workerNodeKey
= this.workerNodes
.indexOf(workerNode
)
2194 if (workerNodeKey
!== -1) {
2195 this.workerNodes
.splice(workerNodeKey
, 1)
2196 this.workerChoiceStrategiesContext
?.remove(workerNodeKey
)
2198 this.checkAndEmitEmptyEvent()
2201 protected flagWorkerNodeAsNotReady (workerNodeKey
: number): void {
2202 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
2203 if (workerInfo
!= null) {
2204 workerInfo
.ready
= false
2208 private hasBackPressure (): boolean {
2210 this.opts
.enableTasksQueue
=== true &&
2211 this.workerNodes
.findIndex(
2212 workerNode
=> !workerNode
.hasBackPressure()
2218 * Executes the given task on the worker given its worker node key.
2219 * @param workerNodeKey - The worker node key.
2220 * @param task - The task to execute.
2222 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
2223 this.beforeTaskExecutionHook(workerNodeKey
, task
)
2224 this.sendToWorker(workerNodeKey
, task
, task
.transferList
)
2225 this.checkAndEmitTaskExecutionEvents()
2228 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
2229 const tasksQueueSize
= this.workerNodes
[workerNodeKey
].enqueueTask(task
)
2230 this.checkAndEmitTaskQueuingEvents()
2231 return tasksQueueSize
2234 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
2235 return this.workerNodes
[workerNodeKey
].dequeueTask()
2238 private tasksQueueSize (workerNodeKey
: number): number {
2239 return this.workerNodes
[workerNodeKey
].tasksQueueSize()
2242 protected flushTasksQueue (workerNodeKey
: number): number {
2243 let flushedTasks
= 0
2244 while (this.tasksQueueSize(workerNodeKey
) > 0) {
2245 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2246 this.executeTask(workerNodeKey
, this.dequeueTask(workerNodeKey
)!)
2249 this.workerNodes
[workerNodeKey
].clearTasksQueue()
2253 private flushTasksQueues (): void {
2254 for (const workerNodeKey
of this.workerNodes
.keys()) {
2255 this.flushTasksQueue(workerNodeKey
)