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(
379 workerNode
=> workerNode
.usage
.runTime
.minimum
?? Infinity
385 ...this.workerNodes
.map(
386 workerNode
=> workerNode
.usage
.runTime
.maximum
?? -Infinity
390 ...(this.workerChoiceStrategiesContext
.getTaskStatisticsRequirements()
391 .runTime
.average
&& {
394 this.workerNodes
.reduce
<number[]>(
395 (accumulator
, workerNode
) =>
396 accumulator
.concat(workerNode
.usage
.runTime
.history
),
402 ...(this.workerChoiceStrategiesContext
.getTaskStatisticsRequirements()
406 this.workerNodes
.reduce
<number[]>(
407 (accumulator
, workerNode
) =>
408 accumulator
.concat(workerNode
.usage
.runTime
.history
),
416 ...(this.workerChoiceStrategiesContext
?.getTaskStatisticsRequirements()
417 .waitTime
.aggregate
=== true && {
421 ...this.workerNodes
.map(
422 workerNode
=> workerNode
.usage
.waitTime
.minimum
?? Infinity
428 ...this.workerNodes
.map(
429 workerNode
=> workerNode
.usage
.waitTime
.maximum
?? -Infinity
433 ...(this.workerChoiceStrategiesContext
.getTaskStatisticsRequirements()
434 .waitTime
.average
&& {
437 this.workerNodes
.reduce
<number[]>(
438 (accumulator
, workerNode
) =>
439 accumulator
.concat(workerNode
.usage
.waitTime
.history
),
445 ...(this.workerChoiceStrategiesContext
.getTaskStatisticsRequirements()
446 .waitTime
.median
&& {
449 this.workerNodes
.reduce
<number[]>(
450 (accumulator
, workerNode
) =>
451 accumulator
.concat(workerNode
.usage
.waitTime
.history
),
459 ...(this.workerChoiceStrategiesContext
?.getTaskStatisticsRequirements()
460 .elu
.aggregate
=== true && {
465 ...this.workerNodes
.map(
466 workerNode
=> workerNode
.usage
.elu
.idle
.minimum
?? Infinity
472 ...this.workerNodes
.map(
473 workerNode
=> workerNode
.usage
.elu
.idle
.maximum
?? -Infinity
477 ...(this.workerChoiceStrategiesContext
.getTaskStatisticsRequirements()
481 this.workerNodes
.reduce
<number[]>(
482 (accumulator
, workerNode
) =>
483 accumulator
.concat(workerNode
.usage
.elu
.idle
.history
),
489 ...(this.workerChoiceStrategiesContext
.getTaskStatisticsRequirements()
493 this.workerNodes
.reduce
<number[]>(
494 (accumulator
, workerNode
) =>
495 accumulator
.concat(workerNode
.usage
.elu
.idle
.history
),
505 ...this.workerNodes
.map(
506 workerNode
=> workerNode
.usage
.elu
.active
.minimum
?? Infinity
512 ...this.workerNodes
.map(
513 workerNode
=> workerNode
.usage
.elu
.active
.maximum
?? -Infinity
517 ...(this.workerChoiceStrategiesContext
.getTaskStatisticsRequirements()
521 this.workerNodes
.reduce
<number[]>(
522 (accumulator
, workerNode
) =>
523 accumulator
.concat(workerNode
.usage
.elu
.active
.history
),
529 ...(this.workerChoiceStrategiesContext
.getTaskStatisticsRequirements()
533 this.workerNodes
.reduce
<number[]>(
534 (accumulator
, workerNode
) =>
535 accumulator
.concat(workerNode
.usage
.elu
.active
.history
),
548 * The pool readiness boolean status.
550 private get
ready (): boolean {
555 this.workerNodes
.reduce(
556 (accumulator
, workerNode
) =>
557 !workerNode
.info
.dynamic
&& workerNode
.info
.ready
561 ) >= this.minimumNumberOfWorkers
566 * The pool emptiness boolean status.
568 protected get
empty (): boolean {
569 return this.minimumNumberOfWorkers
=== 0 && this.workerNodes
.length
=== 0
573 * The approximate pool utilization.
575 * @returns The pool utilization.
577 private get
utilization (): number {
578 if (this.startTimestamp
== null) {
581 const poolTimeCapacity
=
582 (performance
.now() - this.startTimestamp
) *
583 (this.maximumNumberOfWorkers
?? this.minimumNumberOfWorkers
)
584 const totalTasksRunTime
= this.workerNodes
.reduce(
585 (accumulator
, workerNode
) =>
586 accumulator
+ (workerNode
.usage
.runTime
.aggregate
?? 0),
589 const totalTasksWaitTime
= this.workerNodes
.reduce(
590 (accumulator
, workerNode
) =>
591 accumulator
+ (workerNode
.usage
.waitTime
.aggregate
?? 0),
594 return (totalTasksRunTime
+ totalTasksWaitTime
) / poolTimeCapacity
600 * If it is `'dynamic'`, it provides the `max` property.
602 protected abstract get
type (): PoolType
607 protected abstract get
worker (): WorkerType
610 * Checks if the worker id sent in the received message from a worker is valid.
612 * @param message - The received message.
613 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the worker id is invalid.
615 private checkMessageWorkerId (message
: MessageValue
<Data
| Response
>): void {
616 if (message
.workerId
== null) {
617 throw new Error('Worker message received without worker id')
618 } else if (this.getWorkerNodeKeyByWorkerId(message
.workerId
) === -1) {
620 `Worker message received from unknown worker '${message.workerId}'`
626 * Gets the worker node key given its worker id.
628 * @param workerId - The worker id.
629 * @returns The worker node key if the worker id is found in the pool worker nodes, `-1` otherwise.
631 private getWorkerNodeKeyByWorkerId (workerId
: number | undefined): number {
632 return this.workerNodes
.findIndex(
633 workerNode
=> workerNode
.info
.id
=== workerId
638 public setWorkerChoiceStrategy (
639 workerChoiceStrategy
: WorkerChoiceStrategy
,
640 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
642 let requireSync
= false
643 checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
644 if (workerChoiceStrategyOptions
!= null) {
645 requireSync
= !this.setWorkerChoiceStrategyOptions(
646 workerChoiceStrategyOptions
649 if (workerChoiceStrategy
!== this.opts
.workerChoiceStrategy
) {
650 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
651 this.workerChoiceStrategiesContext
?.setDefaultWorkerChoiceStrategy(
652 this.opts
.workerChoiceStrategy
,
653 this.opts
.workerChoiceStrategyOptions
658 this.workerChoiceStrategiesContext
?.syncWorkerChoiceStrategies(
659 this.getWorkerWorkerChoiceStrategies(),
660 this.opts
.workerChoiceStrategyOptions
662 for (const workerNodeKey
of this.workerNodes
.keys()) {
663 this.sendStatisticsMessageToWorker(workerNodeKey
)
669 public setWorkerChoiceStrategyOptions (
670 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
| undefined
672 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
673 if (workerChoiceStrategyOptions
!= null) {
674 this.opts
.workerChoiceStrategyOptions
= workerChoiceStrategyOptions
675 this.workerChoiceStrategiesContext
?.setOptions(
676 this.opts
.workerChoiceStrategyOptions
678 this.workerChoiceStrategiesContext
?.syncWorkerChoiceStrategies(
679 this.getWorkerWorkerChoiceStrategies(),
680 this.opts
.workerChoiceStrategyOptions
682 for (const workerNodeKey
of this.workerNodes
.keys()) {
683 this.sendStatisticsMessageToWorker(workerNodeKey
)
691 public enableTasksQueue (
693 tasksQueueOptions
?: TasksQueueOptions
695 if (this.opts
.enableTasksQueue
=== true && !enable
) {
696 this.unsetTaskStealing()
697 this.unsetTasksStealingOnBackPressure()
698 this.flushTasksQueues()
700 this.opts
.enableTasksQueue
= enable
701 this.setTasksQueueOptions(tasksQueueOptions
)
705 public setTasksQueueOptions (
706 tasksQueueOptions
: TasksQueueOptions
| undefined
708 if (this.opts
.enableTasksQueue
=== true) {
709 checkValidTasksQueueOptions(tasksQueueOptions
)
710 this.opts
.tasksQueueOptions
=
711 this.buildTasksQueueOptions(tasksQueueOptions
)
712 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
713 this.setTasksQueueSize(this.opts
.tasksQueueOptions
.size
!)
714 if (this.opts
.tasksQueueOptions
.taskStealing
=== true) {
715 this.unsetTaskStealing()
716 this.setTaskStealing()
718 this.unsetTaskStealing()
720 if (this.opts
.tasksQueueOptions
.tasksStealingOnBackPressure
=== true) {
721 this.unsetTasksStealingOnBackPressure()
722 this.setTasksStealingOnBackPressure()
724 this.unsetTasksStealingOnBackPressure()
726 } else if (this.opts
.tasksQueueOptions
!= null) {
727 delete this.opts
.tasksQueueOptions
731 private buildTasksQueueOptions (
732 tasksQueueOptions
: TasksQueueOptions
| undefined
733 ): TasksQueueOptions
{
735 ...getDefaultTasksQueueOptions(
736 this.maximumNumberOfWorkers
?? this.minimumNumberOfWorkers
742 private setTasksQueueSize (size
: number): void {
743 for (const workerNode
of this.workerNodes
) {
744 workerNode
.tasksQueueBackPressureSize
= size
748 private setTaskStealing (): void {
749 for (const workerNodeKey
of this.workerNodes
.keys()) {
750 this.workerNodes
[workerNodeKey
].on('idle', this.handleWorkerNodeIdleEvent
)
754 private unsetTaskStealing (): void {
755 for (const workerNodeKey
of this.workerNodes
.keys()) {
756 this.workerNodes
[workerNodeKey
].off(
758 this.handleWorkerNodeIdleEvent
763 private setTasksStealingOnBackPressure (): void {
764 for (const workerNodeKey
of this.workerNodes
.keys()) {
765 this.workerNodes
[workerNodeKey
].on(
767 this.handleWorkerNodeBackPressureEvent
772 private unsetTasksStealingOnBackPressure (): void {
773 for (const workerNodeKey
of this.workerNodes
.keys()) {
774 this.workerNodes
[workerNodeKey
].off(
776 this.handleWorkerNodeBackPressureEvent
782 * Whether the pool is full or not.
784 * The pool filling boolean status.
786 protected get
full (): boolean {
788 this.workerNodes
.length
>=
789 (this.maximumNumberOfWorkers
?? this.minimumNumberOfWorkers
)
794 * Whether the pool is busy or not.
796 * The pool busyness boolean status.
798 protected abstract get
busy (): boolean
801 * Whether worker nodes are executing concurrently their tasks quota or not.
803 * @returns Worker nodes busyness boolean status.
805 protected internalBusy (): boolean {
806 if (this.opts
.enableTasksQueue
=== true) {
808 this.workerNodes
.findIndex(
810 workerNode
.info
.ready
&&
811 workerNode
.usage
.tasks
.executing
<
812 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
813 this.opts
.tasksQueueOptions
!.concurrency
!
818 this.workerNodes
.findIndex(
820 workerNode
.info
.ready
&& workerNode
.usage
.tasks
.executing
=== 0
825 private isWorkerNodeBusy (workerNodeKey
: number): boolean {
826 if (this.opts
.enableTasksQueue
=== true) {
828 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
>=
829 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
830 this.opts
.tasksQueueOptions
!.concurrency
!
833 return this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
> 0
836 private async sendTaskFunctionOperationToWorker (
837 workerNodeKey
: number,
838 message
: MessageValue
<Data
>
839 ): Promise
<boolean> {
840 return await new Promise
<boolean>((resolve
, reject
) => {
841 const taskFunctionOperationListener
= (
842 message
: MessageValue
<Response
>
844 this.checkMessageWorkerId(message
)
845 const workerId
= this.getWorkerInfo(workerNodeKey
)?.id
847 message
.taskFunctionOperationStatus
!= null &&
848 message
.workerId
=== workerId
850 if (message
.taskFunctionOperationStatus
) {
855 `Task function operation '${message.taskFunctionOperation}' failed on worker ${message.workerId} with error: '${message.workerError?.message}'`
859 this.deregisterWorkerMessageListener(
860 this.getWorkerNodeKeyByWorkerId(message
.workerId
),
861 taskFunctionOperationListener
865 this.registerWorkerMessageListener(
867 taskFunctionOperationListener
869 this.sendToWorker(workerNodeKey
, message
)
873 private async sendTaskFunctionOperationToWorkers (
874 message
: MessageValue
<Data
>
875 ): Promise
<boolean> {
876 return await new Promise
<boolean>((resolve
, reject
) => {
877 const responsesReceived
= new Array<MessageValue
<Response
>>()
878 const taskFunctionOperationsListener
= (
879 message
: MessageValue
<Response
>
881 this.checkMessageWorkerId(message
)
882 if (message
.taskFunctionOperationStatus
!= null) {
883 responsesReceived
.push(message
)
884 if (responsesReceived
.length
=== this.workerNodes
.length
) {
886 responsesReceived
.every(
887 message
=> message
.taskFunctionOperationStatus
=== true
892 responsesReceived
.some(
893 message
=> message
.taskFunctionOperationStatus
=== false
896 const errorResponse
= responsesReceived
.find(
897 response
=> response
.taskFunctionOperationStatus
=== false
901 `Task function operation '${
902 message.taskFunctionOperation as string
903 }' failed on worker ${errorResponse?.workerId} with error: '${
904 errorResponse?.workerError?.message
909 this.deregisterWorkerMessageListener(
910 this.getWorkerNodeKeyByWorkerId(message
.workerId
),
911 taskFunctionOperationsListener
916 for (const workerNodeKey
of this.workerNodes
.keys()) {
917 this.registerWorkerMessageListener(
919 taskFunctionOperationsListener
921 this.sendToWorker(workerNodeKey
, message
)
927 public hasTaskFunction (name
: string): boolean {
928 return this.listTaskFunctionsProperties().some(
929 taskFunctionProperties
=> taskFunctionProperties
.name
=== name
934 public async addTaskFunction (
936 fn
: TaskFunction
<Data
, Response
> | TaskFunctionObject
<Data
, Response
>
937 ): Promise
<boolean> {
938 if (typeof name
!== 'string') {
939 throw new TypeError('name argument must be a string')
941 if (typeof name
=== 'string' && name
.trim().length
=== 0) {
942 throw new TypeError('name argument must not be an empty string')
944 if (typeof fn
=== 'function') {
945 fn
= { taskFunction
: fn
} satisfies TaskFunctionObject
<Data
, Response
>
947 if (typeof fn
.taskFunction
!== 'function') {
948 throw new TypeError('taskFunction property must be a function')
950 checkValidPriority(fn
.priority
)
951 checkValidWorkerChoiceStrategy(fn
.strategy
)
952 const opResult
= await this.sendTaskFunctionOperationToWorkers({
953 taskFunctionOperation
: 'add',
954 taskFunctionProperties
: buildTaskFunctionProperties(name
, fn
),
955 taskFunction
: fn
.taskFunction
.toString()
957 this.taskFunctions
.set(name
, fn
)
958 this.workerChoiceStrategiesContext
?.syncWorkerChoiceStrategies(
959 this.getWorkerWorkerChoiceStrategies()
961 for (const workerNodeKey
of this.workerNodes
.keys()) {
962 this.sendStatisticsMessageToWorker(workerNodeKey
)
968 public async removeTaskFunction (name
: string): Promise
<boolean> {
969 if (!this.taskFunctions
.has(name
)) {
971 'Cannot remove a task function not handled on the pool side'
974 const opResult
= await this.sendTaskFunctionOperationToWorkers({
975 taskFunctionOperation
: 'remove',
976 taskFunctionProperties
: buildTaskFunctionProperties(
978 this.taskFunctions
.get(name
)
981 for (const workerNode
of this.workerNodes
) {
982 workerNode
.deleteTaskFunctionWorkerUsage(name
)
984 this.taskFunctions
.delete(name
)
985 this.workerChoiceStrategiesContext
?.syncWorkerChoiceStrategies(
986 this.getWorkerWorkerChoiceStrategies()
988 for (const workerNodeKey
of this.workerNodes
.keys()) {
989 this.sendStatisticsMessageToWorker(workerNodeKey
)
995 public listTaskFunctionsProperties (): TaskFunctionProperties
[] {
996 for (const workerNode
of this.workerNodes
) {
998 Array.isArray(workerNode
.info
.taskFunctionsProperties
) &&
999 workerNode
.info
.taskFunctionsProperties
.length
> 0
1001 return workerNode
.info
.taskFunctionsProperties
1008 * Gets task function strategy, if any.
1010 * @param name - The task function name.
1011 * @returns The task function worker choice strategy if the task function worker choice strategy is defined, `undefined` otherwise.
1013 private readonly getTaskFunctionWorkerWorkerChoiceStrategy
= (
1015 ): WorkerChoiceStrategy
| undefined => {
1017 return this.listTaskFunctionsProperties().find(
1018 (taskFunctionProperties
: TaskFunctionProperties
) =>
1019 taskFunctionProperties
.name
=== name
1025 * Gets worker node task function priority, if any.
1027 * @param workerNodeKey - The worker node key.
1028 * @param name - The task function name.
1029 * @returns The task function worker choice priority if the task function worker choice priority is defined, `undefined` otherwise.
1031 private readonly getWorkerNodeTaskFunctionPriority
= (
1032 workerNodeKey
: number,
1034 ): number | undefined => {
1036 return this.getWorkerInfo(workerNodeKey
)?.taskFunctionsProperties
?.find(
1037 (taskFunctionProperties
: TaskFunctionProperties
) =>
1038 taskFunctionProperties
.name
=== name
1044 * Gets the worker choice strategies registered in this pool.
1046 * @returns The worker choice strategies.
1048 private readonly getWorkerWorkerChoiceStrategies
=
1049 (): Set
<WorkerChoiceStrategy
> => {
1051 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1052 this.opts
.workerChoiceStrategy
!,
1053 ...(this.listTaskFunctionsProperties()
1055 (taskFunctionProperties
: TaskFunctionProperties
) =>
1056 taskFunctionProperties
.strategy
1059 (strategy
: WorkerChoiceStrategy
| undefined) => strategy
!= null
1060 ) as WorkerChoiceStrategy
[])
1065 public async setDefaultTaskFunction (name
: string): Promise
<boolean> {
1066 return await this.sendTaskFunctionOperationToWorkers({
1067 taskFunctionOperation
: 'default',
1068 taskFunctionProperties
: buildTaskFunctionProperties(
1070 this.taskFunctions
.get(name
)
1075 private shallExecuteTask (workerNodeKey
: number): boolean {
1077 this.tasksQueueSize(workerNodeKey
) === 0 &&
1078 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
<
1079 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1080 this.opts
.tasksQueueOptions
!.concurrency
!
1085 public async execute (
1088 transferList
?: readonly TransferListItem
[]
1089 ): Promise
<Response
> {
1090 return await new Promise
<Response
>((resolve
, reject
) => {
1091 if (!this.started
) {
1092 reject(new Error('Cannot execute a task on not started pool'))
1095 if (this.destroying
) {
1096 reject(new Error('Cannot execute a task on destroying pool'))
1099 if (name
!= null && typeof name
!== 'string') {
1100 reject(new TypeError('name argument must be a string'))
1105 typeof name
=== 'string' &&
1106 name
.trim().length
=== 0
1108 reject(new TypeError('name argument must not be an empty string'))
1111 if (transferList
!= null && !Array.isArray(transferList
)) {
1112 reject(new TypeError('transferList argument must be an array'))
1115 const timestamp
= performance
.now()
1116 const taskFunctionStrategy
=
1117 this.getTaskFunctionWorkerWorkerChoiceStrategy(name
)
1118 const workerNodeKey
= this.chooseWorkerNode(taskFunctionStrategy
)
1119 const task
: Task
<Data
> = {
1120 name
: name
?? DEFAULT_TASK_NAME
,
1121 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
1122 data
: data
?? ({} as Data
),
1123 priority
: this.getWorkerNodeTaskFunctionPriority(workerNodeKey
, name
),
1124 strategy
: taskFunctionStrategy
,
1127 taskId
: randomUUID()
1129 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1130 this.promiseResponseMap
.set(task
.taskId
!, {
1134 ...(this.emitter
!= null && {
1135 asyncResource
: new AsyncResource('poolifier:task', {
1136 triggerAsyncId
: this.emitter
.asyncId
,
1137 requireManualDestroy
: true
1142 this.opts
.enableTasksQueue
=== false ||
1143 (this.opts
.enableTasksQueue
=== true &&
1144 this.shallExecuteTask(workerNodeKey
))
1146 this.executeTask(workerNodeKey
, task
)
1148 this.enqueueTask(workerNodeKey
, task
)
1154 * Starts the minimum number of workers.
1156 private startMinimumNumberOfWorkers (initWorkerNodeUsage
= false): void {
1157 this.startingMinimumNumberOfWorkers
= true
1159 this.workerNodes
.reduce(
1160 (accumulator
, workerNode
) =>
1161 !workerNode
.info
.dynamic
? accumulator
+ 1 : accumulator
,
1163 ) < this.minimumNumberOfWorkers
1165 const workerNodeKey
= this.createAndSetupWorkerNode()
1166 initWorkerNodeUsage
&&
1167 this.initWorkerNodeUsage(this.workerNodes
[workerNodeKey
])
1169 this.startingMinimumNumberOfWorkers
= false
1173 public start (): void {
1175 throw new Error('Cannot start an already started pool')
1177 if (this.starting
) {
1178 throw new Error('Cannot start an already starting pool')
1180 if (this.destroying
) {
1181 throw new Error('Cannot start a destroying pool')
1183 this.starting
= true
1184 this.startMinimumNumberOfWorkers()
1185 this.startTimestamp
= performance
.now()
1186 this.starting
= false
1191 public async destroy (): Promise
<void> {
1192 if (!this.started
) {
1193 throw new Error('Cannot destroy an already destroyed pool')
1195 if (this.starting
) {
1196 throw new Error('Cannot destroy an starting pool')
1198 if (this.destroying
) {
1199 throw new Error('Cannot destroy an already destroying pool')
1201 this.destroying
= true
1203 this.workerNodes
.map(async (_
, workerNodeKey
) => {
1204 await this.destroyWorkerNode(workerNodeKey
)
1207 this.emitter
?.emit(PoolEvents
.destroy
, this.info
)
1208 this.emitter
?.emitDestroy()
1209 this.readyEventEmitted
= false
1210 delete this.startTimestamp
1211 this.destroying
= false
1212 this.started
= false
1215 private async sendKillMessageToWorker (workerNodeKey
: number): Promise
<void> {
1216 await new Promise
<void>((resolve
, reject
) => {
1217 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1218 if (this.workerNodes
[workerNodeKey
] == null) {
1222 const killMessageListener
= (message
: MessageValue
<Response
>): void => {
1223 this.checkMessageWorkerId(message
)
1224 if (message
.kill
=== 'success') {
1226 } else if (message
.kill
=== 'failure') {
1229 `Kill message handling failed on worker ${message.workerId}`
1234 // FIXME: should be registered only once
1235 this.registerWorkerMessageListener(workerNodeKey
, killMessageListener
)
1236 this.sendToWorker(workerNodeKey
, { kill
: true })
1241 * Terminates the worker node given its worker node key.
1243 * @param workerNodeKey - The worker node key.
1245 protected async destroyWorkerNode (workerNodeKey
: number): Promise
<void> {
1246 this.flagWorkerNodeAsNotReady(workerNodeKey
)
1247 const flushedTasks
= this.flushTasksQueue(workerNodeKey
)
1248 const workerNode
= this.workerNodes
[workerNodeKey
]
1249 await waitWorkerNodeEvents(
1253 this.opts
.tasksQueueOptions
?.tasksFinishedTimeout
??
1254 getDefaultTasksQueueOptions(
1255 this.maximumNumberOfWorkers
?? this.minimumNumberOfWorkers
1256 ).tasksFinishedTimeout
1258 await this.sendKillMessageToWorker(workerNodeKey
)
1259 await workerNode
.terminate()
1263 * Setup hook to execute code before worker nodes are created in the abstract constructor.
1264 * Can be overridden.
1268 protected setupHook (): void {
1269 /* Intentionally empty */
1273 * Returns whether the worker is the main worker or not.
1275 * @returns `true` if the worker is the main worker, `false` otherwise.
1277 protected abstract isMain (): boolean
1280 * Hook executed before the worker task execution.
1281 * Can be overridden.
1283 * @param workerNodeKey - The worker node key.
1284 * @param task - The task to execute.
1286 protected beforeTaskExecutionHook (
1287 workerNodeKey
: number,
1290 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1291 if (this.workerNodes
[workerNodeKey
]?.usage
!= null) {
1292 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
1293 ++workerUsage
.tasks
.executing
1294 updateWaitTimeWorkerUsage(
1295 this.workerChoiceStrategiesContext
,
1301 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
1302 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1303 this.workerNodes
[workerNodeKey
].getTaskFunctionWorkerUsage(task
.name
!) !=
1306 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1307 const taskFunctionWorkerUsage
= this.workerNodes
[
1309 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1310 ].getTaskFunctionWorkerUsage(task
.name
!)!
1311 ++taskFunctionWorkerUsage
.tasks
.executing
1312 updateWaitTimeWorkerUsage(
1313 this.workerChoiceStrategiesContext
,
1314 taskFunctionWorkerUsage
,
1321 * Hook executed after the worker task execution.
1322 * Can be overridden.
1324 * @param workerNodeKey - The worker node key.
1325 * @param message - The received message.
1327 protected afterTaskExecutionHook (
1328 workerNodeKey
: number,
1329 message
: MessageValue
<Response
>
1331 let needWorkerChoiceStrategiesUpdate
= false
1332 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1333 if (this.workerNodes
[workerNodeKey
]?.usage
!= null) {
1334 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
1335 updateTaskStatisticsWorkerUsage(workerUsage
, message
)
1336 updateRunTimeWorkerUsage(
1337 this.workerChoiceStrategiesContext
,
1341 updateEluWorkerUsage(
1342 this.workerChoiceStrategiesContext
,
1346 needWorkerChoiceStrategiesUpdate
= true
1349 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
1350 this.workerNodes
[workerNodeKey
].getTaskFunctionWorkerUsage(
1351 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1352 message
.taskPerformance
!.name
1355 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1356 const taskFunctionWorkerUsage
= this.workerNodes
[
1358 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1359 ].getTaskFunctionWorkerUsage(message
.taskPerformance
!.name
)!
1360 updateTaskStatisticsWorkerUsage(taskFunctionWorkerUsage
, message
)
1361 updateRunTimeWorkerUsage(
1362 this.workerChoiceStrategiesContext
,
1363 taskFunctionWorkerUsage
,
1366 updateEluWorkerUsage(
1367 this.workerChoiceStrategiesContext
,
1368 taskFunctionWorkerUsage
,
1371 needWorkerChoiceStrategiesUpdate
= true
1373 if (needWorkerChoiceStrategiesUpdate
) {
1374 this.workerChoiceStrategiesContext
?.update(workerNodeKey
)
1379 * Whether the worker node shall update its task function worker usage or not.
1381 * @param workerNodeKey - The worker node key.
1382 * @returns `true` if the worker node shall update its task function worker usage, `false` otherwise.
1384 private shallUpdateTaskFunctionWorkerUsage (workerNodeKey
: number): boolean {
1385 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
1387 workerInfo
!= null &&
1388 Array.isArray(workerInfo
.taskFunctionsProperties
) &&
1389 workerInfo
.taskFunctionsProperties
.length
> 2
1394 * Chooses a worker node for the next task given the worker choice strategy.
1396 * @param workerChoiceStrategy - The worker choice strategy.
1397 * @returns The chosen worker node key
1399 private chooseWorkerNode (
1400 workerChoiceStrategy
?: WorkerChoiceStrategy
1402 if (this.shallCreateDynamicWorker()) {
1403 const workerNodeKey
= this.createAndSetupDynamicWorkerNode()
1405 this.workerChoiceStrategiesContext
?.getPolicy().dynamicWorkerUsage
===
1408 return workerNodeKey
1411 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1412 return this.workerChoiceStrategiesContext
!.execute(workerChoiceStrategy
)
1416 * Conditions for dynamic worker creation.
1418 * @returns Whether to create a dynamic worker or not.
1420 protected abstract shallCreateDynamicWorker (): boolean
1423 * Sends a message to worker given its worker node key.
1425 * @param workerNodeKey - The worker node key.
1426 * @param message - The message.
1427 * @param transferList - The optional array of transferable objects.
1429 protected abstract sendToWorker (
1430 workerNodeKey
: number,
1431 message
: MessageValue
<Data
>,
1432 transferList
?: readonly TransferListItem
[]
1436 * Initializes the worker node usage with sensible default values gathered during runtime.
1438 * @param workerNode - The worker node.
1440 private initWorkerNodeUsage (workerNode
: IWorkerNode
<Worker
, Data
>): void {
1442 this.workerChoiceStrategiesContext
?.getTaskStatisticsRequirements()
1443 .runTime
.aggregate
=== true
1445 workerNode
.usage
.runTime
.aggregate
= min(
1446 ...this.workerNodes
.map(
1447 workerNode
=> workerNode
.usage
.runTime
.aggregate
?? Infinity
1452 this.workerChoiceStrategiesContext
?.getTaskStatisticsRequirements()
1453 .waitTime
.aggregate
=== true
1455 workerNode
.usage
.waitTime
.aggregate
= min(
1456 ...this.workerNodes
.map(
1457 workerNode
=> workerNode
.usage
.waitTime
.aggregate
?? Infinity
1462 this.workerChoiceStrategiesContext
?.getTaskStatisticsRequirements().elu
1465 workerNode
.usage
.elu
.active
.aggregate
= min(
1466 ...this.workerNodes
.map(
1467 workerNode
=> workerNode
.usage
.elu
.active
.aggregate
?? Infinity
1474 * Creates a new, completely set up worker node.
1476 * @returns New, completely set up worker node key.
1478 protected createAndSetupWorkerNode (): number {
1479 const workerNode
= this.createWorkerNode()
1480 workerNode
.registerWorkerEventHandler(
1482 this.opts
.onlineHandler
?? EMPTY_FUNCTION
1484 workerNode
.registerWorkerEventHandler(
1486 this.opts
.messageHandler
?? EMPTY_FUNCTION
1488 workerNode
.registerWorkerEventHandler(
1490 this.opts
.errorHandler
?? EMPTY_FUNCTION
1492 workerNode
.registerOnceWorkerEventHandler('error', (error
: Error) => {
1493 workerNode
.info
.ready
= false
1494 this.emitter
?.emit(PoolEvents
.error
, error
)
1498 this.opts
.restartWorkerOnError
=== true
1500 if (workerNode
.info
.dynamic
) {
1501 this.createAndSetupDynamicWorkerNode()
1502 } else if (!this.startingMinimumNumberOfWorkers
) {
1503 this.startMinimumNumberOfWorkers(true)
1509 this.opts
.enableTasksQueue
=== true
1511 this.redistributeQueuedTasks(this.workerNodes
.indexOf(workerNode
))
1513 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1514 workerNode
?.terminate().catch((error
: unknown
) => {
1515 this.emitter
?.emit(PoolEvents
.error
, error
)
1518 workerNode
.registerWorkerEventHandler(
1520 this.opts
.exitHandler
?? EMPTY_FUNCTION
1522 workerNode
.registerOnceWorkerEventHandler('exit', () => {
1523 this.removeWorkerNode(workerNode
)
1526 !this.startingMinimumNumberOfWorkers
&&
1529 this.startMinimumNumberOfWorkers(true)
1532 const workerNodeKey
= this.addWorkerNode(workerNode
)
1533 this.afterWorkerNodeSetup(workerNodeKey
)
1534 return workerNodeKey
1538 * Creates a new, completely set up dynamic worker node.
1540 * @returns New, completely set up dynamic worker node key.
1542 protected createAndSetupDynamicWorkerNode (): number {
1543 const workerNodeKey
= this.createAndSetupWorkerNode()
1544 this.registerWorkerMessageListener(workerNodeKey
, message
=> {
1545 this.checkMessageWorkerId(message
)
1546 const localWorkerNodeKey
= this.getWorkerNodeKeyByWorkerId(
1549 const workerUsage
= this.workerNodes
[localWorkerNodeKey
]?.usage
1550 // Kill message received from worker
1552 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
1553 (isKillBehavior(KillBehaviors
.SOFT
, message
.kill
) &&
1554 ((this.opts
.enableTasksQueue
=== false &&
1555 workerUsage
.tasks
.executing
=== 0) ||
1556 (this.opts
.enableTasksQueue
=== true &&
1557 workerUsage
.tasks
.executing
=== 0 &&
1558 this.tasksQueueSize(localWorkerNodeKey
) === 0)))
1560 // Flag the worker node as not ready immediately
1561 this.flagWorkerNodeAsNotReady(localWorkerNodeKey
)
1562 this.destroyWorkerNode(localWorkerNodeKey
).catch((error
: unknown
) => {
1563 this.emitter
?.emit(PoolEvents
.error
, error
)
1567 this.sendToWorker(workerNodeKey
, {
1570 if (this.taskFunctions
.size
> 0) {
1571 for (const [taskFunctionName
, taskFunctionObject
] of this.taskFunctions
) {
1572 this.sendTaskFunctionOperationToWorker(workerNodeKey
, {
1573 taskFunctionOperation
: 'add',
1574 taskFunctionProperties
: buildTaskFunctionProperties(
1578 taskFunction
: taskFunctionObject
.taskFunction
.toString()
1579 }).catch((error
: unknown
) => {
1580 this.emitter
?.emit(PoolEvents
.error
, error
)
1584 const workerNode
= this.workerNodes
[workerNodeKey
]
1585 workerNode
.info
.dynamic
= true
1587 this.workerChoiceStrategiesContext
?.getPolicy().dynamicWorkerReady
===
1589 this.workerChoiceStrategiesContext
?.getPolicy().dynamicWorkerUsage
===
1592 workerNode
.info
.ready
= true
1594 this.initWorkerNodeUsage(workerNode
)
1595 this.checkAndEmitDynamicWorkerCreationEvents()
1596 return workerNodeKey
1600 * Registers a listener callback on the worker given its worker node key.
1602 * @param workerNodeKey - The worker node key.
1603 * @param listener - The message listener callback.
1605 protected abstract registerWorkerMessageListener
<
1606 Message
extends Data
| Response
1608 workerNodeKey
: number,
1609 listener
: (message
: MessageValue
<Message
>) => void
1613 * Registers once a listener callback on the worker given its worker node key.
1615 * @param workerNodeKey - The worker node key.
1616 * @param listener - The message listener callback.
1618 protected abstract registerOnceWorkerMessageListener
<
1619 Message
extends Data
| Response
1621 workerNodeKey
: number,
1622 listener
: (message
: MessageValue
<Message
>) => void
1626 * Deregisters a listener callback on the worker given its worker node key.
1628 * @param workerNodeKey - The worker node key.
1629 * @param listener - The message listener callback.
1631 protected abstract deregisterWorkerMessageListener
<
1632 Message
extends Data
| Response
1634 workerNodeKey
: number,
1635 listener
: (message
: MessageValue
<Message
>) => void
1639 * Method hooked up after a worker node has been newly created.
1640 * Can be overridden.
1642 * @param workerNodeKey - The newly created worker node key.
1644 protected afterWorkerNodeSetup (workerNodeKey
: number): void {
1645 // Listen to worker messages.
1646 this.registerWorkerMessageListener(
1648 this.workerMessageListener
1650 // Send the startup message to worker.
1651 this.sendStartupMessageToWorker(workerNodeKey
)
1652 // Send the statistics message to worker.
1653 this.sendStatisticsMessageToWorker(workerNodeKey
)
1654 if (this.opts
.enableTasksQueue
=== true) {
1655 if (this.opts
.tasksQueueOptions
?.taskStealing
=== true) {
1656 this.workerNodes
[workerNodeKey
].on(
1658 this.handleWorkerNodeIdleEvent
1661 if (this.opts
.tasksQueueOptions
?.tasksStealingOnBackPressure
=== true) {
1662 this.workerNodes
[workerNodeKey
].on(
1664 this.handleWorkerNodeBackPressureEvent
1671 * Sends the startup message to worker given its worker node key.
1673 * @param workerNodeKey - The worker node key.
1675 protected abstract sendStartupMessageToWorker (workerNodeKey
: number): void
1678 * Sends the statistics message to worker given its worker node key.
1680 * @param workerNodeKey - The worker node key.
1682 private sendStatisticsMessageToWorker (workerNodeKey
: number): void {
1683 this.sendToWorker(workerNodeKey
, {
1686 this.workerChoiceStrategiesContext
?.getTaskStatisticsRequirements()
1687 .runTime
.aggregate
?? false,
1689 this.workerChoiceStrategiesContext
?.getTaskStatisticsRequirements()
1690 .elu
.aggregate
?? false
1695 private cannotStealTask (): boolean {
1696 return this.workerNodes
.length
<= 1 || this.info
.queuedTasks
=== 0
1699 private handleTask (workerNodeKey
: number, task
: Task
<Data
>): void {
1700 if (this.shallExecuteTask(workerNodeKey
)) {
1701 this.executeTask(workerNodeKey
, task
)
1703 this.enqueueTask(workerNodeKey
, task
)
1707 private redistributeQueuedTasks (sourceWorkerNodeKey
: number): void {
1708 if (sourceWorkerNodeKey
=== -1 || this.cannotStealTask()) {
1711 while (this.tasksQueueSize(sourceWorkerNodeKey
) > 0) {
1712 const destinationWorkerNodeKey
= this.workerNodes
.reduce(
1713 (minWorkerNodeKey
, workerNode
, workerNodeKey
, workerNodes
) => {
1714 return sourceWorkerNodeKey
!== workerNodeKey
&&
1715 workerNode
.info
.ready
&&
1716 workerNode
.usage
.tasks
.queued
<
1717 workerNodes
[minWorkerNodeKey
].usage
.tasks
.queued
1724 destinationWorkerNodeKey
,
1725 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1726 this.dequeueTask(sourceWorkerNodeKey
)!
1731 private updateTaskStolenStatisticsWorkerUsage (
1732 workerNodeKey
: number,
1735 const workerNode
= this.workerNodes
[workerNodeKey
]
1736 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1737 if (workerNode
?.usage
!= null) {
1738 ++workerNode
.usage
.tasks
.stolen
1741 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
1742 workerNode
.getTaskFunctionWorkerUsage(taskName
) != null
1744 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1745 ++workerNode
.getTaskFunctionWorkerUsage(taskName
)!.tasks
.stolen
1749 private updateTaskSequentiallyStolenStatisticsWorkerUsage (
1750 workerNodeKey
: number,
1752 previousTaskName
?: string
1754 const workerNode
= this.workerNodes
[workerNodeKey
]
1755 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1756 if (workerNode
?.usage
!= null) {
1757 ++workerNode
.usage
.tasks
.sequentiallyStolen
1760 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
1761 workerNode
.getTaskFunctionWorkerUsage(taskName
) != null
1763 const taskFunctionWorkerUsage
=
1764 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1765 workerNode
.getTaskFunctionWorkerUsage(taskName
)!
1767 taskFunctionWorkerUsage
.tasks
.sequentiallyStolen
=== 0 ||
1768 (previousTaskName
!= null &&
1769 previousTaskName
=== taskName
&&
1770 taskFunctionWorkerUsage
.tasks
.sequentiallyStolen
> 0)
1772 ++taskFunctionWorkerUsage
.tasks
.sequentiallyStolen
1773 } else if (taskFunctionWorkerUsage
.tasks
.sequentiallyStolen
> 0) {
1774 taskFunctionWorkerUsage
.tasks
.sequentiallyStolen
= 0
1779 private resetTaskSequentiallyStolenStatisticsWorkerUsage (
1780 workerNodeKey
: number,
1783 const workerNode
= this.workerNodes
[workerNodeKey
]
1784 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1785 if (workerNode
?.usage
!= null) {
1786 workerNode
.usage
.tasks
.sequentiallyStolen
= 0
1789 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
1790 workerNode
.getTaskFunctionWorkerUsage(taskName
) != null
1792 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1793 workerNode
.getTaskFunctionWorkerUsage(
1795 )!.tasks
.sequentiallyStolen
= 0
1799 private readonly handleWorkerNodeIdleEvent
= (
1800 eventDetail
: WorkerNodeEventDetail
,
1801 previousStolenTask
?: Task
<Data
>
1803 const { workerNodeKey
} = eventDetail
1804 if (workerNodeKey
== null) {
1806 "WorkerNode event detail 'workerNodeKey' property must be defined"
1809 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
1810 if (workerInfo
== null) {
1812 `Worker node with key '${workerNodeKey}' not found in pool`
1816 this.cannotStealTask() ||
1817 (this.info
.stealingWorkerNodes
?? 0) >
1818 Math.floor(this.workerNodes
.length
/ 2)
1820 if (previousStolenTask
!= null) {
1821 workerInfo
.stealing
= false
1822 this.resetTaskSequentiallyStolenStatisticsWorkerUsage(
1824 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1825 previousStolenTask
.name
!
1830 const workerNodeTasksUsage
= this.workerNodes
[workerNodeKey
].usage
.tasks
1832 previousStolenTask
!= null &&
1833 (workerNodeTasksUsage
.executing
> 0 ||
1834 this.tasksQueueSize(workerNodeKey
) > 0)
1836 workerInfo
.stealing
= false
1837 this.resetTaskSequentiallyStolenStatisticsWorkerUsage(
1839 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1840 previousStolenTask
.name
!
1844 workerInfo
.stealing
= true
1845 const stolenTask
= this.workerNodeStealTask(workerNodeKey
)
1846 if (stolenTask
!= null) {
1847 this.updateTaskSequentiallyStolenStatisticsWorkerUsage(
1849 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1851 previousStolenTask
?.name
1854 sleep(exponentialDelay(workerNodeTasksUsage
.sequentiallyStolen
))
1856 this.handleWorkerNodeIdleEvent(eventDetail
, stolenTask
)
1859 .catch((error
: unknown
) => {
1860 this.emitter
?.emit(PoolEvents
.error
, error
)
1864 private readonly workerNodeStealTask
= (
1865 workerNodeKey
: number
1866 ): Task
<Data
> | undefined => {
1867 const workerNodes
= this.workerNodes
1870 (workerNodeA
, workerNodeB
) =>
1871 workerNodeB
.usage
.tasks
.queued
- workerNodeA
.usage
.tasks
.queued
1873 const sourceWorkerNode
= workerNodes
.find(
1874 (sourceWorkerNode
, sourceWorkerNodeKey
) =>
1875 sourceWorkerNode
.info
.ready
&&
1876 !sourceWorkerNode
.info
.stealing
&&
1877 sourceWorkerNodeKey
!== workerNodeKey
&&
1878 sourceWorkerNode
.usage
.tasks
.queued
> 0
1880 if (sourceWorkerNode
!= null) {
1881 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1882 const task
= sourceWorkerNode
.dequeueLastPrioritizedTask()!
1883 this.handleTask(workerNodeKey
, task
)
1884 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1885 this.updateTaskStolenStatisticsWorkerUsage(workerNodeKey
, task
.name
!)
1890 private readonly handleWorkerNodeBackPressureEvent
= (
1891 eventDetail
: WorkerNodeEventDetail
1894 this.cannotStealTask() ||
1895 this.hasBackPressure() ||
1896 (this.info
.stealingWorkerNodes
?? 0) >
1897 Math.floor(this.workerNodes
.length
/ 2)
1901 const sizeOffset
= 1
1902 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1903 if (this.opts
.tasksQueueOptions
!.size
! <= sizeOffset
) {
1906 const { workerId
} = eventDetail
1907 const sourceWorkerNode
=
1908 this.workerNodes
[this.getWorkerNodeKeyByWorkerId(workerId
)]
1909 const workerNodes
= this.workerNodes
1912 (workerNodeA
, workerNodeB
) =>
1913 workerNodeA
.usage
.tasks
.queued
- workerNodeB
.usage
.tasks
.queued
1915 for (const [workerNodeKey
, workerNode
] of workerNodes
.entries()) {
1917 sourceWorkerNode
.usage
.tasks
.queued
> 0 &&
1918 workerNode
.info
.ready
&&
1919 !workerNode
.info
.stealing
&&
1920 workerNode
.info
.id
!== workerId
&&
1921 workerNode
.usage
.tasks
.queued
<
1922 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1923 this.opts
.tasksQueueOptions
!.size
! - sizeOffset
1925 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
1926 if (workerInfo
== null) {
1928 `Worker node with key '${workerNodeKey}' not found in pool`
1931 workerInfo
.stealing
= true
1932 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1933 const task
= sourceWorkerNode
.dequeueLastPrioritizedTask()!
1934 this.handleTask(workerNodeKey
, task
)
1935 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1936 this.updateTaskStolenStatisticsWorkerUsage(workerNodeKey
, task
.name
!)
1937 workerInfo
.stealing
= false
1943 * This method is the message listener registered on each worker.
1945 protected readonly workerMessageListener
= (
1946 message
: MessageValue
<Response
>
1948 this.checkMessageWorkerId(message
)
1949 const { workerId
, ready
, taskId
, taskFunctionsProperties
} = message
1950 if (ready
!= null && taskFunctionsProperties
!= null) {
1951 // Worker ready response received from worker
1952 this.handleWorkerReadyResponse(message
)
1953 } else if (taskFunctionsProperties
!= null) {
1954 // Task function properties message received from worker
1955 const workerNodeKey
= this.getWorkerNodeKeyByWorkerId(workerId
)
1956 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
1957 if (workerInfo
!= null) {
1958 workerInfo
.taskFunctionsProperties
= taskFunctionsProperties
1959 this.sendStatisticsMessageToWorker(workerNodeKey
)
1961 } else if (taskId
!= null) {
1962 // Task execution response received from worker
1963 this.handleTaskExecutionResponse(message
)
1967 private checkAndEmitReadyEvent (): void {
1968 if (!this.readyEventEmitted
&& this.ready
) {
1969 this.emitter
?.emit(PoolEvents
.ready
, this.info
)
1970 this.readyEventEmitted
= true
1974 private handleWorkerReadyResponse (message
: MessageValue
<Response
>): void {
1975 const { workerId
, ready
, taskFunctionsProperties
} = message
1976 if (ready
== null || !ready
) {
1977 throw new Error(`Worker ${workerId} failed to initialize`)
1979 const workerNodeKey
= this.getWorkerNodeKeyByWorkerId(workerId
)
1980 const workerNode
= this.workerNodes
[workerNodeKey
]
1981 workerNode
.info
.ready
= ready
1982 workerNode
.info
.taskFunctionsProperties
= taskFunctionsProperties
1983 this.sendStatisticsMessageToWorker(workerNodeKey
)
1984 this.checkAndEmitReadyEvent()
1987 private handleTaskExecutionResponse (message
: MessageValue
<Response
>): void {
1988 const { workerId
, taskId
, workerError
, data
} = message
1989 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1990 const promiseResponse
= this.promiseResponseMap
.get(taskId
!)
1991 if (promiseResponse
!= null) {
1992 const { resolve
, reject
, workerNodeKey
, asyncResource
} = promiseResponse
1993 const workerNode
= this.workerNodes
[workerNodeKey
]
1994 if (workerError
!= null) {
1995 this.emitter
?.emit(PoolEvents
.taskError
, workerError
)
1996 asyncResource
!= null
1997 ? asyncResource
.runInAsyncScope(
2002 : reject(workerError
.message
)
2004 asyncResource
!= null
2005 ? asyncResource
.runInAsyncScope(resolve
, this.emitter
, data
)
2006 : resolve(data
as Response
)
2008 asyncResource
?.emitDestroy()
2009 this.afterTaskExecutionHook(workerNodeKey
, message
)
2010 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2011 this.promiseResponseMap
.delete(taskId
!)
2012 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
2013 workerNode
?.emit('taskFinished', taskId
)
2015 this.opts
.enableTasksQueue
=== true &&
2017 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
2020 const workerNodeTasksUsage
= workerNode
.usage
.tasks
2022 this.tasksQueueSize(workerNodeKey
) > 0 &&
2023 workerNodeTasksUsage
.executing
<
2024 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2025 this.opts
.tasksQueueOptions
!.concurrency
!
2027 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2028 this.executeTask(workerNodeKey
, this.dequeueTask(workerNodeKey
)!)
2031 workerNodeTasksUsage
.executing
=== 0 &&
2032 this.tasksQueueSize(workerNodeKey
) === 0 &&
2033 workerNodeTasksUsage
.sequentiallyStolen
=== 0
2035 workerNode
.emit('idle', {
2044 private checkAndEmitTaskExecutionEvents (): void {
2046 this.emitter
?.emit(PoolEvents
.busy
, this.info
)
2050 private checkAndEmitTaskQueuingEvents (): void {
2051 if (this.hasBackPressure()) {
2052 this.emitter
?.emit(PoolEvents
.backPressure
, this.info
)
2057 * Emits dynamic worker creation events.
2059 protected abstract checkAndEmitDynamicWorkerCreationEvents (): void
2062 * Gets the worker information given its worker node key.
2064 * @param workerNodeKey - The worker node key.
2065 * @returns The worker information.
2067 protected getWorkerInfo (workerNodeKey
: number): WorkerInfo
| undefined {
2068 return this.workerNodes
[workerNodeKey
]?.info
2072 * Creates a worker node.
2074 * @returns The created worker node.
2076 private createWorkerNode (): IWorkerNode
<Worker
, Data
> {
2077 const workerNode
= new WorkerNode
<Worker
, Data
>(
2082 workerOptions
: this.opts
.workerOptions
,
2083 tasksQueueBackPressureSize
:
2084 this.opts
.tasksQueueOptions
?.size
??
2085 getDefaultTasksQueueOptions(
2086 this.maximumNumberOfWorkers
?? this.minimumNumberOfWorkers
2088 tasksQueueBucketSize
:
2089 (this.maximumNumberOfWorkers
?? this.minimumNumberOfWorkers
) * 2
2092 // Flag the worker node as ready at pool startup.
2093 if (this.starting
) {
2094 workerNode
.info
.ready
= true
2100 * Adds the given worker node in the pool worker nodes.
2102 * @param workerNode - The worker node.
2103 * @returns The added worker node key.
2104 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the added worker node is not found.
2106 private addWorkerNode (workerNode
: IWorkerNode
<Worker
, Data
>): number {
2107 this.workerNodes
.push(workerNode
)
2108 const workerNodeKey
= this.workerNodes
.indexOf(workerNode
)
2109 if (workerNodeKey
=== -1) {
2110 throw new Error('Worker added not found in worker nodes')
2112 return workerNodeKey
2115 private checkAndEmitEmptyEvent (): void {
2117 this.emitter
?.emit(PoolEvents
.empty
, this.info
)
2118 this.readyEventEmitted
= false
2123 * Removes the worker node from the pool worker nodes.
2125 * @param workerNode - The worker node.
2127 private removeWorkerNode (workerNode
: IWorkerNode
<Worker
, Data
>): void {
2128 const workerNodeKey
= this.workerNodes
.indexOf(workerNode
)
2129 if (workerNodeKey
!== -1) {
2130 this.workerNodes
.splice(workerNodeKey
, 1)
2131 this.workerChoiceStrategiesContext
?.remove(workerNodeKey
)
2133 this.checkAndEmitEmptyEvent()
2136 protected flagWorkerNodeAsNotReady (workerNodeKey
: number): void {
2137 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
2138 if (workerInfo
!= null) {
2139 workerInfo
.ready
= false
2143 private hasBackPressure (): boolean {
2145 this.opts
.enableTasksQueue
=== true &&
2146 this.workerNodes
.findIndex(
2147 workerNode
=> !workerNode
.hasBackPressure()
2153 * Executes the given task on the worker given its worker node key.
2155 * @param workerNodeKey - The worker node key.
2156 * @param task - The task to execute.
2158 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
2159 this.beforeTaskExecutionHook(workerNodeKey
, task
)
2160 this.sendToWorker(workerNodeKey
, task
, task
.transferList
)
2161 this.checkAndEmitTaskExecutionEvents()
2164 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
2165 const tasksQueueSize
= this.workerNodes
[workerNodeKey
].enqueueTask(task
)
2166 this.checkAndEmitTaskQueuingEvents()
2167 return tasksQueueSize
2170 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
2171 return this.workerNodes
[workerNodeKey
].dequeueTask()
2174 private tasksQueueSize (workerNodeKey
: number): number {
2175 return this.workerNodes
[workerNodeKey
].tasksQueueSize()
2178 protected flushTasksQueue (workerNodeKey
: number): number {
2179 let flushedTasks
= 0
2180 while (this.tasksQueueSize(workerNodeKey
) > 0) {
2181 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2182 this.executeTask(workerNodeKey
, this.dequeueTask(workerNodeKey
)!)
2185 this.workerNodes
[workerNodeKey
].clearTasksQueue()
2189 private flushTasksQueues (): void {
2190 for (const workerNodeKey
of this.workerNodes
.keys()) {
2191 this.flushTasksQueue(workerNodeKey
)