1 import { randomUUID
} from
'node:crypto'
2 import { performance
} from
'node:perf_hooks'
5 PromiseResponseWrapper
,
7 } from
'../utility-types'
10 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
,
17 import { KillBehaviors
} from
'../worker/worker-options'
26 type TasksQueueOptions
38 WorkerChoiceStrategies
,
39 type WorkerChoiceStrategy
,
40 type WorkerChoiceStrategyOptions
41 } from
'./selection-strategies/selection-strategies-types'
42 import { WorkerChoiceStrategyContext
} from
'./selection-strategies/worker-choice-strategy-context'
43 import { version
} from
'./version'
44 import { WorkerNode
} from
'./worker-node'
47 * Base class that implements some shared logic for all poolifier pools.
49 * @typeParam Worker - Type of worker which manages this pool.
50 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
51 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
53 export abstract class AbstractPool
<
54 Worker
extends IWorker
,
57 > implements IPool
<Worker
, Data
, Response
> {
59 public readonly workerNodes
: Array<IWorkerNode
<Worker
, Data
>> = []
62 public readonly emitter
?: PoolEmitter
65 * The execution response promise map.
67 * - `key`: The message id of each submitted task.
68 * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks.
70 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
72 protected promiseResponseMap
: Map
<
74 PromiseResponseWrapper
<Worker
, Response
>
75 > = new Map
<string, PromiseResponseWrapper
<Worker
, Response
>>()
78 * Worker choice strategy context referencing a worker choice algorithm implementation.
80 protected workerChoiceStrategyContext
: WorkerChoiceStrategyContext
<
87 * The start timestamp of the pool.
89 private readonly startTimestamp
92 * Constructs a new poolifier pool.
94 * @param numberOfWorkers - Number of workers that this pool should manage.
95 * @param filePath - Path to the worker file.
96 * @param opts - Options for the pool.
99 protected readonly numberOfWorkers
: number,
100 protected readonly filePath
: string,
101 protected readonly opts
: PoolOptions
<Worker
>
103 if (!this.isMain()) {
104 throw new Error('Cannot start a pool from a worker!')
106 this.checkNumberOfWorkers(this.numberOfWorkers
)
107 this.checkFilePath(this.filePath
)
108 this.checkPoolOptions(this.opts
)
110 this.chooseWorkerNode
= this.chooseWorkerNode
.bind(this)
111 this.executeTask
= this.executeTask
.bind(this)
112 this.enqueueTask
= this.enqueueTask
.bind(this)
113 this.checkAndEmitEvents
= this.checkAndEmitEvents
.bind(this)
115 if (this.opts
.enableEvents
=== true) {
116 this.emitter
= new PoolEmitter()
118 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext
<
124 this.opts
.workerChoiceStrategy
,
125 this.opts
.workerChoiceStrategyOptions
130 while (this.workerNodes
.length
< this.numberOfWorkers
) {
131 this.createAndSetupWorker()
134 this.startTimestamp
= performance
.now()
137 private checkFilePath (filePath
: string): void {
140 (typeof filePath
=== 'string' && filePath
.trim().length
=== 0)
142 throw new Error('Please specify a file with a worker implementation')
146 private checkNumberOfWorkers (numberOfWorkers
: number): void {
147 if (numberOfWorkers
== null) {
149 'Cannot instantiate a pool without specifying the number of workers'
151 } else if (!Number.isSafeInteger(numberOfWorkers
)) {
153 'Cannot instantiate a pool with a non safe integer number of workers'
155 } else if (numberOfWorkers
< 0) {
156 throw new RangeError(
157 'Cannot instantiate a pool with a negative number of workers'
159 } else if (this.type === PoolTypes
.fixed
&& numberOfWorkers
=== 0) {
160 throw new RangeError('Cannot instantiate a fixed pool with zero worker')
164 protected checkDynamicPoolSize (min
: number, max
: number): void {
165 if (this.type === PoolTypes
.dynamic
) {
167 throw new RangeError(
168 'Cannot instantiate a dynamic pool with a maximum pool size inferior to the minimum pool size'
170 } else if (min
=== 0 && max
=== 0) {
171 throw new RangeError(
172 'Cannot instantiate a dynamic pool with a minimum pool size and a maximum pool size equal to zero'
174 } else if (min
=== max
) {
175 throw new RangeError(
176 'Cannot instantiate a dynamic pool with a minimum pool size equal to the maximum pool size. Use a fixed pool instead'
182 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
183 if (isPlainObject(opts
)) {
184 this.opts
.workerChoiceStrategy
=
185 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
186 this.checkValidWorkerChoiceStrategy(this.opts
.workerChoiceStrategy
)
187 this.opts
.workerChoiceStrategyOptions
=
188 opts
.workerChoiceStrategyOptions
??
189 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
190 this.checkValidWorkerChoiceStrategyOptions(
191 this.opts
.workerChoiceStrategyOptions
193 this.opts
.restartWorkerOnError
= opts
.restartWorkerOnError
?? true
194 this.opts
.enableEvents
= opts
.enableEvents
?? true
195 this.opts
.enableTasksQueue
= opts
.enableTasksQueue
?? false
196 if (this.opts
.enableTasksQueue
) {
197 this.checkValidTasksQueueOptions(
198 opts
.tasksQueueOptions
as TasksQueueOptions
200 this.opts
.tasksQueueOptions
= this.buildTasksQueueOptions(
201 opts
.tasksQueueOptions
as TasksQueueOptions
205 throw new TypeError('Invalid pool options: must be a plain object')
209 private checkValidWorkerChoiceStrategy (
210 workerChoiceStrategy
: WorkerChoiceStrategy
212 if (!Object.values(WorkerChoiceStrategies
).includes(workerChoiceStrategy
)) {
214 `Invalid worker choice strategy '${workerChoiceStrategy}'`
219 private checkValidWorkerChoiceStrategyOptions (
220 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
222 if (!isPlainObject(workerChoiceStrategyOptions
)) {
224 'Invalid worker choice strategy options: must be a plain object'
228 workerChoiceStrategyOptions
.weights
!= null &&
229 Object.keys(workerChoiceStrategyOptions
.weights
).length
!== this.maxSize
232 'Invalid worker choice strategy options: must have a weight for each worker node'
236 workerChoiceStrategyOptions
.measurement
!= null &&
237 !Object.values(Measurements
).includes(
238 workerChoiceStrategyOptions
.measurement
242 `Invalid worker choice strategy options: invalid measurement '${workerChoiceStrategyOptions.measurement}'`
247 private checkValidTasksQueueOptions (
248 tasksQueueOptions
: TasksQueueOptions
250 if (tasksQueueOptions
!= null && !isPlainObject(tasksQueueOptions
)) {
251 throw new TypeError('Invalid tasks queue options: must be a plain object')
254 tasksQueueOptions
?.concurrency
!= null &&
255 !Number.isSafeInteger(tasksQueueOptions
.concurrency
)
258 'Invalid worker tasks concurrency: must be an integer'
262 tasksQueueOptions
?.concurrency
!= null &&
263 tasksQueueOptions
.concurrency
<= 0
266 `Invalid worker tasks concurrency '${tasksQueueOptions.concurrency}'`
272 public get
info (): PoolInfo
{
278 strategy
: this.opts
.workerChoiceStrategy
as WorkerChoiceStrategy
,
279 minSize
: this.minSize
,
280 maxSize
: this.maxSize
,
281 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
282 .runTime
.aggregate
&&
283 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
284 .waitTime
.aggregate
&& { utilization
: round(this.utilization
) }),
285 workerNodes
: this.workerNodes
.length
,
286 idleWorkerNodes
: this.workerNodes
.reduce(
287 (accumulator
, workerNode
) =>
288 workerNode
.usage
.tasks
.executing
=== 0
293 busyWorkerNodes
: this.workerNodes
.reduce(
294 (accumulator
, workerNode
) =>
295 workerNode
.usage
.tasks
.executing
> 0 ? accumulator
+ 1 : accumulator
,
298 executedTasks
: this.workerNodes
.reduce(
299 (accumulator
, workerNode
) =>
300 accumulator
+ workerNode
.usage
.tasks
.executed
,
303 executingTasks
: this.workerNodes
.reduce(
304 (accumulator
, workerNode
) =>
305 accumulator
+ workerNode
.usage
.tasks
.executing
,
308 queuedTasks
: this.workerNodes
.reduce(
309 (accumulator
, workerNode
) =>
310 accumulator
+ workerNode
.usage
.tasks
.queued
,
313 maxQueuedTasks
: this.workerNodes
.reduce(
314 (accumulator
, workerNode
) =>
315 accumulator
+ (workerNode
.usage
.tasks
?.maxQueued
?? 0),
318 failedTasks
: this.workerNodes
.reduce(
319 (accumulator
, workerNode
) =>
320 accumulator
+ workerNode
.usage
.tasks
.failed
,
323 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
324 .runTime
.aggregate
&& {
328 ...this.workerNodes
.map(
329 workerNode
=> workerNode
.usage
.runTime
?.minimum
?? Infinity
335 ...this.workerNodes
.map(
336 workerNode
=> workerNode
.usage
.runTime
?.maximum
?? -Infinity
341 this.workerNodes
.reduce(
342 (accumulator
, workerNode
) =>
343 accumulator
+ (workerNode
.usage
.runTime
?.aggregate
?? 0),
346 this.workerNodes
.reduce(
347 (accumulator
, workerNode
) =>
348 accumulator
+ (workerNode
.usage
.tasks
?.executed
?? 0),
352 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
356 this.workerNodes
.map(
357 workerNode
=> workerNode
.usage
.runTime
?.median
?? 0
364 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
365 .waitTime
.aggregate
&& {
369 ...this.workerNodes
.map(
370 workerNode
=> workerNode
.usage
.waitTime
?.minimum
?? Infinity
376 ...this.workerNodes
.map(
377 workerNode
=> workerNode
.usage
.waitTime
?.maximum
?? -Infinity
382 this.workerNodes
.reduce(
383 (accumulator
, workerNode
) =>
384 accumulator
+ (workerNode
.usage
.waitTime
?.aggregate
?? 0),
387 this.workerNodes
.reduce(
388 (accumulator
, workerNode
) =>
389 accumulator
+ (workerNode
.usage
.tasks
?.executed
?? 0),
393 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
394 .waitTime
.median
&& {
397 this.workerNodes
.map(
398 workerNode
=> workerNode
.usage
.waitTime
?.median
?? 0
408 private get
starting (): boolean {
410 this.workerNodes
.length
< this.minSize
||
411 (this.workerNodes
.length
>= this.minSize
&&
412 this.workerNodes
.some(workerNode
=> !workerNode
.info
.ready
))
416 private get
ready (): boolean {
418 this.workerNodes
.length
>= this.minSize
&&
419 this.workerNodes
.every(workerNode
=> workerNode
.info
.ready
)
424 * Gets the approximate pool utilization.
426 * @returns The pool utilization.
428 private get
utilization (): number {
429 const poolRunTimeCapacity
=
430 (performance
.now() - this.startTimestamp
) * this.maxSize
431 const totalTasksRunTime
= this.workerNodes
.reduce(
432 (accumulator
, workerNode
) =>
433 accumulator
+ (workerNode
.usage
.runTime
?.aggregate
?? 0),
436 const totalTasksWaitTime
= this.workerNodes
.reduce(
437 (accumulator
, workerNode
) =>
438 accumulator
+ (workerNode
.usage
.waitTime
?.aggregate
?? 0),
441 return (totalTasksRunTime
+ totalTasksWaitTime
) / poolRunTimeCapacity
447 * If it is `'dynamic'`, it provides the `max` property.
449 protected abstract get
type (): PoolType
452 * Gets the worker type.
454 protected abstract get
worker (): WorkerType
459 protected abstract get
minSize (): number
464 protected abstract get
maxSize (): number
467 * Get the worker given its id.
469 * @param workerId - The worker id.
470 * @returns The worker if found in the pool worker nodes, `undefined` otherwise.
472 private getWorkerById (workerId
: number): Worker
| undefined {
473 return this.workerNodes
.find(workerNode
=> workerNode
.info
.id
=== workerId
)
477 private checkMessageWorkerId (message
: MessageValue
<Response
>): void {
479 message
.workerId
!= null &&
480 this.getWorkerById(message
.workerId
) == null
483 `Worker message received from unknown worker '${message.workerId}'`
489 * Gets the given worker its worker node key.
491 * @param worker - The worker.
492 * @returns The worker node key if found in the pool worker nodes, `-1` otherwise.
494 private getWorkerNodeKey (worker
: Worker
): number {
495 return this.workerNodes
.findIndex(
496 workerNode
=> workerNode
.worker
=== worker
501 public setWorkerChoiceStrategy (
502 workerChoiceStrategy
: WorkerChoiceStrategy
,
503 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
505 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
506 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
507 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
508 this.opts
.workerChoiceStrategy
510 if (workerChoiceStrategyOptions
!= null) {
511 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
513 for (const workerNode
of this.workerNodes
) {
514 workerNode
.resetUsage()
515 this.setWorkerStatistics(workerNode
.worker
)
520 public setWorkerChoiceStrategyOptions (
521 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
523 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
524 this.opts
.workerChoiceStrategyOptions
= workerChoiceStrategyOptions
525 this.workerChoiceStrategyContext
.setOptions(
526 this.opts
.workerChoiceStrategyOptions
531 public enableTasksQueue (
533 tasksQueueOptions
?: TasksQueueOptions
535 if (this.opts
.enableTasksQueue
=== true && !enable
) {
536 this.flushTasksQueues()
538 this.opts
.enableTasksQueue
= enable
539 this.setTasksQueueOptions(tasksQueueOptions
as TasksQueueOptions
)
543 public setTasksQueueOptions (tasksQueueOptions
: TasksQueueOptions
): void {
544 if (this.opts
.enableTasksQueue
=== true) {
545 this.checkValidTasksQueueOptions(tasksQueueOptions
)
546 this.opts
.tasksQueueOptions
=
547 this.buildTasksQueueOptions(tasksQueueOptions
)
548 } else if (this.opts
.tasksQueueOptions
!= null) {
549 delete this.opts
.tasksQueueOptions
553 private buildTasksQueueOptions (
554 tasksQueueOptions
: TasksQueueOptions
555 ): TasksQueueOptions
{
557 concurrency
: tasksQueueOptions
?.concurrency
?? 1
562 * Whether the pool is full or not.
564 * The pool filling boolean status.
566 protected get
full (): boolean {
567 return this.workerNodes
.length
>= this.maxSize
571 * Whether the pool is busy or not.
573 * The pool busyness boolean status.
575 protected abstract get
busy (): boolean
578 * Whether worker nodes are executing at least one task.
580 * @returns Worker nodes busyness boolean status.
582 protected internalBusy (): boolean {
584 this.workerNodes
.findIndex(workerNode
=> {
585 return workerNode
.usage
.tasks
.executing
=== 0
591 public async execute (data
?: Data
, name
?: string): Promise
<Response
> {
592 const timestamp
= performance
.now()
593 const workerNodeKey
= this.chooseWorkerNode()
594 const submittedTask
: Task
<Data
> = {
595 name
: name
?? DEFAULT_TASK_NAME
,
596 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
597 data
: data
?? ({} as Data
),
599 workerId
: this.getWorkerInfo(workerNodeKey
).id
as number,
602 const res
= new Promise
<Response
>((resolve
, reject
) => {
603 this.promiseResponseMap
.set(submittedTask
.id
as string, {
606 worker
: this.workerNodes
[workerNodeKey
].worker
610 this.opts
.enableTasksQueue
=== true &&
612 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
>=
613 ((this.opts
.tasksQueueOptions
as TasksQueueOptions
)
614 .concurrency
as number))
616 this.enqueueTask(workerNodeKey
, submittedTask
)
618 this.executeTask(workerNodeKey
, submittedTask
)
620 this.checkAndEmitEvents()
621 // eslint-disable-next-line @typescript-eslint/return-await
626 public async destroy (): Promise
<void> {
628 this.workerNodes
.map(async (workerNode
, workerNodeKey
) => {
629 this.flushTasksQueue(workerNodeKey
)
630 // FIXME: wait for tasks to be finished
631 const workerExitPromise
= new Promise
<void>(resolve
=> {
632 workerNode
.worker
.on('exit', () => {
636 await this.destroyWorker(workerNode
.worker
)
637 await workerExitPromise
643 * Terminates the given worker.
645 * @param worker - A worker within `workerNodes`.
647 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
650 * Setup hook to execute code before worker nodes are created in the abstract constructor.
655 protected setupHook (): void {
656 // Intentionally empty
660 * Should return whether the worker is the main worker or not.
662 protected abstract isMain (): boolean
665 * Hook executed before the worker task execution.
668 * @param workerNodeKey - The worker node key.
669 * @param task - The task to execute.
671 protected beforeTaskExecutionHook (
672 workerNodeKey
: number,
675 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
676 ++workerUsage
.tasks
.executing
677 this.updateWaitTimeWorkerUsage(workerUsage
, task
)
678 const tasksWorkerUsage
= this.workerNodes
[workerNodeKey
].getTaskWorkerUsage(
681 ++tasksWorkerUsage
.tasks
.executing
682 this.updateWaitTimeWorkerUsage(tasksWorkerUsage
, task
)
686 * Hook executed after the worker task execution.
689 * @param worker - The worker.
690 * @param message - The received message.
692 protected afterTaskExecutionHook (
694 message
: MessageValue
<Response
>
696 const workerNodeKey
= this.getWorkerNodeKey(worker
)
697 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
698 this.updateTaskStatisticsWorkerUsage(workerUsage
, message
)
699 this.updateRunTimeWorkerUsage(workerUsage
, message
)
700 this.updateEluWorkerUsage(workerUsage
, message
)
701 const tasksWorkerUsage
= this.workerNodes
[workerNodeKey
].getTaskWorkerUsage(
702 message
.name
as string
704 this.updateTaskStatisticsWorkerUsage(tasksWorkerUsage
, message
)
705 this.updateRunTimeWorkerUsage(tasksWorkerUsage
, message
)
706 this.updateEluWorkerUsage(tasksWorkerUsage
, message
)
709 private updateTaskStatisticsWorkerUsage (
710 workerUsage
: WorkerUsage
,
711 message
: MessageValue
<Response
>
713 const workerTaskStatistics
= workerUsage
.tasks
714 --workerTaskStatistics
.executing
715 if (message
.taskError
== null) {
716 ++workerTaskStatistics
.executed
718 ++workerTaskStatistics
.failed
722 private updateRunTimeWorkerUsage (
723 workerUsage
: WorkerUsage
,
724 message
: MessageValue
<Response
>
727 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
730 const taskRunTime
= message
.taskPerformance
?.runTime
?? 0
731 workerUsage
.runTime
.aggregate
=
732 (workerUsage
.runTime
.aggregate
?? 0) + taskRunTime
733 workerUsage
.runTime
.minimum
= Math.min(
735 workerUsage
.runTime
?.minimum
?? Infinity
737 workerUsage
.runTime
.maximum
= Math.max(
739 workerUsage
.runTime
?.maximum
?? -Infinity
742 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
744 workerUsage
.tasks
.executed
!== 0
746 workerUsage
.runTime
.average
=
747 workerUsage
.runTime
.aggregate
/ workerUsage
.tasks
.executed
750 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
752 message
.taskPerformance
?.runTime
!= null
754 workerUsage
.runTime
.history
.push(message
.taskPerformance
.runTime
)
755 workerUsage
.runTime
.median
= median(workerUsage
.runTime
.history
)
760 private updateWaitTimeWorkerUsage (
761 workerUsage
: WorkerUsage
,
764 const timestamp
= performance
.now()
765 const taskWaitTime
= timestamp
- (task
.timestamp
?? timestamp
)
767 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().waitTime
770 workerUsage
.waitTime
.aggregate
=
771 (workerUsage
.waitTime
?.aggregate
?? 0) + taskWaitTime
772 workerUsage
.waitTime
.minimum
= Math.min(
774 workerUsage
.waitTime
?.minimum
?? Infinity
776 workerUsage
.waitTime
.maximum
= Math.max(
778 workerUsage
.waitTime
?.maximum
?? -Infinity
781 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
783 workerUsage
.tasks
.executed
!== 0
785 workerUsage
.waitTime
.average
=
786 workerUsage
.waitTime
.aggregate
/ workerUsage
.tasks
.executed
789 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
792 workerUsage
.waitTime
.history
.push(taskWaitTime
)
793 workerUsage
.waitTime
.median
= median(workerUsage
.waitTime
.history
)
798 private updateEluWorkerUsage (
799 workerUsage
: WorkerUsage
,
800 message
: MessageValue
<Response
>
803 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
806 if (message
.taskPerformance
?.elu
!= null) {
807 workerUsage
.elu
.idle
.aggregate
=
808 (workerUsage
.elu
.idle
?.aggregate
?? 0) +
809 message
.taskPerformance
.elu
.idle
810 workerUsage
.elu
.active
.aggregate
=
811 (workerUsage
.elu
.active
?.aggregate
?? 0) +
812 message
.taskPerformance
.elu
.active
813 if (workerUsage
.elu
.utilization
!= null) {
814 workerUsage
.elu
.utilization
=
815 (workerUsage
.elu
.utilization
+
816 message
.taskPerformance
.elu
.utilization
) /
819 workerUsage
.elu
.utilization
= message
.taskPerformance
.elu
.utilization
821 workerUsage
.elu
.idle
.minimum
= Math.min(
822 message
.taskPerformance
.elu
.idle
,
823 workerUsage
.elu
.idle
?.minimum
?? Infinity
825 workerUsage
.elu
.idle
.maximum
= Math.max(
826 message
.taskPerformance
.elu
.idle
,
827 workerUsage
.elu
.idle
?.maximum
?? -Infinity
829 workerUsage
.elu
.active
.minimum
= Math.min(
830 message
.taskPerformance
.elu
.active
,
831 workerUsage
.elu
.active
?.minimum
?? Infinity
833 workerUsage
.elu
.active
.maximum
= Math.max(
834 message
.taskPerformance
.elu
.active
,
835 workerUsage
.elu
.active
?.maximum
?? -Infinity
838 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
840 workerUsage
.tasks
.executed
!== 0
842 workerUsage
.elu
.idle
.average
=
843 workerUsage
.elu
.idle
.aggregate
/ workerUsage
.tasks
.executed
844 workerUsage
.elu
.active
.average
=
845 workerUsage
.elu
.active
.aggregate
/ workerUsage
.tasks
.executed
848 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
851 workerUsage
.elu
.idle
.history
.push(message
.taskPerformance
.elu
.idle
)
852 workerUsage
.elu
.active
.history
.push(
853 message
.taskPerformance
.elu
.active
855 workerUsage
.elu
.idle
.median
= median(workerUsage
.elu
.idle
.history
)
856 workerUsage
.elu
.active
.median
= median(workerUsage
.elu
.active
.history
)
863 * Chooses a worker node for the next task.
865 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
867 * @returns The worker node key
869 private chooseWorkerNode (): number {
870 if (this.shallCreateDynamicWorker()) {
871 const worker
= this.createAndSetupDynamicWorker()
873 this.workerChoiceStrategyContext
.getStrategyPolicy().useDynamicWorker
875 return this.getWorkerNodeKey(worker
)
878 return this.workerChoiceStrategyContext
.execute()
882 * Conditions for dynamic worker creation.
884 * @returns Whether to create a dynamic worker or not.
886 private shallCreateDynamicWorker (): boolean {
887 return this.type === PoolTypes
.dynamic
&& !this.full
&& this.internalBusy()
891 * Sends a message to the given worker.
893 * @param worker - The worker which should receive the message.
894 * @param message - The message.
896 protected abstract sendToWorker (
898 message
: MessageValue
<Data
>
902 * Registers a listener callback on the given worker.
904 * @param worker - The worker which should register a listener.
905 * @param listener - The message listener callback.
907 private registerWorkerMessageListener
<Message
extends Data
| Response
>(
909 listener
: (message
: MessageValue
<Message
>) => void
911 worker
.on('message', listener
as MessageHandler
<Worker
>)
915 * Creates a new worker.
917 * @returns Newly created worker.
919 protected abstract createWorker (): Worker
922 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
925 * @param worker - The newly created worker.
927 protected afterWorkerSetup (worker
: Worker
): void {
928 // Listen to worker messages.
929 this.registerWorkerMessageListener(worker
, this.workerListener())
930 // Send startup message to worker.
931 this.sendToWorker(worker
, {
933 workerId
: this.getWorkerInfo(this.getWorkerNodeKey(worker
)).id
as number
935 // Setup worker task statistics computation.
936 this.setWorkerStatistics(worker
)
940 * Creates a new worker and sets it up completely in the pool worker nodes.
942 * @returns New, completely set up worker.
944 protected createAndSetupWorker (): Worker
{
945 const worker
= this.createWorker()
947 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
948 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
949 worker
.on('error', error
=> {
950 if (this.emitter
!= null) {
951 this.emitter
.emit(PoolEvents
.error
, error
)
953 if (this.opts
.enableTasksQueue
=== true) {
954 this.redistributeQueuedTasks(worker
)
956 if (this.opts
.restartWorkerOnError
=== true && !this.starting
) {
957 if (this.getWorkerInfo(this.getWorkerNodeKey(worker
)).dynamic
) {
958 this.createAndSetupDynamicWorker()
960 this.createAndSetupWorker()
964 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
965 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
966 worker
.once('exit', () => {
967 this.removeWorkerNode(worker
)
970 this.pushWorkerNode(worker
)
972 this.afterWorkerSetup(worker
)
977 private redistributeQueuedTasks (worker
: Worker
): void {
978 const workerNodeKey
= this.getWorkerNodeKey(worker
)
979 while (this.tasksQueueSize(workerNodeKey
) > 0) {
980 let targetWorkerNodeKey
: number = workerNodeKey
981 let minQueuedTasks
= Infinity
982 for (const [workerNodeId
, workerNode
] of this.workerNodes
.entries()) {
984 workerNodeId
!== workerNodeKey
&&
985 workerNode
.usage
.tasks
.queued
=== 0
987 targetWorkerNodeKey
= workerNodeId
991 workerNodeId
!== workerNodeKey
&&
992 workerNode
.usage
.tasks
.queued
< minQueuedTasks
994 minQueuedTasks
= workerNode
.usage
.tasks
.queued
995 targetWorkerNodeKey
= workerNodeId
1000 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1006 * Creates a new dynamic worker and sets it up completely in the pool worker nodes.
1008 * @returns New, completely set up dynamic worker.
1010 protected createAndSetupDynamicWorker (): Worker
{
1011 const worker
= this.createAndSetupWorker()
1012 this.registerWorkerMessageListener(worker
, message
=> {
1013 const workerNodeKey
= this.getWorkerNodeKey(worker
)
1015 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
1016 (message
.kill
!= null &&
1017 ((this.opts
.enableTasksQueue
=== false &&
1018 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
=== 0) ||
1019 (this.opts
.enableTasksQueue
=== true &&
1020 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
=== 0 &&
1021 this.tasksQueueSize(workerNodeKey
) === 0)))
1023 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
1024 void (this.destroyWorker(worker
) as Promise
<void>)
1027 const workerInfo
= this.getWorkerInfo(this.getWorkerNodeKey(worker
))
1028 workerInfo
.dynamic
= true
1029 this.sendToWorker(worker
, {
1031 workerId
: workerInfo
.id
as number
1037 * This function is the listener registered for each worker message.
1039 * @returns The listener function to execute when a message is received from a worker.
1041 protected workerListener (): (message
: MessageValue
<Response
>) => void {
1043 this.checkMessageWorkerId(message
)
1044 if (message
.ready
!= null && message
.workerId
!= null) {
1045 // Worker ready message received
1046 this.handleWorkerReadyMessage(message
)
1047 } else if (message
.id
!= null) {
1048 // Task execution response received
1049 this.handleTaskExecutionResponse(message
)
1054 private handleWorkerReadyMessage (message
: MessageValue
<Response
>): void {
1055 const worker
= this.getWorkerById(message
.workerId
)
1056 this.getWorkerInfo(this.getWorkerNodeKey(worker
as Worker
)).ready
=
1057 message
.ready
as boolean
1058 if (this.emitter
!= null && this.ready
) {
1059 this.emitter
.emit(PoolEvents
.ready
, this.info
)
1063 private handleTaskExecutionResponse (message
: MessageValue
<Response
>): void {
1064 const promiseResponse
= this.promiseResponseMap
.get(message
.id
as string)
1065 if (promiseResponse
!= null) {
1066 if (message
.taskError
!= null) {
1067 if (this.emitter
!= null) {
1068 this.emitter
.emit(PoolEvents
.taskError
, message
.taskError
)
1070 promiseResponse
.reject(message
.taskError
.message
)
1072 promiseResponse
.resolve(message
.data
as Response
)
1074 this.afterTaskExecutionHook(promiseResponse
.worker
, message
)
1075 this.promiseResponseMap
.delete(message
.id
as string)
1076 const workerNodeKey
= this.getWorkerNodeKey(promiseResponse
.worker
)
1078 this.opts
.enableTasksQueue
=== true &&
1079 this.tasksQueueSize(workerNodeKey
) > 0
1083 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1086 this.workerChoiceStrategyContext
.update(workerNodeKey
)
1090 private checkAndEmitEvents (): void {
1091 if (this.emitter
!= null) {
1093 this.emitter
.emit(PoolEvents
.busy
, this.info
)
1095 if (this.type === PoolTypes
.dynamic
&& this.full
) {
1096 this.emitter
.emit(PoolEvents
.full
, this.info
)
1102 * Gets the worker information.
1104 * @param workerNodeKey - The worker node key.
1106 private getWorkerInfo (workerNodeKey
: number): WorkerInfo
{
1107 return this.workerNodes
[workerNodeKey
].info
1111 * Pushes the given worker in the pool worker nodes.
1113 * @param worker - The worker.
1114 * @returns The worker nodes length.
1116 private pushWorkerNode (worker
: Worker
): number {
1117 return this.workerNodes
.push(new WorkerNode(worker
, this.worker
))
1121 * Removes the given worker from the pool worker nodes.
1123 * @param worker - The worker.
1125 private removeWorkerNode (worker
: Worker
): void {
1126 const workerNodeKey
= this.getWorkerNodeKey(worker
)
1127 if (workerNodeKey
!== -1) {
1128 this.workerNodes
.splice(workerNodeKey
, 1)
1129 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
1133 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
1134 this.beforeTaskExecutionHook(workerNodeKey
, task
)
1135 this.sendToWorker(this.workerNodes
[workerNodeKey
].worker
, task
)
1138 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
1139 return this.workerNodes
[workerNodeKey
].enqueueTask(task
)
1142 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
1143 return this.workerNodes
[workerNodeKey
].dequeueTask()
1146 private tasksQueueSize (workerNodeKey
: number): number {
1147 return this.workerNodes
[workerNodeKey
].tasksQueueSize()
1150 private flushTasksQueue (workerNodeKey
: number): void {
1151 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1154 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1157 this.workerNodes
[workerNodeKey
].clearTasksQueue()
1160 private flushTasksQueues (): void {
1161 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
1162 this.flushTasksQueue(workerNodeKey
)
1166 private setWorkerStatistics (worker
: Worker
): void {
1167 this.sendToWorker(worker
, {
1170 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1172 elu
: this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1175 workerId
: this.getWorkerInfo(this.getWorkerNodeKey(worker
)).id
as number