1 import { randomUUID
} from
'node:crypto'
2 import { performance
} from
'node:perf_hooks'
3 import type { MessageValue
, PromiseResponseWrapper
} from
'../utility-types'
5 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
,
12 import { KillBehaviors
} from
'../worker/worker-options'
13 import { CircularArray
} from
'../circular-array'
14 import { Queue
} from
'../queue'
23 type TasksQueueOptions
,
37 WorkerChoiceStrategies
,
38 type WorkerChoiceStrategy
,
39 type WorkerChoiceStrategyOptions
40 } from
'./selection-strategies/selection-strategies-types'
41 import { WorkerChoiceStrategyContext
} from
'./selection-strategies/worker-choice-strategy-context'
42 import { version
} from
'./version'
45 * Base class that implements some shared logic for all poolifier pools.
47 * @typeParam Worker - Type of worker which manages this pool.
48 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
49 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
51 export abstract class AbstractPool
<
52 Worker
extends IWorker
,
55 > implements IPool
<Worker
, Data
, Response
> {
57 public readonly workerNodes
: Array<WorkerNode
<Worker
, Data
>> = []
60 public readonly emitter
?: PoolEmitter
63 * The execution response promise map.
65 * - `key`: The message id of each submitted task.
66 * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks.
68 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
70 protected promiseResponseMap
: Map
<
72 PromiseResponseWrapper
<Worker
, Response
>
73 > = new Map
<string, PromiseResponseWrapper
<Worker
, Response
>>()
76 * Worker choice strategy context referencing a worker choice algorithm implementation.
78 protected workerChoiceStrategyContext
: WorkerChoiceStrategyContext
<
85 * The start timestamp of the pool.
87 private readonly startTimestamp
90 * Constructs a new poolifier pool.
92 * @param numberOfWorkers - Number of workers that this pool should manage.
93 * @param filePath - Path to the worker file.
94 * @param opts - Options for the pool.
97 protected readonly numberOfWorkers
: number,
98 protected readonly filePath
: string,
99 protected readonly opts
: PoolOptions
<Worker
>
101 if (!this.isMain()) {
102 throw new Error('Cannot start a pool from a worker!')
104 this.checkNumberOfWorkers(this.numberOfWorkers
)
105 this.checkFilePath(this.filePath
)
106 this.checkPoolOptions(this.opts
)
108 this.chooseWorkerNode
= this.chooseWorkerNode
.bind(this)
109 this.executeTask
= this.executeTask
.bind(this)
110 this.enqueueTask
= this.enqueueTask
.bind(this)
111 this.checkAndEmitEvents
= this.checkAndEmitEvents
.bind(this)
113 if (this.opts
.enableEvents
=== true) {
114 this.emitter
= new PoolEmitter()
116 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext
<
122 this.opts
.workerChoiceStrategy
,
123 this.opts
.workerChoiceStrategyOptions
128 while (this.workerNodes
.length
< this.numberOfWorkers
) {
129 this.createAndSetupWorker()
132 this.startTimestamp
= performance
.now()
135 private checkFilePath (filePath
: string): void {
138 (typeof filePath
=== 'string' && filePath
.trim().length
=== 0)
140 throw new Error('Please specify a file with a worker implementation')
144 private checkNumberOfWorkers (numberOfWorkers
: number): void {
145 if (numberOfWorkers
== null) {
147 'Cannot instantiate a pool without specifying the number of workers'
149 } else if (!Number.isSafeInteger(numberOfWorkers
)) {
151 'Cannot instantiate a pool with a non safe integer number of workers'
153 } else if (numberOfWorkers
< 0) {
154 throw new RangeError(
155 'Cannot instantiate a pool with a negative number of workers'
157 } else if (this.type === PoolTypes
.fixed
&& numberOfWorkers
=== 0) {
158 throw new Error('Cannot instantiate a fixed pool with no worker')
162 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
163 if (isPlainObject(opts
)) {
164 this.opts
.workerChoiceStrategy
=
165 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
166 this.checkValidWorkerChoiceStrategy(this.opts
.workerChoiceStrategy
)
167 this.opts
.workerChoiceStrategyOptions
=
168 opts
.workerChoiceStrategyOptions
??
169 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
170 this.checkValidWorkerChoiceStrategyOptions(
171 this.opts
.workerChoiceStrategyOptions
173 this.opts
.restartWorkerOnError
= opts
.restartWorkerOnError
?? true
174 this.opts
.enableEvents
= opts
.enableEvents
?? true
175 this.opts
.enableTasksQueue
= opts
.enableTasksQueue
?? false
176 if (this.opts
.enableTasksQueue
) {
177 this.checkValidTasksQueueOptions(
178 opts
.tasksQueueOptions
as TasksQueueOptions
180 this.opts
.tasksQueueOptions
= this.buildTasksQueueOptions(
181 opts
.tasksQueueOptions
as TasksQueueOptions
185 throw new TypeError('Invalid pool options: must be a plain object')
189 private checkValidWorkerChoiceStrategy (
190 workerChoiceStrategy
: WorkerChoiceStrategy
192 if (!Object.values(WorkerChoiceStrategies
).includes(workerChoiceStrategy
)) {
194 `Invalid worker choice strategy '${workerChoiceStrategy}'`
199 private checkValidWorkerChoiceStrategyOptions (
200 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
202 if (!isPlainObject(workerChoiceStrategyOptions
)) {
204 'Invalid worker choice strategy options: must be a plain object'
208 workerChoiceStrategyOptions
.weights
!= null &&
209 Object.keys(workerChoiceStrategyOptions
.weights
).length
!== this.maxSize
212 'Invalid worker choice strategy options: must have a weight for each worker node'
216 workerChoiceStrategyOptions
.measurement
!= null &&
217 !Object.values(Measurements
).includes(
218 workerChoiceStrategyOptions
.measurement
222 `Invalid worker choice strategy options: invalid measurement '${workerChoiceStrategyOptions.measurement}'`
227 private checkValidTasksQueueOptions (
228 tasksQueueOptions
: TasksQueueOptions
230 if (tasksQueueOptions
!= null && !isPlainObject(tasksQueueOptions
)) {
231 throw new TypeError('Invalid tasks queue options: must be a plain object')
234 tasksQueueOptions
?.concurrency
!= null &&
235 !Number.isSafeInteger(tasksQueueOptions
.concurrency
)
238 'Invalid worker tasks concurrency: must be an integer'
242 tasksQueueOptions
?.concurrency
!= null &&
243 tasksQueueOptions
.concurrency
<= 0
246 `Invalid worker tasks concurrency '${tasksQueueOptions.concurrency}'`
252 public get
info (): PoolInfo
{
257 minSize
: this.minSize
,
258 maxSize
: this.maxSize
,
259 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
260 .runTime
.aggregate
&&
261 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
262 .waitTime
.aggregate
&& { utilization
: round(this.utilization
) }),
263 workerNodes
: this.workerNodes
.length
,
264 idleWorkerNodes
: this.workerNodes
.reduce(
265 (accumulator
, workerNode
) =>
266 workerNode
.usage
.tasks
.executing
=== 0
271 busyWorkerNodes
: this.workerNodes
.reduce(
272 (accumulator
, workerNode
) =>
273 workerNode
.usage
.tasks
.executing
> 0 ? accumulator
+ 1 : accumulator
,
276 executedTasks
: this.workerNodes
.reduce(
277 (accumulator
, workerNode
) =>
278 accumulator
+ workerNode
.usage
.tasks
.executed
,
281 executingTasks
: this.workerNodes
.reduce(
282 (accumulator
, workerNode
) =>
283 accumulator
+ workerNode
.usage
.tasks
.executing
,
286 queuedTasks
: this.workerNodes
.reduce(
287 (accumulator
, workerNode
) =>
288 accumulator
+ workerNode
.usage
.tasks
.queued
,
291 maxQueuedTasks
: this.workerNodes
.reduce(
292 (accumulator
, workerNode
) =>
293 accumulator
+ workerNode
.usage
.tasks
.maxQueued
,
296 failedTasks
: this.workerNodes
.reduce(
297 (accumulator
, workerNode
) =>
298 accumulator
+ workerNode
.usage
.tasks
.failed
,
301 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
302 .runTime
.aggregate
&& {
305 ...this.workerNodes
.map(
306 workerNode
=> workerNode
.usage
.runTime
?.minimum
?? Infinity
310 ...this.workerNodes
.map(
311 workerNode
=> workerNode
.usage
.runTime
?.maximum
?? -Infinity
316 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
317 .waitTime
.aggregate
&& {
320 ...this.workerNodes
.map(
321 workerNode
=> workerNode
.usage
.waitTime
?.minimum
?? Infinity
325 ...this.workerNodes
.map(
326 workerNode
=> workerNode
.usage
.waitTime
?.maximum
?? -Infinity
335 * Gets the approximate pool utilization.
337 * @returns The pool utilization.
339 private get
utilization (): number {
340 const poolRunTimeCapacity
=
341 (performance
.now() - this.startTimestamp
) * this.maxSize
342 const totalTasksRunTime
= this.workerNodes
.reduce(
343 (accumulator
, workerNode
) =>
344 accumulator
+ (workerNode
.usage
.runTime
?.aggregate
?? 0),
347 const totalTasksWaitTime
= this.workerNodes
.reduce(
348 (accumulator
, workerNode
) =>
349 accumulator
+ (workerNode
.usage
.waitTime
?.aggregate
?? 0),
352 return (totalTasksRunTime
+ totalTasksWaitTime
) / poolRunTimeCapacity
358 * If it is `'dynamic'`, it provides the `max` property.
360 protected abstract get
type (): PoolType
363 * Gets the worker type.
365 protected abstract get
worker (): WorkerType
370 protected abstract get
minSize (): number
375 protected abstract get
maxSize (): number
378 * Get the worker given its id.
380 * @param workerId - The worker id.
381 * @returns The worker if found in the pool worker nodes, `undefined` otherwise.
383 private getWorkerById (workerId
: number): Worker
| undefined {
384 return this.workerNodes
.find(workerNode
=> workerNode
.info
.id
=== workerId
)
389 * Gets the given worker its worker node key.
391 * @param worker - The worker.
392 * @returns The worker node key if found in the pool worker nodes, `-1` otherwise.
394 private getWorkerNodeKey (worker
: Worker
): number {
395 return this.workerNodes
.findIndex(
396 workerNode
=> workerNode
.worker
=== worker
401 public setWorkerChoiceStrategy (
402 workerChoiceStrategy
: WorkerChoiceStrategy
,
403 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
405 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
406 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
407 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
408 this.opts
.workerChoiceStrategy
410 if (workerChoiceStrategyOptions
!= null) {
411 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
413 for (const workerNode
of this.workerNodes
) {
414 this.setWorkerNodeTasksUsage(
416 this.getInitialWorkerUsage(workerNode
.worker
)
418 this.setWorkerStatistics(workerNode
.worker
)
423 public setWorkerChoiceStrategyOptions (
424 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
426 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
427 this.opts
.workerChoiceStrategyOptions
= workerChoiceStrategyOptions
428 this.workerChoiceStrategyContext
.setOptions(
429 this.opts
.workerChoiceStrategyOptions
434 public enableTasksQueue (
436 tasksQueueOptions
?: TasksQueueOptions
438 if (this.opts
.enableTasksQueue
=== true && !enable
) {
439 this.flushTasksQueues()
441 this.opts
.enableTasksQueue
= enable
442 this.setTasksQueueOptions(tasksQueueOptions
as TasksQueueOptions
)
446 public setTasksQueueOptions (tasksQueueOptions
: TasksQueueOptions
): void {
447 if (this.opts
.enableTasksQueue
=== true) {
448 this.checkValidTasksQueueOptions(tasksQueueOptions
)
449 this.opts
.tasksQueueOptions
=
450 this.buildTasksQueueOptions(tasksQueueOptions
)
451 } else if (this.opts
.tasksQueueOptions
!= null) {
452 delete this.opts
.tasksQueueOptions
456 private buildTasksQueueOptions (
457 tasksQueueOptions
: TasksQueueOptions
458 ): TasksQueueOptions
{
460 concurrency
: tasksQueueOptions
?.concurrency
?? 1
465 * Whether the pool is full or not.
467 * The pool filling boolean status.
469 protected get
full (): boolean {
470 return this.workerNodes
.length
>= this.maxSize
474 * Whether the pool is busy or not.
476 * The pool busyness boolean status.
478 protected abstract get
busy (): boolean
481 * Whether worker nodes are executing at least one task.
483 * @returns Worker nodes busyness boolean status.
485 protected internalBusy (): boolean {
487 this.workerNodes
.findIndex(workerNode
=> {
488 return workerNode
.usage
.tasks
.executing
=== 0
494 public async execute (data
?: Data
, name
?: string): Promise
<Response
> {
495 const timestamp
= performance
.now()
496 const workerNodeKey
= this.chooseWorkerNode()
497 const submittedTask
: Task
<Data
> = {
499 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
500 data
: data
?? ({} as Data
),
504 const res
= new Promise
<Response
>((resolve
, reject
) => {
505 this.promiseResponseMap
.set(submittedTask
.id
as string, {
508 worker
: this.workerNodes
[workerNodeKey
].worker
512 this.opts
.enableTasksQueue
=== true &&
514 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
>=
515 ((this.opts
.tasksQueueOptions
as TasksQueueOptions
)
516 .concurrency
as number))
518 this.enqueueTask(workerNodeKey
, submittedTask
)
520 this.executeTask(workerNodeKey
, submittedTask
)
522 this.checkAndEmitEvents()
523 // eslint-disable-next-line @typescript-eslint/return-await
528 public async destroy (): Promise
<void> {
530 this.workerNodes
.map(async (workerNode
, workerNodeKey
) => {
531 this.flushTasksQueue(workerNodeKey
)
532 // FIXME: wait for tasks to be finished
533 const workerExitPromise
= new Promise
<void>(resolve
=> {
534 workerNode
.worker
.on('exit', () => {
538 await this.destroyWorker(workerNode
.worker
)
539 await workerExitPromise
545 * Terminates the given worker.
547 * @param worker - A worker within `workerNodes`.
549 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
552 * Setup hook to execute code before worker nodes are created in the abstract constructor.
557 protected setupHook (): void {
558 // Intentionally empty
562 * Should return whether the worker is the main worker or not.
564 protected abstract isMain (): boolean
567 * Hook executed before the worker task execution.
570 * @param workerNodeKey - The worker node key.
571 * @param task - The task to execute.
573 protected beforeTaskExecutionHook (
574 workerNodeKey
: number,
577 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
578 ++workerUsage
.tasks
.executing
579 this.updateWaitTimeWorkerUsage(workerUsage
, task
)
583 * Hook executed after the worker task execution.
586 * @param worker - The worker.
587 * @param message - The received message.
589 protected afterTaskExecutionHook (
591 message
: MessageValue
<Response
>
593 const workerUsage
= this.workerNodes
[this.getWorkerNodeKey(worker
)].usage
594 this.updateTaskStatisticsWorkerUsage(workerUsage
, message
)
595 this.updateRunTimeWorkerUsage(workerUsage
, message
)
596 this.updateEluWorkerUsage(workerUsage
, message
)
599 private updateTaskStatisticsWorkerUsage (
600 workerUsage
: WorkerUsage
,
601 message
: MessageValue
<Response
>
603 const workerTaskStatistics
= workerUsage
.tasks
604 --workerTaskStatistics
.executing
605 ++workerTaskStatistics
.executed
606 if (message
.taskError
!= null) {
607 ++workerTaskStatistics
.failed
611 private updateRunTimeWorkerUsage (
612 workerUsage
: WorkerUsage
,
613 message
: MessageValue
<Response
>
616 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
619 const taskRunTime
= message
.taskPerformance
?.runTime
?? 0
620 workerUsage
.runTime
.aggregate
=
621 (workerUsage
.runTime
.aggregate
?? 0) + taskRunTime
622 workerUsage
.runTime
.minimum
= Math.min(
624 workerUsage
.runTime
?.minimum
?? Infinity
626 workerUsage
.runTime
.maximum
= Math.max(
628 workerUsage
.runTime
?.maximum
?? -Infinity
631 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
633 workerUsage
.tasks
.executed
!== 0
635 workerUsage
.runTime
.average
=
636 workerUsage
.runTime
.aggregate
/
637 (workerUsage
.tasks
.executed
- workerUsage
.tasks
.failed
)
640 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
642 message
.taskPerformance
?.runTime
!= null
644 workerUsage
.runTime
.history
.push(message
.taskPerformance
.runTime
)
645 workerUsage
.runTime
.median
= median(workerUsage
.runTime
.history
)
650 private updateWaitTimeWorkerUsage (
651 workerUsage
: WorkerUsage
,
654 const timestamp
= performance
.now()
655 const taskWaitTime
= timestamp
- (task
.timestamp
?? timestamp
)
657 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().waitTime
660 workerUsage
.waitTime
.aggregate
=
661 (workerUsage
.waitTime
?.aggregate
?? 0) + taskWaitTime
662 workerUsage
.waitTime
.minimum
= Math.min(
664 workerUsage
.waitTime
?.minimum
?? Infinity
666 workerUsage
.waitTime
.maximum
= Math.max(
668 workerUsage
.waitTime
?.maximum
?? -Infinity
671 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
673 workerUsage
.tasks
.executed
!== 0
675 workerUsage
.waitTime
.average
=
676 workerUsage
.waitTime
.aggregate
/
677 (workerUsage
.tasks
.executed
- workerUsage
.tasks
.failed
)
680 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
683 workerUsage
.waitTime
.history
.push(taskWaitTime
)
684 workerUsage
.waitTime
.median
= median(workerUsage
.waitTime
.history
)
689 private updateEluWorkerUsage (
690 workerUsage
: WorkerUsage
,
691 message
: MessageValue
<Response
>
694 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
697 if (message
.taskPerformance
?.elu
!= null) {
698 workerUsage
.elu
.idle
.aggregate
=
699 (workerUsage
.elu
.idle
?.aggregate
?? 0) +
700 message
.taskPerformance
.elu
.idle
701 workerUsage
.elu
.active
.aggregate
=
702 (workerUsage
.elu
.active
?.aggregate
?? 0) +
703 message
.taskPerformance
.elu
.active
704 if (workerUsage
.elu
.utilization
!= null) {
705 workerUsage
.elu
.utilization
=
706 (workerUsage
.elu
.utilization
+
707 message
.taskPerformance
.elu
.utilization
) /
710 workerUsage
.elu
.utilization
= message
.taskPerformance
.elu
.utilization
712 workerUsage
.elu
.idle
.minimum
= Math.min(
713 message
.taskPerformance
.elu
.idle
,
714 workerUsage
.elu
.idle
?.minimum
?? Infinity
716 workerUsage
.elu
.idle
.maximum
= Math.max(
717 message
.taskPerformance
.elu
.idle
,
718 workerUsage
.elu
.idle
?.maximum
?? -Infinity
720 workerUsage
.elu
.active
.minimum
= Math.min(
721 message
.taskPerformance
.elu
.active
,
722 workerUsage
.elu
.active
?.minimum
?? Infinity
724 workerUsage
.elu
.active
.maximum
= Math.max(
725 message
.taskPerformance
.elu
.active
,
726 workerUsage
.elu
.active
?.maximum
?? -Infinity
729 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
731 workerUsage
.tasks
.executed
!== 0
733 const executedTasks
=
734 workerUsage
.tasks
.executed
- workerUsage
.tasks
.failed
735 workerUsage
.elu
.idle
.average
=
736 workerUsage
.elu
.idle
.aggregate
/ executedTasks
737 workerUsage
.elu
.active
.average
=
738 workerUsage
.elu
.active
.aggregate
/ executedTasks
741 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
744 workerUsage
.elu
.idle
.history
.push(message
.taskPerformance
.elu
.idle
)
745 workerUsage
.elu
.active
.history
.push(
746 message
.taskPerformance
.elu
.active
748 workerUsage
.elu
.idle
.median
= median(workerUsage
.elu
.idle
.history
)
749 workerUsage
.elu
.active
.median
= median(workerUsage
.elu
.active
.history
)
756 * Chooses a worker node for the next task.
758 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
760 * @returns The worker node key
762 private chooseWorkerNode (): number {
763 if (this.shallCreateDynamicWorker()) {
764 const worker
= this.createAndSetupDynamicWorker()
766 this.workerChoiceStrategyContext
.getStrategyPolicy().useDynamicWorker
768 return this.getWorkerNodeKey(worker
)
771 return this.workerChoiceStrategyContext
.execute()
775 * Conditions for dynamic worker creation.
777 * @returns Whether to create a dynamic worker or not.
779 private shallCreateDynamicWorker (): boolean {
780 return this.type === PoolTypes
.dynamic
&& !this.full
&& this.internalBusy()
784 * Sends a message to the given worker.
786 * @param worker - The worker which should receive the message.
787 * @param message - The message.
789 protected abstract sendToWorker (
791 message
: MessageValue
<Data
>
795 * Registers a listener callback on the given worker.
797 * @param worker - The worker which should register a listener.
798 * @param listener - The message listener callback.
800 private registerWorkerMessageListener
<Message
extends Data
| Response
>(
802 listener
: (message
: MessageValue
<Message
>) => void
804 worker
.on('message', listener
as MessageHandler
<Worker
>)
808 * Creates a new worker.
810 * @returns Newly created worker.
812 protected abstract createWorker (): Worker
815 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
818 * @param worker - The newly created worker.
820 protected afterWorkerSetup (worker
: Worker
): void {
821 // Listen to worker messages.
822 this.registerWorkerMessageListener(worker
, this.workerListener())
826 * Creates a new worker and sets it up completely in the pool worker nodes.
828 * @returns New, completely set up worker.
830 protected createAndSetupWorker (): Worker
{
831 const worker
= this.createWorker()
833 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
834 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
835 worker
.on('error', error
=> {
836 if (this.emitter
!= null) {
837 this.emitter
.emit(PoolEvents
.error
, error
)
839 if (this.opts
.enableTasksQueue
=== true) {
840 const workerNodeKey
= this.getWorkerNodeKey(worker
)
841 while (this.tasksQueueSize(workerNodeKey
) > 0) {
842 let targetWorkerNodeKey
: number = workerNodeKey
843 let minQueuedTasks
= Infinity
844 for (const [workerNodeId
, workerNode
] of this.workerNodes
.entries()) {
846 workerNodeId
!== workerNodeKey
&&
847 workerNode
.usage
.tasks
.queued
=== 0
849 targetWorkerNodeKey
= workerNodeId
853 workerNodeId
!== workerNodeKey
&&
854 workerNode
.usage
.tasks
.queued
< minQueuedTasks
856 minQueuedTasks
= workerNode
.usage
.tasks
.queued
857 targetWorkerNodeKey
= workerNodeId
862 this.dequeueTask(workerNodeKey
) as Task
<Data
>
866 if (this.opts
.restartWorkerOnError
=== true) {
867 if (this.getWorkerInfo(this.getWorkerNodeKey(worker
)).dynamic
) {
868 this.createAndSetupDynamicWorker()
870 this.createAndSetupWorker()
874 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
875 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
876 worker
.once('exit', () => {
877 this.removeWorkerNode(worker
)
880 this.pushWorkerNode(worker
)
882 this.setWorkerStatistics(worker
)
884 this.afterWorkerSetup(worker
)
890 * Creates a new dynamic worker and sets it up completely in the pool worker nodes.
892 * @returns New, completely set up dynamic worker.
894 protected createAndSetupDynamicWorker (): Worker
{
895 const worker
= this.createAndSetupWorker()
896 this.getWorkerInfo(this.getWorkerNodeKey(worker
)).dynamic
= true
897 this.registerWorkerMessageListener(worker
, message
=> {
898 const workerNodeKey
= this.getWorkerNodeKey(worker
)
900 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
901 (message
.kill
!= null &&
902 ((this.opts
.enableTasksQueue
=== false &&
903 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
=== 0) ||
904 (this.opts
.enableTasksQueue
=== true &&
905 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
=== 0 &&
906 this.tasksQueueSize(workerNodeKey
) === 0)))
908 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
909 void (this.destroyWorker(worker
) as Promise
<void>)
916 * This function is the listener registered for each worker message.
918 * @returns The listener function to execute when a message is received from a worker.
920 protected workerListener (): (message
: MessageValue
<Response
>) => void {
922 if (message
.workerId
!= null && message
.started
!= null) {
923 // Worker started message received
924 this.handleWorkerStartedMessage(message
)
925 } else if (message
.id
!= null) {
926 // Task execution response received
927 this.handleTaskExecutionResponse(message
)
932 private handleWorkerStartedMessage (message
: MessageValue
<Response
>): void {
933 // Worker started message received
934 const worker
= this.getWorkerById(message
.workerId
as number)
935 if (worker
!= null) {
936 this.workerNodes
[this.getWorkerNodeKey(worker
)].info
.started
=
937 message
.started
as boolean
940 `Worker started message received from unknown worker '${
941 message.workerId as number
947 private handleTaskExecutionResponse (message
: MessageValue
<Response
>): void {
948 const promiseResponse
= this.promiseResponseMap
.get(message
.id
as string)
949 if (promiseResponse
!= null) {
950 if (message
.taskError
!= null) {
951 if (this.emitter
!= null) {
952 this.emitter
.emit(PoolEvents
.taskError
, message
.taskError
)
954 promiseResponse
.reject(message
.taskError
.message
)
956 promiseResponse
.resolve(message
.data
as Response
)
958 this.afterTaskExecutionHook(promiseResponse
.worker
, message
)
959 this.promiseResponseMap
.delete(message
.id
as string)
960 const workerNodeKey
= this.getWorkerNodeKey(promiseResponse
.worker
)
962 this.opts
.enableTasksQueue
=== true &&
963 this.tasksQueueSize(workerNodeKey
) > 0
967 this.dequeueTask(workerNodeKey
) as Task
<Data
>
970 this.workerChoiceStrategyContext
.update(workerNodeKey
)
974 private checkAndEmitEvents (): void {
975 if (this.emitter
!= null) {
977 this.emitter
.emit(PoolEvents
.busy
, this.info
)
979 if (this.type === PoolTypes
.dynamic
&& this.full
) {
980 this.emitter
.emit(PoolEvents
.full
, this.info
)
986 * Sets the given worker node its tasks usage in the pool.
988 * @param workerNode - The worker node.
989 * @param workerUsage - The worker usage.
991 private setWorkerNodeTasksUsage (
992 workerNode
: WorkerNode
<Worker
, Data
>,
993 workerUsage
: WorkerUsage
995 workerNode
.usage
= workerUsage
999 * Gets the worker information.
1001 * @param workerNodeKey - The worker node key.
1003 private getWorkerInfo (workerNodeKey
: number): WorkerInfo
{
1004 return this.workerNodes
[workerNodeKey
].info
1008 * Pushes the given worker in the pool worker nodes.
1010 * @param worker - The worker.
1011 * @returns The worker nodes length.
1013 private pushWorkerNode (worker
: Worker
): number {
1014 this.workerNodes
.push({
1016 info
: this.getInitialWorkerInfo(worker
),
1017 usage
: this.getInitialWorkerUsage(),
1018 tasksQueue
: new Queue
<Task
<Data
>>()
1020 this.setWorkerNodeTasksUsage(
1021 this.workerNodes
[this.getWorkerNodeKey(worker
)],
1022 this.getInitialWorkerUsage(worker
)
1024 return this.workerNodes
.length
1028 * Gets the worker id.
1030 * @param worker - The worker.
1031 * @returns The worker id.
1033 private getWorkerId (worker
: Worker
): number | undefined {
1034 if (this.worker
=== WorkerTypes
.thread
) {
1035 return worker
.threadId
1036 } else if (this.worker
=== WorkerTypes
.cluster
) {
1042 // * Sets the given worker in the pool worker nodes.
1044 // * @param workerNodeKey - The worker node key.
1045 // * @param worker - The worker.
1046 // * @param workerInfo - The worker info.
1047 // * @param workerUsage - The worker usage.
1048 // * @param tasksQueue - The worker task queue.
1050 // private setWorkerNode (
1051 // workerNodeKey: number,
1053 // workerInfo: WorkerInfo,
1054 // workerUsage: WorkerUsage,
1055 // tasksQueue: Queue<Task<Data>>
1057 // this.workerNodes[workerNodeKey] = {
1059 // info: workerInfo,
1060 // usage: workerUsage,
1066 * Removes the given worker from the pool worker nodes.
1068 * @param worker - The worker.
1070 private removeWorkerNode (worker
: Worker
): void {
1071 const workerNodeKey
= this.getWorkerNodeKey(worker
)
1072 if (workerNodeKey
!== -1) {
1073 this.workerNodes
.splice(workerNodeKey
, 1)
1074 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
1078 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
1079 this.beforeTaskExecutionHook(workerNodeKey
, task
)
1080 this.sendToWorker(this.workerNodes
[workerNodeKey
].worker
, task
)
1083 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
1084 return this.workerNodes
[workerNodeKey
].tasksQueue
.enqueue(task
)
1087 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
1088 return this.workerNodes
[workerNodeKey
].tasksQueue
.dequeue()
1091 private tasksQueueSize (workerNodeKey
: number): number {
1092 return this.workerNodes
[workerNodeKey
].tasksQueue
.size
1095 private tasksMaxQueueSize (workerNodeKey
: number): number {
1096 return this.workerNodes
[workerNodeKey
].tasksQueue
.maxSize
1099 private flushTasksQueue (workerNodeKey
: number): void {
1100 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1103 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1106 this.workerNodes
[workerNodeKey
].tasksQueue
.clear()
1109 private flushTasksQueues (): void {
1110 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
1111 this.flushTasksQueue(workerNodeKey
)
1115 private setWorkerStatistics (worker
: Worker
): void {
1116 this.sendToWorker(worker
, {
1119 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1121 elu
: this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1127 private getInitialWorkerUsage (worker
?: Worker
): WorkerUsage
{
1128 const getTasksQueueSize
= (worker
?: Worker
): number => {
1129 if (worker
== null) {
1132 return this.tasksQueueSize(this.getWorkerNodeKey(worker
))
1134 const getTasksMaxQueueSize
= (worker
?: Worker
): number => {
1135 if (worker
== null) {
1138 return this.tasksMaxQueueSize(this.getWorkerNodeKey(worker
))
1144 get
queued (): number {
1145 return getTasksQueueSize(worker
)
1147 get
maxQueued (): number {
1148 return getTasksMaxQueueSize(worker
)
1153 history
: new CircularArray()
1156 history
: new CircularArray()
1160 history
: new CircularArray()
1163 history
: new CircularArray()
1169 private getInitialWorkerInfo (worker
: Worker
): WorkerInfo
{
1170 return { id
: this.getWorkerId(worker
), dynamic
: false, started
: true }