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'
21 type TasksQueueOptions
34 WorkerChoiceStrategies
,
35 type WorkerChoiceStrategy
,
36 type WorkerChoiceStrategyOptions
37 } from
'./selection-strategies/selection-strategies-types'
38 import { WorkerChoiceStrategyContext
} from
'./selection-strategies/worker-choice-strategy-context'
39 import { version
} from
'./version'
40 import { WorkerNode
} from
'./worker-node'
43 * Base class that implements some shared logic for all poolifier pools.
45 * @typeParam Worker - Type of worker which manages this pool.
46 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
47 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
49 export abstract class AbstractPool
<
50 Worker
extends IWorker
,
53 > implements IPool
<Worker
, Data
, Response
> {
55 public readonly workerNodes
: Array<IWorkerNode
<Worker
, Data
>> = []
58 public readonly emitter
?: PoolEmitter
61 * The execution response promise map.
63 * - `key`: The message id of each submitted task.
64 * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks.
66 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
68 protected promiseResponseMap
: Map
<
70 PromiseResponseWrapper
<Worker
, Response
>
71 > = new Map
<string, PromiseResponseWrapper
<Worker
, Response
>>()
74 * Worker choice strategy context referencing a worker choice algorithm implementation.
76 protected workerChoiceStrategyContext
: WorkerChoiceStrategyContext
<
83 * The start timestamp of the pool.
85 private readonly startTimestamp
88 * Constructs a new poolifier pool.
90 * @param numberOfWorkers - Number of workers that this pool should manage.
91 * @param filePath - Path to the worker file.
92 * @param opts - Options for the pool.
95 protected readonly numberOfWorkers
: number,
96 protected readonly filePath
: string,
97 protected readonly opts
: PoolOptions
<Worker
>
100 throw new Error('Cannot start a pool from a worker!')
102 this.checkNumberOfWorkers(this.numberOfWorkers
)
103 this.checkFilePath(this.filePath
)
104 this.checkPoolOptions(this.opts
)
106 this.chooseWorkerNode
= this.chooseWorkerNode
.bind(this)
107 this.executeTask
= this.executeTask
.bind(this)
108 this.enqueueTask
= this.enqueueTask
.bind(this)
109 this.checkAndEmitEvents
= this.checkAndEmitEvents
.bind(this)
111 if (this.opts
.enableEvents
=== true) {
112 this.emitter
= new PoolEmitter()
114 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext
<
120 this.opts
.workerChoiceStrategy
,
121 this.opts
.workerChoiceStrategyOptions
126 while (this.workerNodes
.length
< this.numberOfWorkers
) {
127 this.createAndSetupWorker()
130 this.startTimestamp
= performance
.now()
133 private checkFilePath (filePath
: string): void {
136 (typeof filePath
=== 'string' && filePath
.trim().length
=== 0)
138 throw new Error('Please specify a file with a worker implementation')
142 private checkNumberOfWorkers (numberOfWorkers
: number): void {
143 if (numberOfWorkers
== null) {
145 'Cannot instantiate a pool without specifying the number of workers'
147 } else if (!Number.isSafeInteger(numberOfWorkers
)) {
149 'Cannot instantiate a pool with a non safe integer number of workers'
151 } else if (numberOfWorkers
< 0) {
152 throw new RangeError(
153 'Cannot instantiate a pool with a negative number of workers'
155 } else if (this.type === PoolTypes
.fixed
&& numberOfWorkers
=== 0) {
156 throw new RangeError('Cannot instantiate a fixed pool with zero worker')
160 protected checkDynamicPoolSize (min
: number, max
: number): void {
161 if (this.type === PoolTypes
.dynamic
&& min
> max
) {
162 throw new RangeError(
163 'Cannot instantiate a dynamic pool with a maximum pool size inferior to the minimum pool size'
165 } else if (this.type === PoolTypes
.dynamic
&& min
=== max
) {
166 throw new RangeError(
167 'Cannot instantiate a dynamic pool with a minimum pool size equal to the maximum pool size. Use a fixed pool instead'
172 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
173 if (isPlainObject(opts
)) {
174 this.opts
.workerChoiceStrategy
=
175 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
176 this.checkValidWorkerChoiceStrategy(this.opts
.workerChoiceStrategy
)
177 this.opts
.workerChoiceStrategyOptions
=
178 opts
.workerChoiceStrategyOptions
??
179 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
180 this.checkValidWorkerChoiceStrategyOptions(
181 this.opts
.workerChoiceStrategyOptions
183 this.opts
.restartWorkerOnError
= opts
.restartWorkerOnError
?? true
184 this.opts
.enableEvents
= opts
.enableEvents
?? true
185 this.opts
.enableTasksQueue
= opts
.enableTasksQueue
?? false
186 if (this.opts
.enableTasksQueue
) {
187 this.checkValidTasksQueueOptions(
188 opts
.tasksQueueOptions
as TasksQueueOptions
190 this.opts
.tasksQueueOptions
= this.buildTasksQueueOptions(
191 opts
.tasksQueueOptions
as TasksQueueOptions
195 throw new TypeError('Invalid pool options: must be a plain object')
199 private checkValidWorkerChoiceStrategy (
200 workerChoiceStrategy
: WorkerChoiceStrategy
202 if (!Object.values(WorkerChoiceStrategies
).includes(workerChoiceStrategy
)) {
204 `Invalid worker choice strategy '${workerChoiceStrategy}'`
209 private checkValidWorkerChoiceStrategyOptions (
210 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
212 if (!isPlainObject(workerChoiceStrategyOptions
)) {
214 'Invalid worker choice strategy options: must be a plain object'
218 workerChoiceStrategyOptions
.weights
!= null &&
219 Object.keys(workerChoiceStrategyOptions
.weights
).length
!== this.maxSize
222 'Invalid worker choice strategy options: must have a weight for each worker node'
226 workerChoiceStrategyOptions
.measurement
!= null &&
227 !Object.values(Measurements
).includes(
228 workerChoiceStrategyOptions
.measurement
232 `Invalid worker choice strategy options: invalid measurement '${workerChoiceStrategyOptions.measurement}'`
237 private checkValidTasksQueueOptions (
238 tasksQueueOptions
: TasksQueueOptions
240 if (tasksQueueOptions
!= null && !isPlainObject(tasksQueueOptions
)) {
241 throw new TypeError('Invalid tasks queue options: must be a plain object')
244 tasksQueueOptions
?.concurrency
!= null &&
245 !Number.isSafeInteger(tasksQueueOptions
.concurrency
)
248 'Invalid worker tasks concurrency: must be an integer'
252 tasksQueueOptions
?.concurrency
!= null &&
253 tasksQueueOptions
.concurrency
<= 0
256 `Invalid worker tasks concurrency '${tasksQueueOptions.concurrency}'`
262 public get
info (): PoolInfo
{
268 strategy
: this.opts
.workerChoiceStrategy
as WorkerChoiceStrategy
,
269 minSize
: this.minSize
,
270 maxSize
: this.maxSize
,
271 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
272 .runTime
.aggregate
&&
273 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
274 .waitTime
.aggregate
&& { utilization
: round(this.utilization
) }),
275 workerNodes
: this.workerNodes
.length
,
276 idleWorkerNodes
: this.workerNodes
.reduce(
277 (accumulator
, workerNode
) =>
278 workerNode
.usage
.tasks
.executing
=== 0
283 busyWorkerNodes
: this.workerNodes
.reduce(
284 (accumulator
, workerNode
) =>
285 workerNode
.usage
.tasks
.executing
> 0 ? accumulator
+ 1 : accumulator
,
288 executedTasks
: this.workerNodes
.reduce(
289 (accumulator
, workerNode
) =>
290 accumulator
+ workerNode
.usage
.tasks
.executed
,
293 executingTasks
: this.workerNodes
.reduce(
294 (accumulator
, workerNode
) =>
295 accumulator
+ workerNode
.usage
.tasks
.executing
,
298 queuedTasks
: this.workerNodes
.reduce(
299 (accumulator
, workerNode
) =>
300 accumulator
+ workerNode
.usage
.tasks
.queued
,
303 maxQueuedTasks
: this.workerNodes
.reduce(
304 (accumulator
, workerNode
) =>
305 accumulator
+ workerNode
.usage
.tasks
.maxQueued
,
308 failedTasks
: this.workerNodes
.reduce(
309 (accumulator
, workerNode
) =>
310 accumulator
+ workerNode
.usage
.tasks
.failed
,
313 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
314 .runTime
.aggregate
&& {
318 ...this.workerNodes
.map(
319 workerNode
=> workerNode
.usage
.runTime
?.minimum
?? Infinity
325 ...this.workerNodes
.map(
326 workerNode
=> workerNode
.usage
.runTime
?.maximum
?? -Infinity
331 this.workerNodes
.reduce(
332 (accumulator
, workerNode
) =>
333 accumulator
+ (workerNode
.usage
.runTime
?.aggregate
?? 0),
336 this.workerNodes
.reduce(
337 (accumulator
, workerNode
) =>
338 accumulator
+ (workerNode
.usage
.tasks
?.executed
?? 0),
342 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
346 this.workerNodes
.map(
347 workerNode
=> workerNode
.usage
.runTime
?.median
?? 0
354 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
355 .waitTime
.aggregate
&& {
359 ...this.workerNodes
.map(
360 workerNode
=> workerNode
.usage
.waitTime
?.minimum
?? Infinity
366 ...this.workerNodes
.map(
367 workerNode
=> workerNode
.usage
.waitTime
?.maximum
?? -Infinity
372 this.workerNodes
.reduce(
373 (accumulator
, workerNode
) =>
374 accumulator
+ (workerNode
.usage
.waitTime
?.aggregate
?? 0),
377 this.workerNodes
.reduce(
378 (accumulator
, workerNode
) =>
379 accumulator
+ (workerNode
.usage
.tasks
?.executed
?? 0),
383 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
384 .waitTime
.median
&& {
387 this.workerNodes
.map(
388 workerNode
=> workerNode
.usage
.waitTime
?.median
?? 0
398 private get
starting (): boolean {
401 (this.full
&& this.workerNodes
.some(workerNode
=> !workerNode
.info
.ready
))
405 private get
ready (): boolean {
407 this.full
&& this.workerNodes
.every(workerNode
=> workerNode
.info
.ready
)
412 * Gets the approximate pool utilization.
414 * @returns The pool utilization.
416 private get
utilization (): number {
417 const poolRunTimeCapacity
=
418 (performance
.now() - this.startTimestamp
) * this.maxSize
419 const totalTasksRunTime
= this.workerNodes
.reduce(
420 (accumulator
, workerNode
) =>
421 accumulator
+ (workerNode
.usage
.runTime
?.aggregate
?? 0),
424 const totalTasksWaitTime
= this.workerNodes
.reduce(
425 (accumulator
, workerNode
) =>
426 accumulator
+ (workerNode
.usage
.waitTime
?.aggregate
?? 0),
429 return (totalTasksRunTime
+ totalTasksWaitTime
) / poolRunTimeCapacity
435 * If it is `'dynamic'`, it provides the `max` property.
437 protected abstract get
type (): PoolType
440 * Gets the worker type.
442 protected abstract get
worker (): WorkerType
447 protected abstract get
minSize (): number
452 protected abstract get
maxSize (): number
455 * Get the worker given its id.
457 * @param workerId - The worker id.
458 * @returns The worker if found in the pool worker nodes, `undefined` otherwise.
460 private getWorkerById (workerId
: number): Worker
| undefined {
461 return this.workerNodes
.find(workerNode
=> workerNode
.info
.id
=== workerId
)
466 * Gets the given worker its worker node key.
468 * @param worker - The worker.
469 * @returns The worker node key if found in the pool worker nodes, `-1` otherwise.
471 private getWorkerNodeKey (worker
: Worker
): number {
472 return this.workerNodes
.findIndex(
473 workerNode
=> workerNode
.worker
=== worker
478 public setWorkerChoiceStrategy (
479 workerChoiceStrategy
: WorkerChoiceStrategy
,
480 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
482 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
483 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
484 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
485 this.opts
.workerChoiceStrategy
487 if (workerChoiceStrategyOptions
!= null) {
488 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
490 for (const workerNode
of this.workerNodes
) {
491 workerNode
.resetUsage()
492 this.setWorkerStatistics(workerNode
.worker
)
497 public setWorkerChoiceStrategyOptions (
498 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
500 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
501 this.opts
.workerChoiceStrategyOptions
= workerChoiceStrategyOptions
502 this.workerChoiceStrategyContext
.setOptions(
503 this.opts
.workerChoiceStrategyOptions
508 public enableTasksQueue (
510 tasksQueueOptions
?: TasksQueueOptions
512 if (this.opts
.enableTasksQueue
=== true && !enable
) {
513 this.flushTasksQueues()
515 this.opts
.enableTasksQueue
= enable
516 this.setTasksQueueOptions(tasksQueueOptions
as TasksQueueOptions
)
520 public setTasksQueueOptions (tasksQueueOptions
: TasksQueueOptions
): void {
521 if (this.opts
.enableTasksQueue
=== true) {
522 this.checkValidTasksQueueOptions(tasksQueueOptions
)
523 this.opts
.tasksQueueOptions
=
524 this.buildTasksQueueOptions(tasksQueueOptions
)
525 } else if (this.opts
.tasksQueueOptions
!= null) {
526 delete this.opts
.tasksQueueOptions
530 private buildTasksQueueOptions (
531 tasksQueueOptions
: TasksQueueOptions
532 ): TasksQueueOptions
{
534 concurrency
: tasksQueueOptions
?.concurrency
?? 1
539 * Whether the pool is full or not.
541 * The pool filling boolean status.
543 protected get
full (): boolean {
544 return this.workerNodes
.length
>= this.maxSize
548 * Whether the pool is busy or not.
550 * The pool busyness boolean status.
552 protected abstract get
busy (): boolean
555 * Whether worker nodes are executing at least one task.
557 * @returns Worker nodes busyness boolean status.
559 protected internalBusy (): boolean {
561 this.workerNodes
.findIndex(workerNode
=> {
562 return workerNode
.usage
.tasks
.executing
=== 0
568 public async execute (data
?: Data
, name
?: string): Promise
<Response
> {
569 const timestamp
= performance
.now()
570 const workerNodeKey
= this.chooseWorkerNode()
571 const submittedTask
: Task
<Data
> = {
573 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
574 data
: data
?? ({} as Data
),
578 const res
= new Promise
<Response
>((resolve
, reject
) => {
579 this.promiseResponseMap
.set(submittedTask
.id
as string, {
582 worker
: this.workerNodes
[workerNodeKey
].worker
586 this.opts
.enableTasksQueue
=== true &&
588 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
>=
589 ((this.opts
.tasksQueueOptions
as TasksQueueOptions
)
590 .concurrency
as number))
592 this.enqueueTask(workerNodeKey
, submittedTask
)
594 this.executeTask(workerNodeKey
, submittedTask
)
596 this.checkAndEmitEvents()
597 // eslint-disable-next-line @typescript-eslint/return-await
602 public async destroy (): Promise
<void> {
604 this.workerNodes
.map(async (workerNode
, workerNodeKey
) => {
605 this.flushTasksQueue(workerNodeKey
)
606 // FIXME: wait for tasks to be finished
607 const workerExitPromise
= new Promise
<void>(resolve
=> {
608 workerNode
.worker
.on('exit', () => {
612 await this.destroyWorker(workerNode
.worker
)
613 await workerExitPromise
619 * Terminates the given worker.
621 * @param worker - A worker within `workerNodes`.
623 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
626 * Setup hook to execute code before worker nodes are created in the abstract constructor.
631 protected setupHook (): void {
632 // Intentionally empty
636 * Should return whether the worker is the main worker or not.
638 protected abstract isMain (): boolean
641 * Hook executed before the worker task execution.
644 * @param workerNodeKey - The worker node key.
645 * @param task - The task to execute.
647 protected beforeTaskExecutionHook (
648 workerNodeKey
: number,
651 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
652 ++workerUsage
.tasks
.executing
653 this.updateWaitTimeWorkerUsage(workerUsage
, task
)
657 * Hook executed after the worker task execution.
660 * @param worker - The worker.
661 * @param message - The received message.
663 protected afterTaskExecutionHook (
665 message
: MessageValue
<Response
>
667 const workerUsage
= this.workerNodes
[this.getWorkerNodeKey(worker
)].usage
668 this.updateTaskStatisticsWorkerUsage(workerUsage
, message
)
669 this.updateRunTimeWorkerUsage(workerUsage
, message
)
670 this.updateEluWorkerUsage(workerUsage
, message
)
673 private updateTaskStatisticsWorkerUsage (
674 workerUsage
: WorkerUsage
,
675 message
: MessageValue
<Response
>
677 const workerTaskStatistics
= workerUsage
.tasks
678 --workerTaskStatistics
.executing
679 if (message
.taskError
== null) {
680 ++workerTaskStatistics
.executed
682 ++workerTaskStatistics
.failed
686 private updateRunTimeWorkerUsage (
687 workerUsage
: WorkerUsage
,
688 message
: MessageValue
<Response
>
691 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
694 const taskRunTime
= message
.taskPerformance
?.runTime
?? 0
695 workerUsage
.runTime
.aggregate
=
696 (workerUsage
.runTime
.aggregate
?? 0) + taskRunTime
697 workerUsage
.runTime
.minimum
= Math.min(
699 workerUsage
.runTime
?.minimum
?? Infinity
701 workerUsage
.runTime
.maximum
= Math.max(
703 workerUsage
.runTime
?.maximum
?? -Infinity
706 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
708 workerUsage
.tasks
.executed
!== 0
710 workerUsage
.runTime
.average
=
711 workerUsage
.runTime
.aggregate
/ workerUsage
.tasks
.executed
714 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
716 message
.taskPerformance
?.runTime
!= null
718 workerUsage
.runTime
.history
.push(message
.taskPerformance
.runTime
)
719 workerUsage
.runTime
.median
= median(workerUsage
.runTime
.history
)
724 private updateWaitTimeWorkerUsage (
725 workerUsage
: WorkerUsage
,
728 const timestamp
= performance
.now()
729 const taskWaitTime
= timestamp
- (task
.timestamp
?? timestamp
)
731 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().waitTime
734 workerUsage
.waitTime
.aggregate
=
735 (workerUsage
.waitTime
?.aggregate
?? 0) + taskWaitTime
736 workerUsage
.waitTime
.minimum
= Math.min(
738 workerUsage
.waitTime
?.minimum
?? Infinity
740 workerUsage
.waitTime
.maximum
= Math.max(
742 workerUsage
.waitTime
?.maximum
?? -Infinity
745 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
747 workerUsage
.tasks
.executed
!== 0
749 workerUsage
.waitTime
.average
=
750 workerUsage
.waitTime
.aggregate
/ workerUsage
.tasks
.executed
753 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
756 workerUsage
.waitTime
.history
.push(taskWaitTime
)
757 workerUsage
.waitTime
.median
= median(workerUsage
.waitTime
.history
)
762 private updateEluWorkerUsage (
763 workerUsage
: WorkerUsage
,
764 message
: MessageValue
<Response
>
767 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
770 if (message
.taskPerformance
?.elu
!= null) {
771 workerUsage
.elu
.idle
.aggregate
=
772 (workerUsage
.elu
.idle
?.aggregate
?? 0) +
773 message
.taskPerformance
.elu
.idle
774 workerUsage
.elu
.active
.aggregate
=
775 (workerUsage
.elu
.active
?.aggregate
?? 0) +
776 message
.taskPerformance
.elu
.active
777 if (workerUsage
.elu
.utilization
!= null) {
778 workerUsage
.elu
.utilization
=
779 (workerUsage
.elu
.utilization
+
780 message
.taskPerformance
.elu
.utilization
) /
783 workerUsage
.elu
.utilization
= message
.taskPerformance
.elu
.utilization
785 workerUsage
.elu
.idle
.minimum
= Math.min(
786 message
.taskPerformance
.elu
.idle
,
787 workerUsage
.elu
.idle
?.minimum
?? Infinity
789 workerUsage
.elu
.idle
.maximum
= Math.max(
790 message
.taskPerformance
.elu
.idle
,
791 workerUsage
.elu
.idle
?.maximum
?? -Infinity
793 workerUsage
.elu
.active
.minimum
= Math.min(
794 message
.taskPerformance
.elu
.active
,
795 workerUsage
.elu
.active
?.minimum
?? Infinity
797 workerUsage
.elu
.active
.maximum
= Math.max(
798 message
.taskPerformance
.elu
.active
,
799 workerUsage
.elu
.active
?.maximum
?? -Infinity
802 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
804 workerUsage
.tasks
.executed
!== 0
806 workerUsage
.elu
.idle
.average
=
807 workerUsage
.elu
.idle
.aggregate
/ workerUsage
.tasks
.executed
808 workerUsage
.elu
.active
.average
=
809 workerUsage
.elu
.active
.aggregate
/ workerUsage
.tasks
.executed
812 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
815 workerUsage
.elu
.idle
.history
.push(message
.taskPerformance
.elu
.idle
)
816 workerUsage
.elu
.active
.history
.push(
817 message
.taskPerformance
.elu
.active
819 workerUsage
.elu
.idle
.median
= median(workerUsage
.elu
.idle
.history
)
820 workerUsage
.elu
.active
.median
= median(workerUsage
.elu
.active
.history
)
827 * Chooses a worker node for the next task.
829 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
831 * @returns The worker node key
833 private chooseWorkerNode (): number {
834 if (this.shallCreateDynamicWorker()) {
835 const worker
= this.createAndSetupDynamicWorker()
837 this.workerChoiceStrategyContext
.getStrategyPolicy().useDynamicWorker
839 return this.getWorkerNodeKey(worker
)
842 return this.workerChoiceStrategyContext
.execute()
846 * Conditions for dynamic worker creation.
848 * @returns Whether to create a dynamic worker or not.
850 private shallCreateDynamicWorker (): boolean {
851 return this.type === PoolTypes
.dynamic
&& !this.full
&& this.internalBusy()
855 * Sends a message to the given worker.
857 * @param worker - The worker which should receive the message.
858 * @param message - The message.
860 protected abstract sendToWorker (
862 message
: MessageValue
<Data
>
866 * Registers a listener callback on the given worker.
868 * @param worker - The worker which should register a listener.
869 * @param listener - The message listener callback.
871 private registerWorkerMessageListener
<Message
extends Data
| Response
>(
873 listener
: (message
: MessageValue
<Message
>) => void
875 worker
.on('message', listener
as MessageHandler
<Worker
>)
879 * Creates a new worker.
881 * @returns Newly created worker.
883 protected abstract createWorker (): Worker
886 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
889 * @param worker - The newly created worker.
891 protected afterWorkerSetup (worker
: Worker
): void {
892 // Listen to worker messages.
893 this.registerWorkerMessageListener(worker
, this.workerListener())
894 // Send startup message to worker.
895 this.sendToWorker(worker
, {
897 workerId
: this.getWorkerInfo(this.getWorkerNodeKey(worker
)).id
899 // Setup worker task statistics computation.
900 this.setWorkerStatistics(worker
)
904 * Creates a new worker and sets it up completely in the pool worker nodes.
906 * @returns New, completely set up worker.
908 protected createAndSetupWorker (): Worker
{
909 const worker
= this.createWorker()
911 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
912 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
913 worker
.on('error', error
=> {
914 if (this.emitter
!= null) {
915 this.emitter
.emit(PoolEvents
.error
, error
)
917 if (this.opts
.enableTasksQueue
=== true) {
918 this.redistributeQueuedTasks(worker
)
920 if (this.opts
.restartWorkerOnError
=== true && !this.starting
) {
921 if (this.getWorkerInfo(this.getWorkerNodeKey(worker
)).dynamic
) {
922 this.createAndSetupDynamicWorker()
924 this.createAndSetupWorker()
928 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
929 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
930 worker
.once('exit', () => {
931 this.removeWorkerNode(worker
)
934 this.pushWorkerNode(worker
)
936 this.afterWorkerSetup(worker
)
941 private redistributeQueuedTasks (worker
: Worker
): void {
942 const workerNodeKey
= this.getWorkerNodeKey(worker
)
943 while (this.tasksQueueSize(workerNodeKey
) > 0) {
944 let targetWorkerNodeKey
: number = workerNodeKey
945 let minQueuedTasks
= Infinity
946 for (const [workerNodeId
, workerNode
] of this.workerNodes
.entries()) {
948 workerNodeId
!== workerNodeKey
&&
949 workerNode
.usage
.tasks
.queued
=== 0
951 targetWorkerNodeKey
= workerNodeId
955 workerNodeId
!== workerNodeKey
&&
956 workerNode
.usage
.tasks
.queued
< minQueuedTasks
958 minQueuedTasks
= workerNode
.usage
.tasks
.queued
959 targetWorkerNodeKey
= workerNodeId
964 this.dequeueTask(workerNodeKey
) as Task
<Data
>
970 * Creates a new dynamic worker and sets it up completely in the pool worker nodes.
972 * @returns New, completely set up dynamic worker.
974 protected createAndSetupDynamicWorker (): Worker
{
975 const worker
= this.createAndSetupWorker()
976 this.registerWorkerMessageListener(worker
, message
=> {
977 const workerNodeKey
= this.getWorkerNodeKey(worker
)
979 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
980 (message
.kill
!= null &&
981 ((this.opts
.enableTasksQueue
=== false &&
982 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
=== 0) ||
983 (this.opts
.enableTasksQueue
=== true &&
984 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
=== 0 &&
985 this.tasksQueueSize(workerNodeKey
) === 0)))
987 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
988 void (this.destroyWorker(worker
) as Promise
<void>)
991 this.getWorkerInfo(this.getWorkerNodeKey(worker
)).dynamic
= true
992 this.sendToWorker(worker
, { checkAlive
: true })
997 * This function is the listener registered for each worker message.
999 * @returns The listener function to execute when a message is received from a worker.
1001 protected workerListener (): (message
: MessageValue
<Response
>) => void {
1003 if (message
.ready
!= null && message
.workerId
!= null) {
1004 // Worker ready message received
1005 this.handleWorkerReadyMessage(message
)
1006 } else if (message
.id
!= null) {
1007 // Task execution response received
1008 this.handleTaskExecutionResponse(message
)
1013 private handleWorkerReadyMessage (message
: MessageValue
<Response
>): void {
1014 const worker
= this.getWorkerById(message
.workerId
as number)
1015 if (worker
!= null) {
1016 this.getWorkerInfo(this.getWorkerNodeKey(worker
)).ready
=
1017 message
.ready
as boolean
1020 `Worker ready message received from unknown worker '${
1021 message.workerId as number
1025 if (this.emitter
!= null && this.ready
) {
1026 this.emitter
.emit(PoolEvents
.ready
, this.info
)
1030 private handleTaskExecutionResponse (message
: MessageValue
<Response
>): void {
1031 const promiseResponse
= this.promiseResponseMap
.get(message
.id
as string)
1032 if (promiseResponse
!= null) {
1033 if (message
.taskError
!= null) {
1034 if (this.emitter
!= null) {
1035 this.emitter
.emit(PoolEvents
.taskError
, message
.taskError
)
1037 promiseResponse
.reject(message
.taskError
.message
)
1039 promiseResponse
.resolve(message
.data
as Response
)
1041 this.afterTaskExecutionHook(promiseResponse
.worker
, message
)
1042 this.promiseResponseMap
.delete(message
.id
as string)
1043 const workerNodeKey
= this.getWorkerNodeKey(promiseResponse
.worker
)
1045 this.opts
.enableTasksQueue
=== true &&
1046 this.tasksQueueSize(workerNodeKey
) > 0
1050 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1053 this.workerChoiceStrategyContext
.update(workerNodeKey
)
1057 private checkAndEmitEvents (): void {
1058 if (this.emitter
!= null) {
1060 this.emitter
.emit(PoolEvents
.busy
, this.info
)
1062 if (this.type === PoolTypes
.dynamic
&& this.full
) {
1063 this.emitter
.emit(PoolEvents
.full
, this.info
)
1069 * Gets the worker information.
1071 * @param workerNodeKey - The worker node key.
1073 private getWorkerInfo (workerNodeKey
: number): WorkerInfo
{
1074 return this.workerNodes
[workerNodeKey
].info
1078 * Pushes the given worker in the pool worker nodes.
1080 * @param worker - The worker.
1081 * @returns The worker nodes length.
1083 private pushWorkerNode (worker
: Worker
): number {
1084 return this.workerNodes
.push(new WorkerNode(worker
, this.worker
))
1088 * Removes the given worker from the pool worker nodes.
1090 * @param worker - The worker.
1092 private removeWorkerNode (worker
: Worker
): void {
1093 const workerNodeKey
= this.getWorkerNodeKey(worker
)
1094 if (workerNodeKey
!== -1) {
1095 this.workerNodes
.splice(workerNodeKey
, 1)
1096 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
1100 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
1101 this.beforeTaskExecutionHook(workerNodeKey
, task
)
1102 this.sendToWorker(this.workerNodes
[workerNodeKey
].worker
, task
)
1105 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
1106 return this.workerNodes
[workerNodeKey
].enqueueTask(task
)
1109 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
1110 return this.workerNodes
[workerNodeKey
].dequeueTask()
1113 private tasksQueueSize (workerNodeKey
: number): number {
1114 return this.workerNodes
[workerNodeKey
].tasksQueueSize()
1117 private flushTasksQueue (workerNodeKey
: number): void {
1118 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1121 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1124 this.workerNodes
[workerNodeKey
].clearTasksQueue()
1127 private flushTasksQueues (): void {
1128 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
1129 this.flushTasksQueue(workerNodeKey
)
1133 private setWorkerStatistics (worker
: Worker
): void {
1134 this.sendToWorker(worker
, {
1137 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1139 elu
: this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()