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
) {
177 throw new RangeError(
178 'Cannot instantiate a dynamic pool with a maximum pool size inferior to the minimum pool size'
180 } else if (max
=== 0) {
181 throw new RangeError(
182 'Cannot instantiate a dynamic pool with a pool size equal to zero'
184 } else if (min
=== max
) {
185 throw new RangeError(
186 'Cannot instantiate a dynamic pool with a minimum pool size equal to the maximum pool size. Use a fixed pool instead'
192 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
193 if (isPlainObject(opts
)) {
194 this.opts
.workerChoiceStrategy
=
195 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
196 this.checkValidWorkerChoiceStrategy(this.opts
.workerChoiceStrategy
)
197 this.opts
.workerChoiceStrategyOptions
=
198 opts
.workerChoiceStrategyOptions
??
199 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
200 this.checkValidWorkerChoiceStrategyOptions(
201 this.opts
.workerChoiceStrategyOptions
203 this.opts
.restartWorkerOnError
= opts
.restartWorkerOnError
?? true
204 this.opts
.enableEvents
= opts
.enableEvents
?? true
205 this.opts
.enableTasksQueue
= opts
.enableTasksQueue
?? false
206 if (this.opts
.enableTasksQueue
) {
207 this.checkValidTasksQueueOptions(
208 opts
.tasksQueueOptions
as TasksQueueOptions
210 this.opts
.tasksQueueOptions
= this.buildTasksQueueOptions(
211 opts
.tasksQueueOptions
as TasksQueueOptions
215 throw new TypeError('Invalid pool options: must be a plain object')
219 private checkValidWorkerChoiceStrategy (
220 workerChoiceStrategy
: WorkerChoiceStrategy
222 if (!Object.values(WorkerChoiceStrategies
).includes(workerChoiceStrategy
)) {
224 `Invalid worker choice strategy '${workerChoiceStrategy}'`
229 private checkValidWorkerChoiceStrategyOptions (
230 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
232 if (!isPlainObject(workerChoiceStrategyOptions
)) {
234 'Invalid worker choice strategy options: must be a plain object'
238 workerChoiceStrategyOptions
.weights
!= null &&
239 Object.keys(workerChoiceStrategyOptions
.weights
).length
!== this.maxSize
242 'Invalid worker choice strategy options: must have a weight for each worker node'
246 workerChoiceStrategyOptions
.measurement
!= null &&
247 !Object.values(Measurements
).includes(
248 workerChoiceStrategyOptions
.measurement
252 `Invalid worker choice strategy options: invalid measurement '${workerChoiceStrategyOptions.measurement}'`
257 private checkValidTasksQueueOptions (
258 tasksQueueOptions
: TasksQueueOptions
260 if (tasksQueueOptions
!= null && !isPlainObject(tasksQueueOptions
)) {
261 throw new TypeError('Invalid tasks queue options: must be a plain object')
264 tasksQueueOptions
?.concurrency
!= null &&
265 !Number.isSafeInteger(tasksQueueOptions
.concurrency
)
268 'Invalid worker tasks concurrency: must be an integer'
272 tasksQueueOptions
?.concurrency
!= null &&
273 tasksQueueOptions
.concurrency
<= 0
276 `Invalid worker tasks concurrency '${tasksQueueOptions.concurrency}'`
281 private startPool (): void {
283 this.workerNodes
.reduce(
284 (accumulator
, workerNode
) =>
285 !workerNode
.info
.dynamic
? accumulator
+ 1 : accumulator
,
287 ) < this.numberOfWorkers
289 this.createAndSetupWorkerNode()
294 public get
info (): PoolInfo
{
300 strategy
: this.opts
.workerChoiceStrategy
as WorkerChoiceStrategy
,
301 minSize
: this.minSize
,
302 maxSize
: this.maxSize
,
303 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
304 .runTime
.aggregate
&&
305 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
306 .waitTime
.aggregate
&& { utilization
: round(this.utilization
) }),
307 workerNodes
: this.workerNodes
.length
,
308 idleWorkerNodes
: this.workerNodes
.reduce(
309 (accumulator
, workerNode
) =>
310 workerNode
.usage
.tasks
.executing
=== 0
315 busyWorkerNodes
: this.workerNodes
.reduce(
316 (accumulator
, workerNode
) =>
317 workerNode
.usage
.tasks
.executing
> 0 ? accumulator
+ 1 : accumulator
,
320 executedTasks
: this.workerNodes
.reduce(
321 (accumulator
, workerNode
) =>
322 accumulator
+ workerNode
.usage
.tasks
.executed
,
325 executingTasks
: this.workerNodes
.reduce(
326 (accumulator
, workerNode
) =>
327 accumulator
+ workerNode
.usage
.tasks
.executing
,
330 queuedTasks
: this.workerNodes
.reduce(
331 (accumulator
, workerNode
) =>
332 accumulator
+ workerNode
.usage
.tasks
.queued
,
335 maxQueuedTasks
: this.workerNodes
.reduce(
336 (accumulator
, workerNode
) =>
337 accumulator
+ (workerNode
.usage
.tasks
?.maxQueued
?? 0),
340 failedTasks
: this.workerNodes
.reduce(
341 (accumulator
, workerNode
) =>
342 accumulator
+ workerNode
.usage
.tasks
.failed
,
345 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
346 .runTime
.aggregate
&& {
350 ...this.workerNodes
.map(
351 workerNode
=> workerNode
.usage
.runTime
?.minimum
?? Infinity
357 ...this.workerNodes
.map(
358 workerNode
=> workerNode
.usage
.runTime
?.maximum
?? -Infinity
363 this.workerNodes
.reduce(
364 (accumulator
, workerNode
) =>
365 accumulator
+ (workerNode
.usage
.runTime
?.aggregate
?? 0),
368 this.workerNodes
.reduce(
369 (accumulator
, workerNode
) =>
370 accumulator
+ (workerNode
.usage
.tasks
?.executed
?? 0),
374 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
378 this.workerNodes
.map(
379 workerNode
=> workerNode
.usage
.runTime
?.median
?? 0
386 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
387 .waitTime
.aggregate
&& {
391 ...this.workerNodes
.map(
392 workerNode
=> workerNode
.usage
.waitTime
?.minimum
?? Infinity
398 ...this.workerNodes
.map(
399 workerNode
=> workerNode
.usage
.waitTime
?.maximum
?? -Infinity
404 this.workerNodes
.reduce(
405 (accumulator
, workerNode
) =>
406 accumulator
+ (workerNode
.usage
.waitTime
?.aggregate
?? 0),
409 this.workerNodes
.reduce(
410 (accumulator
, workerNode
) =>
411 accumulator
+ (workerNode
.usage
.tasks
?.executed
?? 0),
415 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
416 .waitTime
.median
&& {
419 this.workerNodes
.map(
420 workerNode
=> workerNode
.usage
.waitTime
?.median
?? 0
431 * The pool readiness boolean status.
433 private get
ready (): boolean {
435 this.workerNodes
.reduce(
436 (accumulator
, workerNode
) =>
437 !workerNode
.info
.dynamic
&& workerNode
.info
.ready
446 * The approximate pool utilization.
448 * @returns The pool utilization.
450 private get
utilization (): number {
451 const poolTimeCapacity
=
452 (performance
.now() - this.startTimestamp
) * this.maxSize
453 const totalTasksRunTime
= this.workerNodes
.reduce(
454 (accumulator
, workerNode
) =>
455 accumulator
+ (workerNode
.usage
.runTime
?.aggregate
?? 0),
458 const totalTasksWaitTime
= this.workerNodes
.reduce(
459 (accumulator
, workerNode
) =>
460 accumulator
+ (workerNode
.usage
.waitTime
?.aggregate
?? 0),
463 return (totalTasksRunTime
+ totalTasksWaitTime
) / poolTimeCapacity
469 * If it is `'dynamic'`, it provides the `max` property.
471 protected abstract get
type (): PoolType
476 protected abstract get
worker (): WorkerType
479 * The pool minimum size.
481 protected abstract get
minSize (): number
484 * The pool maximum size.
486 protected abstract get
maxSize (): number
489 * Checks if the worker id sent in the received message from a worker is valid.
491 * @param message - The received message.
492 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the worker id is invalid.
494 private checkMessageWorkerId (message
: MessageValue
<Response
>): void {
496 message
.workerId
!= null &&
497 this.getWorkerNodeKeyByWorkerId(message
.workerId
) == null
500 `Worker message received from unknown worker '${message.workerId}'`
506 * Gets the given worker its worker node key.
508 * @param worker - The worker.
509 * @returns The worker node key if found in the pool worker nodes, `-1` otherwise.
511 private getWorkerNodeKey (worker
: Worker
): number {
512 return this.workerNodes
.findIndex(
513 workerNode
=> workerNode
.worker
=== worker
518 * Gets the worker node key given its worker id.
520 * @param workerId - The worker id.
521 * @returns The worker node key if the worker id is found in the pool worker nodes, `undefined` otherwise.
523 private getWorkerNodeKeyByWorkerId (workerId
: number): number | undefined {
524 for (const [workerNodeKey
, workerNode
] of this.workerNodes
.entries()) {
525 if (workerNode
.info
.id
=== workerId
) {
532 public setWorkerChoiceStrategy (
533 workerChoiceStrategy
: WorkerChoiceStrategy
,
534 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
536 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
537 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
538 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
539 this.opts
.workerChoiceStrategy
541 if (workerChoiceStrategyOptions
!= null) {
542 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
544 for (const [workerNodeKey
, workerNode
] of this.workerNodes
.entries()) {
545 workerNode
.resetUsage()
546 this.sendWorkerStatisticsMessageToWorker(workerNodeKey
)
551 public setWorkerChoiceStrategyOptions (
552 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
554 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
555 this.opts
.workerChoiceStrategyOptions
= workerChoiceStrategyOptions
556 this.workerChoiceStrategyContext
.setOptions(
557 this.opts
.workerChoiceStrategyOptions
562 public enableTasksQueue (
564 tasksQueueOptions
?: TasksQueueOptions
566 if (this.opts
.enableTasksQueue
=== true && !enable
) {
567 this.flushTasksQueues()
569 this.opts
.enableTasksQueue
= enable
570 this.setTasksQueueOptions(tasksQueueOptions
as TasksQueueOptions
)
574 public setTasksQueueOptions (tasksQueueOptions
: TasksQueueOptions
): void {
575 if (this.opts
.enableTasksQueue
=== true) {
576 this.checkValidTasksQueueOptions(tasksQueueOptions
)
577 this.opts
.tasksQueueOptions
=
578 this.buildTasksQueueOptions(tasksQueueOptions
)
579 } else if (this.opts
.tasksQueueOptions
!= null) {
580 delete this.opts
.tasksQueueOptions
584 private buildTasksQueueOptions (
585 tasksQueueOptions
: TasksQueueOptions
586 ): TasksQueueOptions
{
588 concurrency
: tasksQueueOptions
?.concurrency
?? 1
593 * Whether the pool is full or not.
595 * The pool filling boolean status.
597 protected get
full (): boolean {
598 return this.workerNodes
.length
>= this.maxSize
602 * Whether the pool is busy or not.
604 * The pool busyness boolean status.
606 protected abstract get
busy (): boolean
609 * Whether worker nodes are executing at least one task.
611 * @returns Worker nodes busyness boolean status.
613 protected internalBusy (): boolean {
615 this.workerNodes
.findIndex(workerNode
=> {
616 return workerNode
.usage
.tasks
.executing
=== 0
622 public async execute (data
?: Data
, name
?: string): Promise
<Response
> {
623 return await new Promise
<Response
>((resolve
, reject
) => {
624 const timestamp
= performance
.now()
625 const workerNodeKey
= this.chooseWorkerNode()
626 const task
: Task
<Data
> = {
627 name
: name
?? DEFAULT_TASK_NAME
,
628 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
629 data
: data
?? ({} as Data
),
631 workerId
: this.getWorkerInfo(workerNodeKey
).id
as number,
634 this.promiseResponseMap
.set(task
.id
as string, {
640 this.opts
.enableTasksQueue
=== true &&
642 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
>=
643 ((this.opts
.tasksQueueOptions
as TasksQueueOptions
)
644 .concurrency
as number))
646 this.enqueueTask(workerNodeKey
, task
)
648 this.executeTask(workerNodeKey
, task
)
650 this.checkAndEmitEvents()
655 public async destroy (): Promise
<void> {
657 this.workerNodes
.map(async (workerNode
, workerNodeKey
) => {
658 this.flushTasksQueue(workerNodeKey
)
659 // FIXME: wait for tasks to be finished
660 const workerExitPromise
= new Promise
<void>(resolve
=> {
661 workerNode
.worker
.on('exit', () => {
665 await this.destroyWorkerNode(workerNodeKey
)
666 await workerExitPromise
672 * Terminates the worker node given its worker node key.
674 * @param workerNodeKey - The worker node key.
676 protected abstract destroyWorkerNode (
677 workerNodeKey
: number
678 ): void | Promise
<void>
681 * Setup hook to execute code before worker nodes are created in the abstract constructor.
686 protected setupHook (): void {
687 // Intentionally empty
691 * Should return whether the worker is the main worker or not.
693 protected abstract isMain (): boolean
696 * Hook executed before the worker task execution.
699 * @param workerNodeKey - The worker node key.
700 * @param task - The task to execute.
702 protected beforeTaskExecutionHook (
703 workerNodeKey
: number,
706 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
707 ++workerUsage
.tasks
.executing
708 this.updateWaitTimeWorkerUsage(workerUsage
, task
)
709 const taskWorkerUsage
= this.workerNodes
[workerNodeKey
].getTaskWorkerUsage(
712 ++taskWorkerUsage
.tasks
.executing
713 this.updateWaitTimeWorkerUsage(taskWorkerUsage
, task
)
717 * Hook executed after the worker task execution.
720 * @param workerNodeKey - The worker node key.
721 * @param message - The received message.
723 protected afterTaskExecutionHook (
724 workerNodeKey
: number,
725 message
: MessageValue
<Response
>
727 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
728 this.updateTaskStatisticsWorkerUsage(workerUsage
, message
)
729 this.updateRunTimeWorkerUsage(workerUsage
, message
)
730 this.updateEluWorkerUsage(workerUsage
, message
)
731 const taskWorkerUsage
= this.workerNodes
[workerNodeKey
].getTaskWorkerUsage(
732 message
.taskPerformance
?.name
?? DEFAULT_TASK_NAME
734 this.updateTaskStatisticsWorkerUsage(taskWorkerUsage
, message
)
735 this.updateRunTimeWorkerUsage(taskWorkerUsage
, message
)
736 this.updateEluWorkerUsage(taskWorkerUsage
, message
)
739 private updateTaskStatisticsWorkerUsage (
740 workerUsage
: WorkerUsage
,
741 message
: MessageValue
<Response
>
743 const workerTaskStatistics
= workerUsage
.tasks
744 --workerTaskStatistics
.executing
745 if (message
.taskError
== null) {
746 ++workerTaskStatistics
.executed
748 ++workerTaskStatistics
.failed
752 private updateRunTimeWorkerUsage (
753 workerUsage
: WorkerUsage
,
754 message
: MessageValue
<Response
>
756 updateMeasurementStatistics(
758 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
,
759 message
.taskPerformance
?.runTime
?? 0,
760 workerUsage
.tasks
.executed
764 private updateWaitTimeWorkerUsage (
765 workerUsage
: WorkerUsage
,
768 const timestamp
= performance
.now()
769 const taskWaitTime
= timestamp
- (task
.timestamp
?? timestamp
)
770 updateMeasurementStatistics(
771 workerUsage
.waitTime
,
772 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().waitTime
,
774 workerUsage
.tasks
.executed
778 private updateEluWorkerUsage (
779 workerUsage
: WorkerUsage
,
780 message
: MessageValue
<Response
>
782 const eluTaskStatisticsRequirements
: MeasurementStatisticsRequirements
=
783 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
784 updateMeasurementStatistics(
785 workerUsage
.elu
.active
,
786 eluTaskStatisticsRequirements
,
787 message
.taskPerformance
?.elu
?.active
?? 0,
788 workerUsage
.tasks
.executed
790 updateMeasurementStatistics(
791 workerUsage
.elu
.idle
,
792 eluTaskStatisticsRequirements
,
793 message
.taskPerformance
?.elu
?.idle
?? 0,
794 workerUsage
.tasks
.executed
796 if (eluTaskStatisticsRequirements
.aggregate
) {
797 if (message
.taskPerformance
?.elu
!= null) {
798 if (workerUsage
.elu
.utilization
!= null) {
799 workerUsage
.elu
.utilization
=
800 (workerUsage
.elu
.utilization
+
801 message
.taskPerformance
.elu
.utilization
) /
804 workerUsage
.elu
.utilization
= message
.taskPerformance
.elu
.utilization
811 * Chooses a worker node for the next task.
813 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
815 * @returns The chosen worker node key
817 private chooseWorkerNode (): number {
818 if (this.shallCreateDynamicWorker()) {
819 const workerNodeKey
= this.createAndSetupDynamicWorkerNode()
821 this.workerChoiceStrategyContext
.getStrategyPolicy().useDynamicWorker
826 return this.workerChoiceStrategyContext
.execute()
830 * Conditions for dynamic worker creation.
832 * @returns Whether to create a dynamic worker or not.
834 private shallCreateDynamicWorker (): boolean {
835 return this.type === PoolTypes
.dynamic
&& !this.full
&& this.internalBusy()
839 * Sends a message to worker given its worker node key.
841 * @param workerNodeKey - The worker node key.
842 * @param message - The message.
844 protected abstract sendToWorker (
845 workerNodeKey
: number,
846 message
: MessageValue
<Data
>
850 * Creates a new worker.
852 * @returns Newly created worker.
854 protected abstract createWorker (): Worker
857 * Creates a new, completely set up worker node.
859 * @returns New, completely set up worker node key.
861 protected createAndSetupWorkerNode (): number {
862 const worker
= this.createWorker()
864 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
865 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
866 worker
.on('error', error
=> {
867 const workerNodeKey
= this.getWorkerNodeKey(worker
)
868 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
869 workerInfo
.ready
= false
870 this.workerNodes
[workerNodeKey
].closeChannel()
871 this.emitter
?.emit(PoolEvents
.error
, error
)
872 if (this.opts
.restartWorkerOnError
=== true && !this.starting
) {
873 if (workerInfo
.dynamic
) {
874 this.createAndSetupDynamicWorkerNode()
876 this.createAndSetupWorkerNode()
879 if (this.opts
.enableTasksQueue
=== true) {
880 this.redistributeQueuedTasks(workerNodeKey
)
883 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
884 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
885 worker
.once('exit', () => {
886 this.removeWorkerNode(worker
)
889 const workerNodeKey
= this.addWorkerNode(worker
)
891 this.afterWorkerNodeSetup(workerNodeKey
)
897 * Creates a new, completely set up dynamic worker node.
899 * @returns New, completely set up dynamic worker node key.
901 protected createAndSetupDynamicWorkerNode (): number {
902 const workerNodeKey
= this.createAndSetupWorkerNode()
903 this.registerWorkerMessageListener(workerNodeKey
, message
=> {
904 const localWorkerNodeKey
= this.getWorkerNodeKeyByWorkerId(
907 const workerUsage
= this.workerNodes
[localWorkerNodeKey
].usage
909 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
910 (message
.kill
!= null &&
911 ((this.opts
.enableTasksQueue
=== false &&
912 workerUsage
.tasks
.executing
=== 0) ||
913 (this.opts
.enableTasksQueue
=== true &&
914 workerUsage
.tasks
.executing
=== 0 &&
915 this.tasksQueueSize(localWorkerNodeKey
) === 0)))
917 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
918 const destroyWorkerNodeBounded
= this.destroyWorkerNode
.bind(this)
919 if (isAsyncFunction(destroyWorkerNodeBounded
)) {
921 destroyWorkerNodeBounded
as (workerNodeKey
: number) => Promise
<void>
922 )(localWorkerNodeKey
).catch(EMPTY_FUNCTION
)
924 (destroyWorkerNodeBounded
as (workerNodeKey
: number) => void)(
930 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
931 workerInfo
.dynamic
= true
932 if (this.workerChoiceStrategyContext
.getStrategyPolicy().useDynamicWorker
) {
933 workerInfo
.ready
= true
935 this.sendToWorker(workerNodeKey
, {
937 workerId
: workerInfo
.id
as number
943 * Registers a listener callback on the worker given its worker node key.
945 * @param workerNodeKey - The worker node key.
946 * @param listener - The message listener callback.
948 protected abstract registerWorkerMessageListener
<
949 Message
extends Data
| Response
951 workerNodeKey
: number,
952 listener
: (message
: MessageValue
<Message
>) => void
956 * Method hooked up after a worker node has been newly created.
959 * @param workerNodeKey - The newly created worker node key.
961 protected afterWorkerNodeSetup (workerNodeKey
: number): void {
962 // Listen to worker messages.
963 this.registerWorkerMessageListener(workerNodeKey
, this.workerListener())
964 // Send the startup message to worker.
965 this.sendStartupMessageToWorker(workerNodeKey
)
966 // Send the worker statistics message to worker.
967 this.sendWorkerStatisticsMessageToWorker(workerNodeKey
)
971 * Sends the startup message to worker given its worker node key.
973 * @param workerNodeKey - The worker node key.
975 protected abstract sendStartupMessageToWorker (workerNodeKey
: number): void
978 * Sends the worker statistics message to worker given its worker node key.
980 * @param workerNodeKey - The worker node key.
982 private sendWorkerStatisticsMessageToWorker (workerNodeKey
: number): void {
983 this.sendToWorker(workerNodeKey
, {
986 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
988 elu
: this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
991 workerId
: this.getWorkerInfo(workerNodeKey
).id
as number
995 private redistributeQueuedTasks (workerNodeKey
: number): void {
996 while (this.tasksQueueSize(workerNodeKey
) > 0) {
997 let targetWorkerNodeKey
: number = workerNodeKey
998 let minQueuedTasks
= Infinity
999 let executeTask
= false
1000 for (const [workerNodeId
, workerNode
] of this.workerNodes
.entries()) {
1001 const workerInfo
= this.getWorkerInfo(workerNodeId
)
1003 workerNodeId
!== workerNodeKey
&&
1005 workerNode
.usage
.tasks
.queued
=== 0
1007 if (workerNode
.usage
.tasks
.executing
=== 0) {
1010 targetWorkerNodeKey
= workerNodeId
1014 workerNodeId
!== workerNodeKey
&&
1016 workerNode
.usage
.tasks
.queued
< minQueuedTasks
1018 minQueuedTasks
= workerNode
.usage
.tasks
.queued
1019 targetWorkerNodeKey
= workerNodeId
1024 targetWorkerNodeKey
,
1025 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1029 targetWorkerNodeKey
,
1030 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1037 * This method is the listener registered for each worker message.
1039 * @returns The listener function to execute when a message is received from a worker.
1041 protected workerListener (): (message
: MessageValue
<Response
>) => void {
1043 this.checkMessageWorkerId(message
)
1044 if (message
.ready
!= null) {
1045 // Worker ready response received
1046 this.handleWorkerReadyResponse(message
)
1047 } else if (message
.id
!= null) {
1048 // Task execution response received
1049 this.handleTaskExecutionResponse(message
)
1054 private handleWorkerReadyResponse (message
: MessageValue
<Response
>): void {
1056 this.getWorkerNodeKeyByWorkerId(message
.workerId
) as number
1057 ).ready
= message
.ready
as boolean
1058 if (this.emitter
!= null && this.ready
) {
1059 this.emitter
.emit(PoolEvents
.ready
, this.info
)
1063 private handleTaskExecutionResponse (message
: MessageValue
<Response
>): void {
1064 const promiseResponse
= this.promiseResponseMap
.get(message
.id
as string)
1065 if (promiseResponse
!= null) {
1066 if (message
.taskError
!= null) {
1067 this.emitter
?.emit(PoolEvents
.taskError
, message
.taskError
)
1068 promiseResponse
.reject(message
.taskError
.message
)
1070 promiseResponse
.resolve(message
.data
as Response
)
1072 const workerNodeKey
= promiseResponse
.workerNodeKey
1073 this.afterTaskExecutionHook(workerNodeKey
, message
)
1074 this.promiseResponseMap
.delete(message
.id
as string)
1076 this.opts
.enableTasksQueue
=== true &&
1077 this.tasksQueueSize(workerNodeKey
) > 0
1081 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1084 this.workerChoiceStrategyContext
.update(workerNodeKey
)
1088 private checkAndEmitEvents (): void {
1089 if (this.emitter
!= null) {
1091 this.emitter
.emit(PoolEvents
.busy
, this.info
)
1093 if (this.type === PoolTypes
.dynamic
&& this.full
) {
1094 this.emitter
.emit(PoolEvents
.full
, this.info
)
1100 * Gets the worker information given its worker node key.
1102 * @param workerNodeKey - The worker node key.
1103 * @returns The worker information.
1105 protected getWorkerInfo (workerNodeKey
: number): WorkerInfo
{
1106 return this.workerNodes
[workerNodeKey
].info
1110 * Adds the given worker in the pool worker nodes.
1112 * @param worker - The worker.
1113 * @returns The added worker node key.
1114 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the added worker node is not found.
1116 private addWorkerNode (worker
: Worker
): number {
1117 const workerNode
= new WorkerNode
<Worker
, Data
>(worker
, this.worker
)
1118 // Flag the worker node as ready at pool startup.
1119 if (this.starting
) {
1120 workerNode
.info
.ready
= true
1122 this.workerNodes
.push(workerNode
)
1123 const workerNodeKey
= this.getWorkerNodeKey(worker
)
1124 if (workerNodeKey
=== -1) {
1125 throw new Error('Worker node not found')
1127 return workerNodeKey
1131 * Removes the given worker from the pool worker nodes.
1133 * @param worker - The worker.
1135 private removeWorkerNode (worker
: Worker
): void {
1136 const workerNodeKey
= this.getWorkerNodeKey(worker
)
1137 if (workerNodeKey
!== -1) {
1138 this.workerNodes
.splice(workerNodeKey
, 1)
1139 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
1144 * Executes the given task on the worker given its worker node key.
1146 * @param workerNodeKey - The worker node key.
1147 * @param task - The task to execute.
1149 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
1150 this.beforeTaskExecutionHook(workerNodeKey
, task
)
1151 this.sendToWorker(workerNodeKey
, task
)
1154 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
1155 return this.workerNodes
[workerNodeKey
].enqueueTask(task
)
1158 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
1159 return this.workerNodes
[workerNodeKey
].dequeueTask()
1162 private tasksQueueSize (workerNodeKey
: number): number {
1163 return this.workerNodes
[workerNodeKey
].tasksQueueSize()
1166 private flushTasksQueue (workerNodeKey
: number): void {
1167 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1170 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1173 this.workerNodes
[workerNodeKey
].clearTasksQueue()
1176 private flushTasksQueues (): void {
1177 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
1178 this.flushTasksQueue(workerNodeKey
)