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
743 message
.taskPerformance
?.elu
!= null
745 workerUsage
.elu
.idle
.history
.push(message
.taskPerformance
.elu
.idle
)
746 workerUsage
.elu
.active
.history
.push(
747 message
.taskPerformance
.elu
.active
749 workerUsage
.elu
.idle
.median
= median(workerUsage
.elu
.idle
.history
)
750 workerUsage
.elu
.active
.median
= median(workerUsage
.elu
.active
.history
)
757 * Chooses a worker node for the next task.
759 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
761 * @returns The worker node key
763 private chooseWorkerNode (): number {
764 if (this.shallCreateDynamicWorker()) {
765 const worker
= this.createAndSetupDynamicWorker()
767 this.workerChoiceStrategyContext
.getStrategyPolicy().useDynamicWorker
769 return this.getWorkerNodeKey(worker
)
772 return this.workerChoiceStrategyContext
.execute()
776 * Conditions for dynamic worker creation.
778 * @returns Whether to create a dynamic worker or not.
780 private shallCreateDynamicWorker (): boolean {
781 return this.type === PoolTypes
.dynamic
&& !this.full
&& this.internalBusy()
785 * Sends a message to the given worker.
787 * @param worker - The worker which should receive the message.
788 * @param message - The message.
790 protected abstract sendToWorker (
792 message
: MessageValue
<Data
>
796 * Registers a listener callback on the given worker.
798 * @param worker - The worker which should register a listener.
799 * @param listener - The message listener callback.
801 private registerWorkerMessageListener
<Message
extends Data
| Response
>(
803 listener
: (message
: MessageValue
<Message
>) => void
805 worker
.on('message', listener
as MessageHandler
<Worker
>)
809 * Creates a new worker.
811 * @returns Newly created worker.
813 protected abstract createWorker (): Worker
816 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
819 * @param worker - The newly created worker.
821 protected afterWorkerSetup (worker
: Worker
): void {
822 // Listen to worker messages.
823 this.registerWorkerMessageListener(worker
, this.workerListener())
827 * Creates a new worker and sets it up completely in the pool worker nodes.
829 * @returns New, completely set up worker.
831 protected createAndSetupWorker (): Worker
{
832 const worker
= this.createWorker()
834 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
835 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
836 worker
.on('error', error
=> {
837 if (this.emitter
!= null) {
838 this.emitter
.emit(PoolEvents
.error
, error
)
840 if (this.opts
.enableTasksQueue
=== true) {
841 const workerNodeKey
= this.getWorkerNodeKey(worker
)
842 while (this.tasksQueueSize(workerNodeKey
) > 0) {
843 let targetWorkerNodeKey
: number = workerNodeKey
844 let minQueuedTasks
= Infinity
845 for (const [workerNodeId
, workerNode
] of this.workerNodes
.entries()) {
847 workerNodeId
!== workerNodeKey
&&
848 workerNode
.usage
.tasks
.queued
=== 0
850 targetWorkerNodeKey
= workerNodeId
854 workerNodeId
!== workerNodeKey
&&
855 workerNode
.usage
.tasks
.queued
< minQueuedTasks
857 minQueuedTasks
= workerNode
.usage
.tasks
.queued
858 targetWorkerNodeKey
= workerNodeId
863 this.dequeueTask(workerNodeKey
) as Task
<Data
>
867 if (this.opts
.restartWorkerOnError
=== true) {
868 if (this.getWorkerInfo(this.getWorkerNodeKey(worker
)).dynamic
) {
869 this.createAndSetupDynamicWorker()
871 this.createAndSetupWorker()
875 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
876 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
877 worker
.once('exit', () => {
878 this.removeWorkerNode(worker
)
881 this.pushWorkerNode(worker
)
883 this.setWorkerStatistics(worker
)
885 this.afterWorkerSetup(worker
)
891 * Creates a new dynamic worker and sets it up completely in the pool worker nodes.
893 * @returns New, completely set up dynamic worker.
895 protected createAndSetupDynamicWorker (): Worker
{
896 const worker
= this.createAndSetupWorker()
897 this.getWorkerInfo(this.getWorkerNodeKey(worker
)).dynamic
= true
898 this.registerWorkerMessageListener(worker
, message
=> {
899 const workerNodeKey
= this.getWorkerNodeKey(worker
)
901 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
902 (message
.kill
!= null &&
903 ((this.opts
.enableTasksQueue
=== false &&
904 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
=== 0) ||
905 (this.opts
.enableTasksQueue
=== true &&
906 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
=== 0 &&
907 this.tasksQueueSize(workerNodeKey
) === 0)))
909 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
910 void (this.destroyWorker(worker
) as Promise
<void>)
917 * This function is the listener registered for each worker message.
919 * @returns The listener function to execute when a message is received from a worker.
921 protected workerListener (): (message
: MessageValue
<Response
>) => void {
923 if (message
.workerId
!= null && message
.started
!= null) {
924 // Worker started message received
925 this.handleWorkerStartedMessage(message
)
926 } else if (message
.id
!= null) {
927 // Task execution response received
928 this.handleTaskExecutionResponse(message
)
933 private handleWorkerStartedMessage (message
: MessageValue
<Response
>): void {
934 // Worker started message received
935 const worker
= this.getWorkerById(message
.workerId
as number)
936 if (worker
!= null) {
937 this.workerNodes
[this.getWorkerNodeKey(worker
)].info
.started
=
938 message
.started
as boolean
941 `Worker started message received from unknown worker '${
942 message.workerId as number
948 private handleTaskExecutionResponse (message
: MessageValue
<Response
>): void {
949 const promiseResponse
= this.promiseResponseMap
.get(message
.id
as string)
950 if (promiseResponse
!= null) {
951 if (message
.taskError
!= null) {
952 if (this.emitter
!= null) {
953 this.emitter
.emit(PoolEvents
.taskError
, message
.taskError
)
955 promiseResponse
.reject(message
.taskError
.message
)
957 promiseResponse
.resolve(message
.data
as Response
)
959 this.afterTaskExecutionHook(promiseResponse
.worker
, message
)
960 this.promiseResponseMap
.delete(message
.id
as string)
961 const workerNodeKey
= this.getWorkerNodeKey(promiseResponse
.worker
)
963 this.opts
.enableTasksQueue
=== true &&
964 this.tasksQueueSize(workerNodeKey
) > 0
968 this.dequeueTask(workerNodeKey
) as Task
<Data
>
971 this.workerChoiceStrategyContext
.update(workerNodeKey
)
975 private checkAndEmitEvents (): void {
976 if (this.emitter
!= null) {
978 this.emitter
.emit(PoolEvents
.busy
, this.info
)
980 if (this.type === PoolTypes
.dynamic
&& this.full
) {
981 this.emitter
.emit(PoolEvents
.full
, this.info
)
987 * Sets the given worker node its tasks usage in the pool.
989 * @param workerNode - The worker node.
990 * @param workerUsage - The worker usage.
992 private setWorkerNodeTasksUsage (
993 workerNode
: WorkerNode
<Worker
, Data
>,
994 workerUsage
: WorkerUsage
996 workerNode
.usage
= workerUsage
1000 * Gets the worker information.
1002 * @param workerNodeKey - The worker node key.
1004 private getWorkerInfo (workerNodeKey
: number): WorkerInfo
{
1005 return this.workerNodes
[workerNodeKey
].info
1009 * Pushes the given worker in the pool worker nodes.
1011 * @param worker - The worker.
1012 * @returns The worker nodes length.
1014 private pushWorkerNode (worker
: Worker
): number {
1015 this.workerNodes
.push({
1017 info
: this.getInitialWorkerInfo(worker
),
1018 usage
: this.getInitialWorkerUsage(),
1019 tasksQueue
: new Queue
<Task
<Data
>>()
1021 this.setWorkerNodeTasksUsage(
1022 this.workerNodes
[this.getWorkerNodeKey(worker
)],
1023 this.getInitialWorkerUsage(worker
)
1025 return this.workerNodes
.length
1029 * Gets the worker id.
1031 * @param worker - The worker.
1032 * @returns The worker id.
1034 private getWorkerId (worker
: Worker
): number | undefined {
1035 if (this.worker
=== WorkerTypes
.thread
) {
1036 return worker
.threadId
1037 } else if (this.worker
=== WorkerTypes
.cluster
) {
1043 // * Sets the given worker in the pool worker nodes.
1045 // * @param workerNodeKey - The worker node key.
1046 // * @param worker - The worker.
1047 // * @param workerInfo - The worker info.
1048 // * @param workerUsage - The worker usage.
1049 // * @param tasksQueue - The worker task queue.
1051 // private setWorkerNode (
1052 // workerNodeKey: number,
1054 // workerInfo: WorkerInfo,
1055 // workerUsage: WorkerUsage,
1056 // tasksQueue: Queue<Task<Data>>
1058 // this.workerNodes[workerNodeKey] = {
1060 // info: workerInfo,
1061 // usage: workerUsage,
1067 * Removes the given worker from the pool worker nodes.
1069 * @param worker - The worker.
1071 private removeWorkerNode (worker
: Worker
): void {
1072 const workerNodeKey
= this.getWorkerNodeKey(worker
)
1073 if (workerNodeKey
!== -1) {
1074 this.workerNodes
.splice(workerNodeKey
, 1)
1075 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
1079 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
1080 this.beforeTaskExecutionHook(workerNodeKey
, task
)
1081 this.sendToWorker(this.workerNodes
[workerNodeKey
].worker
, task
)
1084 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
1085 return this.workerNodes
[workerNodeKey
].tasksQueue
.enqueue(task
)
1088 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
1089 return this.workerNodes
[workerNodeKey
].tasksQueue
.dequeue()
1092 private tasksQueueSize (workerNodeKey
: number): number {
1093 return this.workerNodes
[workerNodeKey
].tasksQueue
.size
1096 private tasksMaxQueueSize (workerNodeKey
: number): number {
1097 return this.workerNodes
[workerNodeKey
].tasksQueue
.maxSize
1100 private flushTasksQueue (workerNodeKey
: number): void {
1101 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1104 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1107 this.workerNodes
[workerNodeKey
].tasksQueue
.clear()
1110 private flushTasksQueues (): void {
1111 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
1112 this.flushTasksQueue(workerNodeKey
)
1116 private setWorkerStatistics (worker
: Worker
): void {
1117 this.sendToWorker(worker
, {
1120 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1122 elu
: this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1128 private getInitialWorkerUsage (worker
?: Worker
): WorkerUsage
{
1129 const getTasksQueueSize
= (worker
?: Worker
): number => {
1130 if (worker
== null) {
1133 return this.tasksQueueSize(this.getWorkerNodeKey(worker
))
1135 const getTasksMaxQueueSize
= (worker
?: Worker
): number => {
1136 if (worker
== null) {
1139 return this.tasksMaxQueueSize(this.getWorkerNodeKey(worker
))
1145 get
queued (): number {
1146 return getTasksQueueSize(worker
)
1148 get
maxQueued (): number {
1149 return getTasksMaxQueueSize(worker
)
1154 history
: new CircularArray()
1157 history
: new CircularArray()
1161 history
: new CircularArray()
1164 history
: new CircularArray()
1170 private getInitialWorkerInfo (worker
: Worker
): WorkerInfo
{
1171 return { id
: this.getWorkerId(worker
), dynamic
: false, started
: true }