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
) {
163 throw new RangeError(
164 'Cannot instantiate a dynamic pool with a maximum pool size inferior to the minimum pool size'
166 } else if (min
=== 0 && max
=== 0) {
167 throw new RangeError(
168 'Cannot instantiate a dynamic pool with a minimum pool size and a maximum pool size equal to zero'
170 } else if (min
=== max
) {
171 throw new RangeError(
172 'Cannot instantiate a dynamic pool with a minimum pool size equal to the maximum pool size. Use a fixed pool instead'
178 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
179 if (isPlainObject(opts
)) {
180 this.opts
.workerChoiceStrategy
=
181 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
182 this.checkValidWorkerChoiceStrategy(this.opts
.workerChoiceStrategy
)
183 this.opts
.workerChoiceStrategyOptions
=
184 opts
.workerChoiceStrategyOptions
??
185 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
186 this.checkValidWorkerChoiceStrategyOptions(
187 this.opts
.workerChoiceStrategyOptions
189 this.opts
.restartWorkerOnError
= opts
.restartWorkerOnError
?? true
190 this.opts
.enableEvents
= opts
.enableEvents
?? true
191 this.opts
.enableTasksQueue
= opts
.enableTasksQueue
?? false
192 if (this.opts
.enableTasksQueue
) {
193 this.checkValidTasksQueueOptions(
194 opts
.tasksQueueOptions
as TasksQueueOptions
196 this.opts
.tasksQueueOptions
= this.buildTasksQueueOptions(
197 opts
.tasksQueueOptions
as TasksQueueOptions
201 throw new TypeError('Invalid pool options: must be a plain object')
205 private checkValidWorkerChoiceStrategy (
206 workerChoiceStrategy
: WorkerChoiceStrategy
208 if (!Object.values(WorkerChoiceStrategies
).includes(workerChoiceStrategy
)) {
210 `Invalid worker choice strategy '${workerChoiceStrategy}'`
215 private checkValidWorkerChoiceStrategyOptions (
216 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
218 if (!isPlainObject(workerChoiceStrategyOptions
)) {
220 'Invalid worker choice strategy options: must be a plain object'
224 workerChoiceStrategyOptions
.weights
!= null &&
225 Object.keys(workerChoiceStrategyOptions
.weights
).length
!== this.maxSize
228 'Invalid worker choice strategy options: must have a weight for each worker node'
232 workerChoiceStrategyOptions
.measurement
!= null &&
233 !Object.values(Measurements
).includes(
234 workerChoiceStrategyOptions
.measurement
238 `Invalid worker choice strategy options: invalid measurement '${workerChoiceStrategyOptions.measurement}'`
243 private checkValidTasksQueueOptions (
244 tasksQueueOptions
: TasksQueueOptions
246 if (tasksQueueOptions
!= null && !isPlainObject(tasksQueueOptions
)) {
247 throw new TypeError('Invalid tasks queue options: must be a plain object')
250 tasksQueueOptions
?.concurrency
!= null &&
251 !Number.isSafeInteger(tasksQueueOptions
.concurrency
)
254 'Invalid worker tasks concurrency: must be an integer'
258 tasksQueueOptions
?.concurrency
!= null &&
259 tasksQueueOptions
.concurrency
<= 0
262 `Invalid worker tasks concurrency '${tasksQueueOptions.concurrency}'`
268 public get
info (): PoolInfo
{
274 strategy
: this.opts
.workerChoiceStrategy
as WorkerChoiceStrategy
,
275 minSize
: this.minSize
,
276 maxSize
: this.maxSize
,
277 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
278 .runTime
.aggregate
&&
279 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
280 .waitTime
.aggregate
&& { utilization
: round(this.utilization
) }),
281 workerNodes
: this.workerNodes
.length
,
282 idleWorkerNodes
: this.workerNodes
.reduce(
283 (accumulator
, workerNode
) =>
284 workerNode
.usage
.tasks
.executing
=== 0
289 busyWorkerNodes
: this.workerNodes
.reduce(
290 (accumulator
, workerNode
) =>
291 workerNode
.usage
.tasks
.executing
> 0 ? accumulator
+ 1 : accumulator
,
294 executedTasks
: this.workerNodes
.reduce(
295 (accumulator
, workerNode
) =>
296 accumulator
+ workerNode
.usage
.tasks
.executed
,
299 executingTasks
: this.workerNodes
.reduce(
300 (accumulator
, workerNode
) =>
301 accumulator
+ workerNode
.usage
.tasks
.executing
,
304 queuedTasks
: this.workerNodes
.reduce(
305 (accumulator
, workerNode
) =>
306 accumulator
+ workerNode
.usage
.tasks
.queued
,
309 maxQueuedTasks
: this.workerNodes
.reduce(
310 (accumulator
, workerNode
) =>
311 accumulator
+ workerNode
.usage
.tasks
.maxQueued
,
314 failedTasks
: this.workerNodes
.reduce(
315 (accumulator
, workerNode
) =>
316 accumulator
+ workerNode
.usage
.tasks
.failed
,
319 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
320 .runTime
.aggregate
&& {
324 ...this.workerNodes
.map(
325 workerNode
=> workerNode
.usage
.runTime
?.minimum
?? Infinity
331 ...this.workerNodes
.map(
332 workerNode
=> workerNode
.usage
.runTime
?.maximum
?? -Infinity
337 this.workerNodes
.reduce(
338 (accumulator
, workerNode
) =>
339 accumulator
+ (workerNode
.usage
.runTime
?.aggregate
?? 0),
342 this.workerNodes
.reduce(
343 (accumulator
, workerNode
) =>
344 accumulator
+ (workerNode
.usage
.tasks
?.executed
?? 0),
348 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
352 this.workerNodes
.map(
353 workerNode
=> workerNode
.usage
.runTime
?.median
?? 0
360 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
361 .waitTime
.aggregate
&& {
365 ...this.workerNodes
.map(
366 workerNode
=> workerNode
.usage
.waitTime
?.minimum
?? Infinity
372 ...this.workerNodes
.map(
373 workerNode
=> workerNode
.usage
.waitTime
?.maximum
?? -Infinity
378 this.workerNodes
.reduce(
379 (accumulator
, workerNode
) =>
380 accumulator
+ (workerNode
.usage
.waitTime
?.aggregate
?? 0),
383 this.workerNodes
.reduce(
384 (accumulator
, workerNode
) =>
385 accumulator
+ (workerNode
.usage
.tasks
?.executed
?? 0),
389 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
390 .waitTime
.median
&& {
393 this.workerNodes
.map(
394 workerNode
=> workerNode
.usage
.waitTime
?.median
?? 0
404 private get
starting (): boolean {
407 (this.full
&& this.workerNodes
.some(workerNode
=> !workerNode
.info
.ready
))
411 private get
ready (): boolean {
413 this.full
&& this.workerNodes
.every(workerNode
=> workerNode
.info
.ready
)
418 * Gets the approximate pool utilization.
420 * @returns The pool utilization.
422 private get
utilization (): number {
423 const poolRunTimeCapacity
=
424 (performance
.now() - this.startTimestamp
) * this.maxSize
425 const totalTasksRunTime
= this.workerNodes
.reduce(
426 (accumulator
, workerNode
) =>
427 accumulator
+ (workerNode
.usage
.runTime
?.aggregate
?? 0),
430 const totalTasksWaitTime
= this.workerNodes
.reduce(
431 (accumulator
, workerNode
) =>
432 accumulator
+ (workerNode
.usage
.waitTime
?.aggregate
?? 0),
435 return (totalTasksRunTime
+ totalTasksWaitTime
) / poolRunTimeCapacity
441 * If it is `'dynamic'`, it provides the `max` property.
443 protected abstract get
type (): PoolType
446 * Gets the worker type.
448 protected abstract get
worker (): WorkerType
453 protected abstract get
minSize (): number
458 protected abstract get
maxSize (): number
461 * Get the worker given its id.
463 * @param workerId - The worker id.
464 * @returns The worker if found in the pool worker nodes, `undefined` otherwise.
466 private getWorkerById (workerId
: number): Worker
| undefined {
467 return this.workerNodes
.find(workerNode
=> workerNode
.info
.id
=== workerId
)
471 private checkMessageWorkerId (message
: MessageValue
<Response
>): void {
473 message
.workerId
!= null &&
474 this.getWorkerById(message
.workerId
) == null
477 `Worker message received from unknown worker '${message.workerId}'`
483 * Gets the given worker its worker node key.
485 * @param worker - The worker.
486 * @returns The worker node key if found in the pool worker nodes, `-1` otherwise.
488 private getWorkerNodeKey (worker
: Worker
): number {
489 return this.workerNodes
.findIndex(
490 workerNode
=> workerNode
.worker
=== worker
495 public setWorkerChoiceStrategy (
496 workerChoiceStrategy
: WorkerChoiceStrategy
,
497 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
499 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
500 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
501 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
502 this.opts
.workerChoiceStrategy
504 if (workerChoiceStrategyOptions
!= null) {
505 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
507 for (const workerNode
of this.workerNodes
) {
508 workerNode
.resetUsage()
509 this.setWorkerStatistics(workerNode
.worker
)
514 public setWorkerChoiceStrategyOptions (
515 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
517 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
518 this.opts
.workerChoiceStrategyOptions
= workerChoiceStrategyOptions
519 this.workerChoiceStrategyContext
.setOptions(
520 this.opts
.workerChoiceStrategyOptions
525 public enableTasksQueue (
527 tasksQueueOptions
?: TasksQueueOptions
529 if (this.opts
.enableTasksQueue
=== true && !enable
) {
530 this.flushTasksQueues()
532 this.opts
.enableTasksQueue
= enable
533 this.setTasksQueueOptions(tasksQueueOptions
as TasksQueueOptions
)
537 public setTasksQueueOptions (tasksQueueOptions
: TasksQueueOptions
): void {
538 if (this.opts
.enableTasksQueue
=== true) {
539 this.checkValidTasksQueueOptions(tasksQueueOptions
)
540 this.opts
.tasksQueueOptions
=
541 this.buildTasksQueueOptions(tasksQueueOptions
)
542 } else if (this.opts
.tasksQueueOptions
!= null) {
543 delete this.opts
.tasksQueueOptions
547 private buildTasksQueueOptions (
548 tasksQueueOptions
: TasksQueueOptions
549 ): TasksQueueOptions
{
551 concurrency
: tasksQueueOptions
?.concurrency
?? 1
556 * Whether the pool is full or not.
558 * The pool filling boolean status.
560 protected get
full (): boolean {
561 return this.workerNodes
.length
>= this.maxSize
565 * Whether the pool is busy or not.
567 * The pool busyness boolean status.
569 protected abstract get
busy (): boolean
572 * Whether worker nodes are executing at least one task.
574 * @returns Worker nodes busyness boolean status.
576 protected internalBusy (): boolean {
578 this.workerNodes
.findIndex(workerNode
=> {
579 return workerNode
.usage
.tasks
.executing
=== 0
585 public async execute (data
?: Data
, name
?: string): Promise
<Response
> {
586 const timestamp
= performance
.now()
587 const workerNodeKey
= this.chooseWorkerNode()
588 const submittedTask
: Task
<Data
> = {
590 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
591 data
: data
?? ({} as Data
),
593 workerId
: this.getWorkerInfo(workerNodeKey
).id
as number,
596 const res
= new Promise
<Response
>((resolve
, reject
) => {
597 this.promiseResponseMap
.set(submittedTask
.id
as string, {
600 worker
: this.workerNodes
[workerNodeKey
].worker
604 this.opts
.enableTasksQueue
=== true &&
606 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
>=
607 ((this.opts
.tasksQueueOptions
as TasksQueueOptions
)
608 .concurrency
as number))
610 this.enqueueTask(workerNodeKey
, submittedTask
)
612 this.executeTask(workerNodeKey
, submittedTask
)
614 this.checkAndEmitEvents()
615 // eslint-disable-next-line @typescript-eslint/return-await
620 public async destroy (): Promise
<void> {
622 this.workerNodes
.map(async (workerNode
, workerNodeKey
) => {
623 this.flushTasksQueue(workerNodeKey
)
624 // FIXME: wait for tasks to be finished
625 const workerExitPromise
= new Promise
<void>(resolve
=> {
626 workerNode
.worker
.on('exit', () => {
630 await this.destroyWorker(workerNode
.worker
)
631 await workerExitPromise
637 * Terminates the given worker.
639 * @param worker - A worker within `workerNodes`.
641 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
644 * Setup hook to execute code before worker nodes are created in the abstract constructor.
649 protected setupHook (): void {
650 // Intentionally empty
654 * Should return whether the worker is the main worker or not.
656 protected abstract isMain (): boolean
659 * Hook executed before the worker task execution.
662 * @param workerNodeKey - The worker node key.
663 * @param task - The task to execute.
665 protected beforeTaskExecutionHook (
666 workerNodeKey
: number,
669 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
670 ++workerUsage
.tasks
.executing
671 this.updateWaitTimeWorkerUsage(workerUsage
, task
)
675 * Hook executed after the worker task execution.
678 * @param worker - The worker.
679 * @param message - The received message.
681 protected afterTaskExecutionHook (
683 message
: MessageValue
<Response
>
685 const workerUsage
= this.workerNodes
[this.getWorkerNodeKey(worker
)].usage
686 this.updateTaskStatisticsWorkerUsage(workerUsage
, message
)
687 this.updateRunTimeWorkerUsage(workerUsage
, message
)
688 this.updateEluWorkerUsage(workerUsage
, message
)
691 private updateTaskStatisticsWorkerUsage (
692 workerUsage
: WorkerUsage
,
693 message
: MessageValue
<Response
>
695 const workerTaskStatistics
= workerUsage
.tasks
696 --workerTaskStatistics
.executing
697 if (message
.taskError
== null) {
698 ++workerTaskStatistics
.executed
700 ++workerTaskStatistics
.failed
704 private updateRunTimeWorkerUsage (
705 workerUsage
: WorkerUsage
,
706 message
: MessageValue
<Response
>
709 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
712 const taskRunTime
= message
.taskPerformance
?.runTime
?? 0
713 workerUsage
.runTime
.aggregate
=
714 (workerUsage
.runTime
.aggregate
?? 0) + taskRunTime
715 workerUsage
.runTime
.minimum
= Math.min(
717 workerUsage
.runTime
?.minimum
?? Infinity
719 workerUsage
.runTime
.maximum
= Math.max(
721 workerUsage
.runTime
?.maximum
?? -Infinity
724 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
726 workerUsage
.tasks
.executed
!== 0
728 workerUsage
.runTime
.average
=
729 workerUsage
.runTime
.aggregate
/ workerUsage
.tasks
.executed
732 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
734 message
.taskPerformance
?.runTime
!= null
736 workerUsage
.runTime
.history
.push(message
.taskPerformance
.runTime
)
737 workerUsage
.runTime
.median
= median(workerUsage
.runTime
.history
)
742 private updateWaitTimeWorkerUsage (
743 workerUsage
: WorkerUsage
,
746 const timestamp
= performance
.now()
747 const taskWaitTime
= timestamp
- (task
.timestamp
?? timestamp
)
749 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().waitTime
752 workerUsage
.waitTime
.aggregate
=
753 (workerUsage
.waitTime
?.aggregate
?? 0) + taskWaitTime
754 workerUsage
.waitTime
.minimum
= Math.min(
756 workerUsage
.waitTime
?.minimum
?? Infinity
758 workerUsage
.waitTime
.maximum
= Math.max(
760 workerUsage
.waitTime
?.maximum
?? -Infinity
763 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
765 workerUsage
.tasks
.executed
!== 0
767 workerUsage
.waitTime
.average
=
768 workerUsage
.waitTime
.aggregate
/ workerUsage
.tasks
.executed
771 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
774 workerUsage
.waitTime
.history
.push(taskWaitTime
)
775 workerUsage
.waitTime
.median
= median(workerUsage
.waitTime
.history
)
780 private updateEluWorkerUsage (
781 workerUsage
: WorkerUsage
,
782 message
: MessageValue
<Response
>
785 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
788 if (message
.taskPerformance
?.elu
!= null) {
789 workerUsage
.elu
.idle
.aggregate
=
790 (workerUsage
.elu
.idle
?.aggregate
?? 0) +
791 message
.taskPerformance
.elu
.idle
792 workerUsage
.elu
.active
.aggregate
=
793 (workerUsage
.elu
.active
?.aggregate
?? 0) +
794 message
.taskPerformance
.elu
.active
795 if (workerUsage
.elu
.utilization
!= null) {
796 workerUsage
.elu
.utilization
=
797 (workerUsage
.elu
.utilization
+
798 message
.taskPerformance
.elu
.utilization
) /
801 workerUsage
.elu
.utilization
= message
.taskPerformance
.elu
.utilization
803 workerUsage
.elu
.idle
.minimum
= Math.min(
804 message
.taskPerformance
.elu
.idle
,
805 workerUsage
.elu
.idle
?.minimum
?? Infinity
807 workerUsage
.elu
.idle
.maximum
= Math.max(
808 message
.taskPerformance
.elu
.idle
,
809 workerUsage
.elu
.idle
?.maximum
?? -Infinity
811 workerUsage
.elu
.active
.minimum
= Math.min(
812 message
.taskPerformance
.elu
.active
,
813 workerUsage
.elu
.active
?.minimum
?? Infinity
815 workerUsage
.elu
.active
.maximum
= Math.max(
816 message
.taskPerformance
.elu
.active
,
817 workerUsage
.elu
.active
?.maximum
?? -Infinity
820 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
822 workerUsage
.tasks
.executed
!== 0
824 workerUsage
.elu
.idle
.average
=
825 workerUsage
.elu
.idle
.aggregate
/ workerUsage
.tasks
.executed
826 workerUsage
.elu
.active
.average
=
827 workerUsage
.elu
.active
.aggregate
/ workerUsage
.tasks
.executed
830 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
833 workerUsage
.elu
.idle
.history
.push(message
.taskPerformance
.elu
.idle
)
834 workerUsage
.elu
.active
.history
.push(
835 message
.taskPerformance
.elu
.active
837 workerUsage
.elu
.idle
.median
= median(workerUsage
.elu
.idle
.history
)
838 workerUsage
.elu
.active
.median
= median(workerUsage
.elu
.active
.history
)
845 * Chooses a worker node for the next task.
847 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
849 * @returns The worker node key
851 private chooseWorkerNode (): number {
852 if (this.shallCreateDynamicWorker()) {
853 const worker
= this.createAndSetupDynamicWorker()
855 this.workerChoiceStrategyContext
.getStrategyPolicy().useDynamicWorker
857 return this.getWorkerNodeKey(worker
)
860 return this.workerChoiceStrategyContext
.execute()
864 * Conditions for dynamic worker creation.
866 * @returns Whether to create a dynamic worker or not.
868 private shallCreateDynamicWorker (): boolean {
869 return this.type === PoolTypes
.dynamic
&& !this.full
&& this.internalBusy()
873 * Sends a message to the given worker.
875 * @param worker - The worker which should receive the message.
876 * @param message - The message.
878 protected abstract sendToWorker (
880 message
: MessageValue
<Data
>
884 * Registers a listener callback on the given worker.
886 * @param worker - The worker which should register a listener.
887 * @param listener - The message listener callback.
889 private registerWorkerMessageListener
<Message
extends Data
| Response
>(
891 listener
: (message
: MessageValue
<Message
>) => void
893 worker
.on('message', listener
as MessageHandler
<Worker
>)
897 * Creates a new worker.
899 * @returns Newly created worker.
901 protected abstract createWorker (): Worker
904 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
907 * @param worker - The newly created worker.
909 protected afterWorkerSetup (worker
: Worker
): void {
910 // Listen to worker messages.
911 this.registerWorkerMessageListener(worker
, this.workerListener())
912 // Send startup message to worker.
913 this.sendToWorker(worker
, {
915 workerId
: this.getWorkerInfo(this.getWorkerNodeKey(worker
)).id
as number
917 // Setup worker task statistics computation.
918 this.setWorkerStatistics(worker
)
922 * Creates a new worker and sets it up completely in the pool worker nodes.
924 * @returns New, completely set up worker.
926 protected createAndSetupWorker (): Worker
{
927 const worker
= this.createWorker()
929 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
930 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
931 worker
.on('error', error
=> {
932 if (this.emitter
!= null) {
933 this.emitter
.emit(PoolEvents
.error
, error
)
935 if (this.opts
.enableTasksQueue
=== true) {
936 this.redistributeQueuedTasks(worker
)
938 if (this.opts
.restartWorkerOnError
=== true && !this.starting
) {
939 if (this.getWorkerInfo(this.getWorkerNodeKey(worker
)).dynamic
) {
940 this.createAndSetupDynamicWorker()
942 this.createAndSetupWorker()
946 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
947 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
948 worker
.once('exit', () => {
949 this.removeWorkerNode(worker
)
952 this.pushWorkerNode(worker
)
954 this.afterWorkerSetup(worker
)
959 private redistributeQueuedTasks (worker
: Worker
): void {
960 const workerNodeKey
= this.getWorkerNodeKey(worker
)
961 while (this.tasksQueueSize(workerNodeKey
) > 0) {
962 let targetWorkerNodeKey
: number = workerNodeKey
963 let minQueuedTasks
= Infinity
964 for (const [workerNodeId
, workerNode
] of this.workerNodes
.entries()) {
966 workerNodeId
!== workerNodeKey
&&
967 workerNode
.usage
.tasks
.queued
=== 0
969 targetWorkerNodeKey
= workerNodeId
973 workerNodeId
!== workerNodeKey
&&
974 workerNode
.usage
.tasks
.queued
< minQueuedTasks
976 minQueuedTasks
= workerNode
.usage
.tasks
.queued
977 targetWorkerNodeKey
= workerNodeId
982 this.dequeueTask(workerNodeKey
) as Task
<Data
>
988 * Creates a new dynamic worker and sets it up completely in the pool worker nodes.
990 * @returns New, completely set up dynamic worker.
992 protected createAndSetupDynamicWorker (): Worker
{
993 const worker
= this.createAndSetupWorker()
994 this.registerWorkerMessageListener(worker
, message
=> {
995 const workerNodeKey
= this.getWorkerNodeKey(worker
)
997 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
998 (message
.kill
!= null &&
999 ((this.opts
.enableTasksQueue
=== false &&
1000 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
=== 0) ||
1001 (this.opts
.enableTasksQueue
=== true &&
1002 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
=== 0 &&
1003 this.tasksQueueSize(workerNodeKey
) === 0)))
1005 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
1006 void (this.destroyWorker(worker
) as Promise
<void>)
1009 const workerInfo
= this.getWorkerInfo(this.getWorkerNodeKey(worker
))
1010 workerInfo
.dynamic
= true
1011 this.sendToWorker(worker
, {
1013 workerId
: workerInfo
.id
as number
1019 * This function is the listener registered for each worker message.
1021 * @returns The listener function to execute when a message is received from a worker.
1023 protected workerListener (): (message
: MessageValue
<Response
>) => void {
1025 this.checkMessageWorkerId(message
)
1026 if (message
.ready
!= null && message
.workerId
!= null) {
1027 // Worker ready message received
1028 this.handleWorkerReadyMessage(message
)
1029 } else if (message
.id
!= null) {
1030 // Task execution response received
1031 this.handleTaskExecutionResponse(message
)
1036 private handleWorkerReadyMessage (message
: MessageValue
<Response
>): void {
1037 const worker
= this.getWorkerById(message
.workerId
)
1038 this.getWorkerInfo(this.getWorkerNodeKey(worker
as Worker
)).ready
=
1039 message
.ready
as boolean
1040 if (this.emitter
!= null && this.ready
) {
1041 this.emitter
.emit(PoolEvents
.ready
, this.info
)
1045 private handleTaskExecutionResponse (message
: MessageValue
<Response
>): void {
1046 const promiseResponse
= this.promiseResponseMap
.get(message
.id
as string)
1047 if (promiseResponse
!= null) {
1048 if (message
.taskError
!= null) {
1049 if (this.emitter
!= null) {
1050 this.emitter
.emit(PoolEvents
.taskError
, message
.taskError
)
1052 promiseResponse
.reject(message
.taskError
.message
)
1054 promiseResponse
.resolve(message
.data
as Response
)
1056 this.afterTaskExecutionHook(promiseResponse
.worker
, message
)
1057 this.promiseResponseMap
.delete(message
.id
as string)
1058 const workerNodeKey
= this.getWorkerNodeKey(promiseResponse
.worker
)
1060 this.opts
.enableTasksQueue
=== true &&
1061 this.tasksQueueSize(workerNodeKey
) > 0
1065 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1068 this.workerChoiceStrategyContext
.update(workerNodeKey
)
1072 private checkAndEmitEvents (): void {
1073 if (this.emitter
!= null) {
1075 this.emitter
.emit(PoolEvents
.busy
, this.info
)
1077 if (this.type === PoolTypes
.dynamic
&& this.full
) {
1078 this.emitter
.emit(PoolEvents
.full
, this.info
)
1084 * Gets the worker information.
1086 * @param workerNodeKey - The worker node key.
1088 private getWorkerInfo (workerNodeKey
: number): WorkerInfo
{
1089 return this.workerNodes
[workerNodeKey
].info
1093 * Pushes the given worker in the pool worker nodes.
1095 * @param worker - The worker.
1096 * @returns The worker nodes length.
1098 private pushWorkerNode (worker
: Worker
): number {
1099 return this.workerNodes
.push(new WorkerNode(worker
, this.worker
))
1103 * Removes the given worker from the pool worker nodes.
1105 * @param worker - The worker.
1107 private removeWorkerNode (worker
: Worker
): void {
1108 const workerNodeKey
= this.getWorkerNodeKey(worker
)
1109 if (workerNodeKey
!== -1) {
1110 this.workerNodes
.splice(workerNodeKey
, 1)
1111 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
1115 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
1116 this.beforeTaskExecutionHook(workerNodeKey
, task
)
1117 this.sendToWorker(this.workerNodes
[workerNodeKey
].worker
, task
)
1120 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
1121 return this.workerNodes
[workerNodeKey
].enqueueTask(task
)
1124 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
1125 return this.workerNodes
[workerNodeKey
].dequeueTask()
1128 private tasksQueueSize (workerNodeKey
: number): number {
1129 return this.workerNodes
[workerNodeKey
].tasksQueueSize()
1132 private flushTasksQueue (workerNodeKey
: number): void {
1133 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1136 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1139 this.workerNodes
[workerNodeKey
].clearTasksQueue()
1142 private flushTasksQueues (): void {
1143 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
1144 this.flushTasksQueue(workerNodeKey
)
1148 private setWorkerStatistics (worker
: Worker
): void {
1149 this.sendToWorker(worker
, {
1152 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1154 elu
: this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1157 workerId
: this.getWorkerInfo(this.getWorkerNodeKey(worker
)).id
as number