1 import { randomUUID
} from
'node:crypto'
2 import { performance
} from
'node:perf_hooks'
3 import { existsSync
} from
'node:fs'
6 PromiseResponseWrapper
,
8 } from
'../utility-types'
11 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()) {
109 throw new Error('Cannot start a pool from a worker!')
111 this.checkNumberOfWorkers(this.numberOfWorkers
)
112 this.checkFilePath(this.filePath
)
113 this.checkPoolOptions(this.opts
)
115 this.chooseWorkerNode
= this.chooseWorkerNode
.bind(this)
116 this.executeTask
= this.executeTask
.bind(this)
117 this.enqueueTask
= this.enqueueTask
.bind(this)
118 this.dequeueTask
= this.dequeueTask
.bind(this)
119 this.checkAndEmitEvents
= this.checkAndEmitEvents
.bind(this)
121 if (this.opts
.enableEvents
=== true) {
122 this.emitter
= new PoolEmitter()
124 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext
<
130 this.opts
.workerChoiceStrategy
,
131 this.opts
.workerChoiceStrategyOptions
138 this.starting
= false
140 this.startTimestamp
= performance
.now()
143 private checkFilePath (filePath
: string): void {
146 typeof filePath
!== 'string' ||
147 (typeof filePath
=== 'string' && filePath
.trim().length
=== 0)
149 throw new Error('Please specify a file with a worker implementation')
151 if (!existsSync(filePath
)) {
152 throw new Error(`Cannot find the worker file '${filePath}'`)
156 private checkNumberOfWorkers (numberOfWorkers
: number): void {
157 if (numberOfWorkers
== null) {
159 'Cannot instantiate a pool without specifying the number of workers'
161 } else if (!Number.isSafeInteger(numberOfWorkers
)) {
163 'Cannot instantiate a pool with a non safe integer number of workers'
165 } else if (numberOfWorkers
< 0) {
166 throw new RangeError(
167 'Cannot instantiate a pool with a negative number of workers'
169 } else if (this.type === PoolTypes
.fixed
&& numberOfWorkers
=== 0) {
170 throw new RangeError('Cannot instantiate a fixed pool with zero worker')
174 protected checkDynamicPoolSize (min
: number, max
: number): void {
175 if (this.type === PoolTypes
.dynamic
) {
178 'Cannot instantiate a dynamic pool without specifying the maximum pool size'
180 } else if (!Number.isSafeInteger(max
)) {
182 'Cannot instantiate a dynamic pool with a non safe integer maximum pool size'
184 } else if (min
> max
) {
185 throw new RangeError(
186 'Cannot instantiate a dynamic pool with a maximum pool size inferior to the minimum pool size'
188 } else if (max
=== 0) {
189 throw new RangeError(
190 'Cannot instantiate a dynamic pool with a pool size equal to zero'
192 } else if (min
=== max
) {
193 throw new RangeError(
194 'Cannot instantiate a dynamic pool with a minimum pool size equal to the maximum pool size. Use a fixed pool instead'
200 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
201 if (isPlainObject(opts
)) {
202 this.opts
.workerChoiceStrategy
=
203 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
204 this.checkValidWorkerChoiceStrategy(this.opts
.workerChoiceStrategy
)
205 this.opts
.workerChoiceStrategyOptions
=
206 opts
.workerChoiceStrategyOptions
??
207 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
208 this.checkValidWorkerChoiceStrategyOptions(
209 this.opts
.workerChoiceStrategyOptions
211 this.opts
.restartWorkerOnError
= opts
.restartWorkerOnError
?? true
212 this.opts
.enableEvents
= opts
.enableEvents
?? true
213 this.opts
.enableTasksQueue
= opts
.enableTasksQueue
?? false
214 if (this.opts
.enableTasksQueue
) {
215 this.checkValidTasksQueueOptions(
216 opts
.tasksQueueOptions
as TasksQueueOptions
218 this.opts
.tasksQueueOptions
= this.buildTasksQueueOptions(
219 opts
.tasksQueueOptions
as TasksQueueOptions
223 throw new TypeError('Invalid pool options: must be a plain object')
227 private checkValidWorkerChoiceStrategy (
228 workerChoiceStrategy
: WorkerChoiceStrategy
230 if (!Object.values(WorkerChoiceStrategies
).includes(workerChoiceStrategy
)) {
232 `Invalid worker choice strategy '${workerChoiceStrategy}'`
237 private checkValidWorkerChoiceStrategyOptions (
238 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
240 if (!isPlainObject(workerChoiceStrategyOptions
)) {
242 'Invalid worker choice strategy options: must be a plain object'
246 workerChoiceStrategyOptions
.weights
!= null &&
247 Object.keys(workerChoiceStrategyOptions
.weights
).length
!== this.maxSize
250 'Invalid worker choice strategy options: must have a weight for each worker node'
254 workerChoiceStrategyOptions
.measurement
!= null &&
255 !Object.values(Measurements
).includes(
256 workerChoiceStrategyOptions
.measurement
260 `Invalid worker choice strategy options: invalid measurement '${workerChoiceStrategyOptions.measurement}'`
265 private checkValidTasksQueueOptions (
266 tasksQueueOptions
: TasksQueueOptions
268 if (tasksQueueOptions
!= null && !isPlainObject(tasksQueueOptions
)) {
269 throw new TypeError('Invalid tasks queue options: must be a plain object')
272 tasksQueueOptions
?.concurrency
!= null &&
273 !Number.isSafeInteger(tasksQueueOptions
.concurrency
)
276 'Invalid worker tasks concurrency: must be an integer'
280 tasksQueueOptions
?.concurrency
!= null &&
281 tasksQueueOptions
.concurrency
<= 0
284 `Invalid worker tasks concurrency '${tasksQueueOptions.concurrency}'`
289 private startPool (): void {
291 this.workerNodes
.reduce(
292 (accumulator
, workerNode
) =>
293 !workerNode
.info
.dynamic
? accumulator
+ 1 : accumulator
,
295 ) < this.numberOfWorkers
297 this.createAndSetupWorkerNode()
302 public get
info (): PoolInfo
{
308 strategy
: this.opts
.workerChoiceStrategy
as WorkerChoiceStrategy
,
309 minSize
: this.minSize
,
310 maxSize
: this.maxSize
,
311 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
312 .runTime
.aggregate
&&
313 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
314 .waitTime
.aggregate
&& { utilization
: round(this.utilization
) }),
315 workerNodes
: this.workerNodes
.length
,
316 idleWorkerNodes
: this.workerNodes
.reduce(
317 (accumulator
, workerNode
) =>
318 workerNode
.usage
.tasks
.executing
=== 0
323 busyWorkerNodes
: this.workerNodes
.reduce(
324 (accumulator
, workerNode
) =>
325 workerNode
.usage
.tasks
.executing
> 0 ? accumulator
+ 1 : accumulator
,
328 executedTasks
: this.workerNodes
.reduce(
329 (accumulator
, workerNode
) =>
330 accumulator
+ workerNode
.usage
.tasks
.executed
,
333 executingTasks
: this.workerNodes
.reduce(
334 (accumulator
, workerNode
) =>
335 accumulator
+ workerNode
.usage
.tasks
.executing
,
338 queuedTasks
: this.workerNodes
.reduce(
339 (accumulator
, workerNode
) =>
340 accumulator
+ workerNode
.usage
.tasks
.queued
,
343 maxQueuedTasks
: this.workerNodes
.reduce(
344 (accumulator
, workerNode
) =>
345 accumulator
+ (workerNode
.usage
.tasks
?.maxQueued
?? 0),
348 failedTasks
: this.workerNodes
.reduce(
349 (accumulator
, workerNode
) =>
350 accumulator
+ workerNode
.usage
.tasks
.failed
,
353 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
354 .runTime
.aggregate
&& {
358 ...this.workerNodes
.map(
359 workerNode
=> workerNode
.usage
.runTime
?.minimum
?? Infinity
365 ...this.workerNodes
.map(
366 workerNode
=> workerNode
.usage
.runTime
?.maximum
?? -Infinity
371 this.workerNodes
.reduce(
372 (accumulator
, workerNode
) =>
373 accumulator
+ (workerNode
.usage
.runTime
?.aggregate
?? 0),
376 this.workerNodes
.reduce(
377 (accumulator
, workerNode
) =>
378 accumulator
+ (workerNode
.usage
.tasks
?.executed
?? 0),
382 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
386 this.workerNodes
.map(
387 workerNode
=> workerNode
.usage
.runTime
?.median
?? 0
394 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
395 .waitTime
.aggregate
&& {
399 ...this.workerNodes
.map(
400 workerNode
=> workerNode
.usage
.waitTime
?.minimum
?? Infinity
406 ...this.workerNodes
.map(
407 workerNode
=> workerNode
.usage
.waitTime
?.maximum
?? -Infinity
412 this.workerNodes
.reduce(
413 (accumulator
, workerNode
) =>
414 accumulator
+ (workerNode
.usage
.waitTime
?.aggregate
?? 0),
417 this.workerNodes
.reduce(
418 (accumulator
, workerNode
) =>
419 accumulator
+ (workerNode
.usage
.tasks
?.executed
?? 0),
423 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
424 .waitTime
.median
&& {
427 this.workerNodes
.map(
428 workerNode
=> workerNode
.usage
.waitTime
?.median
?? 0
439 * The pool readiness boolean status.
441 private get
ready (): boolean {
443 this.workerNodes
.reduce(
444 (accumulator
, workerNode
) =>
445 !workerNode
.info
.dynamic
&& workerNode
.info
.ready
454 * The approximate pool utilization.
456 * @returns The pool utilization.
458 private get
utilization (): number {
459 const poolTimeCapacity
=
460 (performance
.now() - this.startTimestamp
) * this.maxSize
461 const totalTasksRunTime
= this.workerNodes
.reduce(
462 (accumulator
, workerNode
) =>
463 accumulator
+ (workerNode
.usage
.runTime
?.aggregate
?? 0),
466 const totalTasksWaitTime
= this.workerNodes
.reduce(
467 (accumulator
, workerNode
) =>
468 accumulator
+ (workerNode
.usage
.waitTime
?.aggregate
?? 0),
471 return (totalTasksRunTime
+ totalTasksWaitTime
) / poolTimeCapacity
477 * If it is `'dynamic'`, it provides the `max` property.
479 protected abstract get
type (): PoolType
484 protected abstract get
worker (): WorkerType
487 * The pool minimum size.
489 protected abstract get
minSize (): number
492 * The pool maximum size.
494 protected abstract get
maxSize (): number
497 * Checks if the worker id sent in the received message from a worker is valid.
499 * @param message - The received message.
500 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the worker id is invalid.
502 private checkMessageWorkerId (message
: MessageValue
<Response
>): void {
504 message
.workerId
!= null &&
505 this.getWorkerNodeKeyByWorkerId(message
.workerId
) === -1
508 `Worker message received from unknown worker '${message.workerId}'`
514 * Gets the given worker its worker node key.
516 * @param worker - The worker.
517 * @returns The worker node key if found in the pool worker nodes, `-1` otherwise.
519 private getWorkerNodeKeyByWorker (worker
: Worker
): number {
520 return this.workerNodes
.findIndex(
521 workerNode
=> workerNode
.worker
=== worker
526 * Gets the worker node key given its worker id.
528 * @param workerId - The worker id.
529 * @returns The worker node key if the worker id is found in the pool worker nodes, `-1` otherwise.
531 private getWorkerNodeKeyByWorkerId (workerId
: number): number {
532 return this.workerNodes
.findIndex(
533 workerNode
=> workerNode
.info
.id
=== workerId
538 public setWorkerChoiceStrategy (
539 workerChoiceStrategy
: WorkerChoiceStrategy
,
540 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
542 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
543 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
544 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
545 this.opts
.workerChoiceStrategy
547 if (workerChoiceStrategyOptions
!= null) {
548 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
550 for (const [workerNodeKey
, workerNode
] of this.workerNodes
.entries()) {
551 workerNode
.resetUsage()
552 this.sendWorkerStatisticsMessageToWorker(workerNodeKey
)
557 public setWorkerChoiceStrategyOptions (
558 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
560 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
561 this.opts
.workerChoiceStrategyOptions
= workerChoiceStrategyOptions
562 this.workerChoiceStrategyContext
.setOptions(
563 this.opts
.workerChoiceStrategyOptions
568 public enableTasksQueue (
570 tasksQueueOptions
?: TasksQueueOptions
572 if (this.opts
.enableTasksQueue
=== true && !enable
) {
573 this.flushTasksQueues()
575 this.opts
.enableTasksQueue
= enable
576 this.setTasksQueueOptions(tasksQueueOptions
as TasksQueueOptions
)
580 public setTasksQueueOptions (tasksQueueOptions
: TasksQueueOptions
): void {
581 if (this.opts
.enableTasksQueue
=== true) {
582 this.checkValidTasksQueueOptions(tasksQueueOptions
)
583 this.opts
.tasksQueueOptions
=
584 this.buildTasksQueueOptions(tasksQueueOptions
)
585 } else if (this.opts
.tasksQueueOptions
!= null) {
586 delete this.opts
.tasksQueueOptions
590 private buildTasksQueueOptions (
591 tasksQueueOptions
: TasksQueueOptions
592 ): TasksQueueOptions
{
594 concurrency
: tasksQueueOptions
?.concurrency
?? 1
599 * Whether the pool is full or not.
601 * The pool filling boolean status.
603 protected get
full (): boolean {
604 return this.workerNodes
.length
>= this.maxSize
608 * Whether the pool is busy or not.
610 * The pool busyness boolean status.
612 protected abstract get
busy (): boolean
615 * Whether worker nodes are executing at least one task.
617 * @returns Worker nodes busyness boolean status.
619 protected internalBusy (): boolean {
621 this.workerNodes
.findIndex(workerNode
=> {
622 return workerNode
.usage
.tasks
.executing
=== 0
628 public async execute (data
?: Data
, name
?: string): Promise
<Response
> {
629 return await new Promise
<Response
>((resolve
, reject
) => {
630 const timestamp
= performance
.now()
631 const workerNodeKey
= this.chooseWorkerNode()
632 const task
: Task
<Data
> = {
633 name
: name
?? DEFAULT_TASK_NAME
,
634 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
635 data
: data
?? ({} as Data
),
637 workerId
: this.getWorkerInfo(workerNodeKey
).id
as number,
640 this.promiseResponseMap
.set(task
.id
as string, {
646 this.opts
.enableTasksQueue
=== true &&
648 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
>=
649 (this.opts
.tasksQueueOptions
?.concurrency
as number))
651 this.enqueueTask(workerNodeKey
, task
)
653 this.executeTask(workerNodeKey
, task
)
655 this.checkAndEmitEvents()
660 public async destroy (): Promise
<void> {
662 this.workerNodes
.map(async (workerNode
, workerNodeKey
) => {
663 this.flushTasksQueue(workerNodeKey
)
664 // FIXME: wait for tasks to be finished
665 const workerExitPromise
= new Promise
<void>(resolve
=> {
666 workerNode
.worker
.on('exit', () => {
670 await this.destroyWorkerNode(workerNodeKey
)
671 await workerExitPromise
677 * Terminates the worker node given its worker node key.
679 * @param workerNodeKey - The worker node key.
681 protected abstract destroyWorkerNode (
682 workerNodeKey
: number
683 ): void | Promise
<void>
686 * Setup hook to execute code before worker nodes are created in the abstract constructor.
691 protected setupHook (): void {
692 // Intentionally empty
696 * Should return whether the worker is the main worker or not.
698 protected abstract isMain (): boolean
701 * Hook executed before the worker task execution.
704 * @param workerNodeKey - The worker node key.
705 * @param task - The task to execute.
707 protected beforeTaskExecutionHook (
708 workerNodeKey
: number,
711 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
712 ++workerUsage
.tasks
.executing
713 this.updateWaitTimeWorkerUsage(workerUsage
, task
)
714 const taskWorkerUsage
= this.workerNodes
[workerNodeKey
].getTaskWorkerUsage(
717 ++taskWorkerUsage
.tasks
.executing
718 this.updateWaitTimeWorkerUsage(taskWorkerUsage
, task
)
722 * Hook executed after the worker task execution.
725 * @param workerNodeKey - The worker node key.
726 * @param message - The received message.
728 protected afterTaskExecutionHook (
729 workerNodeKey
: number,
730 message
: MessageValue
<Response
>
732 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
733 this.updateTaskStatisticsWorkerUsage(workerUsage
, message
)
734 this.updateRunTimeWorkerUsage(workerUsage
, message
)
735 this.updateEluWorkerUsage(workerUsage
, message
)
736 const taskWorkerUsage
= this.workerNodes
[workerNodeKey
].getTaskWorkerUsage(
737 message
.taskPerformance
?.name
?? DEFAULT_TASK_NAME
739 this.updateTaskStatisticsWorkerUsage(taskWorkerUsage
, message
)
740 this.updateRunTimeWorkerUsage(taskWorkerUsage
, message
)
741 this.updateEluWorkerUsage(taskWorkerUsage
, message
)
744 private updateTaskStatisticsWorkerUsage (
745 workerUsage
: WorkerUsage
,
746 message
: MessageValue
<Response
>
748 const workerTaskStatistics
= workerUsage
.tasks
749 --workerTaskStatistics
.executing
750 if (message
.taskError
== null) {
751 ++workerTaskStatistics
.executed
753 ++workerTaskStatistics
.failed
757 private updateRunTimeWorkerUsage (
758 workerUsage
: WorkerUsage
,
759 message
: MessageValue
<Response
>
761 updateMeasurementStatistics(
763 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
,
764 message
.taskPerformance
?.runTime
?? 0,
765 workerUsage
.tasks
.executed
769 private updateWaitTimeWorkerUsage (
770 workerUsage
: WorkerUsage
,
773 const timestamp
= performance
.now()
774 const taskWaitTime
= timestamp
- (task
.timestamp
?? timestamp
)
775 updateMeasurementStatistics(
776 workerUsage
.waitTime
,
777 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().waitTime
,
779 workerUsage
.tasks
.executed
783 private updateEluWorkerUsage (
784 workerUsage
: WorkerUsage
,
785 message
: MessageValue
<Response
>
787 const eluTaskStatisticsRequirements
: MeasurementStatisticsRequirements
=
788 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
789 updateMeasurementStatistics(
790 workerUsage
.elu
.active
,
791 eluTaskStatisticsRequirements
,
792 message
.taskPerformance
?.elu
?.active
?? 0,
793 workerUsage
.tasks
.executed
795 updateMeasurementStatistics(
796 workerUsage
.elu
.idle
,
797 eluTaskStatisticsRequirements
,
798 message
.taskPerformance
?.elu
?.idle
?? 0,
799 workerUsage
.tasks
.executed
801 if (eluTaskStatisticsRequirements
.aggregate
) {
802 if (message
.taskPerformance
?.elu
!= null) {
803 if (workerUsage
.elu
.utilization
!= null) {
804 workerUsage
.elu
.utilization
=
805 (workerUsage
.elu
.utilization
+
806 message
.taskPerformance
.elu
.utilization
) /
809 workerUsage
.elu
.utilization
= message
.taskPerformance
.elu
.utilization
816 * Chooses a worker node for the next task.
818 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
820 * @returns The chosen worker node key
822 private chooseWorkerNode (): number {
823 if (this.shallCreateDynamicWorker()) {
824 const workerNodeKey
= this.createAndSetupDynamicWorkerNode()
826 this.workerChoiceStrategyContext
.getStrategyPolicy().useDynamicWorker
831 return this.workerChoiceStrategyContext
.execute()
835 * Conditions for dynamic worker creation.
837 * @returns Whether to create a dynamic worker or not.
839 private shallCreateDynamicWorker (): boolean {
840 return this.type === PoolTypes
.dynamic
&& !this.full
&& this.internalBusy()
844 * Sends a message to worker given its worker node key.
846 * @param workerNodeKey - The worker node key.
847 * @param message - The message.
849 protected abstract sendToWorker (
850 workerNodeKey
: number,
851 message
: MessageValue
<Data
>
855 * Creates a new worker.
857 * @returns Newly created worker.
859 protected abstract createWorker (): Worker
862 * Creates a new, completely set up worker node.
864 * @returns New, completely set up worker node key.
866 protected createAndSetupWorkerNode (): number {
867 const worker
= this.createWorker()
869 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
870 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
871 worker
.on('error', error
=> {
872 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
873 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
874 workerInfo
.ready
= false
875 this.workerNodes
[workerNodeKey
].closeChannel()
876 this.emitter
?.emit(PoolEvents
.error
, error
)
877 if (this.opts
.restartWorkerOnError
=== true && !this.starting
) {
878 if (workerInfo
.dynamic
) {
879 this.createAndSetupDynamicWorkerNode()
881 this.createAndSetupWorkerNode()
884 if (this.opts
.enableTasksQueue
=== true) {
885 this.redistributeQueuedTasks(workerNodeKey
)
888 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
889 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
890 worker
.once('exit', () => {
891 this.removeWorkerNode(worker
)
894 const workerNodeKey
= this.addWorkerNode(worker
)
896 this.afterWorkerNodeSetup(workerNodeKey
)
902 * Creates a new, completely set up dynamic worker node.
904 * @returns New, completely set up dynamic worker node key.
906 protected createAndSetupDynamicWorkerNode (): number {
907 const workerNodeKey
= this.createAndSetupWorkerNode()
908 this.registerWorkerMessageListener(workerNodeKey
, message
=> {
909 const localWorkerNodeKey
= this.getWorkerNodeKeyByWorkerId(
912 const workerUsage
= this.workerNodes
[localWorkerNodeKey
].usage
914 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
915 (message
.kill
!= null &&
916 ((this.opts
.enableTasksQueue
=== false &&
917 workerUsage
.tasks
.executing
=== 0) ||
918 (this.opts
.enableTasksQueue
=== true &&
919 workerUsage
.tasks
.executing
=== 0 &&
920 this.tasksQueueSize(localWorkerNodeKey
) === 0)))
922 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
923 const destroyWorkerNodeBounded
= this.destroyWorkerNode
.bind(this)
924 if (isAsyncFunction(destroyWorkerNodeBounded
)) {
926 destroyWorkerNodeBounded
as (workerNodeKey
: number) => Promise
<void>
927 )(localWorkerNodeKey
).catch(EMPTY_FUNCTION
)
929 (destroyWorkerNodeBounded
as (workerNodeKey
: number) => void)(
935 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
936 this.sendToWorker(workerNodeKey
, {
938 workerId
: workerInfo
.id
as number
940 workerInfo
.dynamic
= true
941 if (this.workerChoiceStrategyContext
.getStrategyPolicy().useDynamicWorker
) {
942 workerInfo
.ready
= true
948 * Registers a listener callback on the worker given its worker node key.
950 * @param workerNodeKey - The worker node key.
951 * @param listener - The message listener callback.
953 protected abstract registerWorkerMessageListener
<
954 Message
extends Data
| Response
956 workerNodeKey
: number,
957 listener
: (message
: MessageValue
<Message
>) => void
961 * Method hooked up after a worker node has been newly created.
964 * @param workerNodeKey - The newly created worker node key.
966 protected afterWorkerNodeSetup (workerNodeKey
: number): void {
967 // Listen to worker messages.
968 this.registerWorkerMessageListener(workerNodeKey
, this.workerListener())
969 // Send the startup message to worker.
970 this.sendStartupMessageToWorker(workerNodeKey
)
971 // Send the worker statistics message to worker.
972 this.sendWorkerStatisticsMessageToWorker(workerNodeKey
)
976 * Sends the startup message to worker given its worker node key.
978 * @param workerNodeKey - The worker node key.
980 protected abstract sendStartupMessageToWorker (workerNodeKey
: number): void
983 * Sends the worker statistics message to worker given its worker node key.
985 * @param workerNodeKey - The worker node key.
987 private sendWorkerStatisticsMessageToWorker (workerNodeKey
: number): void {
988 this.sendToWorker(workerNodeKey
, {
991 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
993 elu
: this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
996 workerId
: this.getWorkerInfo(workerNodeKey
).id
as number
1000 private redistributeQueuedTasks (workerNodeKey
: number): void {
1001 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1002 let targetWorkerNodeKey
: number = workerNodeKey
1003 let minQueuedTasks
= Infinity
1004 let executeTask
= false
1005 for (const [workerNodeId
, workerNode
] of this.workerNodes
.entries()) {
1006 const workerInfo
= this.getWorkerInfo(workerNodeId
)
1008 workerNodeId
!== workerNodeKey
&&
1010 workerNode
.usage
.tasks
.queued
=== 0
1013 this.workerNodes
[workerNodeId
].usage
.tasks
.executing
<
1014 (this.opts
.tasksQueueOptions
?.concurrency
as number)
1018 targetWorkerNodeKey
= workerNodeId
1022 workerNodeId
!== workerNodeKey
&&
1024 workerNode
.usage
.tasks
.queued
< minQueuedTasks
1026 minQueuedTasks
= workerNode
.usage
.tasks
.queued
1027 targetWorkerNodeKey
= workerNodeId
1032 targetWorkerNodeKey
,
1033 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1037 targetWorkerNodeKey
,
1038 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1045 * This method is the listener registered for each worker message.
1047 * @returns The listener function to execute when a message is received from a worker.
1049 protected workerListener (): (message
: MessageValue
<Response
>) => void {
1051 this.checkMessageWorkerId(message
)
1052 if (message
.ready
!= null) {
1053 // Worker ready response received
1054 this.handleWorkerReadyResponse(message
)
1055 } else if (message
.id
!= null) {
1056 // Task execution response received
1057 this.handleTaskExecutionResponse(message
)
1062 private handleWorkerReadyResponse (message
: MessageValue
<Response
>): void {
1064 this.getWorkerNodeKeyByWorkerId(message
.workerId
)
1065 ).ready
= message
.ready
as boolean
1066 if (this.emitter
!= null && this.ready
) {
1067 this.emitter
.emit(PoolEvents
.ready
, this.info
)
1071 private handleTaskExecutionResponse (message
: MessageValue
<Response
>): void {
1072 const promiseResponse
= this.promiseResponseMap
.get(message
.id
as string)
1073 if (promiseResponse
!= null) {
1074 if (message
.taskError
!= null) {
1075 this.emitter
?.emit(PoolEvents
.taskError
, message
.taskError
)
1076 promiseResponse
.reject(message
.taskError
.message
)
1078 promiseResponse
.resolve(message
.data
as Response
)
1080 const workerNodeKey
= promiseResponse
.workerNodeKey
1081 this.afterTaskExecutionHook(workerNodeKey
, message
)
1082 this.promiseResponseMap
.delete(message
.id
as string)
1084 this.opts
.enableTasksQueue
=== true &&
1085 this.tasksQueueSize(workerNodeKey
) > 0 &&
1086 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
<
1087 (this.opts
.tasksQueueOptions
?.concurrency
as number)
1091 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1094 this.workerChoiceStrategyContext
.update(workerNodeKey
)
1098 private checkAndEmitEvents (): void {
1099 if (this.emitter
!= null) {
1101 this.emitter
.emit(PoolEvents
.busy
, this.info
)
1103 if (this.type === PoolTypes
.dynamic
&& this.full
) {
1104 this.emitter
.emit(PoolEvents
.full
, this.info
)
1110 * Gets the worker information given its worker node key.
1112 * @param workerNodeKey - The worker node key.
1113 * @returns The worker information.
1115 protected getWorkerInfo (workerNodeKey
: number): WorkerInfo
{
1116 return this.workerNodes
[workerNodeKey
].info
1120 * Adds the given worker in the pool worker nodes.
1122 * @param worker - The worker.
1123 * @returns The added worker node key.
1124 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the added worker node is not found.
1126 private addWorkerNode (worker
: Worker
): number {
1127 const workerNode
= new WorkerNode
<Worker
, Data
>(worker
, this.worker
)
1128 // Flag the worker node as ready at pool startup.
1129 if (this.starting
) {
1130 workerNode
.info
.ready
= true
1132 this.workerNodes
.push(workerNode
)
1133 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
1134 if (workerNodeKey
=== -1) {
1135 throw new Error('Worker node not found')
1137 return workerNodeKey
1141 * Removes the given worker from the pool worker nodes.
1143 * @param worker - The worker.
1145 private removeWorkerNode (worker
: Worker
): void {
1146 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
1147 if (workerNodeKey
!== -1) {
1148 this.workerNodes
.splice(workerNodeKey
, 1)
1149 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
1154 * Executes the given task on the worker given its worker node key.
1156 * @param workerNodeKey - The worker node key.
1157 * @param task - The task to execute.
1159 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
1160 this.beforeTaskExecutionHook(workerNodeKey
, task
)
1161 this.sendToWorker(workerNodeKey
, task
)
1164 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
1165 return this.workerNodes
[workerNodeKey
].enqueueTask(task
)
1168 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
1169 return this.workerNodes
[workerNodeKey
].dequeueTask()
1172 private tasksQueueSize (workerNodeKey
: number): number {
1173 return this.workerNodes
[workerNodeKey
].tasksQueueSize()
1176 private flushTasksQueue (workerNodeKey
: number): void {
1177 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1180 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1183 this.workerNodes
[workerNodeKey
].clearTasksQueue()
1186 private flushTasksQueues (): void {
1187 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
1188 this.flushTasksQueue(workerNodeKey
)