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 Error('Cannot instantiate a fixed pool with no worker')
160 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
161 if (isPlainObject(opts
)) {
162 this.opts
.workerChoiceStrategy
=
163 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
164 this.checkValidWorkerChoiceStrategy(this.opts
.workerChoiceStrategy
)
165 this.opts
.workerChoiceStrategyOptions
=
166 opts
.workerChoiceStrategyOptions
??
167 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
168 this.checkValidWorkerChoiceStrategyOptions(
169 this.opts
.workerChoiceStrategyOptions
171 this.opts
.restartWorkerOnError
= opts
.restartWorkerOnError
?? true
172 this.opts
.enableEvents
= opts
.enableEvents
?? true
173 this.opts
.enableTasksQueue
= opts
.enableTasksQueue
?? false
174 if (this.opts
.enableTasksQueue
) {
175 this.checkValidTasksQueueOptions(
176 opts
.tasksQueueOptions
as TasksQueueOptions
178 this.opts
.tasksQueueOptions
= this.buildTasksQueueOptions(
179 opts
.tasksQueueOptions
as TasksQueueOptions
183 throw new TypeError('Invalid pool options: must be a plain object')
187 private checkValidWorkerChoiceStrategy (
188 workerChoiceStrategy
: WorkerChoiceStrategy
190 if (!Object.values(WorkerChoiceStrategies
).includes(workerChoiceStrategy
)) {
192 `Invalid worker choice strategy '${workerChoiceStrategy}'`
197 private checkValidWorkerChoiceStrategyOptions (
198 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
200 if (!isPlainObject(workerChoiceStrategyOptions
)) {
202 'Invalid worker choice strategy options: must be a plain object'
206 workerChoiceStrategyOptions
.weights
!= null &&
207 Object.keys(workerChoiceStrategyOptions
.weights
).length
!== this.maxSize
210 'Invalid worker choice strategy options: must have a weight for each worker node'
214 workerChoiceStrategyOptions
.measurement
!= null &&
215 !Object.values(Measurements
).includes(
216 workerChoiceStrategyOptions
.measurement
220 `Invalid worker choice strategy options: invalid measurement '${workerChoiceStrategyOptions.measurement}'`
225 private checkValidTasksQueueOptions (
226 tasksQueueOptions
: TasksQueueOptions
228 if (tasksQueueOptions
!= null && !isPlainObject(tasksQueueOptions
)) {
229 throw new TypeError('Invalid tasks queue options: must be a plain object')
232 tasksQueueOptions
?.concurrency
!= null &&
233 !Number.isSafeInteger(tasksQueueOptions
.concurrency
)
236 'Invalid worker tasks concurrency: must be an integer'
240 tasksQueueOptions
?.concurrency
!= null &&
241 tasksQueueOptions
.concurrency
<= 0
244 `Invalid worker tasks concurrency '${tasksQueueOptions.concurrency}'`
250 public get
info (): PoolInfo
{
255 minSize
: this.minSize
,
256 maxSize
: this.maxSize
,
257 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
258 .runTime
.aggregate
&&
259 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
260 .waitTime
.aggregate
&& { utilization
: round(this.utilization
) }),
261 workerNodes
: this.workerNodes
.length
,
262 idleWorkerNodes
: this.workerNodes
.reduce(
263 (accumulator
, workerNode
) =>
264 workerNode
.usage
.tasks
.executing
=== 0
269 busyWorkerNodes
: this.workerNodes
.reduce(
270 (accumulator
, workerNode
) =>
271 workerNode
.usage
.tasks
.executing
> 0 ? accumulator
+ 1 : accumulator
,
274 executedTasks
: this.workerNodes
.reduce(
275 (accumulator
, workerNode
) =>
276 accumulator
+ workerNode
.usage
.tasks
.executed
,
279 executingTasks
: this.workerNodes
.reduce(
280 (accumulator
, workerNode
) =>
281 accumulator
+ workerNode
.usage
.tasks
.executing
,
284 queuedTasks
: this.workerNodes
.reduce(
285 (accumulator
, workerNode
) =>
286 accumulator
+ workerNode
.usage
.tasks
.queued
,
289 maxQueuedTasks
: this.workerNodes
.reduce(
290 (accumulator
, workerNode
) =>
291 accumulator
+ workerNode
.usage
.tasks
.maxQueued
,
294 failedTasks
: this.workerNodes
.reduce(
295 (accumulator
, workerNode
) =>
296 accumulator
+ workerNode
.usage
.tasks
.failed
,
299 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
300 .runTime
.aggregate
&& {
304 ...this.workerNodes
.map(
305 workerNode
=> workerNode
.usage
.runTime
?.minimum
?? Infinity
311 ...this.workerNodes
.map(
312 workerNode
=> workerNode
.usage
.runTime
?.maximum
?? -Infinity
317 this.workerNodes
.reduce(
318 (accumulator
, workerNode
) =>
319 accumulator
+ (workerNode
.usage
.runTime
?.aggregate
?? 0),
322 this.workerNodes
.reduce(
323 (accumulator
, workerNode
) =>
324 accumulator
+ (workerNode
.usage
.tasks
?.executed
?? 0),
328 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
332 this.workerNodes
.map(
333 workerNode
=> workerNode
.usage
.runTime
?.median
?? 0
340 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
341 .waitTime
.aggregate
&& {
345 ...this.workerNodes
.map(
346 workerNode
=> workerNode
.usage
.waitTime
?.minimum
?? Infinity
352 ...this.workerNodes
.map(
353 workerNode
=> workerNode
.usage
.waitTime
?.maximum
?? -Infinity
358 this.workerNodes
.reduce(
359 (accumulator
, workerNode
) =>
360 accumulator
+ (workerNode
.usage
.waitTime
?.aggregate
?? 0),
363 this.workerNodes
.reduce(
364 (accumulator
, workerNode
) =>
365 accumulator
+ (workerNode
.usage
.tasks
?.executed
?? 0),
369 ...(this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
370 .waitTime
.median
&& {
373 this.workerNodes
.map(
374 workerNode
=> workerNode
.usage
.waitTime
?.median
?? 0
385 * Gets the approximate pool utilization.
387 * @returns The pool utilization.
389 private get
utilization (): number {
390 const poolRunTimeCapacity
=
391 (performance
.now() - this.startTimestamp
) * this.maxSize
392 const totalTasksRunTime
= this.workerNodes
.reduce(
393 (accumulator
, workerNode
) =>
394 accumulator
+ (workerNode
.usage
.runTime
?.aggregate
?? 0),
397 const totalTasksWaitTime
= this.workerNodes
.reduce(
398 (accumulator
, workerNode
) =>
399 accumulator
+ (workerNode
.usage
.waitTime
?.aggregate
?? 0),
402 return (totalTasksRunTime
+ totalTasksWaitTime
) / poolRunTimeCapacity
408 * If it is `'dynamic'`, it provides the `max` property.
410 protected abstract get
type (): PoolType
413 * Gets the worker type.
415 protected abstract get
worker (): WorkerType
420 protected abstract get
minSize (): number
425 protected abstract get
maxSize (): number
428 * Get the worker given its id.
430 * @param workerId - The worker id.
431 * @returns The worker if found in the pool worker nodes, `undefined` otherwise.
433 private getWorkerById (workerId
: number): Worker
| undefined {
434 return this.workerNodes
.find(workerNode
=> workerNode
.info
.id
=== workerId
)
439 * Gets the given worker its worker node key.
441 * @param worker - The worker.
442 * @returns The worker node key if found in the pool worker nodes, `-1` otherwise.
444 private getWorkerNodeKey (worker
: Worker
): number {
445 return this.workerNodes
.findIndex(
446 workerNode
=> workerNode
.worker
=== worker
451 public setWorkerChoiceStrategy (
452 workerChoiceStrategy
: WorkerChoiceStrategy
,
453 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
455 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
456 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
457 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
458 this.opts
.workerChoiceStrategy
460 if (workerChoiceStrategyOptions
!= null) {
461 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
463 for (const workerNode
of this.workerNodes
) {
464 workerNode
.resetUsage()
465 this.setWorkerStatistics(workerNode
.worker
)
470 public setWorkerChoiceStrategyOptions (
471 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
473 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
474 this.opts
.workerChoiceStrategyOptions
= workerChoiceStrategyOptions
475 this.workerChoiceStrategyContext
.setOptions(
476 this.opts
.workerChoiceStrategyOptions
481 public enableTasksQueue (
483 tasksQueueOptions
?: TasksQueueOptions
485 if (this.opts
.enableTasksQueue
=== true && !enable
) {
486 this.flushTasksQueues()
488 this.opts
.enableTasksQueue
= enable
489 this.setTasksQueueOptions(tasksQueueOptions
as TasksQueueOptions
)
493 public setTasksQueueOptions (tasksQueueOptions
: TasksQueueOptions
): void {
494 if (this.opts
.enableTasksQueue
=== true) {
495 this.checkValidTasksQueueOptions(tasksQueueOptions
)
496 this.opts
.tasksQueueOptions
=
497 this.buildTasksQueueOptions(tasksQueueOptions
)
498 } else if (this.opts
.tasksQueueOptions
!= null) {
499 delete this.opts
.tasksQueueOptions
503 private buildTasksQueueOptions (
504 tasksQueueOptions
: TasksQueueOptions
505 ): TasksQueueOptions
{
507 concurrency
: tasksQueueOptions
?.concurrency
?? 1
512 * Whether the pool is full or not.
514 * The pool filling boolean status.
516 protected get
full (): boolean {
517 return this.workerNodes
.length
>= this.maxSize
521 * Whether the pool is busy or not.
523 * The pool busyness boolean status.
525 protected abstract get
busy (): boolean
528 * Whether worker nodes are executing at least one task.
530 * @returns Worker nodes busyness boolean status.
532 protected internalBusy (): boolean {
534 this.workerNodes
.findIndex(workerNode
=> {
535 return workerNode
.usage
.tasks
.executing
=== 0
541 public async execute (data
?: Data
, name
?: string): Promise
<Response
> {
542 const timestamp
= performance
.now()
543 const workerNodeKey
= this.chooseWorkerNode()
544 const submittedTask
: Task
<Data
> = {
546 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
547 data
: data
?? ({} as Data
),
551 const res
= new Promise
<Response
>((resolve
, reject
) => {
552 this.promiseResponseMap
.set(submittedTask
.id
as string, {
555 worker
: this.workerNodes
[workerNodeKey
].worker
559 this.opts
.enableTasksQueue
=== true &&
561 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
>=
562 ((this.opts
.tasksQueueOptions
as TasksQueueOptions
)
563 .concurrency
as number))
565 this.enqueueTask(workerNodeKey
, submittedTask
)
567 this.executeTask(workerNodeKey
, submittedTask
)
569 this.checkAndEmitEvents()
570 // eslint-disable-next-line @typescript-eslint/return-await
575 public async destroy (): Promise
<void> {
577 this.workerNodes
.map(async (workerNode
, workerNodeKey
) => {
578 this.flushTasksQueue(workerNodeKey
)
579 // FIXME: wait for tasks to be finished
580 const workerExitPromise
= new Promise
<void>(resolve
=> {
581 workerNode
.worker
.on('exit', () => {
585 await this.destroyWorker(workerNode
.worker
)
586 await workerExitPromise
592 * Terminates the given worker.
594 * @param worker - A worker within `workerNodes`.
596 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
599 * Setup hook to execute code before worker nodes are created in the abstract constructor.
604 protected setupHook (): void {
605 // Intentionally empty
609 * Should return whether the worker is the main worker or not.
611 protected abstract isMain (): boolean
614 * Hook executed before the worker task execution.
617 * @param workerNodeKey - The worker node key.
618 * @param task - The task to execute.
620 protected beforeTaskExecutionHook (
621 workerNodeKey
: number,
624 const workerUsage
= this.workerNodes
[workerNodeKey
].usage
625 ++workerUsage
.tasks
.executing
626 this.updateWaitTimeWorkerUsage(workerUsage
, task
)
630 * Hook executed after the worker task execution.
633 * @param worker - The worker.
634 * @param message - The received message.
636 protected afterTaskExecutionHook (
638 message
: MessageValue
<Response
>
640 const workerUsage
= this.workerNodes
[this.getWorkerNodeKey(worker
)].usage
641 this.updateTaskStatisticsWorkerUsage(workerUsage
, message
)
642 this.updateRunTimeWorkerUsage(workerUsage
, message
)
643 this.updateEluWorkerUsage(workerUsage
, message
)
646 private updateTaskStatisticsWorkerUsage (
647 workerUsage
: WorkerUsage
,
648 message
: MessageValue
<Response
>
650 const workerTaskStatistics
= workerUsage
.tasks
651 --workerTaskStatistics
.executing
652 if (message
.taskError
== null) {
653 ++workerTaskStatistics
.executed
655 ++workerTaskStatistics
.failed
659 private updateRunTimeWorkerUsage (
660 workerUsage
: WorkerUsage
,
661 message
: MessageValue
<Response
>
664 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
667 const taskRunTime
= message
.taskPerformance
?.runTime
?? 0
668 workerUsage
.runTime
.aggregate
=
669 (workerUsage
.runTime
.aggregate
?? 0) + taskRunTime
670 workerUsage
.runTime
.minimum
= Math.min(
672 workerUsage
.runTime
?.minimum
?? Infinity
674 workerUsage
.runTime
.maximum
= Math.max(
676 workerUsage
.runTime
?.maximum
?? -Infinity
679 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
681 workerUsage
.tasks
.executed
!== 0
683 workerUsage
.runTime
.average
=
684 workerUsage
.runTime
.aggregate
/ workerUsage
.tasks
.executed
687 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().runTime
689 message
.taskPerformance
?.runTime
!= null
691 workerUsage
.runTime
.history
.push(message
.taskPerformance
.runTime
)
692 workerUsage
.runTime
.median
= median(workerUsage
.runTime
.history
)
697 private updateWaitTimeWorkerUsage (
698 workerUsage
: WorkerUsage
,
701 const timestamp
= performance
.now()
702 const taskWaitTime
= timestamp
- (task
.timestamp
?? timestamp
)
704 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().waitTime
707 workerUsage
.waitTime
.aggregate
=
708 (workerUsage
.waitTime
?.aggregate
?? 0) + taskWaitTime
709 workerUsage
.waitTime
.minimum
= Math.min(
711 workerUsage
.waitTime
?.minimum
?? Infinity
713 workerUsage
.waitTime
.maximum
= Math.max(
715 workerUsage
.waitTime
?.maximum
?? -Infinity
718 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
720 workerUsage
.tasks
.executed
!== 0
722 workerUsage
.waitTime
.average
=
723 workerUsage
.waitTime
.aggregate
/ workerUsage
.tasks
.executed
726 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
729 workerUsage
.waitTime
.history
.push(taskWaitTime
)
730 workerUsage
.waitTime
.median
= median(workerUsage
.waitTime
.history
)
735 private updateEluWorkerUsage (
736 workerUsage
: WorkerUsage
,
737 message
: MessageValue
<Response
>
740 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
743 if (message
.taskPerformance
?.elu
!= null) {
744 workerUsage
.elu
.idle
.aggregate
=
745 (workerUsage
.elu
.idle
?.aggregate
?? 0) +
746 message
.taskPerformance
.elu
.idle
747 workerUsage
.elu
.active
.aggregate
=
748 (workerUsage
.elu
.active
?.aggregate
?? 0) +
749 message
.taskPerformance
.elu
.active
750 if (workerUsage
.elu
.utilization
!= null) {
751 workerUsage
.elu
.utilization
=
752 (workerUsage
.elu
.utilization
+
753 message
.taskPerformance
.elu
.utilization
) /
756 workerUsage
.elu
.utilization
= message
.taskPerformance
.elu
.utilization
758 workerUsage
.elu
.idle
.minimum
= Math.min(
759 message
.taskPerformance
.elu
.idle
,
760 workerUsage
.elu
.idle
?.minimum
?? Infinity
762 workerUsage
.elu
.idle
.maximum
= Math.max(
763 message
.taskPerformance
.elu
.idle
,
764 workerUsage
.elu
.idle
?.maximum
?? -Infinity
766 workerUsage
.elu
.active
.minimum
= Math.min(
767 message
.taskPerformance
.elu
.active
,
768 workerUsage
.elu
.active
?.minimum
?? Infinity
770 workerUsage
.elu
.active
.maximum
= Math.max(
771 message
.taskPerformance
.elu
.active
,
772 workerUsage
.elu
.active
?.maximum
?? -Infinity
775 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
777 workerUsage
.tasks
.executed
!== 0
779 workerUsage
.elu
.idle
.average
=
780 workerUsage
.elu
.idle
.aggregate
/ workerUsage
.tasks
.executed
781 workerUsage
.elu
.active
.average
=
782 workerUsage
.elu
.active
.aggregate
/ workerUsage
.tasks
.executed
785 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements().elu
788 workerUsage
.elu
.idle
.history
.push(message
.taskPerformance
.elu
.idle
)
789 workerUsage
.elu
.active
.history
.push(
790 message
.taskPerformance
.elu
.active
792 workerUsage
.elu
.idle
.median
= median(workerUsage
.elu
.idle
.history
)
793 workerUsage
.elu
.active
.median
= median(workerUsage
.elu
.active
.history
)
800 * Chooses a worker node for the next task.
802 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
804 * @returns The worker node key
806 private chooseWorkerNode (): number {
807 if (this.shallCreateDynamicWorker()) {
808 const worker
= this.createAndSetupDynamicWorker()
810 this.workerChoiceStrategyContext
.getStrategyPolicy().useDynamicWorker
812 return this.getWorkerNodeKey(worker
)
815 return this.workerChoiceStrategyContext
.execute()
819 * Conditions for dynamic worker creation.
821 * @returns Whether to create a dynamic worker or not.
823 private shallCreateDynamicWorker (): boolean {
824 return this.type === PoolTypes
.dynamic
&& !this.full
&& this.internalBusy()
828 * Sends a message to the given worker.
830 * @param worker - The worker which should receive the message.
831 * @param message - The message.
833 protected abstract sendToWorker (
835 message
: MessageValue
<Data
>
839 * Registers a listener callback on the given worker.
841 * @param worker - The worker which should register a listener.
842 * @param listener - The message listener callback.
844 private registerWorkerMessageListener
<Message
extends Data
| Response
>(
846 listener
: (message
: MessageValue
<Message
>) => void
848 worker
.on('message', listener
as MessageHandler
<Worker
>)
852 * Creates a new worker.
854 * @returns Newly created worker.
856 protected abstract createWorker (): Worker
859 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
862 * @param worker - The newly created worker.
864 protected afterWorkerSetup (worker
: Worker
): void {
865 // Listen to worker messages.
866 this.registerWorkerMessageListener(worker
, this.workerListener())
870 * Creates a new worker and sets it up completely in the pool worker nodes.
872 * @returns New, completely set up worker.
874 protected createAndSetupWorker (): Worker
{
875 const worker
= this.createWorker()
877 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
878 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
879 worker
.on('error', error
=> {
880 if (this.emitter
!= null) {
881 this.emitter
.emit(PoolEvents
.error
, error
)
883 if (this.opts
.enableTasksQueue
=== true) {
884 this.redistributeQueuedTasks(worker
)
886 if (this.opts
.restartWorkerOnError
=== true) {
887 if (this.getWorkerInfo(this.getWorkerNodeKey(worker
)).dynamic
) {
888 this.createAndSetupDynamicWorker()
890 this.createAndSetupWorker()
894 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
895 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
896 worker
.once('exit', () => {
897 this.removeWorkerNode(worker
)
900 this.pushWorkerNode(worker
)
902 this.setWorkerStatistics(worker
)
904 this.afterWorkerSetup(worker
)
909 private redistributeQueuedTasks (worker
: Worker
): void {
910 const workerNodeKey
= this.getWorkerNodeKey(worker
)
911 while (this.tasksQueueSize(workerNodeKey
) > 0) {
912 let targetWorkerNodeKey
: number = workerNodeKey
913 let minQueuedTasks
= Infinity
914 for (const [workerNodeId
, workerNode
] of this.workerNodes
.entries()) {
916 workerNodeId
!== workerNodeKey
&&
917 workerNode
.usage
.tasks
.queued
=== 0
919 targetWorkerNodeKey
= workerNodeId
923 workerNodeId
!== workerNodeKey
&&
924 workerNode
.usage
.tasks
.queued
< minQueuedTasks
926 minQueuedTasks
= workerNode
.usage
.tasks
.queued
927 targetWorkerNodeKey
= workerNodeId
932 this.dequeueTask(workerNodeKey
) as Task
<Data
>
938 * Creates a new dynamic worker and sets it up completely in the pool worker nodes.
940 * @returns New, completely set up dynamic worker.
942 protected createAndSetupDynamicWorker (): Worker
{
943 const worker
= this.createAndSetupWorker()
944 this.getWorkerInfo(this.getWorkerNodeKey(worker
)).dynamic
= true
945 this.registerWorkerMessageListener(worker
, message
=> {
946 const workerNodeKey
= this.getWorkerNodeKey(worker
)
948 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
949 (message
.kill
!= null &&
950 ((this.opts
.enableTasksQueue
=== false &&
951 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
=== 0) ||
952 (this.opts
.enableTasksQueue
=== true &&
953 this.workerNodes
[workerNodeKey
].usage
.tasks
.executing
=== 0 &&
954 this.tasksQueueSize(workerNodeKey
) === 0)))
956 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
957 void (this.destroyWorker(worker
) as Promise
<void>)
960 this.sendToWorker(worker
, { dynamic
: true })
965 * This function is the listener registered for each worker message.
967 * @returns The listener function to execute when a message is received from a worker.
969 protected workerListener (): (message
: MessageValue
<Response
>) => void {
971 if (message
.workerId
!= null && message
.started
!= null) {
972 // Worker started message received
973 this.handleWorkerStartedMessage(message
)
974 } else if (message
.id
!= null) {
975 // Task execution response received
976 this.handleTaskExecutionResponse(message
)
981 private handleWorkerStartedMessage (message
: MessageValue
<Response
>): void {
982 // Worker started message received
983 const worker
= this.getWorkerById(message
.workerId
as number)
984 if (worker
!= null) {
985 this.workerNodes
[this.getWorkerNodeKey(worker
)].info
.started
=
986 message
.started
as boolean
989 `Worker started message received from unknown worker '${
990 message.workerId as number
996 private handleTaskExecutionResponse (message
: MessageValue
<Response
>): void {
997 const promiseResponse
= this.promiseResponseMap
.get(message
.id
as string)
998 if (promiseResponse
!= null) {
999 if (message
.taskError
!= null) {
1000 if (this.emitter
!= null) {
1001 this.emitter
.emit(PoolEvents
.taskError
, message
.taskError
)
1003 promiseResponse
.reject(message
.taskError
.message
)
1005 promiseResponse
.resolve(message
.data
as Response
)
1007 this.afterTaskExecutionHook(promiseResponse
.worker
, message
)
1008 this.promiseResponseMap
.delete(message
.id
as string)
1009 const workerNodeKey
= this.getWorkerNodeKey(promiseResponse
.worker
)
1011 this.opts
.enableTasksQueue
=== true &&
1012 this.tasksQueueSize(workerNodeKey
) > 0
1016 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1019 this.workerChoiceStrategyContext
.update(workerNodeKey
)
1023 private checkAndEmitEvents (): void {
1024 if (this.emitter
!= null) {
1026 this.emitter
.emit(PoolEvents
.busy
, this.info
)
1028 if (this.type === PoolTypes
.dynamic
&& this.full
) {
1029 this.emitter
.emit(PoolEvents
.full
, this.info
)
1035 * Gets the worker information.
1037 * @param workerNodeKey - The worker node key.
1039 private getWorkerInfo (workerNodeKey
: number): WorkerInfo
{
1040 return this.workerNodes
[workerNodeKey
].info
1044 * Pushes the given worker in the pool worker nodes.
1046 * @param worker - The worker.
1047 * @returns The worker nodes length.
1049 private pushWorkerNode (worker
: Worker
): number {
1050 return this.workerNodes
.push(new WorkerNode(worker
, this.worker
))
1054 * Removes the given worker from the pool worker nodes.
1056 * @param worker - The worker.
1058 private removeWorkerNode (worker
: Worker
): void {
1059 const workerNodeKey
= this.getWorkerNodeKey(worker
)
1060 if (workerNodeKey
!== -1) {
1061 this.workerNodes
.splice(workerNodeKey
, 1)
1062 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
1066 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
1067 this.beforeTaskExecutionHook(workerNodeKey
, task
)
1068 this.sendToWorker(this.workerNodes
[workerNodeKey
].worker
, task
)
1071 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
1072 return this.workerNodes
[workerNodeKey
].enqueueTask(task
)
1075 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
1076 return this.workerNodes
[workerNodeKey
].dequeueTask()
1079 private tasksQueueSize (workerNodeKey
: number): number {
1080 return this.workerNodes
[workerNodeKey
].tasksQueueSize()
1083 private flushTasksQueue (workerNodeKey
: number): void {
1084 while (this.tasksQueueSize(workerNodeKey
) > 0) {
1087 this.dequeueTask(workerNodeKey
) as Task
<Data
>
1090 this.workerNodes
[workerNodeKey
].clearTasksQueue()
1093 private flushTasksQueues (): void {
1094 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
1095 this.flushTasksQueue(workerNodeKey
)
1099 private setWorkerStatistics (worker
: Worker
): void {
1100 this.sendToWorker(worker
, {
1103 this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()
1105 elu
: this.workerChoiceStrategyContext
.getTaskStatisticsRequirements()