1 import { randomUUID
} from
'node:crypto'
2 import { performance
} from
'node:perf_hooks'
3 import { existsSync
} from
'node:fs'
4 import { type TransferListItem
} from
'node:worker_threads'
7 PromiseResponseWrapper
,
9 } from
'../utility-types'
12 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
,
18 updateMeasurementStatistics
20 import { KillBehaviors
} from
'../worker/worker-options'
29 type TasksQueueOptions
39 type MeasurementStatisticsRequirements
,
41 WorkerChoiceStrategies
,
42 type WorkerChoiceStrategy
,
43 type WorkerChoiceStrategyOptions
44 } from
'./selection-strategies/selection-strategies-types'
45 import { WorkerChoiceStrategyContext
} from
'./selection-strategies/worker-choice-strategy-context'
46 import { version
} from
'./version'
47 import { WorkerNode
} from
'./worker-node'
50 * Base class that implements some shared logic for all poolifier pools.
52 * @typeParam Worker - Type of worker which manages this pool.
53 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
54 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
56 export abstract class AbstractPool
<
57 Worker
extends IWorker
,
60 > implements IPool
<Worker
, Data
, Response
> {
62 public readonly workerNodes
: Array<IWorkerNode
<Worker
, Data
>> = []
65 public readonly emitter
?: PoolEmitter
68 * The task execution response promise map.
70 * - `key`: The message id of each submitted task.
71 * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks.
73 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
75 protected promiseResponseMap
: Map
<string, PromiseResponseWrapper
<Response
>> =
76 new Map
<string, PromiseResponseWrapper
<Response
>>()
79 * Worker choice strategy context referencing a worker choice algorithm implementation.
81 protected workerChoiceStrategyContext
: WorkerChoiceStrategyContext
<
88 * Whether the pool is starting or not.
90 private readonly starting
: boolean
92 * The start timestamp of the pool.
94 private readonly startTimestamp
97 * Constructs a new poolifier pool.
99 * @param numberOfWorkers - Number of workers that this pool should manage.
100 * @param filePath - Path to the worker file.
101 * @param opts - Options for the pool.
104 protected readonly numberOfWorkers
: number,
105 protected readonly filePath
: string,
106 protected readonly opts
: PoolOptions
<Worker
>
108 if (!this.isMain()) {
110 'Cannot start a pool from a worker with the same type as the pool'
113 this.checkNumberOfWorkers(this.numberOfWorkers
)
114 this.checkFilePath(this.filePath
)
115 this.checkPoolOptions(this.opts
)
117 this.chooseWorkerNode
= this.chooseWorkerNode
.bind(this)
118 this.executeTask
= this.executeTask
.bind(this)
119 this.enqueueTask
= this.enqueueTask
.bind(this)
120 this.dequeueTask
= this.dequeueTask
.bind(this)
121 this.checkAndEmitEvents
= this.checkAndEmitEvents
.bind(this)
123 if (this.opts
.enableEvents
=== true) {
124 this.emitter
= new PoolEmitter()
126 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext
<
132 this.opts
.workerChoiceStrategy
,
133 this.opts
.workerChoiceStrategyOptions
140 this.starting
= false
142 this.startTimestamp
= performance
.now()
145 private checkFilePath (filePath
: string): void {
148 typeof filePath
!== 'string' ||
149 (typeof filePath
=== 'string' && filePath
.trim().length
=== 0)
151 throw new Error('Please specify a file with a worker implementation')
153 if (!existsSync(filePath
)) {
154 throw new Error(`Cannot find the worker file '${filePath}'`)
158 private checkNumberOfWorkers (numberOfWorkers
: number): void {
159 if (numberOfWorkers
== null) {
161 'Cannot instantiate a pool without specifying the number of workers'
163 } else if (!Number.isSafeInteger(numberOfWorkers
)) {
165 'Cannot instantiate a pool with a non safe integer number of workers'
167 } else if (numberOfWorkers
< 0) {
168 throw new RangeError(
169 'Cannot instantiate a pool with a negative number of workers'
171 } else if (this.type === PoolTypes
.fixed
&& numberOfWorkers
=== 0) {
172 throw new RangeError('Cannot instantiate a fixed pool with zero worker')
176 protected checkDynamicPoolSize (min
: number, max
: number): void {
177 if (this.type === PoolTypes
.dynamic
) {
180 'Cannot instantiate a dynamic pool without specifying the maximum pool size'
182 } else if (!Number.isSafeInteger(max
)) {
184 'Cannot instantiate a dynamic pool with a non safe integer maximum pool size'
186 } else if (min
> max
) {
187 throw new RangeError(
188 'Cannot instantiate a dynamic pool with a maximum pool size inferior to the minimum pool size'
190 } else if (max
=== 0) {
191 throw new RangeError(
192 'Cannot instantiate a dynamic pool with a maximum pool size equal to zero'
194 } else if (min
=== max
) {
195 throw new RangeError(
196 'Cannot instantiate a dynamic pool with a minimum pool size equal to the maximum pool size. Use a fixed pool instead'
202 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
203 if (isPlainObject(opts
)) {
204 this.opts
.workerChoiceStrategy
=
205 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
206 this.checkValidWorkerChoiceStrategy(this.opts
.workerChoiceStrategy
)
207 this.opts
.workerChoiceStrategyOptions
=
208 opts
.workerChoiceStrategyOptions
??
209 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
210 this.checkValidWorkerChoiceStrategyOptions(
211 this.opts
.workerChoiceStrategyOptions
213 this.opts
.restartWorkerOnError
= opts
.restartWorkerOnError
?? true
214 this.opts
.enableEvents
= opts
.enableEvents
?? true
215 this.opts
.enableTasksQueue
= opts
.enableTasksQueue
?? false
216 if (this.opts
.enableTasksQueue
) {
217 this.checkValidTasksQueueOptions(
218 opts
.tasksQueueOptions
as TasksQueueOptions
220 this.opts
.tasksQueueOptions
= this.buildTasksQueueOptions(
221 opts
.tasksQueueOptions
as TasksQueueOptions
225 throw new TypeError('Invalid pool options: must be a plain object')
229 private checkValidWorkerChoiceStrategy (
230 workerChoiceStrategy
: WorkerChoiceStrategy
232 if (!Object.values(WorkerChoiceStrategies
).includes(workerChoiceStrategy
)) {
234 `Invalid worker choice strategy '${workerChoiceStrategy}'`
239 private checkValidWorkerChoiceStrategyOptions (
240 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
242 if (!isPlainObject(workerChoiceStrategyOptions
)) {
244 'Invalid worker choice strategy options: must be a plain object'
248 workerChoiceStrategyOptions
.weights
!= null &&
249 Object.keys(workerChoiceStrategyOptions
.weights
).length
!== this.maxSize
252 'Invalid worker choice strategy options: must have a weight for each worker node'
256 workerChoiceStrategyOptions
.measurement
!= null &&
257 !Object.values(Measurements
).includes(
258 workerChoiceStrategyOptions
.measurement
262 `Invalid worker choice strategy options: invalid measurement '${workerChoiceStrategyOptions.measurement}'`
267 private checkValidTasksQueueOptions (
268 tasksQueueOptions
: TasksQueueOptions
270 if (tasksQueueOptions
!= null && !isPlainObject(tasksQueueOptions
)) {
271 throw new TypeError('Invalid tasks queue options: must be a plain object')
274 tasksQueueOptions
?.concurrency
!= null &&
275 !Number.isSafeInteger(tasksQueueOptions
.concurrency
)
278 'Invalid worker tasks concurrency: must be an integer'
282 tasksQueueOptions
?.concurrency
!= null &&
283 tasksQueueOptions
.concurrency
<= 0
286 `Invalid worker tasks concurrency '${tasksQueueOptions.concurrency}'`
291 private startPool (): void {
293 this.workerNodes
.reduce(
294 (accumulator
, workerNode
) =>
295 !workerNode
.info
.dynamic
? accumulator
+ 1 : accumulator
,
297 ) < this.numberOfWorkers
299 this.createAndSetupWorkerNode()
304 public get
info (): PoolInfo
{
310 strategy
: this.opts
.workerChoiceStrategy
as WorkerChoiceStrategy
,
311 minSize
: this.minSize
,
312 maxSize
: this.maxSize
,
313 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
314 .runTime
.aggregate
&&
315 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
316 .waitTime
.aggregate
&& { utilization
: round(this.utilization
) }),
317 workerNodes
: this.workerNodes
.length
,
318 idleWorkerNodes
: this.workerNodes
.reduce(
319 (accumulator
, workerNode
) =>
320 workerNode
.usage
.tasks
.executing
=== 0
325 busyWorkerNodes
: this.workerNodes
.reduce(
326 (accumulator
, workerNode
) =>
327 workerNode
.usage
.tasks
.executing
> 0 ? accumulator
+ 1 : accumulator
,
330 executedTasks
: this.workerNodes
.reduce(
331 (accumulator
, workerNode
) =>
332 accumulator
+ workerNode
.usage
.tasks
.executed
,
335 executingTasks
: this.workerNodes
.reduce(
336 (accumulator
, workerNode
) =>
337 accumulator
+ workerNode
.usage
.tasks
.executing
,
340 ...(this.opts
.enableTasksQueue
=== true && {
341 queuedTasks
: this.workerNodes
.reduce(
342 (accumulator
, workerNode
) =>
343 accumulator
+ workerNode
.usage
.tasks
.queued
,
347 ...(this.opts
.enableTasksQueue
=== true && {
348 maxQueuedTasks
: this.workerNodes
.reduce(
349 (accumulator
, workerNode
) =>
350 accumulator
+ (workerNode
.usage
.tasks
?.maxQueued
?? 0),
354 failedTasks
: this.workerNodes
.reduce(
355 (accumulator
, workerNode
) =>
356 accumulator
+ workerNode
.usage
.tasks
.failed
,
359 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
360 .runTime
.aggregate
&& {
364 ...this.workerNodes
.map(
365 (workerNode
) => workerNode
.usage
.runTime
?.minimum
?? Infinity
371 ...this.workerNodes
.map(
372 (workerNode
) => workerNode
.usage
.runTime
?.maximum
?? -Infinity
377 this.workerNodes
.reduce(
378 (accumulator
, workerNode
) =>
379 accumulator
+ (workerNode
.usage
.runTime
?.aggregate
?? 0),
382 this.workerNodes
.reduce(
383 (accumulator
, workerNode
) =>
384 accumulator
+ (workerNode
.usage
.tasks
?.executed
?? 0),
388 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
392 this.workerNodes
.map(
393 (workerNode
) => workerNode
.usage
.runTime
?.median
?? 0
400 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
401 .waitTime
.aggregate
&& {
405 ...this.workerNodes
.map(
406 (workerNode
) => workerNode
.usage
.waitTime
?.minimum
?? Infinity
412 ...this.workerNodes
.map(
413 (workerNode
) => workerNode
.usage
.waitTime
?.maximum
?? -Infinity
418 this.workerNodes
.reduce(
419 (accumulator
, workerNode
) =>
420 accumulator
+ (workerNode
.usage
.waitTime
?.aggregate
?? 0),
423 this.workerNodes
.reduce(
424 (accumulator
, workerNode
) =>
425 accumulator
+ (workerNode
.usage
.tasks
?.executed
?? 0),
429 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
430 .waitTime
.median
&& {
433 this.workerNodes
.map(
434 (workerNode
) => workerNode
.usage
.waitTime
?.median
?? 0
445 * The pool readiness boolean status.
447 private get
ready (): boolean {
449 this.workerNodes
.reduce(
450 (accumulator
, workerNode
) =>
451 !workerNode
.info
.dynamic
&& workerNode
.info
.ready
460 * The approximate pool utilization.
462 * @returns The pool utilization.
464 private get
utilization (): number {
465 const poolTimeCapacity
=
466 (performance
.now() - this.startTimestamp
) * this.maxSize
467 const totalTasksRunTime
= this.workerNodes
.reduce(
468 (accumulator
, workerNode
) =>
469 accumulator
+ (workerNode
.usage
.runTime
?.aggregate
?? 0),
472 const totalTasksWaitTime
= this.workerNodes
.reduce(
473 (accumulator
, workerNode
) =>
474 accumulator
+ (workerNode
.usage
.waitTime
?.aggregate
?? 0),
477 return (totalTasksRunTime
+ totalTasksWaitTime
) / poolTimeCapacity
483 * If it is `'dynamic'`, it provides the `max` property.
485 protected abstract get
type (): PoolType
490 protected abstract get
worker (): WorkerType
493 * The pool minimum size.
495 protected abstract get
minSize (): number
498 * The pool maximum size.
500 protected abstract get
maxSize (): number
503 * Checks if the worker id sent in the received message from a worker is valid.
505 * @param message - The received message.
506 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the worker id is invalid.
508 private checkMessageWorkerId (message
: MessageValue
<Response
>): void {
509 if (message
.workerId
== null) {
510 throw new Error('Worker message received without worker id')
512 message
.workerId
!= null &&
513 this.getWorkerNodeKeyByWorkerId(message
.workerId
) === -1
516 `Worker message received from unknown worker '${message.workerId}'`
522 * Gets the given worker its worker node key.
524 * @param worker - The worker.
525 * @returns The worker node key if found in the pool worker nodes, `-1` otherwise.
527 private getWorkerNodeKeyByWorker (worker
: Worker
): number {
528 return this.workerNodes
.findIndex(
529 (workerNode
) => workerNode
.worker
=== worker
534 * Gets the worker node key given its worker id.
536 * @param workerId - The worker id.
537 * @returns The worker node key if the worker id is found in the pool worker nodes, `-1` otherwise.
539 private getWorkerNodeKeyByWorkerId (workerId
: number): number {
540 return this.workerNodes
.findIndex(
541 (workerNode
) => workerNode
.info
.id
=== workerId
546 public setWorkerChoiceStrategy (
547 workerChoiceStrategy
: WorkerChoiceStrategy
,
548 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
550 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
551 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
552 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
553 this.opts
.workerChoiceStrategy
555 if (workerChoiceStrategyOptions
!= null) {
556 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
558 for (const [workerNodeKey
, workerNode
] of this.workerNodes
.entries()) {
559 workerNode
.resetUsage()
560 this.sendStatisticsMessageToWorker(workerNodeKey
)
565 public setWorkerChoiceStrategyOptions (
566 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
568 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
569 this.opts
.workerChoiceStrategyOptions
= workerChoiceStrategyOptions
570 this.workerChoiceStrategyContext
.setOptions(
571 this.opts
.workerChoiceStrategyOptions
576 public enableTasksQueue (
578 tasksQueueOptions
?: TasksQueueOptions
580 if (this.opts
.enableTasksQueue
=== true && !enable
) {
581 this.flushTasksQueues()
583 this.opts
.enableTasksQueue
= enable
584 this.setTasksQueueOptions(tasksQueueOptions
as TasksQueueOptions
)
588 public setTasksQueueOptions (tasksQueueOptions
: TasksQueueOptions
): void {
589 if (this.opts
.enableTasksQueue
=== true) {
590 this.checkValidTasksQueueOptions(tasksQueueOptions
)
591 this.opts
.tasksQueueOptions
=
592 this.buildTasksQueueOptions(tasksQueueOptions
)
593 } else if (this.opts
.tasksQueueOptions
!= null) {
594 delete this.opts
.tasksQueueOptions
598 private buildTasksQueueOptions (
599 tasksQueueOptions
: TasksQueueOptions
600 ): TasksQueueOptions
{
602 concurrency
: tasksQueueOptions
?.concurrency
?? 1
607 * Whether the pool is full or not.
609 * The pool filling boolean status.
611 protected get
full (): boolean {
612 return this.workerNodes
.length
>= this.maxSize
616 * Whether the pool is busy or not.
618 * The pool busyness boolean status.
620 protected abstract get
busy (): boolean
623 * Whether worker nodes are executing concurrently their tasks quota or not.
625 * @returns Worker nodes busyness boolean status.
627 protected internalBusy (): boolean {
628 if (this.opts
.enableTasksQueue
=== true) {
630 this.workerNodes
.findIndex(
632 workerNode
.info
.ready
&&
633 workerNode
.usage
.tasks
.executing
<
634 (this.opts
.tasksQueueOptions
?.concurrency
as number)
639 this.workerNodes
.findIndex(
641 workerNode
.info
.ready
&& workerNode
.usage
.tasks
.executing
=== 0
648 public listTaskFunctions (): string[] {
650 Array.isArray(this.getWorkerInfo(0).taskFunctions
) &&
651 (this.getWorkerInfo(0).taskFunctions
as string[]).length
> 0
653 return this.getWorkerInfo(0).taskFunctions
as string[]
660 public async execute (
663 transferList
?: TransferListItem
[]
664 ): Promise
<Response
> {
665 return await new Promise
<Response
>((resolve
, reject
) => {
666 if (name
!= null && typeof name
!== 'string') {
667 reject(new TypeError('name argument must be a string'))
671 typeof name
=== 'string' &&
672 name
.trim().length
=== 0
674 reject(new TypeError('name argument must not be an empty string'))
676 if (transferList
!= null && !Array.isArray(transferList
)) {
677 reject(new TypeError('transferList argument must be an array'))
679 const timestamp
= performance
.now()
680 const workerNodeKey
= this.chooseWorkerNode()
683 Array.isArray(this.getWorkerInfo(workerNodeKey
).taskFunctions
) &&
684 !(this.getWorkerInfo(workerNodeKey
).taskFunctions
as string[]).includes(
689 new Error(`Task function '${name}' is not registered in the pool`)
692 const task
: Task
<Data
> = {
693 name
: name
?? DEFAULT_TASK_NAME
,
694 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
695 data
: data
?? ({} as Data
),
698 workerId
: this.getWorkerInfo(workerNodeKey
).id
as number,
701 this.promiseResponseMap
.set(task
.taskId
as string, {
707 this.opts
.enableTasksQueue
=== false ||
708 (this.opts
.enableTasksQueue
=== true &&
709 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
<
710 (this.opts
.tasksQueueOptions
?.concurrency
as number))
712 this.executeTask(workerNodeKey
, task
)
714 this.enqueueTask(workerNodeKey
, task
)
716 this.checkAndEmitEvents()
721 public async destroy (): Promise
<void> {
723 this.workerNodes
.map(async (_
, workerNodeKey
) => {
724 await this.destroyWorkerNode(workerNodeKey
)
727 this.emitter
?.emit(PoolEvents
.destroy
)
730 protected async sendKillMessageToWorker (
731 workerNodeKey
: number,
734 await new Promise
<void>((resolve
, reject
) => {
735 this.registerWorkerMessageListener(workerNodeKey
, (message
) => {
736 if (message
.kill
=== 'success') {
738 } else if (message
.kill
=== 'failure') {
739 reject(new Error(`Worker ${workerId} kill message handling failed`))
742 this.sendToWorker(workerNodeKey
, { kill
: true, workerId
})
747 * Terminates the worker node given its worker node key.
749 * @param workerNodeKey - The worker node key.
751 protected abstract destroyWorkerNode (workerNodeKey
: number): Promise
<void>
754 * Setup hook to execute code before worker nodes are created in the abstract constructor.
759 protected setupHook (): void {
760 // Intentionally empty
764 * Should return whether the worker is the main worker or not.
766 protected abstract isMain (): boolean
769 * Hook executed before the worker task execution.
772 * @param workerNodeKey - The worker node key.
773 * @param task - The task to execute.
775 protected beforeTaskExecutionHook (
776 workerNodeKey
: number,
779 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
780 ++workerUsage
.tasks
.executing
781 this.updateWaitTimeWorkerUsage(workerUsage
, task
)
782 if (this.canUpdateTaskWorkerUsage(workerNodeKey
)) {
783 const taskWorkerUsage
= this.workerNodes
[
785 ].getTaskWorkerUsage(task
.name
as string) as WorkerUsage
786 ++taskWorkerUsage
.tasks
.executing
787 this.updateWaitTimeWorkerUsage(taskWorkerUsage
, task
)
792 * Hook executed after the worker task execution.
795 * @param workerNodeKey - The worker node key.
796 * @param message - The received message.
798 protected afterTaskExecutionHook (
799 workerNodeKey
: number,
800 message
: MessageValue
<Response
>
802 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
803 this.updateTaskStatisticsWorkerUsage(workerUsage
, message
)
804 this.updateRunTimeWorkerUsage(workerUsage
, message
)
805 this.updateEluWorkerUsage(workerUsage
, message
)
806 if (this.canUpdateTaskWorkerUsage(workerNodeKey
)) {
807 const taskWorkerUsage
= this.workerNodes
[
809 ].getTaskWorkerUsage(
810 message
.taskPerformance
?.name
?? DEFAULT_TASK_NAME
812 this.updateTaskStatisticsWorkerUsage(taskWorkerUsage
, message
)
813 this.updateRunTimeWorkerUsage(taskWorkerUsage
, message
)
814 this.updateEluWorkerUsage(taskWorkerUsage
, message
)
818 private canUpdateTaskWorkerUsage (workerNodeKey
: number): boolean {
820 Array.isArray(this.getWorkerInfo(workerNodeKey
).taskFunctions
) &&
821 (this.getWorkerInfo(workerNodeKey
).taskFunctions
as string[]).length
> 1
825 private updateTaskStatisticsWorkerUsage (
826 workerUsage
: WorkerUsage
,
827 message
: MessageValue
<Response
>
829 const workerTaskStatistics
= workerUsage
.tasks
830 --workerTaskStatistics
.executing
831 if (message
.taskError
== null) {
832 ++workerTaskStatistics
.executed
834 ++workerTaskStatistics
.failed
838 private updateRunTimeWorkerUsage (
839 workerUsage
: WorkerUsage
,
840 message
: MessageValue
<Response
>
842 updateMeasurementStatistics(
844 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
,
845 message
.taskPerformance
?.runTime
?? 0,
846 workerUsage
.tasks
.executed
850 private updateWaitTimeWorkerUsage (
851 workerUsage
: WorkerUsage
,
854 const timestamp
= performance
.now()
855 const taskWaitTime
= timestamp
- (task
.timestamp
?? timestamp
)
856 updateMeasurementStatistics(
857 workerUsage
.waitTime
,
858 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().waitTime
,
860 workerUsage
.tasks
.executed
864 private updateEluWorkerUsage (
865 workerUsage
: WorkerUsage
,
866 message
: MessageValue
<Response
>
868 const eluTaskStatisticsRequirements
: MeasurementStatisticsRequirements
=
869 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
870 updateMeasurementStatistics(
871 workerUsage
.elu
.active
,
872 eluTaskStatisticsRequirements
,
873 message
.taskPerformance
?.elu
?.active
?? 0,
874 workerUsage
.tasks
.executed
876 updateMeasurementStatistics(
877 workerUsage
.elu
.idle
,
878 eluTaskStatisticsRequirements
,
879 message
.taskPerformance
?.elu
?.idle
?? 0,
880 workerUsage
.tasks
.executed
882 if (eluTaskStatisticsRequirements
.aggregate
) {
883 if (message
.taskPerformance
?.elu
!= null) {
884 if (workerUsage
.elu
.utilization
!= null) {
885 workerUsage
.elu
.utilization
=
886 (workerUsage
.elu
.utilization
+
887 message
.taskPerformance
.elu
.utilization
) /
890 workerUsage
.elu
.utilization
= message
.taskPerformance
.elu
.utilization
897 * Chooses a worker node for the next task.
899 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
901 * @returns The chosen worker node key
903 private chooseWorkerNode (): number {
904 if (this.shallCreateDynamicWorker()) {
905 const workerNodeKey
= this.createAndSetupDynamicWorkerNode()
907 this.workerChoiceStrategyContext
.getStrategyPolicy().useDynamicWorker
912 return this.workerChoiceStrategyContext
.execute()
916 * Conditions for dynamic worker creation.
918 * @returns Whether to create a dynamic worker or not.
920 private shallCreateDynamicWorker (): boolean {
921 return this.type === PoolTypes
.dynamic
&& !this.full
&& this.internalBusy()
925 * Sends a message to worker given its worker node key.
927 * @param workerNodeKey - The worker node key.
928 * @param message - The message.
929 * @param transferList - The optional array of transferable objects.
931 protected abstract sendToWorker (
932 workerNodeKey
: number,
933 message
: MessageValue
<Data
>,
934 transferList
?: TransferListItem
[]
938 * Creates a new worker.
940 * @returns Newly created worker.
942 protected abstract createWorker (): Worker
945 * Creates a new, completely set up worker node.
947 * @returns New, completely set up worker node key.
949 protected createAndSetupWorkerNode (): number {
950 const worker
= this.createWorker()
952 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
953 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
954 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
955 worker
.on('error', (error
) => {
956 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
957 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
958 workerInfo
.ready
= false
959 this.workerNodes
[workerNodeKey
].closeChannel()
960 this.emitter
?.emit(PoolEvents
.error
, error
)
961 if (this.opts
.restartWorkerOnError
=== true && !this.starting
) {
962 if (workerInfo
.dynamic
) {
963 this.createAndSetupDynamicWorkerNode()
965 this.createAndSetupWorkerNode()
968 if (this.opts
.enableTasksQueue
=== true) {
969 this.redistributeQueuedTasks(workerNodeKey
)
972 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
973 worker
.once('exit', () => {
974 this.removeWorkerNode(worker
)
977 const workerNodeKey
= this.addWorkerNode(worker
)
979 this.afterWorkerNodeSetup(workerNodeKey
)
985 * Creates a new, completely set up dynamic worker node.
987 * @returns New, completely set up dynamic worker node key.
989 protected createAndSetupDynamicWorkerNode (): number {
990 const workerNodeKey
= this.createAndSetupWorkerNode()
991 this.registerWorkerMessageListener(workerNodeKey
, (message
) => {
992 const localWorkerNodeKey
= this.getWorkerNodeKeyByWorkerId(
995 const workerUsage
= this.workerNodes
[localWorkerNodeKey
].usage
996 // Kill message received from worker
998 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
999 (isKillBehavior(KillBehaviors
.SOFT
, message
.kill
) &&
1000 ((this.opts
.enableTasksQueue
=== false &&
1001 workerUsage
.tasks
.executing
=== 0) ||
1002 (this.opts
.enableTasksQueue
=== true &&
1003 workerUsage
.tasks
.executing
=== 0 &&
1004 this.tasksQueueSize(localWorkerNodeKey
) === 0)))
1006 this.destroyWorkerNode(localWorkerNodeKey
).catch((error
) => {
1007 this.emitter
?.emit(PoolEvents
.error
, error
)
1011 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
1012 this.sendToWorker(workerNodeKey
, {
1014 workerId
: workerInfo
.id
as number
1016 workerInfo
.dynamic
= true
1017 if (this.workerChoiceStrategyContext
.getStrategyPolicy().useDynamicWorker
) {
1018 workerInfo
.ready
= true
1020 return workerNodeKey
1024 * Registers a listener callback on the worker given its worker node key.
1026 * @param workerNodeKey - The worker node key.
1027 * @param listener - The message listener callback.
1029 protected abstract registerWorkerMessageListener
<
1030 Message
extends Data
| Response
1032 workerNodeKey
: number,
1033 listener
: (message
: MessageValue
<Message
>) => void
1037 * Method hooked up after a worker node has been newly created.
1038 * Can be overridden.
1040 * @param workerNodeKey - The newly created worker node key.
1042 protected afterWorkerNodeSetup (workerNodeKey
: number): void {
1043 // Listen to worker messages.
1044 this.registerWorkerMessageListener(workerNodeKey
, this.workerListener())
1045 // Send the startup message to worker.
1046 this.sendStartupMessageToWorker(workerNodeKey
)
1047 // Send the statistics message to worker.
1048 this.sendStatisticsMessageToWorker(workerNodeKey
)
1052 * Sends the startup message to worker given its worker node key.
1054 * @param workerNodeKey - The worker node key.
1056 protected abstract sendStartupMessageToWorker (workerNodeKey
: number): void
1059 * Sends the statistics message to worker given its worker node key.
1061 * @param workerNodeKey - The worker node key.
1063 private sendStatisticsMessageToWorker (workerNodeKey
: number): void {
1064 this.sendToWorker(workerNodeKey
, {
1067 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1069 elu
: this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1072 workerId
: this.getWorkerInfo(workerNodeKey
).id
as number
1076 private redistributeQueuedTasks (workerNodeKey
: number): void {
1077 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1078 let targetWorkerNodeKey
: number = workerNodeKey
1079 let minQueuedTasks
= Infinity
1080 let executeTask
= false
1081 for (const [workerNodeId
, workerNode
] of this.workerNodes
.entries()) {
1082 const workerInfo
= this.getWorkerInfo(workerNodeId
)
1084 workerNodeId
!== workerNodeKey
&&
1086 workerNode
.usage
.tasks
.queued
=== 0
1089 this.workerNodes
[workerNodeId
].usage
.tasks
.executing
<
1090 (this.opts
.tasksQueueOptions
?.concurrency
as number)
1094 targetWorkerNodeKey
= workerNodeId
1098 workerNodeId
!== workerNodeKey
&&
1100 workerNode
.usage
.tasks
.queued
< minQueuedTasks
1102 minQueuedTasks
= workerNode
.usage
.tasks
.queued
1103 targetWorkerNodeKey
= workerNodeId
1108 targetWorkerNodeKey
,
1109 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1113 targetWorkerNodeKey
,
1114 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1121 * This method is the listener registered for each worker message.
1123 * @returns The listener function to execute when a message is received from a worker.
1125 protected workerListener (): (message
: MessageValue
<Response
>) => void {
1126 return (message
) => {
1127 this.checkMessageWorkerId(message
)
1128 if (message
.ready
!= null) {
1129 // Worker ready response received from worker
1130 this.handleWorkerReadyResponse(message
)
1131 } else if (message
.taskId
!= null) {
1132 // Task execution response received from worker
1133 this.handleTaskExecutionResponse(message
)
1134 } else if (message
.taskFunctions
!= null) {
1135 // Task functions message received from worker
1137 this.getWorkerNodeKeyByWorkerId(message
.workerId
)
1138 ).taskFunctions
= message
.taskFunctions
1143 private handleWorkerReadyResponse (message
: MessageValue
<Response
>): void {
1144 if (message
.ready
=== false) {
1145 throw new Error(`Worker ${message.workerId} failed to initialize`)
1148 this.getWorkerNodeKeyByWorkerId(message
.workerId
)
1149 ).ready
= message
.ready
as boolean
1150 if (this.emitter
!= null && this.ready
) {
1151 this.emitter
.emit(PoolEvents
.ready
, this.info
)
1155 private handleTaskExecutionResponse (message
: MessageValue
<Response
>): void {
1156 const promiseResponse
= this.promiseResponseMap
.get(
1157 message
.taskId
as string
1159 if (promiseResponse
!= null) {
1160 if (message
.taskError
!= null) {
1161 this.emitter
?.emit(PoolEvents
.taskError
, message
.taskError
)
1162 promiseResponse
.reject(message
.taskError
.message
)
1164 promiseResponse
.resolve(message
.data
as Response
)
1166 const workerNodeKey
= promiseResponse
.workerNodeKey
1167 this.afterTaskExecutionHook(workerNodeKey
, message
)
1168 this.promiseResponseMap
.delete(message
.taskId
as string)
1170 this.opts
.enableTasksQueue
=== true &&
1171 this.tasksQueueSize(workerNodeKey
) > 0 &&
1172 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
<
1173 (this.opts
.tasksQueueOptions
?.concurrency
as number)
1177 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1180 this.workerChoiceStrategyContext
.update(workerNodeKey
)
1184 private checkAndEmitEvents (): void {
1185 if (this.emitter
!= null) {
1187 this.emitter
.emit(PoolEvents
.busy
, this.info
)
1189 if (this.type === PoolTypes
.dynamic
&& this.full
) {
1190 this.emitter
.emit(PoolEvents
.full
, this.info
)
1196 * Gets the worker information given its worker node key.
1198 * @param workerNodeKey - The worker node key.
1199 * @returns The worker information.
1201 protected getWorkerInfo (workerNodeKey
: number): WorkerInfo
{
1202 return this.workerNodes
[workerNodeKey
].info
1206 * Adds the given worker in the pool worker nodes.
1208 * @param worker - The worker.
1209 * @returns The added worker node key.
1210 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the added worker node is not found.
1212 private addWorkerNode (worker
: Worker
): number {
1213 const workerNode
= new WorkerNode
<Worker
, Data
>(worker
, this.worker
)
1214 // Flag the worker node as ready at pool startup.
1215 if (this.starting
) {
1216 workerNode
.info
.ready
= true
1218 this.workerNodes
.push(workerNode
)
1219 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
1220 if (workerNodeKey
=== -1) {
1221 throw new Error('Worker node not found')
1223 return workerNodeKey
1227 * Removes the given worker from the pool worker nodes.
1229 * @param worker - The worker.
1231 private removeWorkerNode (worker
: Worker
): void {
1232 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
1233 if (workerNodeKey
!== -1) {
1234 this.workerNodes
.splice(workerNodeKey
, 1)
1235 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
1240 * Executes the given task on the worker given its worker node key.
1242 * @param workerNodeKey - The worker node key.
1243 * @param task - The task to execute.
1245 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
1246 this.beforeTaskExecutionHook(workerNodeKey
, task
)
1247 this.sendToWorker(workerNodeKey
, task
, task
.transferList
)
1250 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
1251 return this.workerNodes
[workerNodeKey
].enqueueTask(task
)
1254 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
1255 return this.workerNodes
[workerNodeKey
].dequeueTask()
1258 private tasksQueueSize (workerNodeKey
: number): number {
1259 return this.workerNodes
[workerNodeKey
].tasksQueueSize()
1262 protected flushTasksQueue (workerNodeKey
: number): void {
1263 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1266 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1269 this.workerNodes
[workerNodeKey
].clearTasksQueue()
1272 private flushTasksQueues (): void {
1273 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
1274 this.flushTasksQueue(workerNodeKey
)