1 import { randomUUID
} from
'node:crypto'
2 import { performance
} from
'node:perf_hooks'
3 import type { TransferListItem
} from
'node:worker_threads'
4 import { EventEmitterAsyncResource
} from
'node:events'
5 import { AsyncResource
} from
'node:async_hooks'
8 PromiseResponseWrapper
,
10 } from
'../utility-types.js'
24 import { KillBehaviors
} from
'../worker/worker-options.js'
25 import type { TaskFunction
} from
'../worker/task-functions.js'
33 type TasksQueueOptions
39 WorkerNodeEventDetail
,
44 WorkerChoiceStrategies
,
45 type WorkerChoiceStrategy
,
46 type WorkerChoiceStrategyOptions
47 } from
'./selection-strategies/selection-strategies-types.js'
48 import { WorkerChoiceStrategyContext
} from
'./selection-strategies/worker-choice-strategy-context.js'
49 import { version
} from
'./version.js'
50 import { WorkerNode
} from
'./worker-node.js'
53 checkValidTasksQueueOptions
,
54 checkValidWorkerChoiceStrategy
,
55 getDefaultTasksQueueOptions
,
57 updateRunTimeWorkerUsage
,
58 updateTaskStatisticsWorkerUsage
,
59 updateWaitTimeWorkerUsage
,
64 * Base class that implements some shared logic for all poolifier pools.
66 * @typeParam Worker - Type of worker which manages this pool.
67 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
68 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
70 export abstract class AbstractPool
<
71 Worker
extends IWorker
,
74 > implements IPool
<Worker
, Data
, Response
> {
76 public readonly workerNodes
: Array<IWorkerNode
<Worker
, Data
>> = []
79 public emitter
?: EventEmitterAsyncResource
82 * The task execution response promise map:
83 * - `key`: The message id of each submitted task.
84 * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks.
86 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
88 protected promiseResponseMap
: Map
<string, PromiseResponseWrapper
<Response
>> =
89 new Map
<string, PromiseResponseWrapper
<Response
>>()
92 * Worker choice strategy context referencing a worker choice algorithm implementation.
94 protected workerChoiceStrategyContext
?: WorkerChoiceStrategyContext
<
101 * The task functions added at runtime map:
102 * - `key`: The task function name.
103 * - `value`: The task function itself.
105 private readonly taskFunctions
: Map
<string, TaskFunction
<Data
, Response
>>
108 * Whether the pool is started or not.
110 private started
: boolean
112 * Whether the pool is starting or not.
114 private starting
: boolean
116 * Whether the pool is destroying or not.
118 private destroying
: boolean
120 * Whether the pool ready event has been emitted or not.
122 private readyEventEmitted
: boolean
124 * The start timestamp of the pool.
126 private readonly startTimestamp
129 * Constructs a new poolifier pool.
131 * @param minimumNumberOfWorkers - Minimum number of workers that this pool manages.
132 * @param filePath - Path to the worker file.
133 * @param opts - Options for the pool.
134 * @param maximumNumberOfWorkers - Maximum number of workers that this pool manages.
137 protected readonly minimumNumberOfWorkers
: number,
138 protected readonly filePath
: string,
139 protected readonly opts
: PoolOptions
<Worker
>,
140 protected readonly maximumNumberOfWorkers
?: number
142 if (!this.isMain()) {
144 'Cannot start a pool from a worker with the same type as the pool'
148 checkFilePath(this.filePath
)
149 this.checkMinimumNumberOfWorkers(this.minimumNumberOfWorkers
)
150 this.checkPoolOptions(this.opts
)
152 this.chooseWorkerNode
= this.chooseWorkerNode
.bind(this)
153 this.executeTask
= this.executeTask
.bind(this)
154 this.enqueueTask
= this.enqueueTask
.bind(this)
156 if (this.opts
.enableEvents
=== true) {
157 this.initializeEventEmitter()
159 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext
<
165 this.opts
.workerChoiceStrategy
,
166 this.opts
.workerChoiceStrategyOptions
171 this.taskFunctions
= new Map
<string, TaskFunction
<Data
, Response
>>()
174 this.starting
= false
175 this.destroying
= false
176 this.readyEventEmitted
= false
177 if (this.opts
.startWorkers
=== true) {
181 this.startTimestamp
= performance
.now()
184 private checkPoolType (): void {
185 if (this.type === PoolTypes
.fixed
&& this.maximumNumberOfWorkers
!= null) {
187 'Cannot instantiate a fixed pool with a maximum number of workers specified at initialization'
192 private checkMinimumNumberOfWorkers (
193 minimumNumberOfWorkers
: number | undefined
195 if (minimumNumberOfWorkers
== null) {
197 'Cannot instantiate a pool without specifying the number of workers'
199 } else if (!Number.isSafeInteger(minimumNumberOfWorkers
)) {
201 'Cannot instantiate a pool with a non safe integer number of workers'
203 } else if (minimumNumberOfWorkers
< 0) {
204 throw new RangeError(
205 'Cannot instantiate a pool with a negative number of workers'
207 } else if (this.type === PoolTypes
.fixed
&& minimumNumberOfWorkers
=== 0) {
208 throw new RangeError('Cannot instantiate a fixed pool with zero worker')
212 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
213 if (isPlainObject(opts
)) {
214 this.opts
.startWorkers
= opts
.startWorkers
?? true
215 checkValidWorkerChoiceStrategy(opts
.workerChoiceStrategy
)
216 this.opts
.workerChoiceStrategy
=
217 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
218 this.checkValidWorkerChoiceStrategyOptions(
219 opts
.workerChoiceStrategyOptions
221 if (opts
.workerChoiceStrategyOptions
!= null) {
222 this.opts
.workerChoiceStrategyOptions
= opts
.workerChoiceStrategyOptions
224 this.opts
.restartWorkerOnError
= opts
.restartWorkerOnError
?? true
225 this.opts
.enableEvents
= opts
.enableEvents
?? true
226 this.opts
.enableTasksQueue
= opts
.enableTasksQueue
?? false
227 if (this.opts
.enableTasksQueue
) {
228 checkValidTasksQueueOptions(opts
.tasksQueueOptions
)
229 this.opts
.tasksQueueOptions
= this.buildTasksQueueOptions(
230 opts
.tasksQueueOptions
234 throw new TypeError('Invalid pool options: must be a plain object')
238 private checkValidWorkerChoiceStrategyOptions (
239 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
| undefined
242 workerChoiceStrategyOptions
!= null &&
243 !isPlainObject(workerChoiceStrategyOptions
)
246 'Invalid worker choice strategy options: must be a plain object'
250 workerChoiceStrategyOptions
?.weights
!= null &&
251 Object.keys(workerChoiceStrategyOptions
.weights
).length
!==
252 (this.maximumNumberOfWorkers
?? this.minimumNumberOfWorkers
)
255 'Invalid worker choice strategy options: must have a weight for each worker node'
259 workerChoiceStrategyOptions
?.measurement
!= null &&
260 !Object.values(Measurements
).includes(
261 workerChoiceStrategyOptions
.measurement
265 `Invalid worker choice strategy options: invalid measurement '${workerChoiceStrategyOptions.measurement}'`
270 private initializeEventEmitter (): void {
271 this.emitter
= new EventEmitterAsyncResource({
272 name
: `poolifier:${this.type}-${this.worker}-pool`
277 public get
info (): PoolInfo
{
282 started
: this.started
,
284 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
285 strategy
: this.opts
.workerChoiceStrategy
!,
286 minSize
: this.minimumNumberOfWorkers
,
287 maxSize
: this.maximumNumberOfWorkers
?? this.minimumNumberOfWorkers
,
288 ...(this.workerChoiceStrategyContext
?.getTaskStatisticsRequirements()
289 ?.runTime
.aggregate
=== true &&
290 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
291 .waitTime
.aggregate
&& {
292 utilization
: round(this.utilization
)
294 workerNodes
: this.workerNodes
.length
,
295 idleWorkerNodes
: this.workerNodes
.reduce(
296 (accumulator
, workerNode
) =>
297 workerNode
.usage
.tasks
.executing
=== 0
302 ...(this.opts
.enableTasksQueue
=== true && {
303 stealingWorkerNodes
: this.workerNodes
.reduce(
304 (accumulator
, workerNode
) =>
305 workerNode
.info
.stealing
? accumulator
+ 1 : accumulator
,
309 busyWorkerNodes
: this.workerNodes
.reduce(
310 (accumulator
, _workerNode
, workerNodeKey
) =>
311 this.isWorkerNodeBusy(workerNodeKey
) ? accumulator
+ 1 : accumulator
,
314 executedTasks
: this.workerNodes
.reduce(
315 (accumulator
, workerNode
) =>
316 accumulator
+ workerNode
.usage
.tasks
.executed
,
319 executingTasks
: this.workerNodes
.reduce(
320 (accumulator
, workerNode
) =>
321 accumulator
+ workerNode
.usage
.tasks
.executing
,
324 ...(this.opts
.enableTasksQueue
=== true && {
325 queuedTasks
: this.workerNodes
.reduce(
326 (accumulator
, workerNode
) =>
327 accumulator
+ workerNode
.usage
.tasks
.queued
,
331 ...(this.opts
.enableTasksQueue
=== true && {
332 maxQueuedTasks
: this.workerNodes
.reduce(
333 (accumulator
, workerNode
) =>
334 accumulator
+ (workerNode
.usage
.tasks
.maxQueued
?? 0),
338 ...(this.opts
.enableTasksQueue
=== true && {
339 backPressure
: this.hasBackPressure()
341 ...(this.opts
.enableTasksQueue
=== true && {
342 stolenTasks
: this.workerNodes
.reduce(
343 (accumulator
, workerNode
) =>
344 accumulator
+ workerNode
.usage
.tasks
.stolen
,
348 failedTasks
: this.workerNodes
.reduce(
349 (accumulator
, workerNode
) =>
350 accumulator
+ workerNode
.usage
.tasks
.failed
,
353 ...(this.workerChoiceStrategyContext
?.getTaskStatisticsRequirements()
354 ?.runTime
.aggregate
=== true && {
358 ...this.workerNodes
.map(
359 workerNode
=> workerNode
.usage
.runTime
.minimum
?? Infinity
365 ...this.workerNodes
.map(
366 workerNode
=> workerNode
.usage
.runTime
.maximum
?? -Infinity
370 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
371 .runTime
.average
&& {
374 this.workerNodes
.reduce
<number[]>(
375 (accumulator
, workerNode
) =>
376 accumulator
.concat(workerNode
.usage
.runTime
.history
),
382 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
386 this.workerNodes
.reduce
<number[]>(
387 (accumulator
, workerNode
) =>
388 accumulator
.concat(workerNode
.usage
.runTime
.history
),
396 ...(this.workerChoiceStrategyContext
?.getTaskStatisticsRequirements()
397 ?.waitTime
.aggregate
=== true && {
401 ...this.workerNodes
.map(
402 workerNode
=> workerNode
.usage
.waitTime
.minimum
?? Infinity
408 ...this.workerNodes
.map(
409 workerNode
=> workerNode
.usage
.waitTime
.maximum
?? -Infinity
413 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
414 .waitTime
.average
&& {
417 this.workerNodes
.reduce
<number[]>(
418 (accumulator
, workerNode
) =>
419 accumulator
.concat(workerNode
.usage
.waitTime
.history
),
425 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
426 .waitTime
.median
&& {
429 this.workerNodes
.reduce
<number[]>(
430 (accumulator
, workerNode
) =>
431 accumulator
.concat(workerNode
.usage
.waitTime
.history
),
443 * The pool readiness boolean status.
445 private get
ready (): boolean {
447 this.workerNodes
.reduce(
448 (accumulator
, workerNode
) =>
449 !workerNode
.info
.dynamic
&& workerNode
.info
.ready
453 ) >= this.minimumNumberOfWorkers
458 * The approximate pool utilization.
460 * @returns The pool utilization.
462 private get
utilization (): number {
463 const poolTimeCapacity
=
464 (performance
.now() - this.startTimestamp
) *
465 (this.maximumNumberOfWorkers
?? this.minimumNumberOfWorkers
)
466 const totalTasksRunTime
= this.workerNodes
.reduce(
467 (accumulator
, workerNode
) =>
468 accumulator
+ (workerNode
.usage
.runTime
.aggregate
?? 0),
471 const totalTasksWaitTime
= this.workerNodes
.reduce(
472 (accumulator
, workerNode
) =>
473 accumulator
+ (workerNode
.usage
.waitTime
.aggregate
?? 0),
476 return (totalTasksRunTime
+ totalTasksWaitTime
) / poolTimeCapacity
482 * If it is `'dynamic'`, it provides the `max` property.
484 protected abstract get
type (): PoolType
489 protected abstract get
worker (): WorkerType
492 * Checks if the worker id sent in the received message from a worker is valid.
494 * @param message - The received message.
495 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the worker id is invalid.
497 private checkMessageWorkerId (message
: MessageValue
<Data
| Response
>): void {
498 if (message
.workerId
== null) {
499 throw new Error('Worker message received without worker id')
500 } else if (this.getWorkerNodeKeyByWorkerId(message
.workerId
) === -1) {
502 `Worker message received from unknown worker '${message.workerId}'`
508 * Gets the worker node key given its worker id.
510 * @param workerId - The worker id.
511 * @returns The worker node key if the worker id is found in the pool worker nodes, `-1` otherwise.
513 private getWorkerNodeKeyByWorkerId (workerId
: number | undefined): number {
514 return this.workerNodes
.findIndex(
515 workerNode
=> workerNode
.info
.id
=== workerId
520 public setWorkerChoiceStrategy (
521 workerChoiceStrategy
: WorkerChoiceStrategy
,
522 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
524 checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
525 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
526 this.workerChoiceStrategyContext
?.setWorkerChoiceStrategy(
527 this.opts
.workerChoiceStrategy
529 if (workerChoiceStrategyOptions
!= null) {
530 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
532 for (const [workerNodeKey
, workerNode
] of this.workerNodes
.entries()) {
533 workerNode
.resetUsage()
534 this.sendStatisticsMessageToWorker(workerNodeKey
)
539 public setWorkerChoiceStrategyOptions (
540 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
| undefined
542 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
543 if (workerChoiceStrategyOptions
!= null) {
544 this.opts
.workerChoiceStrategyOptions
= workerChoiceStrategyOptions
546 this.workerChoiceStrategyContext
?.setOptions(
547 this.opts
.workerChoiceStrategyOptions
552 public enableTasksQueue (
554 tasksQueueOptions
?: TasksQueueOptions
556 if (this.opts
.enableTasksQueue
=== true && !enable
) {
557 this.unsetTaskStealing()
558 this.unsetTasksStealingOnBackPressure()
559 this.flushTasksQueues()
561 this.opts
.enableTasksQueue
= enable
562 this.setTasksQueueOptions(tasksQueueOptions
)
566 public setTasksQueueOptions (
567 tasksQueueOptions
: TasksQueueOptions
| undefined
569 if (this.opts
.enableTasksQueue
=== true) {
570 checkValidTasksQueueOptions(tasksQueueOptions
)
571 this.opts
.tasksQueueOptions
=
572 this.buildTasksQueueOptions(tasksQueueOptions
)
573 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
574 this.setTasksQueueSize(this.opts
.tasksQueueOptions
.size
!)
575 if (this.opts
.tasksQueueOptions
.taskStealing
=== true) {
576 this.unsetTaskStealing()
577 this.setTaskStealing()
579 this.unsetTaskStealing()
581 if (this.opts
.tasksQueueOptions
.tasksStealingOnBackPressure
=== true) {
582 this.unsetTasksStealingOnBackPressure()
583 this.setTasksStealingOnBackPressure()
585 this.unsetTasksStealingOnBackPressure()
587 } else if (this.opts
.tasksQueueOptions
!= null) {
588 delete this.opts
.tasksQueueOptions
592 private buildTasksQueueOptions (
593 tasksQueueOptions
: TasksQueueOptions
| undefined
594 ): TasksQueueOptions
{
596 ...getDefaultTasksQueueOptions(
597 this.maximumNumberOfWorkers
?? this.minimumNumberOfWorkers
603 private setTasksQueueSize (size
: number): void {
604 for (const workerNode
of this.workerNodes
) {
605 workerNode
.tasksQueueBackPressureSize
= size
609 private setTaskStealing (): void {
610 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
611 this.workerNodes
[workerNodeKey
].on('idle', this.handleWorkerNodeIdleEvent
)
615 private unsetTaskStealing (): void {
616 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
617 this.workerNodes
[workerNodeKey
].off(
619 this.handleWorkerNodeIdleEvent
624 private setTasksStealingOnBackPressure (): void {
625 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
626 this.workerNodes
[workerNodeKey
].on(
628 this.handleWorkerNodeBackPressureEvent
633 private unsetTasksStealingOnBackPressure (): void {
634 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
635 this.workerNodes
[workerNodeKey
].off(
637 this.handleWorkerNodeBackPressureEvent
643 * Whether the pool is full or not.
645 * The pool filling boolean status.
647 protected get
full (): boolean {
649 this.workerNodes
.length
>=
650 (this.maximumNumberOfWorkers
?? this.minimumNumberOfWorkers
)
655 * Whether the pool is busy or not.
657 * The pool busyness boolean status.
659 protected abstract get
busy (): boolean
662 * Whether worker nodes are executing concurrently their tasks quota or not.
664 * @returns Worker nodes busyness boolean status.
666 protected internalBusy (): boolean {
667 if (this.opts
.enableTasksQueue
=== true) {
669 this.workerNodes
.findIndex(
671 workerNode
.info
.ready
&&
672 workerNode
.usage
.tasks
.executing
<
673 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
674 this.opts
.tasksQueueOptions
!.concurrency
!
679 this.workerNodes
.findIndex(
681 workerNode
.info
.ready
&& workerNode
.usage
.tasks
.executing
=== 0
686 private isWorkerNodeBusy (workerNodeKey
: number): boolean {
687 if (this.opts
.enableTasksQueue
=== true) {
689 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
>=
690 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
691 this.opts
.tasksQueueOptions
!.concurrency
!
694 return this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
> 0
697 private async sendTaskFunctionOperationToWorker (
698 workerNodeKey
: number,
699 message
: MessageValue
<Data
>
700 ): Promise
<boolean> {
701 return await new Promise
<boolean>((resolve
, reject
) => {
702 const taskFunctionOperationListener
= (
703 message
: MessageValue
<Response
>
705 this.checkMessageWorkerId(message
)
706 const workerId
= this.getWorkerInfo(workerNodeKey
).id
708 message
.taskFunctionOperationStatus
!= null &&
709 message
.workerId
=== workerId
711 if (message
.taskFunctionOperationStatus
) {
716 `Task function operation '${message.taskFunctionOperation}' failed on worker ${message.workerId} with error: '${message.workerError?.message}'`
720 this.deregisterWorkerMessageListener(
721 this.getWorkerNodeKeyByWorkerId(message
.workerId
),
722 taskFunctionOperationListener
726 this.registerWorkerMessageListener(
728 taskFunctionOperationListener
730 this.sendToWorker(workerNodeKey
, message
)
734 private async sendTaskFunctionOperationToWorkers (
735 message
: MessageValue
<Data
>
736 ): Promise
<boolean> {
737 return await new Promise
<boolean>((resolve
, reject
) => {
738 const responsesReceived
= new Array<MessageValue
<Response
>>()
739 const taskFunctionOperationsListener
= (
740 message
: MessageValue
<Response
>
742 this.checkMessageWorkerId(message
)
743 if (message
.taskFunctionOperationStatus
!= null) {
744 responsesReceived
.push(message
)
745 if (responsesReceived
.length
=== this.workerNodes
.length
) {
747 responsesReceived
.every(
748 message
=> message
.taskFunctionOperationStatus
=== true
753 responsesReceived
.some(
754 message
=> message
.taskFunctionOperationStatus
=== false
757 const errorResponse
= responsesReceived
.find(
758 response
=> response
.taskFunctionOperationStatus
=== false
762 `Task function operation '${
763 message.taskFunctionOperation as string
764 }' failed on worker ${errorResponse?.workerId} with error: '${
765 errorResponse?.workerError?.message
770 this.deregisterWorkerMessageListener(
771 this.getWorkerNodeKeyByWorkerId(message
.workerId
),
772 taskFunctionOperationsListener
777 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
778 this.registerWorkerMessageListener(
780 taskFunctionOperationsListener
782 this.sendToWorker(workerNodeKey
, message
)
788 public hasTaskFunction (name
: string): boolean {
789 for (const workerNode
of this.workerNodes
) {
791 Array.isArray(workerNode
.info
.taskFunctionNames
) &&
792 workerNode
.info
.taskFunctionNames
.includes(name
)
801 public async addTaskFunction (
803 fn
: TaskFunction
<Data
, Response
>
804 ): Promise
<boolean> {
805 if (typeof name
!== 'string') {
806 throw new TypeError('name argument must be a string')
808 if (typeof name
=== 'string' && name
.trim().length
=== 0) {
809 throw new TypeError('name argument must not be an empty string')
811 if (typeof fn
!== 'function') {
812 throw new TypeError('fn argument must be a function')
814 const opResult
= await this.sendTaskFunctionOperationToWorkers({
815 taskFunctionOperation
: 'add',
816 taskFunctionName
: name
,
817 taskFunction
: fn
.toString()
819 this.taskFunctions
.set(name
, fn
)
824 public async removeTaskFunction (name
: string): Promise
<boolean> {
825 if (!this.taskFunctions
.has(name
)) {
827 'Cannot remove a task function not handled on the pool side'
830 const opResult
= await this.sendTaskFunctionOperationToWorkers({
831 taskFunctionOperation
: 'remove',
832 taskFunctionName
: name
834 this.deleteTaskFunctionWorkerUsages(name
)
835 this.taskFunctions
.delete(name
)
840 public listTaskFunctionNames (): string[] {
841 for (const workerNode
of this.workerNodes
) {
843 Array.isArray(workerNode
.info
.taskFunctionNames
) &&
844 workerNode
.info
.taskFunctionNames
.length
> 0
846 return workerNode
.info
.taskFunctionNames
853 public async setDefaultTaskFunction (name
: string): Promise
<boolean> {
854 return await this.sendTaskFunctionOperationToWorkers({
855 taskFunctionOperation
: 'default',
856 taskFunctionName
: name
860 private deleteTaskFunctionWorkerUsages (name
: string): void {
861 for (const workerNode
of this.workerNodes
) {
862 workerNode
.deleteTaskFunctionWorkerUsage(name
)
866 private shallExecuteTask (workerNodeKey
: number): boolean {
868 this.tasksQueueSize(workerNodeKey
) === 0 &&
869 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
<
870 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
871 this.opts
.tasksQueueOptions
!.concurrency
!
876 public async execute (
879 transferList
?: TransferListItem
[]
880 ): Promise
<Response
> {
881 return await new Promise
<Response
>((resolve
, reject
) => {
883 reject(new Error('Cannot execute a task on not started pool'))
886 if (this.destroying
) {
887 reject(new Error('Cannot execute a task on destroying pool'))
890 if (name
!= null && typeof name
!== 'string') {
891 reject(new TypeError('name argument must be a string'))
896 typeof name
=== 'string' &&
897 name
.trim().length
=== 0
899 reject(new TypeError('name argument must not be an empty string'))
902 if (transferList
!= null && !Array.isArray(transferList
)) {
903 reject(new TypeError('transferList argument must be an array'))
906 const timestamp
= performance
.now()
907 const workerNodeKey
= this.chooseWorkerNode()
908 const task
: Task
<Data
> = {
909 name
: name
?? DEFAULT_TASK_NAME
,
910 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
911 data
: data
?? ({} as Data
),
916 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
917 this.promiseResponseMap
.set(task
.taskId
!, {
921 ...(this.emitter
!= null && {
922 asyncResource
: new AsyncResource('poolifier:task', {
923 triggerAsyncId
: this.emitter
.asyncId
,
924 requireManualDestroy
: true
929 this.opts
.enableTasksQueue
=== false ||
930 (this.opts
.enableTasksQueue
=== true &&
931 this.shallExecuteTask(workerNodeKey
))
933 this.executeTask(workerNodeKey
, task
)
935 this.enqueueTask(workerNodeKey
, task
)
941 public start (): void {
943 throw new Error('Cannot start an already started pool')
946 throw new Error('Cannot start an already starting pool')
948 if (this.destroying
) {
949 throw new Error('Cannot start a destroying pool')
953 this.workerNodes
.reduce(
954 (accumulator
, workerNode
) =>
955 !workerNode
.info
.dynamic
? accumulator
+ 1 : accumulator
,
957 ) < this.minimumNumberOfWorkers
959 this.createAndSetupWorkerNode()
961 this.starting
= false
966 public async destroy (): Promise
<void> {
968 throw new Error('Cannot destroy an already destroyed pool')
971 throw new Error('Cannot destroy an starting pool')
973 if (this.destroying
) {
974 throw new Error('Cannot destroy an already destroying pool')
976 this.destroying
= true
978 this.workerNodes
.map(async (_workerNode
, workerNodeKey
) => {
979 await this.destroyWorkerNode(workerNodeKey
)
982 this.emitter
?.emit(PoolEvents
.destroy
, this.info
)
983 this.emitter
?.emitDestroy()
984 this.emitter
?.removeAllListeners()
985 this.readyEventEmitted
= false
986 this.destroying
= false
990 private async sendKillMessageToWorker (workerNodeKey
: number): Promise
<void> {
991 await new Promise
<void>((resolve
, reject
) => {
992 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
993 if (this.workerNodes
[workerNodeKey
] == null) {
997 const killMessageListener
= (message
: MessageValue
<Response
>): void => {
998 this.checkMessageWorkerId(message
)
999 if (message
.kill
=== 'success') {
1001 } else if (message
.kill
=== 'failure') {
1004 `Kill message handling failed on worker ${message.workerId}`
1009 // FIXME: should be registered only once
1010 this.registerWorkerMessageListener(workerNodeKey
, killMessageListener
)
1011 this.sendToWorker(workerNodeKey
, { kill
: true })
1016 * Terminates the worker node given its worker node key.
1018 * @param workerNodeKey - The worker node key.
1020 protected async destroyWorkerNode (workerNodeKey
: number): Promise
<void> {
1021 this.flagWorkerNodeAsNotReady(workerNodeKey
)
1022 const flushedTasks
= this.flushTasksQueue(workerNodeKey
)
1023 const workerNode
= this.workerNodes
[workerNodeKey
]
1024 await waitWorkerNodeEvents(
1028 this.opts
.tasksQueueOptions
?.tasksFinishedTimeout
??
1029 getDefaultTasksQueueOptions(
1030 this.maximumNumberOfWorkers
?? this.minimumNumberOfWorkers
1031 ).tasksFinishedTimeout
1033 await this.sendKillMessageToWorker(workerNodeKey
)
1034 await workerNode
.terminate()
1038 * Setup hook to execute code before worker nodes are created in the abstract constructor.
1039 * Can be overridden.
1043 protected setupHook (): void {
1044 /* Intentionally empty */
1048 * Should return whether the worker is the main worker or not.
1050 protected abstract isMain (): boolean
1053 * Hook executed before the worker task execution.
1054 * Can be overridden.
1056 * @param workerNodeKey - The worker node key.
1057 * @param task - The task to execute.
1059 protected beforeTaskExecutionHook (
1060 workerNodeKey
: number,
1063 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1064 if (this.workerNodes
[workerNodeKey
].usage
!= null) {
1065 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
1066 ++workerUsage
.tasks
.executing
1067 updateWaitTimeWorkerUsage(
1068 this.workerChoiceStrategyContext
,
1074 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
1075 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1076 this.workerNodes
[workerNodeKey
].getTaskFunctionWorkerUsage(task
.name
!) !=
1079 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1080 const taskFunctionWorkerUsage
= this.workerNodes
[
1082 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1083 ].getTaskFunctionWorkerUsage(task
.name
!)!
1084 ++taskFunctionWorkerUsage
.tasks
.executing
1085 updateWaitTimeWorkerUsage(
1086 this.workerChoiceStrategyContext
,
1087 taskFunctionWorkerUsage
,
1094 * Hook executed after the worker task execution.
1095 * Can be overridden.
1097 * @param workerNodeKey - The worker node key.
1098 * @param message - The received message.
1100 protected afterTaskExecutionHook (
1101 workerNodeKey
: number,
1102 message
: MessageValue
<Response
>
1104 let needWorkerChoiceStrategyUpdate
= false
1105 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1106 if (this.workerNodes
[workerNodeKey
].usage
!= null) {
1107 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
1108 updateTaskStatisticsWorkerUsage(workerUsage
, message
)
1109 updateRunTimeWorkerUsage(
1110 this.workerChoiceStrategyContext
,
1114 updateEluWorkerUsage(
1115 this.workerChoiceStrategyContext
,
1119 needWorkerChoiceStrategyUpdate
= true
1122 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
1123 this.workerNodes
[workerNodeKey
].getTaskFunctionWorkerUsage(
1124 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1125 message
.taskPerformance
!.name
1128 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1129 const taskFunctionWorkerUsage
= this.workerNodes
[
1131 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1132 ].getTaskFunctionWorkerUsage(message
.taskPerformance
!.name
)!
1133 updateTaskStatisticsWorkerUsage(taskFunctionWorkerUsage
, message
)
1134 updateRunTimeWorkerUsage(
1135 this.workerChoiceStrategyContext
,
1136 taskFunctionWorkerUsage
,
1139 updateEluWorkerUsage(
1140 this.workerChoiceStrategyContext
,
1141 taskFunctionWorkerUsage
,
1144 needWorkerChoiceStrategyUpdate
= true
1146 if (needWorkerChoiceStrategyUpdate
) {
1147 this.workerChoiceStrategyContext
?.update(workerNodeKey
)
1152 * Whether the worker node shall update its task function worker usage or not.
1154 * @param workerNodeKey - The worker node key.
1155 * @returns `true` if the worker node shall update its task function worker usage, `false` otherwise.
1157 private shallUpdateTaskFunctionWorkerUsage (workerNodeKey
: number): boolean {
1158 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
1160 Array.isArray(workerInfo
.taskFunctionNames
) &&
1161 workerInfo
.taskFunctionNames
.length
> 2
1166 * Chooses a worker node for the next task.
1168 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
1170 * @returns The chosen worker node key
1172 private chooseWorkerNode (): number {
1173 if (this.shallCreateDynamicWorker()) {
1174 const workerNodeKey
= this.createAndSetupDynamicWorkerNode()
1176 this.workerChoiceStrategyContext
?.getStrategyPolicy()
1177 .dynamicWorkerUsage
=== true
1179 return workerNodeKey
1182 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1183 return this.workerChoiceStrategyContext
!.execute()!
1187 * Conditions for dynamic worker creation.
1189 * @returns Whether to create a dynamic worker or not.
1191 protected abstract shallCreateDynamicWorker (): boolean
1194 * Sends a message to worker given its worker node key.
1196 * @param workerNodeKey - The worker node key.
1197 * @param message - The message.
1198 * @param transferList - The optional array of transferable objects.
1200 protected abstract sendToWorker (
1201 workerNodeKey
: number,
1202 message
: MessageValue
<Data
>,
1203 transferList
?: TransferListItem
[]
1207 * Creates a new, completely set up worker node.
1209 * @returns New, completely set up worker node key.
1211 protected createAndSetupWorkerNode (): number {
1212 const workerNode
= this.createWorkerNode()
1213 workerNode
.registerWorkerEventHandler(
1215 this.opts
.onlineHandler
?? EMPTY_FUNCTION
1217 workerNode
.registerWorkerEventHandler(
1219 this.opts
.messageHandler
?? EMPTY_FUNCTION
1221 workerNode
.registerWorkerEventHandler(
1223 this.opts
.errorHandler
?? EMPTY_FUNCTION
1225 workerNode
.registerWorkerEventHandler('error', (error
: Error) => {
1226 workerNode
.info
.ready
= false
1227 this.emitter
?.emit(PoolEvents
.error
, error
)
1231 this.opts
.restartWorkerOnError
=== true
1233 if (workerNode
.info
.dynamic
) {
1234 this.createAndSetupDynamicWorkerNode()
1236 this.createAndSetupWorkerNode()
1242 this.opts
.enableTasksQueue
=== true
1244 this.redistributeQueuedTasks(this.workerNodes
.indexOf(workerNode
))
1246 workerNode
.terminate().catch(error
=> {
1247 this.emitter
?.emit(PoolEvents
.error
, error
)
1250 workerNode
.registerWorkerEventHandler(
1252 this.opts
.exitHandler
?? EMPTY_FUNCTION
1254 workerNode
.registerOnceWorkerEventHandler('exit', () => {
1255 this.removeWorkerNode(workerNode
)
1257 const workerNodeKey
= this.addWorkerNode(workerNode
)
1258 this.afterWorkerNodeSetup(workerNodeKey
)
1259 return workerNodeKey
1263 * Creates a new, completely set up dynamic worker node.
1265 * @returns New, completely set up dynamic worker node key.
1267 protected createAndSetupDynamicWorkerNode (): number {
1268 const workerNodeKey
= this.createAndSetupWorkerNode()
1269 this.registerWorkerMessageListener(workerNodeKey
, message
=> {
1270 this.checkMessageWorkerId(message
)
1271 const localWorkerNodeKey
= this.getWorkerNodeKeyByWorkerId(
1274 const workerUsage
= this.workerNodes
[localWorkerNodeKey
].usage
1275 // Kill message received from worker
1277 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
1278 (isKillBehavior(KillBehaviors
.SOFT
, message
.kill
) &&
1279 ((this.opts
.enableTasksQueue
=== false &&
1280 workerUsage
.tasks
.executing
=== 0) ||
1281 (this.opts
.enableTasksQueue
=== true &&
1282 workerUsage
.tasks
.executing
=== 0 &&
1283 this.tasksQueueSize(localWorkerNodeKey
) === 0)))
1285 // Flag the worker node as not ready immediately
1286 this.flagWorkerNodeAsNotReady(localWorkerNodeKey
)
1287 this.destroyWorkerNode(localWorkerNodeKey
).catch(error
=> {
1288 this.emitter
?.emit(PoolEvents
.error
, error
)
1292 this.sendToWorker(workerNodeKey
, {
1295 if (this.taskFunctions
.size
> 0) {
1296 for (const [taskFunctionName
, taskFunction
] of this.taskFunctions
) {
1297 this.sendTaskFunctionOperationToWorker(workerNodeKey
, {
1298 taskFunctionOperation
: 'add',
1300 taskFunction
: taskFunction
.toString()
1302 this.emitter
?.emit(PoolEvents
.error
, error
)
1306 const workerNode
= this.workerNodes
[workerNodeKey
]
1307 workerNode
.info
.dynamic
= true
1309 this.workerChoiceStrategyContext
?.getStrategyPolicy()
1310 .dynamicWorkerReady
=== true ||
1311 this.workerChoiceStrategyContext
?.getStrategyPolicy()
1312 .dynamicWorkerUsage
=== true
1314 workerNode
.info
.ready
= true
1316 this.checkAndEmitDynamicWorkerCreationEvents()
1317 return workerNodeKey
1321 * Registers a listener callback on the worker given its worker node key.
1323 * @param workerNodeKey - The worker node key.
1324 * @param listener - The message listener callback.
1326 protected abstract registerWorkerMessageListener
<
1327 Message
extends Data
| Response
1329 workerNodeKey
: number,
1330 listener
: (message
: MessageValue
<Message
>) => void
1334 * Registers once a listener callback on the worker given its worker node key.
1336 * @param workerNodeKey - The worker node key.
1337 * @param listener - The message listener callback.
1339 protected abstract registerOnceWorkerMessageListener
<
1340 Message
extends Data
| Response
1342 workerNodeKey
: number,
1343 listener
: (message
: MessageValue
<Message
>) => void
1347 * Deregisters a listener callback on the worker given its worker node key.
1349 * @param workerNodeKey - The worker node key.
1350 * @param listener - The message listener callback.
1352 protected abstract deregisterWorkerMessageListener
<
1353 Message
extends Data
| Response
1355 workerNodeKey
: number,
1356 listener
: (message
: MessageValue
<Message
>) => void
1360 * Method hooked up after a worker node has been newly created.
1361 * Can be overridden.
1363 * @param workerNodeKey - The newly created worker node key.
1365 protected afterWorkerNodeSetup (workerNodeKey
: number): void {
1366 // Listen to worker messages.
1367 this.registerWorkerMessageListener(
1369 this.workerMessageListener
1371 // Send the startup message to worker.
1372 this.sendStartupMessageToWorker(workerNodeKey
)
1373 // Send the statistics message to worker.
1374 this.sendStatisticsMessageToWorker(workerNodeKey
)
1375 if (this.opts
.enableTasksQueue
=== true) {
1376 if (this.opts
.tasksQueueOptions
?.taskStealing
=== true) {
1377 this.workerNodes
[workerNodeKey
].on(
1379 this.handleWorkerNodeIdleEvent
1382 if (this.opts
.tasksQueueOptions
?.tasksStealingOnBackPressure
=== true) {
1383 this.workerNodes
[workerNodeKey
].on(
1385 this.handleWorkerNodeBackPressureEvent
1392 * Sends the startup message to worker given its worker node key.
1394 * @param workerNodeKey - The worker node key.
1396 protected abstract sendStartupMessageToWorker (workerNodeKey
: number): void
1399 * Sends the statistics message to worker given its worker node key.
1401 * @param workerNodeKey - The worker node key.
1403 private sendStatisticsMessageToWorker (workerNodeKey
: number): void {
1404 this.sendToWorker(workerNodeKey
, {
1407 this.workerChoiceStrategyContext
?.getTaskStatisticsRequirements()
1408 ?.runTime
.aggregate
?? false,
1410 this.workerChoiceStrategyContext
?.getTaskStatisticsRequirements()?.elu
1416 private cannotStealTask (): boolean {
1417 return this.workerNodes
.length
<= 1 || this.info
.queuedTasks
=== 0
1420 private handleTask (workerNodeKey
: number, task
: Task
<Data
>): void {
1421 if (this.shallExecuteTask(workerNodeKey
)) {
1422 this.executeTask(workerNodeKey
, task
)
1424 this.enqueueTask(workerNodeKey
, task
)
1428 private redistributeQueuedTasks (workerNodeKey
: number): void {
1429 if (workerNodeKey
=== -1 || this.cannotStealTask()) {
1432 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1433 const destinationWorkerNodeKey
= this.workerNodes
.reduce(
1434 (minWorkerNodeKey
, workerNode
, workerNodeKey
, workerNodes
) => {
1435 return workerNode
.info
.ready
&&
1436 workerNode
.usage
.tasks
.queued
<
1437 workerNodes
[minWorkerNodeKey
].usage
.tasks
.queued
1444 destinationWorkerNodeKey
,
1445 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1446 this.dequeueTask(workerNodeKey
)!
1451 private updateTaskStolenStatisticsWorkerUsage (
1452 workerNodeKey
: number,
1455 const workerNode
= this.workerNodes
[workerNodeKey
]
1456 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1457 if (workerNode
.usage
!= null) {
1458 ++workerNode
.usage
.tasks
.stolen
1461 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
1462 workerNode
.getTaskFunctionWorkerUsage(taskName
) != null
1464 const taskFunctionWorkerUsage
=
1465 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1466 workerNode
.getTaskFunctionWorkerUsage(taskName
)!
1467 ++taskFunctionWorkerUsage
.tasks
.stolen
1471 private updateTaskSequentiallyStolenStatisticsWorkerUsage (
1472 workerNodeKey
: number
1474 const workerNode
= this.workerNodes
[workerNodeKey
]
1475 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1476 if (workerNode
.usage
!= null) {
1477 ++workerNode
.usage
.tasks
.sequentiallyStolen
1481 private updateTaskSequentiallyStolenStatisticsTaskFunctionWorkerUsage (
1482 workerNodeKey
: number,
1485 const workerNode
= this.workerNodes
[workerNodeKey
]
1487 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
1488 workerNode
.getTaskFunctionWorkerUsage(taskName
) != null
1490 const taskFunctionWorkerUsage
=
1491 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1492 workerNode
.getTaskFunctionWorkerUsage(taskName
)!
1493 ++taskFunctionWorkerUsage
.tasks
.sequentiallyStolen
1497 private resetTaskSequentiallyStolenStatisticsWorkerUsage (
1498 workerNodeKey
: number
1500 const workerNode
= this.workerNodes
[workerNodeKey
]
1501 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1502 if (workerNode
.usage
!= null) {
1503 workerNode
.usage
.tasks
.sequentiallyStolen
= 0
1507 private resetTaskSequentiallyStolenStatisticsTaskFunctionWorkerUsage (
1508 workerNodeKey
: number,
1511 const workerNode
= this.workerNodes
[workerNodeKey
]
1513 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
1514 workerNode
.getTaskFunctionWorkerUsage(taskName
) != null
1516 const taskFunctionWorkerUsage
=
1517 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1518 workerNode
.getTaskFunctionWorkerUsage(taskName
)!
1519 taskFunctionWorkerUsage
.tasks
.sequentiallyStolen
= 0
1523 private readonly handleWorkerNodeIdleEvent
= (
1524 eventDetail
: WorkerNodeEventDetail
,
1525 previousStolenTask
?: Task
<Data
>
1527 const { workerNodeKey
} = eventDetail
1528 if (workerNodeKey
== null) {
1530 "WorkerNode event detail 'workerNodeKey' property must be defined"
1533 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
1535 this.cannotStealTask() ||
1536 (this.info
.stealingWorkerNodes
?? 0) >
1537 Math.floor(this.workerNodes
.length
/ 2)
1539 if (previousStolenTask
!= null) {
1540 workerInfo
.stealing
= false
1544 const workerNodeTasksUsage
= this.workerNodes
[workerNodeKey
].usage
.tasks
1546 previousStolenTask
!= null &&
1547 workerNodeTasksUsage
.sequentiallyStolen
> 0 &&
1548 (workerNodeTasksUsage
.executing
> 0 ||
1549 this.tasksQueueSize(workerNodeKey
) > 0)
1551 workerInfo
.stealing
= false
1552 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1553 for (const taskName
of this.workerNodes
[workerNodeKey
].info
1554 .taskFunctionNames
!) {
1555 this.resetTaskSequentiallyStolenStatisticsTaskFunctionWorkerUsage(
1560 this.resetTaskSequentiallyStolenStatisticsWorkerUsage(workerNodeKey
)
1563 workerInfo
.stealing
= true
1564 const stolenTask
= this.workerNodeStealTask(workerNodeKey
)
1566 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey
) &&
1569 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1570 const taskFunctionTasksWorkerUsage
= this.workerNodes
[
1572 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1573 ].getTaskFunctionWorkerUsage(stolenTask
.name
!)!.tasks
1575 taskFunctionTasksWorkerUsage
.sequentiallyStolen
=== 0 ||
1576 (previousStolenTask
!= null &&
1577 previousStolenTask
.name
=== stolenTask
.name
&&
1578 taskFunctionTasksWorkerUsage
.sequentiallyStolen
> 0)
1580 this.updateTaskSequentiallyStolenStatisticsTaskFunctionWorkerUsage(
1582 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1586 this.resetTaskSequentiallyStolenStatisticsTaskFunctionWorkerUsage(
1588 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1593 sleep(exponentialDelay(workerNodeTasksUsage
.sequentiallyStolen
))
1595 this.handleWorkerNodeIdleEvent(eventDetail
, stolenTask
)
1598 .catch(EMPTY_FUNCTION
)
1601 private readonly workerNodeStealTask
= (
1602 workerNodeKey
: number
1603 ): Task
<Data
> | undefined => {
1604 const workerNodes
= this.workerNodes
1607 (workerNodeA
, workerNodeB
) =>
1608 workerNodeB
.usage
.tasks
.queued
- workerNodeA
.usage
.tasks
.queued
1610 const sourceWorkerNode
= workerNodes
.find(
1611 (sourceWorkerNode
, sourceWorkerNodeKey
) =>
1612 sourceWorkerNode
.info
.ready
&&
1613 !sourceWorkerNode
.info
.stealing
&&
1614 sourceWorkerNodeKey
!== workerNodeKey
&&
1615 sourceWorkerNode
.usage
.tasks
.queued
> 0
1617 if (sourceWorkerNode
!= null) {
1618 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1619 const task
= sourceWorkerNode
.popTask()!
1620 this.handleTask(workerNodeKey
, task
)
1621 this.updateTaskSequentiallyStolenStatisticsWorkerUsage(workerNodeKey
)
1622 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1623 this.updateTaskStolenStatisticsWorkerUsage(workerNodeKey
, task
.name
!)
1628 private readonly handleWorkerNodeBackPressureEvent
= (
1629 eventDetail
: WorkerNodeEventDetail
1632 this.cannotStealTask() ||
1633 (this.info
.stealingWorkerNodes
?? 0) >
1634 Math.floor(this.workerNodes
.length
/ 2)
1638 const { workerId
} = eventDetail
1639 const sizeOffset
= 1
1640 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1641 if (this.opts
.tasksQueueOptions
!.size
! <= sizeOffset
) {
1644 const sourceWorkerNode
=
1645 this.workerNodes
[this.getWorkerNodeKeyByWorkerId(workerId
)]
1646 const workerNodes
= this.workerNodes
1649 (workerNodeA
, workerNodeB
) =>
1650 workerNodeA
.usage
.tasks
.queued
- workerNodeB
.usage
.tasks
.queued
1652 for (const [workerNodeKey
, workerNode
] of workerNodes
.entries()) {
1654 sourceWorkerNode
.usage
.tasks
.queued
> 0 &&
1655 workerNode
.info
.ready
&&
1656 !workerNode
.info
.stealing
&&
1657 workerNode
.info
.id
!== workerId
&&
1658 workerNode
.usage
.tasks
.queued
<
1659 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1660 this.opts
.tasksQueueOptions
!.size
! - sizeOffset
1662 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
1663 workerInfo
.stealing
= true
1664 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1665 const task
= sourceWorkerNode
.popTask()!
1666 this.handleTask(workerNodeKey
, task
)
1667 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1668 this.updateTaskStolenStatisticsWorkerUsage(workerNodeKey
, task
.name
!)
1669 workerInfo
.stealing
= false
1675 * This method is the message listener registered on each worker.
1677 protected readonly workerMessageListener
= (
1678 message
: MessageValue
<Response
>
1680 this.checkMessageWorkerId(message
)
1681 const { workerId
, ready
, taskId
, taskFunctionNames
} = message
1682 if (ready
!= null && taskFunctionNames
!= null) {
1683 // Worker ready response received from worker
1684 this.handleWorkerReadyResponse(message
)
1685 } else if (taskId
!= null) {
1686 // Task execution response received from worker
1687 this.handleTaskExecutionResponse(message
)
1688 } else if (taskFunctionNames
!= null) {
1689 // Task function names message received from worker
1691 this.getWorkerNodeKeyByWorkerId(workerId
)
1692 ).taskFunctionNames
= taskFunctionNames
1696 private handleWorkerReadyResponse (message
: MessageValue
<Response
>): void {
1697 const { workerId
, ready
, taskFunctionNames
} = message
1698 if (ready
== null || !ready
) {
1699 throw new Error(`Worker ${workerId} failed to initialize`)
1702 this.workerNodes
[this.getWorkerNodeKeyByWorkerId(workerId
)]
1703 workerNode
.info
.ready
= ready
1704 workerNode
.info
.taskFunctionNames
= taskFunctionNames
1705 if (!this.readyEventEmitted
&& this.ready
) {
1706 this.emitter
?.emit(PoolEvents
.ready
, this.info
)
1707 this.readyEventEmitted
= true
1711 private handleTaskExecutionResponse (message
: MessageValue
<Response
>): void {
1712 const { workerId
, taskId
, workerError
, data
} = message
1713 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1714 const promiseResponse
= this.promiseResponseMap
.get(taskId
!)
1715 if (promiseResponse
!= null) {
1716 const { resolve
, reject
, workerNodeKey
, asyncResource
} = promiseResponse
1717 const workerNode
= this.workerNodes
[workerNodeKey
]
1718 if (workerError
!= null) {
1719 this.emitter
?.emit(PoolEvents
.taskError
, workerError
)
1720 asyncResource
!= null
1721 ? asyncResource
.runInAsyncScope(
1726 : reject(workerError
.message
)
1728 asyncResource
!= null
1729 ? asyncResource
.runInAsyncScope(resolve
, this.emitter
, data
)
1730 : resolve(data
as Response
)
1732 asyncResource
?.emitDestroy()
1733 this.afterTaskExecutionHook(workerNodeKey
, message
)
1734 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1735 this.promiseResponseMap
.delete(taskId
!)
1736 workerNode
.emit('taskFinished', taskId
)
1737 if (this.opts
.enableTasksQueue
=== true && !this.destroying
) {
1738 const workerNodeTasksUsage
= workerNode
.usage
.tasks
1740 this.tasksQueueSize(workerNodeKey
) > 0 &&
1741 workerNodeTasksUsage
.executing
<
1742 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1743 this.opts
.tasksQueueOptions
!.concurrency
!
1745 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1746 this.executeTask(workerNodeKey
, this.dequeueTask(workerNodeKey
)!)
1749 workerNodeTasksUsage
.executing
=== 0 &&
1750 this.tasksQueueSize(workerNodeKey
) === 0 &&
1751 workerNodeTasksUsage
.sequentiallyStolen
=== 0
1753 workerNode
.emit('idle', {
1754 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1755 workerId
: workerId
!,
1763 private checkAndEmitTaskExecutionEvents (): void {
1765 this.emitter
?.emit(PoolEvents
.busy
, this.info
)
1769 private checkAndEmitTaskQueuingEvents (): void {
1770 if (this.hasBackPressure()) {
1771 this.emitter
?.emit(PoolEvents
.backPressure
, this.info
)
1776 * Emits dynamic worker creation events.
1778 protected abstract checkAndEmitDynamicWorkerCreationEvents (): void
1781 * Gets the worker information given its worker node key.
1783 * @param workerNodeKey - The worker node key.
1784 * @returns The worker information.
1786 protected getWorkerInfo (workerNodeKey
: number): WorkerInfo
{
1787 const workerInfo
= this.workerNodes
[workerNodeKey
]?.info
1788 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1789 if (workerInfo
== null) {
1790 throw new Error(`Worker node with key '${workerNodeKey}' not found`)
1796 * Creates a worker node.
1798 * @returns The created worker node.
1800 private createWorkerNode (): IWorkerNode
<Worker
, Data
> {
1801 const workerNode
= new WorkerNode
<Worker
, Data
>(
1806 workerOptions
: this.opts
.workerOptions
,
1807 tasksQueueBackPressureSize
:
1808 this.opts
.tasksQueueOptions
?.size
??
1809 getDefaultTasksQueueOptions(
1810 this.maximumNumberOfWorkers
?? this.minimumNumberOfWorkers
1814 // Flag the worker node as ready at pool startup.
1815 if (this.starting
) {
1816 workerNode
.info
.ready
= true
1822 * Adds the given worker node in the pool worker nodes.
1824 * @param workerNode - The worker node.
1825 * @returns The added worker node key.
1826 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the added worker node is not found.
1828 private addWorkerNode (workerNode
: IWorkerNode
<Worker
, Data
>): number {
1829 this.workerNodes
.push(workerNode
)
1830 const workerNodeKey
= this.workerNodes
.indexOf(workerNode
)
1831 if (workerNodeKey
=== -1) {
1832 throw new Error('Worker added not found in worker nodes')
1834 return workerNodeKey
1838 * Removes the worker node from the pool worker nodes.
1840 * @param workerNode - The worker node.
1842 private removeWorkerNode (workerNode
: IWorkerNode
<Worker
, Data
>): void {
1843 const workerNodeKey
= this.workerNodes
.indexOf(workerNode
)
1844 if (workerNodeKey
!== -1) {
1845 this.workerNodes
.splice(workerNodeKey
, 1)
1846 this.workerChoiceStrategyContext
?.remove(workerNodeKey
)
1850 protected flagWorkerNodeAsNotReady (workerNodeKey
: number): void {
1851 this.getWorkerInfo(workerNodeKey
).ready
= false
1854 private hasBackPressure (): boolean {
1856 this.opts
.enableTasksQueue
=== true &&
1857 this.workerNodes
.findIndex(
1858 workerNode
=> !workerNode
.hasBackPressure()
1864 * Executes the given task on the worker given its worker node key.
1866 * @param workerNodeKey - The worker node key.
1867 * @param task - The task to execute.
1869 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
1870 this.beforeTaskExecutionHook(workerNodeKey
, task
)
1871 this.sendToWorker(workerNodeKey
, task
, task
.transferList
)
1872 this.checkAndEmitTaskExecutionEvents()
1875 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
1876 const tasksQueueSize
= this.workerNodes
[workerNodeKey
].enqueueTask(task
)
1877 this.checkAndEmitTaskQueuingEvents()
1878 return tasksQueueSize
1881 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
1882 return this.workerNodes
[workerNodeKey
].dequeueTask()
1885 private tasksQueueSize (workerNodeKey
: number): number {
1886 return this.workerNodes
[workerNodeKey
].tasksQueueSize()
1889 protected flushTasksQueue (workerNodeKey
: number): number {
1890 let flushedTasks
= 0
1891 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1892 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1893 this.executeTask(workerNodeKey
, this.dequeueTask(workerNodeKey
)!)
1896 this.workerNodes
[workerNodeKey
].clearTasksQueue()
1900 private flushTasksQueues (): void {
1901 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
1902 this.flushTasksQueue(workerNodeKey
)