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
,
17 updateMeasurementStatistics
19 import { KillBehaviors
} from
'../worker/worker-options'
28 type TasksQueueOptions
38 type MeasurementStatisticsRequirements
,
40 WorkerChoiceStrategies
,
41 type WorkerChoiceStrategy
,
42 type WorkerChoiceStrategyOptions
43 } from
'./selection-strategies/selection-strategies-types'
44 import { WorkerChoiceStrategyContext
} from
'./selection-strategies/worker-choice-strategy-context'
45 import { version
} from
'./version'
46 import { WorkerNode
} from
'./worker-node'
49 * Base class that implements some shared logic for all poolifier pools.
51 * @typeParam Worker - Type of worker which manages this pool.
52 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
53 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
55 export abstract class AbstractPool
<
56 Worker
extends IWorker
,
59 > implements IPool
<Worker
, Data
, Response
> {
61 public readonly workerNodes
: Array<IWorkerNode
<Worker
, Data
>> = []
64 public readonly emitter
?: PoolEmitter
67 * The task execution response promise map.
69 * - `key`: The message id of each submitted task.
70 * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks.
72 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
74 protected promiseResponseMap
: Map
<string, PromiseResponseWrapper
<Response
>> =
75 new Map
<string, PromiseResponseWrapper
<Response
>>()
78 * Worker choice strategy context referencing a worker choice algorithm implementation.
80 protected workerChoiceStrategyContext
: WorkerChoiceStrategyContext
<
87 * Whether the pool is starting or not.
89 private readonly starting
: boolean
91 * The start timestamp of the pool.
93 private readonly startTimestamp
96 * Constructs a new poolifier pool.
98 * @param numberOfWorkers - Number of workers that this pool should manage.
99 * @param filePath - Path to the worker file.
100 * @param opts - Options for the pool.
103 protected readonly numberOfWorkers
: number,
104 protected readonly filePath
: string,
105 protected readonly opts
: PoolOptions
<Worker
>
107 if (!this.isMain()) {
108 throw new Error('Cannot start a pool from a worker!')
110 this.checkNumberOfWorkers(this.numberOfWorkers
)
111 this.checkFilePath(this.filePath
)
112 this.checkPoolOptions(this.opts
)
114 this.chooseWorkerNode
= this.chooseWorkerNode
.bind(this)
115 this.executeTask
= this.executeTask
.bind(this)
116 this.enqueueTask
= this.enqueueTask
.bind(this)
117 this.dequeueTask
= this.dequeueTask
.bind(this)
118 this.checkAndEmitEvents
= this.checkAndEmitEvents
.bind(this)
120 if (this.opts
.enableEvents
=== true) {
121 this.emitter
= new PoolEmitter()
123 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext
<
129 this.opts
.workerChoiceStrategy
,
130 this.opts
.workerChoiceStrategyOptions
137 this.starting
= false
139 this.startTimestamp
= performance
.now()
142 private checkFilePath (filePath
: string): void {
145 typeof filePath
!== 'string' ||
146 (typeof filePath
=== 'string' && filePath
.trim().length
=== 0)
148 throw new Error('Please specify a file with a worker implementation')
150 if (!existsSync(filePath
)) {
151 throw new Error(`Cannot find the worker file '${filePath}'`)
155 private checkNumberOfWorkers (numberOfWorkers
: number): void {
156 if (numberOfWorkers
== null) {
158 'Cannot instantiate a pool without specifying the number of workers'
160 } else if (!Number.isSafeInteger(numberOfWorkers
)) {
162 'Cannot instantiate a pool with a non safe integer number of workers'
164 } else if (numberOfWorkers
< 0) {
165 throw new RangeError(
166 'Cannot instantiate a pool with a negative number of workers'
168 } else if (this.type === PoolTypes
.fixed
&& numberOfWorkers
=== 0) {
169 throw new RangeError('Cannot instantiate a fixed pool with zero worker')
173 protected checkDynamicPoolSize (min
: number, max
: number): void {
174 if (this.type === PoolTypes
.dynamic
) {
177 'Cannot instantiate a dynamic pool without specifying the maximum pool size'
179 } else if (!Number.isSafeInteger(max
)) {
181 'Cannot instantiate a dynamic pool with a non safe integer maximum pool size'
183 } else if (min
> max
) {
184 throw new RangeError(
185 'Cannot instantiate a dynamic pool with a maximum pool size inferior to the minimum pool size'
187 } else if (max
=== 0) {
188 throw new RangeError(
189 'Cannot instantiate a dynamic pool with a pool size equal to zero'
191 } else if (min
=== max
) {
192 throw new RangeError(
193 'Cannot instantiate a dynamic pool with a minimum pool size equal to the maximum pool size. Use a fixed pool instead'
199 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
200 if (isPlainObject(opts
)) {
201 this.opts
.workerChoiceStrategy
=
202 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
203 this.checkValidWorkerChoiceStrategy(this.opts
.workerChoiceStrategy
)
204 this.opts
.workerChoiceStrategyOptions
=
205 opts
.workerChoiceStrategyOptions
??
206 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
207 this.checkValidWorkerChoiceStrategyOptions(
208 this.opts
.workerChoiceStrategyOptions
210 this.opts
.restartWorkerOnError
= opts
.restartWorkerOnError
?? true
211 this.opts
.enableEvents
= opts
.enableEvents
?? true
212 this.opts
.enableTasksQueue
= opts
.enableTasksQueue
?? false
213 if (this.opts
.enableTasksQueue
) {
214 this.checkValidTasksQueueOptions(
215 opts
.tasksQueueOptions
as TasksQueueOptions
217 this.opts
.tasksQueueOptions
= this.buildTasksQueueOptions(
218 opts
.tasksQueueOptions
as TasksQueueOptions
222 throw new TypeError('Invalid pool options: must be a plain object')
226 private checkValidWorkerChoiceStrategy (
227 workerChoiceStrategy
: WorkerChoiceStrategy
229 if (!Object.values(WorkerChoiceStrategies
).includes(workerChoiceStrategy
)) {
231 `Invalid worker choice strategy '${workerChoiceStrategy}'`
236 private checkValidWorkerChoiceStrategyOptions (
237 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
239 if (!isPlainObject(workerChoiceStrategyOptions
)) {
241 'Invalid worker choice strategy options: must be a plain object'
245 workerChoiceStrategyOptions
.weights
!= null &&
246 Object.keys(workerChoiceStrategyOptions
.weights
).length
!== this.maxSize
249 'Invalid worker choice strategy options: must have a weight for each worker node'
253 workerChoiceStrategyOptions
.measurement
!= null &&
254 !Object.values(Measurements
).includes(
255 workerChoiceStrategyOptions
.measurement
259 `Invalid worker choice strategy options: invalid measurement '${workerChoiceStrategyOptions.measurement}'`
264 private checkValidTasksQueueOptions (
265 tasksQueueOptions
: TasksQueueOptions
267 if (tasksQueueOptions
!= null && !isPlainObject(tasksQueueOptions
)) {
268 throw new TypeError('Invalid tasks queue options: must be a plain object')
271 tasksQueueOptions
?.concurrency
!= null &&
272 !Number.isSafeInteger(tasksQueueOptions
.concurrency
)
275 'Invalid worker tasks concurrency: must be an integer'
279 tasksQueueOptions
?.concurrency
!= null &&
280 tasksQueueOptions
.concurrency
<= 0
283 `Invalid worker tasks concurrency '${tasksQueueOptions.concurrency}'`
288 private startPool (): void {
290 this.workerNodes
.reduce(
291 (accumulator
, workerNode
) =>
292 !workerNode
.info
.dynamic
? accumulator
+ 1 : accumulator
,
294 ) < this.numberOfWorkers
296 this.createAndSetupWorkerNode()
301 public get
info (): PoolInfo
{
307 strategy
: this.opts
.workerChoiceStrategy
as WorkerChoiceStrategy
,
308 minSize
: this.minSize
,
309 maxSize
: this.maxSize
,
310 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
311 .runTime
.aggregate
&&
312 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
313 .waitTime
.aggregate
&& { utilization
: round(this.utilization
) }),
314 workerNodes
: this.workerNodes
.length
,
315 idleWorkerNodes
: this.workerNodes
.reduce(
316 (accumulator
, workerNode
) =>
317 workerNode
.usage
.tasks
.executing
=== 0
322 busyWorkerNodes
: this.workerNodes
.reduce(
323 (accumulator
, workerNode
) =>
324 workerNode
.usage
.tasks
.executing
> 0 ? accumulator
+ 1 : accumulator
,
327 executedTasks
: this.workerNodes
.reduce(
328 (accumulator
, workerNode
) =>
329 accumulator
+ workerNode
.usage
.tasks
.executed
,
332 executingTasks
: this.workerNodes
.reduce(
333 (accumulator
, workerNode
) =>
334 accumulator
+ workerNode
.usage
.tasks
.executing
,
337 queuedTasks
: this.workerNodes
.reduce(
338 (accumulator
, workerNode
) =>
339 accumulator
+ workerNode
.usage
.tasks
.queued
,
342 maxQueuedTasks
: this.workerNodes
.reduce(
343 (accumulator
, workerNode
) =>
344 accumulator
+ (workerNode
.usage
.tasks
?.maxQueued
?? 0),
347 failedTasks
: this.workerNodes
.reduce(
348 (accumulator
, workerNode
) =>
349 accumulator
+ workerNode
.usage
.tasks
.failed
,
352 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
353 .runTime
.aggregate
&& {
357 ...this.workerNodes
.map(
358 workerNode
=> workerNode
.usage
.runTime
?.minimum
?? Infinity
364 ...this.workerNodes
.map(
365 workerNode
=> workerNode
.usage
.runTime
?.maximum
?? -Infinity
370 this.workerNodes
.reduce(
371 (accumulator
, workerNode
) =>
372 accumulator
+ (workerNode
.usage
.runTime
?.aggregate
?? 0),
375 this.workerNodes
.reduce(
376 (accumulator
, workerNode
) =>
377 accumulator
+ (workerNode
.usage
.tasks
?.executed
?? 0),
381 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
385 this.workerNodes
.map(
386 workerNode
=> workerNode
.usage
.runTime
?.median
?? 0
393 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
394 .waitTime
.aggregate
&& {
398 ...this.workerNodes
.map(
399 workerNode
=> workerNode
.usage
.waitTime
?.minimum
?? Infinity
405 ...this.workerNodes
.map(
406 workerNode
=> workerNode
.usage
.waitTime
?.maximum
?? -Infinity
411 this.workerNodes
.reduce(
412 (accumulator
, workerNode
) =>
413 accumulator
+ (workerNode
.usage
.waitTime
?.aggregate
?? 0),
416 this.workerNodes
.reduce(
417 (accumulator
, workerNode
) =>
418 accumulator
+ (workerNode
.usage
.tasks
?.executed
?? 0),
422 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
423 .waitTime
.median
&& {
426 this.workerNodes
.map(
427 workerNode
=> workerNode
.usage
.waitTime
?.median
?? 0
438 * The pool readiness boolean status.
440 private get
ready (): boolean {
442 this.workerNodes
.reduce(
443 (accumulator
, workerNode
) =>
444 !workerNode
.info
.dynamic
&& workerNode
.info
.ready
453 * The approximate pool utilization.
455 * @returns The pool utilization.
457 private get
utilization (): number {
458 const poolTimeCapacity
=
459 (performance
.now() - this.startTimestamp
) * this.maxSize
460 const totalTasksRunTime
= this.workerNodes
.reduce(
461 (accumulator
, workerNode
) =>
462 accumulator
+ (workerNode
.usage
.runTime
?.aggregate
?? 0),
465 const totalTasksWaitTime
= this.workerNodes
.reduce(
466 (accumulator
, workerNode
) =>
467 accumulator
+ (workerNode
.usage
.waitTime
?.aggregate
?? 0),
470 return (totalTasksRunTime
+ totalTasksWaitTime
) / poolTimeCapacity
476 * If it is `'dynamic'`, it provides the `max` property.
478 protected abstract get
type (): PoolType
483 protected abstract get
worker (): WorkerType
486 * The pool minimum size.
488 protected abstract get
minSize (): number
491 * The pool maximum size.
493 protected abstract get
maxSize (): number
496 * Checks if the worker id sent in the received message from a worker is valid.
498 * @param message - The received message.
499 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the worker id is invalid.
501 private checkMessageWorkerId (message
: MessageValue
<Response
>): void {
503 message
.workerId
!= null &&
504 this.getWorkerNodeKeyByWorkerId(message
.workerId
) === -1
507 `Worker message received from unknown worker '${message.workerId}'`
513 * Gets the given worker its worker node key.
515 * @param worker - The worker.
516 * @returns The worker node key if found in the pool worker nodes, `-1` otherwise.
518 private getWorkerNodeKeyByWorker (worker
: Worker
): number {
519 return this.workerNodes
.findIndex(
520 workerNode
=> workerNode
.worker
=== worker
525 * Gets the worker node key given its worker id.
527 * @param workerId - The worker id.
528 * @returns The worker node key if the worker id is found in the pool worker nodes, `-1` otherwise.
530 private getWorkerNodeKeyByWorkerId (workerId
: number): number {
531 return this.workerNodes
.findIndex(
532 workerNode
=> workerNode
.info
.id
=== workerId
537 public setWorkerChoiceStrategy (
538 workerChoiceStrategy
: WorkerChoiceStrategy
,
539 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
541 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
542 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
543 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
544 this.opts
.workerChoiceStrategy
546 if (workerChoiceStrategyOptions
!= null) {
547 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
549 for (const [workerNodeKey
, workerNode
] of this.workerNodes
.entries()) {
550 workerNode
.resetUsage()
551 this.sendWorkerStatisticsMessageToWorker(workerNodeKey
)
556 public setWorkerChoiceStrategyOptions (
557 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
559 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
560 this.opts
.workerChoiceStrategyOptions
= workerChoiceStrategyOptions
561 this.workerChoiceStrategyContext
.setOptions(
562 this.opts
.workerChoiceStrategyOptions
567 public enableTasksQueue (
569 tasksQueueOptions
?: TasksQueueOptions
571 if (this.opts
.enableTasksQueue
=== true && !enable
) {
572 this.flushTasksQueues()
574 this.opts
.enableTasksQueue
= enable
575 this.setTasksQueueOptions(tasksQueueOptions
as TasksQueueOptions
)
579 public setTasksQueueOptions (tasksQueueOptions
: TasksQueueOptions
): void {
580 if (this.opts
.enableTasksQueue
=== true) {
581 this.checkValidTasksQueueOptions(tasksQueueOptions
)
582 this.opts
.tasksQueueOptions
=
583 this.buildTasksQueueOptions(tasksQueueOptions
)
584 } else if (this.opts
.tasksQueueOptions
!= null) {
585 delete this.opts
.tasksQueueOptions
589 private buildTasksQueueOptions (
590 tasksQueueOptions
: TasksQueueOptions
591 ): TasksQueueOptions
{
593 concurrency
: tasksQueueOptions
?.concurrency
?? 1
598 * Whether the pool is full or not.
600 * The pool filling boolean status.
602 protected get
full (): boolean {
603 return this.workerNodes
.length
>= this.maxSize
607 * Whether the pool is busy or not.
609 * The pool busyness boolean status.
611 protected abstract get
busy (): boolean
614 * Whether worker nodes are executing at least one task.
616 * @returns Worker nodes busyness boolean status.
618 protected internalBusy (): boolean {
620 this.workerNodes
.findIndex(workerNode
=> {
621 return workerNode
.usage
.tasks
.executing
=== 0
627 public async execute (data
?: Data
, name
?: string): Promise
<Response
> {
628 return await new Promise
<Response
>((resolve
, reject
) => {
629 const timestamp
= performance
.now()
630 const workerNodeKey
= this.chooseWorkerNode()
631 const task
: Task
<Data
> = {
632 name
: name
?? DEFAULT_TASK_NAME
,
633 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
634 data
: data
?? ({} as Data
),
636 workerId
: this.getWorkerInfo(workerNodeKey
).id
as number,
639 this.promiseResponseMap
.set(task
.id
as string, {
645 this.opts
.enableTasksQueue
=== true &&
647 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
>=
648 (this.opts
.tasksQueueOptions
?.concurrency
as number))
650 this.enqueueTask(workerNodeKey
, task
)
652 this.executeTask(workerNodeKey
, task
)
654 this.checkAndEmitEvents()
659 public async destroy (): Promise
<void> {
661 this.workerNodes
.map(async (_
, workerNodeKey
) => {
662 await this.destroyWorkerNode(workerNodeKey
)
668 * Terminates the worker node given its worker node key.
670 * @param workerNodeKey - The worker node key.
672 protected abstract destroyWorkerNode (workerNodeKey
: number): Promise
<void>
675 * Setup hook to execute code before worker nodes are created in the abstract constructor.
680 protected setupHook (): void {
681 // Intentionally empty
685 * Should return whether the worker is the main worker or not.
687 protected abstract isMain (): boolean
690 * Hook executed before the worker task execution.
693 * @param workerNodeKey - The worker node key.
694 * @param task - The task to execute.
696 protected beforeTaskExecutionHook (
697 workerNodeKey
: number,
700 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
701 ++workerUsage
.tasks
.executing
702 this.updateWaitTimeWorkerUsage(workerUsage
, task
)
703 const taskWorkerUsage
= this.workerNodes
[workerNodeKey
].getTaskWorkerUsage(
706 ++taskWorkerUsage
.tasks
.executing
707 this.updateWaitTimeWorkerUsage(taskWorkerUsage
, task
)
711 * Hook executed after the worker task execution.
714 * @param workerNodeKey - The worker node key.
715 * @param message - The received message.
717 protected afterTaskExecutionHook (
718 workerNodeKey
: number,
719 message
: MessageValue
<Response
>
721 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
722 this.updateTaskStatisticsWorkerUsage(workerUsage
, message
)
723 this.updateRunTimeWorkerUsage(workerUsage
, message
)
724 this.updateEluWorkerUsage(workerUsage
, message
)
725 const taskWorkerUsage
= this.workerNodes
[workerNodeKey
].getTaskWorkerUsage(
726 message
.taskPerformance
?.name
?? DEFAULT_TASK_NAME
728 this.updateTaskStatisticsWorkerUsage(taskWorkerUsage
, message
)
729 this.updateRunTimeWorkerUsage(taskWorkerUsage
, message
)
730 this.updateEluWorkerUsage(taskWorkerUsage
, message
)
733 private updateTaskStatisticsWorkerUsage (
734 workerUsage
: WorkerUsage
,
735 message
: MessageValue
<Response
>
737 const workerTaskStatistics
= workerUsage
.tasks
738 --workerTaskStatistics
.executing
739 if (message
.taskError
== null) {
740 ++workerTaskStatistics
.executed
742 ++workerTaskStatistics
.failed
746 private updateRunTimeWorkerUsage (
747 workerUsage
: WorkerUsage
,
748 message
: MessageValue
<Response
>
750 updateMeasurementStatistics(
752 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
,
753 message
.taskPerformance
?.runTime
?? 0,
754 workerUsage
.tasks
.executed
758 private updateWaitTimeWorkerUsage (
759 workerUsage
: WorkerUsage
,
762 const timestamp
= performance
.now()
763 const taskWaitTime
= timestamp
- (task
.timestamp
?? timestamp
)
764 updateMeasurementStatistics(
765 workerUsage
.waitTime
,
766 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().waitTime
,
768 workerUsage
.tasks
.executed
772 private updateEluWorkerUsage (
773 workerUsage
: WorkerUsage
,
774 message
: MessageValue
<Response
>
776 const eluTaskStatisticsRequirements
: MeasurementStatisticsRequirements
=
777 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
778 updateMeasurementStatistics(
779 workerUsage
.elu
.active
,
780 eluTaskStatisticsRequirements
,
781 message
.taskPerformance
?.elu
?.active
?? 0,
782 workerUsage
.tasks
.executed
784 updateMeasurementStatistics(
785 workerUsage
.elu
.idle
,
786 eluTaskStatisticsRequirements
,
787 message
.taskPerformance
?.elu
?.idle
?? 0,
788 workerUsage
.tasks
.executed
790 if (eluTaskStatisticsRequirements
.aggregate
) {
791 if (message
.taskPerformance
?.elu
!= null) {
792 if (workerUsage
.elu
.utilization
!= null) {
793 workerUsage
.elu
.utilization
=
794 (workerUsage
.elu
.utilization
+
795 message
.taskPerformance
.elu
.utilization
) /
798 workerUsage
.elu
.utilization
= message
.taskPerformance
.elu
.utilization
805 * Chooses a worker node for the next task.
807 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
809 * @returns The chosen worker node key
811 private chooseWorkerNode (): number {
812 if (this.shallCreateDynamicWorker()) {
813 const workerNodeKey
= this.createAndSetupDynamicWorkerNode()
815 this.workerChoiceStrategyContext
.getStrategyPolicy().useDynamicWorker
820 return this.workerChoiceStrategyContext
.execute()
824 * Conditions for dynamic worker creation.
826 * @returns Whether to create a dynamic worker or not.
828 private shallCreateDynamicWorker (): boolean {
829 return this.type === PoolTypes
.dynamic
&& !this.full
&& this.internalBusy()
833 * Sends a message to worker given its worker node key.
835 * @param workerNodeKey - The worker node key.
836 * @param message - The message.
838 protected abstract sendToWorker (
839 workerNodeKey
: number,
840 message
: MessageValue
<Data
>
844 * Creates a new worker.
846 * @returns Newly created worker.
848 protected abstract createWorker (): Worker
851 * Creates a new, completely set up worker node.
853 * @returns New, completely set up worker node key.
855 protected createAndSetupWorkerNode (): number {
856 const worker
= this.createWorker()
858 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
859 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
860 worker
.on('error', error
=> {
861 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
862 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
863 workerInfo
.ready
= false
864 this.workerNodes
[workerNodeKey
].closeChannel()
865 this.emitter
?.emit(PoolEvents
.error
, error
)
866 if (this.opts
.restartWorkerOnError
=== true && !this.starting
) {
867 if (workerInfo
.dynamic
) {
868 this.createAndSetupDynamicWorkerNode()
870 this.createAndSetupWorkerNode()
873 if (this.opts
.enableTasksQueue
=== true) {
874 this.redistributeQueuedTasks(workerNodeKey
)
877 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
878 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
879 worker
.once('exit', () => {
880 this.removeWorkerNode(worker
)
883 const workerNodeKey
= this.addWorkerNode(worker
)
885 this.afterWorkerNodeSetup(workerNodeKey
)
891 * Creates a new, completely set up dynamic worker node.
893 * @returns New, completely set up dynamic worker node key.
895 protected createAndSetupDynamicWorkerNode (): number {
896 const workerNodeKey
= this.createAndSetupWorkerNode()
897 this.registerWorkerMessageListener(workerNodeKey
, message
=> {
898 const localWorkerNodeKey
= this.getWorkerNodeKeyByWorkerId(
901 const workerUsage
= this.workerNodes
[localWorkerNodeKey
].usage
902 // Kill message received from worker
904 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
905 (message
.kill
!= null &&
906 ((this.opts
.enableTasksQueue
=== false &&
907 workerUsage
.tasks
.executing
=== 0) ||
908 (this.opts
.enableTasksQueue
=== true &&
909 workerUsage
.tasks
.executing
=== 0 &&
910 this.tasksQueueSize(localWorkerNodeKey
) === 0)))
912 this.destroyWorkerNode(localWorkerNodeKey
).catch(EMPTY_FUNCTION
)
915 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
916 this.sendToWorker(workerNodeKey
, {
918 workerId
: workerInfo
.id
as number
920 workerInfo
.dynamic
= true
921 if (this.workerChoiceStrategyContext
.getStrategyPolicy().useDynamicWorker
) {
922 workerInfo
.ready
= true
928 * Registers a listener callback on the worker given its worker node key.
930 * @param workerNodeKey - The worker node key.
931 * @param listener - The message listener callback.
933 protected abstract registerWorkerMessageListener
<
934 Message
extends Data
| Response
936 workerNodeKey
: number,
937 listener
: (message
: MessageValue
<Message
>) => void
941 * Method hooked up after a worker node has been newly created.
944 * @param workerNodeKey - The newly created worker node key.
946 protected afterWorkerNodeSetup (workerNodeKey
: number): void {
947 // Listen to worker messages.
948 this.registerWorkerMessageListener(workerNodeKey
, this.workerListener())
949 // Send the startup message to worker.
950 this.sendStartupMessageToWorker(workerNodeKey
)
951 // Send the worker statistics message to worker.
952 this.sendWorkerStatisticsMessageToWorker(workerNodeKey
)
956 * Sends the startup message to worker given its worker node key.
958 * @param workerNodeKey - The worker node key.
960 protected abstract sendStartupMessageToWorker (workerNodeKey
: number): void
963 * Sends the worker statistics message to worker given its worker node key.
965 * @param workerNodeKey - The worker node key.
967 private sendWorkerStatisticsMessageToWorker (workerNodeKey
: number): void {
968 this.sendToWorker(workerNodeKey
, {
971 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
973 elu
: this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
976 workerId
: this.getWorkerInfo(workerNodeKey
).id
as number
980 private redistributeQueuedTasks (workerNodeKey
: number): void {
981 while (this.tasksQueueSize(workerNodeKey
) > 0) {
982 let targetWorkerNodeKey
: number = workerNodeKey
983 let minQueuedTasks
= Infinity
984 let executeTask
= false
985 for (const [workerNodeId
, workerNode
] of this.workerNodes
.entries()) {
986 const workerInfo
= this.getWorkerInfo(workerNodeId
)
988 workerNodeId
!== workerNodeKey
&&
990 workerNode
.usage
.tasks
.queued
=== 0
993 this.workerNodes
[workerNodeId
].usage
.tasks
.executing
<
994 (this.opts
.tasksQueueOptions
?.concurrency
as number)
998 targetWorkerNodeKey
= workerNodeId
1002 workerNodeId
!== workerNodeKey
&&
1004 workerNode
.usage
.tasks
.queued
< minQueuedTasks
1006 minQueuedTasks
= workerNode
.usage
.tasks
.queued
1007 targetWorkerNodeKey
= workerNodeId
1012 targetWorkerNodeKey
,
1013 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1017 targetWorkerNodeKey
,
1018 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1025 * This method is the listener registered for each worker message.
1027 * @returns The listener function to execute when a message is received from a worker.
1029 protected workerListener (): (message
: MessageValue
<Response
>) => void {
1031 this.checkMessageWorkerId(message
)
1032 if (message
.ready
!= null) {
1033 // Worker ready response received from worker
1034 this.handleWorkerReadyResponse(message
)
1035 } else if (message
.id
!= null) {
1036 // Task execution response received from worker
1037 this.handleTaskExecutionResponse(message
)
1042 private handleWorkerReadyResponse (message
: MessageValue
<Response
>): void {
1044 this.getWorkerNodeKeyByWorkerId(message
.workerId
)
1045 ).ready
= message
.ready
as boolean
1046 if (this.emitter
!= null && this.ready
) {
1047 this.emitter
.emit(PoolEvents
.ready
, this.info
)
1051 private handleTaskExecutionResponse (message
: MessageValue
<Response
>): void {
1052 const promiseResponse
= this.promiseResponseMap
.get(message
.id
as string)
1053 if (promiseResponse
!= null) {
1054 if (message
.taskError
!= null) {
1055 this.emitter
?.emit(PoolEvents
.taskError
, message
.taskError
)
1056 promiseResponse
.reject(message
.taskError
.message
)
1058 promiseResponse
.resolve(message
.data
as Response
)
1060 const workerNodeKey
= promiseResponse
.workerNodeKey
1061 this.afterTaskExecutionHook(workerNodeKey
, message
)
1062 this.promiseResponseMap
.delete(message
.id
as string)
1064 this.opts
.enableTasksQueue
=== true &&
1065 this.tasksQueueSize(workerNodeKey
) > 0 &&
1066 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
<
1067 (this.opts
.tasksQueueOptions
?.concurrency
as number)
1071 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1074 this.workerChoiceStrategyContext
.update(workerNodeKey
)
1078 private checkAndEmitEvents (): void {
1079 if (this.emitter
!= null) {
1081 this.emitter
.emit(PoolEvents
.busy
, this.info
)
1083 if (this.type === PoolTypes
.dynamic
&& this.full
) {
1084 this.emitter
.emit(PoolEvents
.full
, this.info
)
1090 * Gets the worker information given its worker node key.
1092 * @param workerNodeKey - The worker node key.
1093 * @returns The worker information.
1095 protected getWorkerInfo (workerNodeKey
: number): WorkerInfo
{
1096 return this.workerNodes
[workerNodeKey
].info
1100 * Adds the given worker in the pool worker nodes.
1102 * @param worker - The worker.
1103 * @returns The added worker node key.
1104 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the added worker node is not found.
1106 private addWorkerNode (worker
: Worker
): number {
1107 const workerNode
= new WorkerNode
<Worker
, Data
>(worker
, this.worker
)
1108 // Flag the worker node as ready at pool startup.
1109 if (this.starting
) {
1110 workerNode
.info
.ready
= true
1112 this.workerNodes
.push(workerNode
)
1113 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
1114 if (workerNodeKey
=== -1) {
1115 throw new Error('Worker node not found')
1117 return workerNodeKey
1121 * Removes the given worker from the pool worker nodes.
1123 * @param worker - The worker.
1125 private removeWorkerNode (worker
: Worker
): void {
1126 const workerNodeKey
= this.getWorkerNodeKeyByWorker(worker
)
1127 if (workerNodeKey
!== -1) {
1128 this.workerNodes
.splice(workerNodeKey
, 1)
1129 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
1134 * Executes the given task on the worker given its worker node key.
1136 * @param workerNodeKey - The worker node key.
1137 * @param task - The task to execute.
1139 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
1140 this.beforeTaskExecutionHook(workerNodeKey
, task
)
1141 this.sendToWorker(workerNodeKey
, task
)
1144 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
1145 return this.workerNodes
[workerNodeKey
].enqueueTask(task
)
1148 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
1149 return this.workerNodes
[workerNodeKey
].dequeueTask()
1152 private tasksQueueSize (workerNodeKey
: number): number {
1153 return this.workerNodes
[workerNodeKey
].tasksQueueSize()
1156 protected flushTasksQueue (workerNodeKey
: number): void {
1157 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1160 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1163 this.workerNodes
[workerNodeKey
].clearTasksQueue()
1166 private flushTasksQueues (): void {
1167 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
1168 this.flushTasksQueue(workerNodeKey
)