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.checkAndEmitEvents
= this.checkAndEmitEvents
.bind(this)
119 if (this.opts
.enableEvents
=== true) {
120 this.emitter
= new PoolEmitter()
122 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext
<
128 this.opts
.workerChoiceStrategy
,
129 this.opts
.workerChoiceStrategyOptions
136 this.starting
= false
138 this.startTimestamp
= performance
.now()
141 private checkFilePath (filePath
: string): void {
144 typeof filePath
!== 'string' ||
145 (typeof filePath
=== 'string' && filePath
.trim().length
=== 0)
147 throw new Error('Please specify a file with a worker implementation')
149 if (!existsSync(filePath
)) {
150 throw new Error(`Cannot find the worker file '${filePath}'`)
154 private checkNumberOfWorkers (numberOfWorkers
: number): void {
155 if (numberOfWorkers
== null) {
157 'Cannot instantiate a pool without specifying the number of workers'
159 } else if (!Number.isSafeInteger(numberOfWorkers
)) {
161 'Cannot instantiate a pool with a non safe integer number of workers'
163 } else if (numberOfWorkers
< 0) {
164 throw new RangeError(
165 'Cannot instantiate a pool with a negative number of workers'
167 } else if (this.type === PoolTypes
.fixed
&& numberOfWorkers
=== 0) {
168 throw new RangeError('Cannot instantiate a fixed pool with zero worker')
172 protected checkDynamicPoolSize (min
: number, max
: number): void {
173 if (this.type === PoolTypes
.dynamic
) {
175 throw new RangeError(
176 'Cannot instantiate a dynamic pool with a maximum pool size inferior to the minimum pool size'
178 } else if (max
=== 0) {
179 throw new RangeError(
180 'Cannot instantiate a dynamic pool with a pool size equal to zero'
182 } else if (min
=== max
) {
183 throw new RangeError(
184 'Cannot instantiate a dynamic pool with a minimum pool size equal to the maximum pool size. Use a fixed pool instead'
190 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
191 if (isPlainObject(opts
)) {
192 this.opts
.workerChoiceStrategy
=
193 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
194 this.checkValidWorkerChoiceStrategy(this.opts
.workerChoiceStrategy
)
195 this.opts
.workerChoiceStrategyOptions
=
196 opts
.workerChoiceStrategyOptions
??
197 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
198 this.checkValidWorkerChoiceStrategyOptions(
199 this.opts
.workerChoiceStrategyOptions
201 this.opts
.restartWorkerOnError
= opts
.restartWorkerOnError
?? true
202 this.opts
.enableEvents
= opts
.enableEvents
?? true
203 this.opts
.enableTasksQueue
= opts
.enableTasksQueue
?? false
204 if (this.opts
.enableTasksQueue
) {
205 this.checkValidTasksQueueOptions(
206 opts
.tasksQueueOptions
as TasksQueueOptions
208 this.opts
.tasksQueueOptions
= this.buildTasksQueueOptions(
209 opts
.tasksQueueOptions
as TasksQueueOptions
213 throw new TypeError('Invalid pool options: must be a plain object')
217 private checkValidWorkerChoiceStrategy (
218 workerChoiceStrategy
: WorkerChoiceStrategy
220 if (!Object.values(WorkerChoiceStrategies
).includes(workerChoiceStrategy
)) {
222 `Invalid worker choice strategy '${workerChoiceStrategy}'`
227 private checkValidWorkerChoiceStrategyOptions (
228 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
230 if (!isPlainObject(workerChoiceStrategyOptions
)) {
232 'Invalid worker choice strategy options: must be a plain object'
236 workerChoiceStrategyOptions
.weights
!= null &&
237 Object.keys(workerChoiceStrategyOptions
.weights
).length
!== this.maxSize
240 'Invalid worker choice strategy options: must have a weight for each worker node'
244 workerChoiceStrategyOptions
.measurement
!= null &&
245 !Object.values(Measurements
).includes(
246 workerChoiceStrategyOptions
.measurement
250 `Invalid worker choice strategy options: invalid measurement '${workerChoiceStrategyOptions.measurement}'`
255 private checkValidTasksQueueOptions (
256 tasksQueueOptions
: TasksQueueOptions
258 if (tasksQueueOptions
!= null && !isPlainObject(tasksQueueOptions
)) {
259 throw new TypeError('Invalid tasks queue options: must be a plain object')
262 tasksQueueOptions
?.concurrency
!= null &&
263 !Number.isSafeInteger(tasksQueueOptions
.concurrency
)
266 'Invalid worker tasks concurrency: must be an integer'
270 tasksQueueOptions
?.concurrency
!= null &&
271 tasksQueueOptions
.concurrency
<= 0
274 `Invalid worker tasks concurrency '${tasksQueueOptions.concurrency}'`
279 private startPool (): void {
281 this.workerNodes
.reduce(
282 (accumulator
, workerNode
) =>
283 !workerNode
.info
.dynamic
? accumulator
+ 1 : accumulator
,
285 ) < this.numberOfWorkers
287 this.createAndSetupWorker()
292 public get
info (): PoolInfo
{
298 strategy
: this.opts
.workerChoiceStrategy
as WorkerChoiceStrategy
,
299 minSize
: this.minSize
,
300 maxSize
: this.maxSize
,
301 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
302 .runTime
.aggregate
&&
303 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
304 .waitTime
.aggregate
&& { utilization
: round(this.utilization
) }),
305 workerNodes
: this.workerNodes
.length
,
306 idleWorkerNodes
: this.workerNodes
.reduce(
307 (accumulator
, workerNode
) =>
308 workerNode
.usage
.tasks
.executing
=== 0
313 busyWorkerNodes
: this.workerNodes
.reduce(
314 (accumulator
, workerNode
) =>
315 workerNode
.usage
.tasks
.executing
> 0 ? accumulator
+ 1 : accumulator
,
318 executedTasks
: this.workerNodes
.reduce(
319 (accumulator
, workerNode
) =>
320 accumulator
+ workerNode
.usage
.tasks
.executed
,
323 executingTasks
: this.workerNodes
.reduce(
324 (accumulator
, workerNode
) =>
325 accumulator
+ workerNode
.usage
.tasks
.executing
,
328 queuedTasks
: this.workerNodes
.reduce(
329 (accumulator
, workerNode
) =>
330 accumulator
+ workerNode
.usage
.tasks
.queued
,
333 maxQueuedTasks
: this.workerNodes
.reduce(
334 (accumulator
, workerNode
) =>
335 accumulator
+ (workerNode
.usage
.tasks
?.maxQueued
?? 0),
338 failedTasks
: this.workerNodes
.reduce(
339 (accumulator
, workerNode
) =>
340 accumulator
+ workerNode
.usage
.tasks
.failed
,
343 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
344 .runTime
.aggregate
&& {
348 ...this.workerNodes
.map(
349 workerNode
=> workerNode
.usage
.runTime
?.minimum
?? Infinity
355 ...this.workerNodes
.map(
356 workerNode
=> workerNode
.usage
.runTime
?.maximum
?? -Infinity
361 this.workerNodes
.reduce(
362 (accumulator
, workerNode
) =>
363 accumulator
+ (workerNode
.usage
.runTime
?.aggregate
?? 0),
366 this.workerNodes
.reduce(
367 (accumulator
, workerNode
) =>
368 accumulator
+ (workerNode
.usage
.tasks
?.executed
?? 0),
372 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
376 this.workerNodes
.map(
377 workerNode
=> workerNode
.usage
.runTime
?.median
?? 0
384 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
385 .waitTime
.aggregate
&& {
389 ...this.workerNodes
.map(
390 workerNode
=> workerNode
.usage
.waitTime
?.minimum
?? Infinity
396 ...this.workerNodes
.map(
397 workerNode
=> workerNode
.usage
.waitTime
?.maximum
?? -Infinity
402 this.workerNodes
.reduce(
403 (accumulator
, workerNode
) =>
404 accumulator
+ (workerNode
.usage
.waitTime
?.aggregate
?? 0),
407 this.workerNodes
.reduce(
408 (accumulator
, workerNode
) =>
409 accumulator
+ (workerNode
.usage
.tasks
?.executed
?? 0),
413 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
414 .waitTime
.median
&& {
417 this.workerNodes
.map(
418 workerNode
=> workerNode
.usage
.waitTime
?.median
?? 0
428 private get
ready (): boolean {
430 this.workerNodes
.reduce(
431 (accumulator
, workerNode
) =>
432 !workerNode
.info
.dynamic
&& workerNode
.info
.ready
441 * Gets the approximate pool utilization.
443 * @returns The pool utilization.
445 private get
utilization (): number {
446 const poolTimeCapacity
=
447 (performance
.now() - this.startTimestamp
) * this.maxSize
448 const totalTasksRunTime
= this.workerNodes
.reduce(
449 (accumulator
, workerNode
) =>
450 accumulator
+ (workerNode
.usage
.runTime
?.aggregate
?? 0),
453 const totalTasksWaitTime
= this.workerNodes
.reduce(
454 (accumulator
, workerNode
) =>
455 accumulator
+ (workerNode
.usage
.waitTime
?.aggregate
?? 0),
458 return (totalTasksRunTime
+ totalTasksWaitTime
) / poolTimeCapacity
464 * If it is `'dynamic'`, it provides the `max` property.
466 protected abstract get
type (): PoolType
469 * Gets the worker type.
471 protected abstract get
worker (): WorkerType
476 protected abstract get
minSize (): number
481 protected abstract get
maxSize (): number
484 * Get the worker given its id.
486 * @param workerId - The worker id.
487 * @returns The worker if found in the pool worker nodes, `undefined` otherwise.
489 private getWorkerById (workerId
: number): Worker
| undefined {
490 return this.workerNodes
.find(workerNode
=> workerNode
.info
.id
=== workerId
)
495 * Checks if the worker id sent in the received message from a worker is valid.
497 * @param message - The received message.
498 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the worker id is invalid.
500 private checkMessageWorkerId (message
: MessageValue
<Response
>): void {
502 message
.workerId
!= null &&
503 this.getWorkerById(message
.workerId
) == null
506 `Worker message received from unknown worker '${message.workerId}'`
512 * Gets the given worker its worker node key.
514 * @param worker - The worker.
515 * @returns The worker node key if found in the pool worker nodes, `-1` otherwise.
517 protected getWorkerNodeKey (worker
: Worker
): number {
518 return this.workerNodes
.findIndex(
519 workerNode
=> workerNode
.worker
=== worker
524 public setWorkerChoiceStrategy (
525 workerChoiceStrategy
: WorkerChoiceStrategy
,
526 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
528 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
529 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
530 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
531 this.opts
.workerChoiceStrategy
533 if (workerChoiceStrategyOptions
!= null) {
534 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
536 for (const workerNode
of this.workerNodes
) {
537 workerNode
.resetUsage()
538 this.setWorkerStatistics(workerNode
.worker
)
543 public setWorkerChoiceStrategyOptions (
544 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
546 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
547 this.opts
.workerChoiceStrategyOptions
= workerChoiceStrategyOptions
548 this.workerChoiceStrategyContext
.setOptions(
549 this.opts
.workerChoiceStrategyOptions
554 public enableTasksQueue (
556 tasksQueueOptions
?: TasksQueueOptions
558 if (this.opts
.enableTasksQueue
=== true && !enable
) {
559 this.flushTasksQueues()
561 this.opts
.enableTasksQueue
= enable
562 this.setTasksQueueOptions(tasksQueueOptions
as TasksQueueOptions
)
566 public setTasksQueueOptions (tasksQueueOptions
: TasksQueueOptions
): void {
567 if (this.opts
.enableTasksQueue
=== true) {
568 this.checkValidTasksQueueOptions(tasksQueueOptions
)
569 this.opts
.tasksQueueOptions
=
570 this.buildTasksQueueOptions(tasksQueueOptions
)
571 } else if (this.opts
.tasksQueueOptions
!= null) {
572 delete this.opts
.tasksQueueOptions
576 private buildTasksQueueOptions (
577 tasksQueueOptions
: TasksQueueOptions
578 ): TasksQueueOptions
{
580 concurrency
: tasksQueueOptions
?.concurrency
?? 1
585 * Whether the pool is full or not.
587 * The pool filling boolean status.
589 protected get
full (): boolean {
590 return this.workerNodes
.length
>= this.maxSize
594 * Whether the pool is busy or not.
596 * The pool busyness boolean status.
598 protected abstract get
busy (): boolean
601 * Whether worker nodes are executing at least one task.
603 * @returns Worker nodes busyness boolean status.
605 protected internalBusy (): boolean {
607 this.workerNodes
.findIndex(workerNode
=> {
608 return workerNode
.usage
.tasks
.executing
=== 0
614 public async execute (data
?: Data
, name
?: string): Promise
<Response
> {
615 return await new Promise
<Response
>((resolve
, reject
) => {
616 const timestamp
= performance
.now()
617 const workerNodeKey
= this.chooseWorkerNode()
618 const task
: Task
<Data
> = {
619 name
: name
?? DEFAULT_TASK_NAME
,
620 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
621 data
: data
?? ({} as Data
),
623 workerId
: this.getWorkerInfo(workerNodeKey
).id
as number,
626 this.promiseResponseMap
.set(task
.id
as string, {
632 this.opts
.enableTasksQueue
=== true &&
634 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
>=
635 ((this.opts
.tasksQueueOptions
as TasksQueueOptions
)
636 .concurrency
as number))
638 this.enqueueTask(workerNodeKey
, task
)
640 this.executeTask(workerNodeKey
, task
)
642 this.checkAndEmitEvents()
647 public async destroy (): Promise
<void> {
649 this.workerNodes
.map(async (workerNode
, workerNodeKey
) => {
650 this.flushTasksQueue(workerNodeKey
)
651 // FIXME: wait for tasks to be finished
652 const workerExitPromise
= new Promise
<void>(resolve
=> {
653 workerNode
.worker
.on('exit', () => {
657 await this.destroyWorker(workerNode
.worker
)
658 await workerExitPromise
664 * Terminates the given worker.
666 * @param worker - A worker within `workerNodes`.
668 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
671 * Setup hook to execute code before worker nodes are created in the abstract constructor.
676 protected setupHook (): void {
677 // Intentionally empty
681 * Should return whether the worker is the main worker or not.
683 protected abstract isMain (): boolean
686 * Hook executed before the worker task execution.
689 * @param workerNodeKey - The worker node key.
690 * @param task - The task to execute.
692 protected beforeTaskExecutionHook (
693 workerNodeKey
: number,
696 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
697 ++workerUsage
.tasks
.executing
698 this.updateWaitTimeWorkerUsage(workerUsage
, task
)
699 const taskWorkerUsage
= this.workerNodes
[workerNodeKey
].getTaskWorkerUsage(
702 ++taskWorkerUsage
.tasks
.executing
703 this.updateWaitTimeWorkerUsage(taskWorkerUsage
, task
)
707 * Hook executed after the worker task execution.
710 * @param workerNodeKey - The worker node key.
711 * @param message - The received message.
713 protected afterTaskExecutionHook (
714 workerNodeKey
: number,
715 message
: MessageValue
<Response
>
717 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
718 this.updateTaskStatisticsWorkerUsage(workerUsage
, message
)
719 this.updateRunTimeWorkerUsage(workerUsage
, message
)
720 this.updateEluWorkerUsage(workerUsage
, message
)
721 const taskWorkerUsage
= this.workerNodes
[workerNodeKey
].getTaskWorkerUsage(
722 message
.taskPerformance
?.name
?? DEFAULT_TASK_NAME
724 this.updateTaskStatisticsWorkerUsage(taskWorkerUsage
, message
)
725 this.updateRunTimeWorkerUsage(taskWorkerUsage
, message
)
726 this.updateEluWorkerUsage(taskWorkerUsage
, message
)
729 private updateTaskStatisticsWorkerUsage (
730 workerUsage
: WorkerUsage
,
731 message
: MessageValue
<Response
>
733 const workerTaskStatistics
= workerUsage
.tasks
734 --workerTaskStatistics
.executing
735 if (message
.taskError
== null) {
736 ++workerTaskStatistics
.executed
738 ++workerTaskStatistics
.failed
742 private updateRunTimeWorkerUsage (
743 workerUsage
: WorkerUsage
,
744 message
: MessageValue
<Response
>
746 updateMeasurementStatistics(
748 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
,
749 message
.taskPerformance
?.runTime
?? 0,
750 workerUsage
.tasks
.executed
754 private updateWaitTimeWorkerUsage (
755 workerUsage
: WorkerUsage
,
758 const timestamp
= performance
.now()
759 const taskWaitTime
= timestamp
- (task
.timestamp
?? timestamp
)
760 updateMeasurementStatistics(
761 workerUsage
.waitTime
,
762 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().waitTime
,
764 workerUsage
.tasks
.executed
768 private updateEluWorkerUsage (
769 workerUsage
: WorkerUsage
,
770 message
: MessageValue
<Response
>
772 const eluTaskStatisticsRequirements
: MeasurementStatisticsRequirements
=
773 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
774 updateMeasurementStatistics(
775 workerUsage
.elu
.active
,
776 eluTaskStatisticsRequirements
,
777 message
.taskPerformance
?.elu
?.active
?? 0,
778 workerUsage
.tasks
.executed
780 updateMeasurementStatistics(
781 workerUsage
.elu
.idle
,
782 eluTaskStatisticsRequirements
,
783 message
.taskPerformance
?.elu
?.idle
?? 0,
784 workerUsage
.tasks
.executed
786 if (eluTaskStatisticsRequirements
.aggregate
) {
787 if (message
.taskPerformance
?.elu
!= null) {
788 if (workerUsage
.elu
.utilization
!= null) {
789 workerUsage
.elu
.utilization
=
790 (workerUsage
.elu
.utilization
+
791 message
.taskPerformance
.elu
.utilization
) /
794 workerUsage
.elu
.utilization
= message
.taskPerformance
.elu
.utilization
801 * Chooses a worker node for the next task.
803 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
805 * @returns The worker node key
807 private chooseWorkerNode (): number {
808 if (this.shallCreateDynamicWorker()) {
809 const worker
= this.createAndSetupDynamicWorker()
811 this.workerChoiceStrategyContext
.getStrategyPolicy().useDynamicWorker
813 return this.getWorkerNodeKey(worker
)
816 return this.workerChoiceStrategyContext
.execute()
820 * Conditions for dynamic worker creation.
822 * @returns Whether to create a dynamic worker or not.
824 private shallCreateDynamicWorker (): boolean {
825 return this.type === PoolTypes
.dynamic
&& !this.full
&& this.internalBusy()
829 * Sends a message to the given worker.
831 * @param worker - The worker which should receive the message.
832 * @param message - The message.
834 protected abstract sendToWorker (
836 message
: MessageValue
<Data
>
840 * Creates a new worker.
842 * @returns Newly created worker.
844 protected abstract createWorker (): Worker
847 * Creates a new worker and sets it up completely in the pool worker nodes.
849 * @returns New, completely set up worker.
851 protected createAndSetupWorker (): Worker
{
852 const worker
= this.createWorker()
854 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
855 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
856 worker
.on('error', error
=> {
857 const workerNodeKey
= this.getWorkerNodeKey(worker
)
858 const workerInfo
= this.getWorkerInfo(workerNodeKey
)
859 workerInfo
.ready
= false
860 this.workerNodes
[workerNodeKey
].closeChannel()
861 this.emitter
?.emit(PoolEvents
.error
, error
)
862 if (this.opts
.restartWorkerOnError
=== true && !this.starting
) {
863 if (workerInfo
.dynamic
) {
864 this.createAndSetupDynamicWorker()
866 this.createAndSetupWorker()
869 if (this.opts
.enableTasksQueue
=== true) {
870 this.redistributeQueuedTasks(workerNodeKey
)
873 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
874 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
875 worker
.once('exit', () => {
876 this.removeWorkerNode(worker
)
879 this.addWorkerNode(worker
)
881 this.afterWorkerSetup(worker
)
887 * Creates a new dynamic worker and sets it up completely in the pool worker nodes.
889 * @returns New, completely set up dynamic worker.
891 protected createAndSetupDynamicWorker (): Worker
{
892 const worker
= this.createAndSetupWorker()
893 this.registerWorkerMessageListener(worker
, message
=> {
894 const workerNodeKey
= this.getWorkerNodeKey(worker
)
896 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
897 (message
.kill
!= null &&
898 ((this.opts
.enableTasksQueue
=== false &&
899 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
=== 0) ||
900 (this.opts
.enableTasksQueue
=== true &&
901 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
=== 0 &&
902 this.tasksQueueSize(workerNodeKey
) === 0)))
904 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
905 void (this.destroyWorker(worker
) as Promise
<void>)
908 const workerInfo
= this.getWorkerInfoByWorker(worker
)
909 workerInfo
.dynamic
= true
910 if (this.workerChoiceStrategyContext
.getStrategyPolicy().useDynamicWorker
) {
911 workerInfo
.ready
= true
913 this.sendToWorker(worker
, {
915 workerId
: workerInfo
.id
as number
921 * Registers a listener callback on the given worker.
923 * @param worker - The worker which should register a listener.
924 * @param listener - The message listener callback.
926 protected abstract registerWorkerMessageListener
<
927 Message
extends Data
| Response
928 >(worker
: Worker
, listener
: (message
: MessageValue
<Message
>) => void): void
931 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
934 * @param worker - The newly created worker.
936 protected afterWorkerSetup (worker
: Worker
): void {
937 // Listen to worker messages.
938 this.registerWorkerMessageListener(worker
, this.workerListener())
939 // Send the startup message to worker.
940 this.sendStartupMessageToWorker(worker
)
941 // Setup worker task statistics computation.
942 this.setWorkerStatistics(worker
)
946 * Sends the startup message to the given worker.
948 * @param worker - The worker which should receive the startup message.
950 protected abstract sendStartupMessageToWorker (worker
: Worker
): void
952 private redistributeQueuedTasks (workerNodeKey
: number): void {
953 while (this.tasksQueueSize(workerNodeKey
) > 0) {
954 let targetWorkerNodeKey
: number = workerNodeKey
955 let minQueuedTasks
= Infinity
956 for (const [workerNodeId
, workerNode
] of this.workerNodes
.entries()) {
957 const workerInfo
= this.getWorkerInfo(workerNodeId
)
959 workerNodeId
!== workerNodeKey
&&
961 workerNode
.usage
.tasks
.queued
=== 0
963 targetWorkerNodeKey
= workerNodeId
967 workerNodeId
!== workerNodeKey
&&
969 workerNode
.usage
.tasks
.queued
< minQueuedTasks
971 minQueuedTasks
= workerNode
.usage
.tasks
.queued
972 targetWorkerNodeKey
= workerNodeId
977 this.dequeueTask(workerNodeKey
) as Task
<Data
>
983 * This function is the listener registered for each worker message.
985 * @returns The listener function to execute when a message is received from a worker.
987 protected workerListener (): (message
: MessageValue
<Response
>) => void {
989 this.checkMessageWorkerId(message
)
990 if (message
.ready
!= null) {
991 // Worker ready response received
992 this.handleWorkerReadyResponse(message
)
993 } else if (message
.id
!= null) {
994 // Task execution response received
995 this.handleTaskExecutionResponse(message
)
1000 private handleWorkerReadyResponse (message
: MessageValue
<Response
>): void {
1001 this.getWorkerInfoByWorker(
1002 this.getWorkerById(message
.workerId
) as Worker
1003 ).ready
= message
.ready
as boolean
1004 if (this.emitter
!= null && this.ready
) {
1005 this.emitter
.emit(PoolEvents
.ready
, this.info
)
1009 private handleTaskExecutionResponse (message
: MessageValue
<Response
>): void {
1010 const promiseResponse
= this.promiseResponseMap
.get(message
.id
as string)
1011 if (promiseResponse
!= null) {
1012 if (message
.taskError
!= null) {
1013 this.emitter
?.emit(PoolEvents
.taskError
, message
.taskError
)
1014 promiseResponse
.reject(message
.taskError
.message
)
1016 promiseResponse
.resolve(message
.data
as Response
)
1018 const workerNodeKey
= promiseResponse
.workerNodeKey
1019 this.afterTaskExecutionHook(workerNodeKey
, message
)
1020 this.promiseResponseMap
.delete(message
.id
as string)
1022 this.opts
.enableTasksQueue
=== true &&
1023 this.tasksQueueSize(workerNodeKey
) > 0
1027 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1030 this.workerChoiceStrategyContext
.update(workerNodeKey
)
1034 private checkAndEmitEvents (): void {
1035 if (this.emitter
!= null) {
1037 this.emitter
.emit(PoolEvents
.busy
, this.info
)
1039 if (this.type === PoolTypes
.dynamic
&& this.full
) {
1040 this.emitter
.emit(PoolEvents
.full
, this.info
)
1046 * Gets the worker information from the given worker node key.
1048 * @param workerNodeKey - The worker node key.
1049 * @returns The worker information.
1051 private getWorkerInfo (workerNodeKey
: number): WorkerInfo
{
1052 return this.workerNodes
[workerNodeKey
].info
1056 * Gets the worker information from the given worker.
1058 * @param worker - The worker.
1059 * @returns The worker information.
1060 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the worker is not found.
1062 protected getWorkerInfoByWorker (worker
: Worker
): WorkerInfo
{
1063 const workerNodeKey
= this.getWorkerNodeKey(worker
)
1064 if (workerNodeKey
=== -1) {
1065 throw new Error('Worker not found')
1067 return this.workerNodes
[workerNodeKey
].info
1071 * Adds the given worker in the pool worker nodes.
1073 * @param worker - The worker.
1074 * @returns The worker nodes length.
1076 private addWorkerNode (worker
: Worker
): number {
1077 const workerNode
= new WorkerNode
<Worker
, Data
>(worker
, this.worker
)
1078 // Flag the worker node as ready at pool startup.
1079 if (this.starting
) {
1080 workerNode
.info
.ready
= true
1082 return this.workerNodes
.push(workerNode
)
1086 * Removes the given worker from the pool worker nodes.
1088 * @param worker - The worker.
1090 private removeWorkerNode (worker
: Worker
): void {
1091 const workerNodeKey
= this.getWorkerNodeKey(worker
)
1092 if (workerNodeKey
!== -1) {
1093 this.workerNodes
.splice(workerNodeKey
, 1)
1094 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
1099 * Executes the given task on the given worker.
1101 * @param worker - The worker.
1102 * @param task - The task to execute.
1104 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
1105 this.beforeTaskExecutionHook(workerNodeKey
, task
)
1106 this.sendToWorker(this.workerNodes
[workerNodeKey
].worker
, task
)
1109 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
1110 return this.workerNodes
[workerNodeKey
].enqueueTask(task
)
1113 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
1114 return this.workerNodes
[workerNodeKey
].dequeueTask()
1117 private tasksQueueSize (workerNodeKey
: number): number {
1118 return this.workerNodes
[workerNodeKey
].tasksQueueSize()
1121 private flushTasksQueue (workerNodeKey
: number): void {
1122 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1125 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1128 this.workerNodes
[workerNodeKey
].clearTasksQueue()
1131 private flushTasksQueues (): void {
1132 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
1133 this.flushTasksQueue(workerNodeKey
)
1137 private setWorkerStatistics (worker
: Worker
): void {
1138 this.sendToWorker(worker
, {
1141 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1143 elu
: this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1146 workerId
: this.getWorkerInfoByWorker(worker
).id
as number