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
,
305 * Gets the approximate pool utilization.
307 * @returns The pool utilization.
309 private get
utilization (): number {
310 const poolRunTimeCapacity
=
311 (performance
.now() - this.startTimestamp
) * this.maxSize
312 const totalTasksRunTime
= this.workerNodes
.reduce(
313 (accumulator
, workerNode
) =>
314 accumulator
+ workerNode
.usage
.runTime
.aggregate
,
317 const totalTasksWaitTime
= this.workerNodes
.reduce(
318 (accumulator
, workerNode
) =>
319 accumulator
+ workerNode
.usage
.waitTime
.aggregate
,
322 return (totalTasksRunTime
+ totalTasksWaitTime
) / poolRunTimeCapacity
328 * If it is `'dynamic'`, it provides the `max` property.
330 protected abstract get
type (): PoolType
333 * Gets the worker type.
335 protected abstract get
worker (): WorkerType
340 protected abstract get
minSize (): number
345 protected abstract get
maxSize (): number
348 * Get the worker given its id.
350 * @param workerId - The worker id.
351 * @returns The worker if found in the pool worker nodes, `undefined` otherwise.
353 private getWorkerById (workerId
: number): Worker
| undefined {
354 return this.workerNodes
.find(workerNode
=> workerNode
.info
.id
=== workerId
)
359 * Gets the given worker its worker node key.
361 * @param worker - The worker.
362 * @returns The worker node key if found in the pool worker nodes, `-1` otherwise.
364 private getWorkerNodeKey (worker
: Worker
): number {
365 return this.workerNodes
.findIndex(
366 workerNode
=> workerNode
.worker
=== worker
371 public setWorkerChoiceStrategy (
372 workerChoiceStrategy
: WorkerChoiceStrategy
,
373 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
375 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
376 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
377 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
378 this.opts
.workerChoiceStrategy
380 if (workerChoiceStrategyOptions
!= null) {
381 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
383 for (const workerNode
of this.workerNodes
) {
384 this.setWorkerNodeTasksUsage(
386 this.getInitialWorkerUsage(workerNode
.worker
)
388 this.setWorkerStatistics(workerNode
.worker
)
393 public setWorkerChoiceStrategyOptions (
394 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
396 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
397 this.opts
.workerChoiceStrategyOptions
= workerChoiceStrategyOptions
398 this.workerChoiceStrategyContext
.setOptions(
399 this.opts
.workerChoiceStrategyOptions
404 public enableTasksQueue (
406 tasksQueueOptions
?: TasksQueueOptions
408 if (this.opts
.enableTasksQueue
=== true && !enable
) {
409 this.flushTasksQueues()
411 this.opts
.enableTasksQueue
= enable
412 this.setTasksQueueOptions(tasksQueueOptions
as TasksQueueOptions
)
416 public setTasksQueueOptions (tasksQueueOptions
: TasksQueueOptions
): void {
417 if (this.opts
.enableTasksQueue
=== true) {
418 this.checkValidTasksQueueOptions(tasksQueueOptions
)
419 this.opts
.tasksQueueOptions
=
420 this.buildTasksQueueOptions(tasksQueueOptions
)
421 } else if (this.opts
.tasksQueueOptions
!= null) {
422 delete this.opts
.tasksQueueOptions
426 private buildTasksQueueOptions (
427 tasksQueueOptions
: TasksQueueOptions
428 ): TasksQueueOptions
{
430 concurrency
: tasksQueueOptions
?.concurrency
?? 1
435 * Whether the pool is full or not.
437 * The pool filling boolean status.
439 protected get
full (): boolean {
440 return this.workerNodes
.length
>= this.maxSize
444 * Whether the pool is busy or not.
446 * The pool busyness boolean status.
448 protected abstract get
busy (): boolean
451 * Whether worker nodes are executing at least one task.
453 * @returns Worker nodes busyness boolean status.
455 protected internalBusy (): boolean {
457 this.workerNodes
.findIndex(workerNode
=> {
458 return workerNode
.usage
.tasks
.executing
=== 0
464 public async execute (data
?: Data
, name
?: string): Promise
<Response
> {
465 const timestamp
= performance
.now()
466 const workerNodeKey
= this.chooseWorkerNode()
467 const submittedTask
: Task
<Data
> = {
469 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
470 data
: data
?? ({} as Data
),
474 const res
= new Promise
<Response
>((resolve
, reject
) => {
475 this.promiseResponseMap
.set(submittedTask
.id
as string, {
478 worker
: this.workerNodes
[workerNodeKey
].worker
482 this.opts
.enableTasksQueue
=== true &&
484 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
>=
485 ((this.opts
.tasksQueueOptions
as TasksQueueOptions
)
486 .concurrency
as number))
488 this.enqueueTask(workerNodeKey
, submittedTask
)
490 this.executeTask(workerNodeKey
, submittedTask
)
492 this.checkAndEmitEvents()
493 // eslint-disable-next-line @typescript-eslint/return-await
498 public async destroy (): Promise
<void> {
500 this.workerNodes
.map(async (workerNode
, workerNodeKey
) => {
501 this.flushTasksQueue(workerNodeKey
)
502 // FIXME: wait for tasks to be finished
503 const workerExitPromise
= new Promise
<void>(resolve
=> {
504 workerNode
.worker
.on('exit', () => {
508 await this.destroyWorker(workerNode
.worker
)
509 await workerExitPromise
515 * Terminates the given worker.
517 * @param worker - A worker within `workerNodes`.
519 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
522 * Setup hook to execute code before worker nodes are created in the abstract constructor.
527 protected setupHook (): void {
528 // Intentionally empty
532 * Should return whether the worker is the main worker or not.
534 protected abstract isMain (): boolean
537 * Hook executed before the worker task execution.
540 * @param workerNodeKey - The worker node key.
541 * @param task - The task to execute.
543 protected beforeTaskExecutionHook (
544 workerNodeKey
: number,
547 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
548 ++workerUsage
.tasks
.executing
549 this.updateWaitTimeWorkerUsage(workerUsage
, task
)
553 * Hook executed after the worker task execution.
556 * @param worker - The worker.
557 * @param message - The received message.
559 protected afterTaskExecutionHook (
561 message
: MessageValue
<Response
>
563 const workerUsage
= this.workerNodes
[this.getWorkerNodeKey(worker
)].usage
564 this.updateTaskStatisticsWorkerUsage(workerUsage
, message
)
565 this.updateRunTimeWorkerUsage(workerUsage
, message
)
566 this.updateEluWorkerUsage(workerUsage
, message
)
569 private updateTaskStatisticsWorkerUsage (
570 workerUsage
: WorkerUsage
,
571 message
: MessageValue
<Response
>
573 const workerTaskStatistics
= workerUsage
.tasks
574 --workerTaskStatistics
.executing
575 ++workerTaskStatistics
.executed
576 if (message
.taskError
!= null) {
577 ++workerTaskStatistics
.failed
581 private updateRunTimeWorkerUsage (
582 workerUsage
: WorkerUsage
,
583 message
: MessageValue
<Response
>
586 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
589 const taskRunTime
= message
.taskPerformance
?.runTime
?? 0
590 workerUsage
.runTime
.aggregate
+= taskRunTime
591 workerUsage
.runTime
.minimum
= Math.min(
593 workerUsage
.runTime
.minimum
?? Infinity
595 workerUsage
.runTime
.maximum
= Math.max(
597 workerUsage
.runTime
.maximum
?? -Infinity
600 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
602 workerUsage
.tasks
.executed
!== 0
604 workerUsage
.runTime
.average
=
605 workerUsage
.runTime
.aggregate
/
606 (workerUsage
.tasks
.executed
- workerUsage
.tasks
.failed
)
609 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
611 message
.taskPerformance
?.runTime
!= null
613 workerUsage
.runTime
.history
.push(message
.taskPerformance
.runTime
)
614 workerUsage
.runTime
.median
= median(workerUsage
.runTime
.history
)
619 private updateWaitTimeWorkerUsage (
620 workerUsage
: WorkerUsage
,
623 const timestamp
= performance
.now()
624 const taskWaitTime
= timestamp
- (task
.timestamp
?? timestamp
)
626 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().waitTime
629 workerUsage
.waitTime
.aggregate
+= taskWaitTime
630 workerUsage
.waitTime
.minimum
= Math.min(
632 workerUsage
.waitTime
.minimum
?? Infinity
634 workerUsage
.waitTime
.maximum
= Math.max(
636 workerUsage
.waitTime
.maximum
?? -Infinity
639 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
641 workerUsage
.tasks
.executed
!== 0
643 workerUsage
.waitTime
.average
=
644 workerUsage
.waitTime
.aggregate
/
645 (workerUsage
.tasks
.executed
- workerUsage
.tasks
.failed
)
648 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
652 workerUsage
.waitTime
.history
.push(taskWaitTime
)
653 workerUsage
.waitTime
.median
= median(workerUsage
.waitTime
.history
)
658 private updateEluWorkerUsage (
659 workerUsage
: WorkerUsage
,
660 message
: MessageValue
<Response
>
663 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
666 if (message
.taskPerformance
?.elu
!= null) {
667 workerUsage
.elu
.idle
.aggregate
+= message
.taskPerformance
.elu
.idle
668 workerUsage
.elu
.active
.aggregate
+= message
.taskPerformance
.elu
.active
669 if (workerUsage
.elu
.utilization
!= null) {
670 workerUsage
.elu
.utilization
=
671 (workerUsage
.elu
.utilization
+
672 message
.taskPerformance
.elu
.utilization
) /
675 workerUsage
.elu
.utilization
= message
.taskPerformance
.elu
.utilization
677 workerUsage
.elu
.idle
.minimum
= Math.min(
678 message
.taskPerformance
.elu
.idle
,
679 workerUsage
.elu
.idle
.minimum
?? Infinity
681 workerUsage
.elu
.idle
.maximum
= Math.max(
682 message
.taskPerformance
.elu
.idle
,
683 workerUsage
.elu
.idle
.maximum
?? -Infinity
685 workerUsage
.elu
.active
.minimum
= Math.min(
686 message
.taskPerformance
.elu
.active
,
687 workerUsage
.elu
.active
.minimum
?? Infinity
689 workerUsage
.elu
.active
.maximum
= Math.max(
690 message
.taskPerformance
.elu
.active
,
691 workerUsage
.elu
.active
.maximum
?? -Infinity
695 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
697 workerUsage
.tasks
.executed
!== 0
699 const executedTasks
=
700 workerUsage
.tasks
.executed
- workerUsage
.tasks
.failed
701 workerUsage
.elu
.idle
.average
=
702 workerUsage
.elu
.idle
.aggregate
/ executedTasks
703 workerUsage
.elu
.active
.average
=
704 workerUsage
.elu
.active
.aggregate
/ executedTasks
707 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
709 message
.taskPerformance
?.elu
!= null
711 workerUsage
.elu
.idle
.history
.push(message
.taskPerformance
.elu
.idle
)
712 workerUsage
.elu
.active
.history
.push(message
.taskPerformance
.elu
.active
)
713 workerUsage
.elu
.idle
.median
= median(workerUsage
.elu
.idle
.history
)
714 workerUsage
.elu
.active
.median
= median(workerUsage
.elu
.active
.history
)
720 * Chooses a worker node for the next task.
722 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
724 * @returns The worker node key
726 private chooseWorkerNode (): number {
727 if (this.shallCreateDynamicWorker()) {
728 const worker
= this.createAndSetupDynamicWorker()
730 this.workerChoiceStrategyContext
.getStrategyPolicy().useDynamicWorker
732 return this.getWorkerNodeKey(worker
)
735 return this.workerChoiceStrategyContext
.execute()
739 * Conditions for dynamic worker creation.
741 * @returns Whether to create a dynamic worker or not.
743 private shallCreateDynamicWorker (): boolean {
744 return this.type === PoolTypes
.dynamic
&& !this.full
&& this.internalBusy()
748 * Sends a message to the given worker.
750 * @param worker - The worker which should receive the message.
751 * @param message - The message.
753 protected abstract sendToWorker (
755 message
: MessageValue
<Data
>
759 * Registers a listener callback on the given worker.
761 * @param worker - The worker which should register a listener.
762 * @param listener - The message listener callback.
764 private registerWorkerMessageListener
<Message
extends Data
| Response
>(
766 listener
: (message
: MessageValue
<Message
>) => void
768 worker
.on('message', listener
as MessageHandler
<Worker
>)
772 * Creates a new worker.
774 * @returns Newly created worker.
776 protected abstract createWorker (): Worker
779 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
782 * @param worker - The newly created worker.
784 protected afterWorkerSetup (worker
: Worker
): void {
785 // Listen to worker messages.
786 this.registerWorkerMessageListener(worker
, this.workerListener())
790 * Creates a new worker and sets it up completely in the pool worker nodes.
792 * @returns New, completely set up worker.
794 protected createAndSetupWorker (): Worker
{
795 const worker
= this.createWorker()
797 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
798 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
799 worker
.on('error', error
=> {
800 if (this.emitter
!= null) {
801 this.emitter
.emit(PoolEvents
.error
, error
)
803 if (this.opts
.enableTasksQueue
=== true) {
804 const workerNodeKey
= this.getWorkerNodeKey(worker
)
805 while (this.tasksQueueSize(workerNodeKey
) > 0) {
806 let targetWorkerNodeKey
: number = workerNodeKey
807 let minQueuedTasks
= Infinity
808 for (const [workerNodeId
, workerNode
] of this.workerNodes
.entries()) {
810 workerNodeId
!== workerNodeKey
&&
811 workerNode
.usage
.tasks
.queued
=== 0
813 targetWorkerNodeKey
= workerNodeId
817 workerNodeId
!== workerNodeKey
&&
818 workerNode
.usage
.tasks
.queued
< minQueuedTasks
820 minQueuedTasks
= workerNode
.usage
.tasks
.queued
821 targetWorkerNodeKey
= workerNodeId
826 this.dequeueTask(workerNodeKey
) as Task
<Data
>
830 if (this.opts
.restartWorkerOnError
=== true) {
831 if (this.getWorkerInfo(this.getWorkerNodeKey(worker
)).dynamic
) {
832 this.createAndSetupDynamicWorker()
834 this.createAndSetupWorker()
838 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
839 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
840 worker
.once('exit', () => {
841 this.removeWorkerNode(worker
)
844 this.pushWorkerNode(worker
)
846 this.setWorkerStatistics(worker
)
848 this.afterWorkerSetup(worker
)
854 * Creates a new dynamic worker and sets it up completely in the pool worker nodes.
856 * @returns New, completely set up dynamic worker.
858 protected createAndSetupDynamicWorker (): Worker
{
859 const worker
= this.createAndSetupWorker()
860 this.getWorkerInfo(this.getWorkerNodeKey(worker
)).dynamic
= true
861 this.registerWorkerMessageListener(worker
, message
=> {
862 const workerNodeKey
= this.getWorkerNodeKey(worker
)
864 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
865 (message
.kill
!= null &&
866 ((this.opts
.enableTasksQueue
=== false &&
867 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
=== 0) ||
868 (this.opts
.enableTasksQueue
=== true &&
869 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
=== 0 &&
870 this.tasksQueueSize(workerNodeKey
) === 0)))
872 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
873 void (this.destroyWorker(worker
) as Promise
<void>)
880 * This function is the listener registered for each worker message.
882 * @returns The listener function to execute when a message is received from a worker.
884 protected workerListener (): (message
: MessageValue
<Response
>) => void {
886 if (message
.workerId
!= null && message
.started
!= null) {
887 // Worker started message received
888 this.handleWorkerStartedMessage(message
)
889 } else if (message
.id
!= null) {
890 // Task execution response received
891 this.handleTaskExecutionResponse(message
)
896 private handleWorkerStartedMessage (message
: MessageValue
<Response
>): void {
897 // Worker started message received
898 const worker
= this.getWorkerById(message
.workerId
as number)
899 if (worker
!= null) {
900 this.workerNodes
[this.getWorkerNodeKey(worker
)].info
.started
=
901 message
.started
as boolean
904 `Worker started message received from unknown worker '${
905 message.workerId as number
911 private handleTaskExecutionResponse (message
: MessageValue
<Response
>): void {
912 const promiseResponse
= this.promiseResponseMap
.get(message
.id
as string)
913 if (promiseResponse
!= null) {
914 if (message
.taskError
!= null) {
915 if (this.emitter
!= null) {
916 this.emitter
.emit(PoolEvents
.taskError
, message
.taskError
)
918 promiseResponse
.reject(message
.taskError
.message
)
920 promiseResponse
.resolve(message
.data
as Response
)
922 this.afterTaskExecutionHook(promiseResponse
.worker
, message
)
923 this.promiseResponseMap
.delete(message
.id
as string)
924 const workerNodeKey
= this.getWorkerNodeKey(promiseResponse
.worker
)
926 this.opts
.enableTasksQueue
=== true &&
927 this.tasksQueueSize(workerNodeKey
) > 0
931 this.dequeueTask(workerNodeKey
) as Task
<Data
>
934 this.workerChoiceStrategyContext
.update(workerNodeKey
)
938 private checkAndEmitEvents (): void {
939 if (this.emitter
!= null) {
941 this.emitter
.emit(PoolEvents
.busy
, this.info
)
943 if (this.type === PoolTypes
.dynamic
&& this.full
) {
944 this.emitter
.emit(PoolEvents
.full
, this.info
)
950 * Sets the given worker node its tasks usage in the pool.
952 * @param workerNode - The worker node.
953 * @param workerUsage - The worker usage.
955 private setWorkerNodeTasksUsage (
956 workerNode
: WorkerNode
<Worker
, Data
>,
957 workerUsage
: WorkerUsage
959 workerNode
.usage
= workerUsage
963 * Gets the worker information.
965 * @param workerNodeKey - The worker node key.
967 private getWorkerInfo (workerNodeKey
: number): WorkerInfo
{
968 return this.workerNodes
[workerNodeKey
].info
972 * Pushes the given worker in the pool worker nodes.
974 * @param worker - The worker.
975 * @returns The worker nodes length.
977 private pushWorkerNode (worker
: Worker
): number {
978 this.workerNodes
.push({
980 info
: this.getInitialWorkerInfo(worker
),
981 usage
: this.getInitialWorkerUsage(),
982 tasksQueue
: new Queue
<Task
<Data
>>()
984 this.setWorkerNodeTasksUsage(
985 this.workerNodes
[this.getWorkerNodeKey(worker
)],
986 this.getInitialWorkerUsage(worker
)
988 return this.workerNodes
.length
992 * Gets the worker id.
994 * @param worker - The worker.
995 * @returns The worker id.
997 private getWorkerId (worker
: Worker
): number | undefined {
998 if (this.worker
=== WorkerTypes
.thread
) {
999 return worker
.threadId
1000 } else if (this.worker
=== WorkerTypes
.cluster
) {
1006 // * Sets the given worker in the pool worker nodes.
1008 // * @param workerNodeKey - The worker node key.
1009 // * @param worker - The worker.
1010 // * @param workerInfo - The worker info.
1011 // * @param workerUsage - The worker usage.
1012 // * @param tasksQueue - The worker task queue.
1014 // private setWorkerNode (
1015 // workerNodeKey: number,
1017 // workerInfo: WorkerInfo,
1018 // workerUsage: WorkerUsage,
1019 // tasksQueue: Queue<Task<Data>>
1021 // this.workerNodes[workerNodeKey] = {
1023 // info: workerInfo,
1024 // usage: workerUsage,
1030 * Removes the given worker from the pool worker nodes.
1032 * @param worker - The worker.
1034 private removeWorkerNode (worker
: Worker
): void {
1035 const workerNodeKey
= this.getWorkerNodeKey(worker
)
1036 if (workerNodeKey
!== -1) {
1037 this.workerNodes
.splice(workerNodeKey
, 1)
1038 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
1042 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
1043 this.beforeTaskExecutionHook(workerNodeKey
, task
)
1044 this.sendToWorker(this.workerNodes
[workerNodeKey
].worker
, task
)
1047 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
1048 return this.workerNodes
[workerNodeKey
].tasksQueue
.enqueue(task
)
1051 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
1052 return this.workerNodes
[workerNodeKey
].tasksQueue
.dequeue()
1055 private tasksQueueSize (workerNodeKey
: number): number {
1056 return this.workerNodes
[workerNodeKey
].tasksQueue
.size
1059 private tasksMaxQueueSize (workerNodeKey
: number): number {
1060 return this.workerNodes
[workerNodeKey
].tasksQueue
.maxSize
1063 private flushTasksQueue (workerNodeKey
: number): void {
1064 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1067 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1070 this.workerNodes
[workerNodeKey
].tasksQueue
.clear()
1073 private flushTasksQueues (): void {
1074 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
1075 this.flushTasksQueue(workerNodeKey
)
1079 private setWorkerStatistics (worker
: Worker
): void {
1080 this.sendToWorker(worker
, {
1083 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1085 elu
: this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1091 private getInitialWorkerUsage (worker
?: Worker
): WorkerUsage
{
1092 const getTasksQueueSize
= (worker
?: Worker
): number => {
1093 return worker
!= null
1094 ? this.tasksQueueSize(this.getWorkerNodeKey(worker
))
1097 const getTasksMaxQueueSize
= (worker
?: Worker
): number => {
1098 return worker
!= null
1099 ? this.tasksMaxQueueSize(this.getWorkerNodeKey(worker
))
1106 get
queued (): number {
1107 return getTasksQueueSize(worker
)
1109 get
maxQueued (): number {
1110 return getTasksMaxQueueSize(worker
)
1120 history
: new CircularArray()
1128 history
: new CircularArray()
1137 history
: new CircularArray()
1145 history
: new CircularArray()
1151 private getInitialWorkerInfo (worker
: Worker
): WorkerInfo
{
1152 return { id
: this.getWorkerId(worker
), dynamic
: false, started
: true }