1 import crypto from
'node:crypto'
2 import { performance
} from
'node:perf_hooks'
3 import type { MessageValue
, PromiseResponseWrapper
} from
'../utility-types'
5 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
,
10 import { KillBehaviors
, isKillBehavior
} from
'../worker/worker-options'
11 import { CircularArray
} from
'../circular-array'
12 import { Queue
} from
'../queue'
21 type TasksQueueOptions
,
24 import type { IWorker
, Task
, TasksUsage
, WorkerNode
} from
'./worker'
26 WorkerChoiceStrategies
,
27 type WorkerChoiceStrategy
,
28 type WorkerChoiceStrategyOptions
29 } from
'./selection-strategies/selection-strategies-types'
30 import { WorkerChoiceStrategyContext
} from
'./selection-strategies/worker-choice-strategy-context'
33 * Base class that implements some shared logic for all poolifier pools.
35 * @typeParam Worker - Type of worker which manages this pool.
36 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
37 * @typeParam Response - Type of execution response. This can only be serializable data.
39 export abstract class AbstractPool
<
40 Worker
extends IWorker
,
43 > implements IPool
<Worker
, Data
, Response
> {
45 public readonly workerNodes
: Array<WorkerNode
<Worker
, Data
>> = []
48 public readonly emitter
?: PoolEmitter
51 * The execution response promise map.
53 * - `key`: The message id of each submitted task.
54 * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks.
56 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
58 protected promiseResponseMap
: Map
<
60 PromiseResponseWrapper
<Worker
, Response
>
61 > = new Map
<string, PromiseResponseWrapper
<Worker
, Response
>>()
64 * Worker choice strategy context referencing a worker choice algorithm implementation.
66 * Default to a round robin algorithm.
68 protected workerChoiceStrategyContext
: WorkerChoiceStrategyContext
<
75 * Constructs a new poolifier pool.
77 * @param numberOfWorkers - Number of workers that this pool should manage.
78 * @param filePath - Path to the worker file.
79 * @param opts - Options for the pool.
82 protected readonly numberOfWorkers
: number,
83 protected readonly filePath
: string,
84 protected readonly opts
: PoolOptions
<Worker
>
87 throw new Error('Cannot start a pool from a worker!')
89 this.checkNumberOfWorkers(this.numberOfWorkers
)
90 this.checkFilePath(this.filePath
)
91 this.checkPoolOptions(this.opts
)
93 this.chooseWorkerNode
= this.chooseWorkerNode
.bind(this)
94 this.executeTask
= this.executeTask
.bind(this)
95 this.enqueueTask
= this.enqueueTask
.bind(this)
96 this.checkAndEmitEvents
= this.checkAndEmitEvents
.bind(this)
98 if (this.opts
.enableEvents
=== true) {
99 this.emitter
= new PoolEmitter()
101 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext
<
107 this.opts
.workerChoiceStrategy
,
108 this.opts
.workerChoiceStrategyOptions
113 for (let i
= 1; i
<= this.numberOfWorkers
; i
++) {
114 this.createAndSetupWorker()
118 private checkFilePath (filePath
: string): void {
121 (typeof filePath
=== 'string' && filePath
.trim().length
=== 0)
123 throw new Error('Please specify a file with a worker implementation')
127 private checkNumberOfWorkers (numberOfWorkers
: number): void {
128 if (numberOfWorkers
== null) {
130 'Cannot instantiate a pool without specifying the number of workers'
132 } else if (!Number.isSafeInteger(numberOfWorkers
)) {
134 'Cannot instantiate a pool with a non safe integer number of workers'
136 } else if (numberOfWorkers
< 0) {
137 throw new RangeError(
138 'Cannot instantiate a pool with a negative number of workers'
140 } else if (this.type === PoolTypes
.fixed
&& numberOfWorkers
=== 0) {
141 throw new Error('Cannot instantiate a fixed pool with no worker')
145 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
146 if (isPlainObject(opts
)) {
147 this.opts
.workerChoiceStrategy
=
148 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
149 this.checkValidWorkerChoiceStrategy(this.opts
.workerChoiceStrategy
)
150 this.opts
.workerChoiceStrategyOptions
=
151 opts
.workerChoiceStrategyOptions
??
152 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
153 this.checkValidWorkerChoiceStrategyOptions(
154 this.opts
.workerChoiceStrategyOptions
156 this.opts
.restartWorkerOnError
= opts
.restartWorkerOnError
?? true
157 this.opts
.enableEvents
= opts
.enableEvents
?? true
158 this.opts
.enableTasksQueue
= opts
.enableTasksQueue
?? false
159 if (this.opts
.enableTasksQueue
) {
160 this.checkValidTasksQueueOptions(
161 opts
.tasksQueueOptions
as TasksQueueOptions
163 this.opts
.tasksQueueOptions
= this.buildTasksQueueOptions(
164 opts
.tasksQueueOptions
as TasksQueueOptions
168 throw new TypeError('Invalid pool options: must be a plain object')
172 private checkValidWorkerChoiceStrategy (
173 workerChoiceStrategy
: WorkerChoiceStrategy
175 if (!Object.values(WorkerChoiceStrategies
).includes(workerChoiceStrategy
)) {
177 `Invalid worker choice strategy '${workerChoiceStrategy}'`
182 private checkValidWorkerChoiceStrategyOptions (
183 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
185 if (!isPlainObject(workerChoiceStrategyOptions
)) {
187 'Invalid worker choice strategy options: must be a plain object'
191 workerChoiceStrategyOptions
.weights
!= null &&
192 Object.keys(workerChoiceStrategyOptions
.weights
).length
!== this.maxSize
195 'Invalid worker choice strategy options: must have a weight for each worker node'
200 private checkValidTasksQueueOptions (
201 tasksQueueOptions
: TasksQueueOptions
203 if (tasksQueueOptions
!= null && !isPlainObject(tasksQueueOptions
)) {
204 throw new TypeError('Invalid tasks queue options: must be a plain object')
206 if ((tasksQueueOptions
?.concurrency
as number) <= 0) {
208 `Invalid worker tasks concurrency '${
209 tasksQueueOptions.concurrency as number
216 public get
info (): PoolInfo
{
220 minSize
: this.minSize
,
221 maxSize
: this.maxSize
,
222 workerNodes
: this.workerNodes
.length
,
223 idleWorkerNodes
: this.workerNodes
.reduce(
224 (accumulator
, workerNode
) =>
225 workerNode
.tasksUsage
.running
=== 0 ? accumulator
+ 1 : accumulator
,
228 busyWorkerNodes
: this.workerNodes
.reduce(
229 (accumulator
, workerNode
) =>
230 workerNode
.tasksUsage
.running
> 0 ? accumulator
+ 1 : accumulator
,
233 runningTasks
: this.workerNodes
.reduce(
234 (accumulator
, workerNode
) =>
235 accumulator
+ workerNode
.tasksUsage
.running
,
238 queuedTasks
: this.workerNodes
.reduce(
239 (accumulator
, workerNode
) => accumulator
+ workerNode
.tasksQueue
.size
,
242 maxQueuedTasks
: this.workerNodes
.reduce(
243 (accumulator
, workerNode
) =>
244 accumulator
+ workerNode
.tasksQueue
.maxSize
,
253 * If it is `'dynamic'`, it provides the `max` property.
255 protected abstract get
type (): PoolType
258 * Gets the worker type.
260 protected abstract get
worker (): WorkerType
265 protected abstract get
minSize (): number
270 protected abstract get
maxSize (): number
273 * Gets the given worker its worker node key.
275 * @param worker - The worker.
276 * @returns The worker node key if the worker is found in the pool worker nodes, `-1` otherwise.
278 private getWorkerNodeKey (worker
: Worker
): number {
279 return this.workerNodes
.findIndex(
280 workerNode
=> workerNode
.worker
=== worker
285 public setWorkerChoiceStrategy (
286 workerChoiceStrategy
: WorkerChoiceStrategy
,
287 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
289 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
290 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
291 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
292 this.opts
.workerChoiceStrategy
294 if (workerChoiceStrategyOptions
!= null) {
295 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
297 for (const workerNode
of this.workerNodes
) {
298 this.setWorkerNodeTasksUsage(workerNode
, {
302 runTimeHistory
: new CircularArray(),
306 waitTimeHistory
: new CircularArray(),
312 this.setWorkerStatistics(workerNode
.worker
)
317 public setWorkerChoiceStrategyOptions (
318 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
320 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
321 this.opts
.workerChoiceStrategyOptions
= workerChoiceStrategyOptions
322 this.workerChoiceStrategyContext
.setOptions(
323 this.opts
.workerChoiceStrategyOptions
328 public enableTasksQueue (
330 tasksQueueOptions
?: TasksQueueOptions
332 if (this.opts
.enableTasksQueue
=== true && !enable
) {
333 this.flushTasksQueues()
335 this.opts
.enableTasksQueue
= enable
336 this.setTasksQueueOptions(tasksQueueOptions
as TasksQueueOptions
)
340 public setTasksQueueOptions (tasksQueueOptions
: TasksQueueOptions
): void {
341 if (this.opts
.enableTasksQueue
=== true) {
342 this.checkValidTasksQueueOptions(tasksQueueOptions
)
343 this.opts
.tasksQueueOptions
=
344 this.buildTasksQueueOptions(tasksQueueOptions
)
345 } else if (this.opts
.tasksQueueOptions
!= null) {
346 delete this.opts
.tasksQueueOptions
350 private buildTasksQueueOptions (
351 tasksQueueOptions
: TasksQueueOptions
352 ): TasksQueueOptions
{
354 concurrency
: tasksQueueOptions
?.concurrency
?? 1
359 * Whether the pool is full or not.
361 * The pool filling boolean status.
363 protected get
full (): boolean {
364 return this.workerNodes
.length
>= this.maxSize
368 * Whether the pool is busy or not.
370 * The pool busyness boolean status.
372 protected abstract get
busy (): boolean
374 protected internalBusy (): boolean {
376 this.workerNodes
.findIndex(workerNode
=> {
377 return workerNode
.tasksUsage
.running
=== 0
383 public async execute (data
?: Data
, name
?: string): Promise
<Response
> {
384 const timestamp
= performance
.now()
385 const workerNodeKey
= this.chooseWorkerNode()
386 const submittedTask
: Task
<Data
> = {
388 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
389 data
: data
?? ({} as Data
),
391 id
: crypto
.randomUUID()
393 const res
= new Promise
<Response
>((resolve
, reject
) => {
394 this.promiseResponseMap
.set(submittedTask
.id
as string, {
397 worker
: this.workerNodes
[workerNodeKey
].worker
401 this.opts
.enableTasksQueue
=== true &&
403 this.workerNodes
[workerNodeKey
].tasksUsage
.running
>=
404 ((this.opts
.tasksQueueOptions
as TasksQueueOptions
)
405 .concurrency
as number))
407 this.enqueueTask(workerNodeKey
, submittedTask
)
409 this.executeTask(workerNodeKey
, submittedTask
)
411 this.workerChoiceStrategyContext
.update(workerNodeKey
)
412 this.checkAndEmitEvents()
413 // eslint-disable-next-line @typescript-eslint/return-await
418 public async destroy (): Promise
<void> {
420 this.workerNodes
.map(async (workerNode
, workerNodeKey
) => {
421 this.flushTasksQueue(workerNodeKey
)
422 // FIXME: wait for tasks to be finished
423 await this.destroyWorker(workerNode
.worker
)
429 * Shutdowns the given worker.
431 * @param worker - A worker within `workerNodes`.
433 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
436 * Setup hook to execute code before worker node are created in the abstract constructor.
441 protected setupHook (): void {
442 // Intentionally empty
446 * Should return whether the worker is the main worker or not.
448 protected abstract isMain (): boolean
451 * Hook executed before the worker task execution.
454 * @param workerNodeKey - The worker node key.
456 protected beforeTaskExecutionHook (workerNodeKey
: number): void {
457 ++this.workerNodes
[workerNodeKey
].tasksUsage
.running
461 * Hook executed after the worker task execution.
464 * @param worker - The worker.
465 * @param message - The received message.
467 protected afterTaskExecutionHook (
469 message
: MessageValue
<Response
>
471 const workerTasksUsage
=
472 this.workerNodes
[this.getWorkerNodeKey(worker
)].tasksUsage
473 --workerTasksUsage
.running
474 ++workerTasksUsage
.ran
475 if (message
.error
!= null) {
476 ++workerTasksUsage
.error
478 this.updateRunTimeTasksUsage(workerTasksUsage
, message
)
479 this.updateWaitTimeTasksUsage(workerTasksUsage
, message
)
480 this.updateEluTasksUsage(workerTasksUsage
, message
)
483 private updateRunTimeTasksUsage (
484 workerTasksUsage
: TasksUsage
,
485 message
: MessageValue
<Response
>
487 if (this.workerChoiceStrategyContext
.getTaskStatistics().runTime
) {
488 workerTasksUsage
.runTime
+= message
.runTime
?? 0
490 this.workerChoiceStrategyContext
.getTaskStatistics().avgRunTime
&&
491 workerTasksUsage
.ran
!== 0
493 workerTasksUsage
.avgRunTime
=
494 workerTasksUsage
.runTime
/ workerTasksUsage
.ran
497 this.workerChoiceStrategyContext
.getTaskStatistics().medRunTime
&&
498 message
.runTime
!= null
500 workerTasksUsage
.runTimeHistory
.push(message
.runTime
)
501 workerTasksUsage
.medRunTime
= median(workerTasksUsage
.runTimeHistory
)
506 private updateWaitTimeTasksUsage (
507 workerTasksUsage
: TasksUsage
,
508 message
: MessageValue
<Response
>
510 if (this.workerChoiceStrategyContext
.getTaskStatistics().waitTime
) {
511 workerTasksUsage
.waitTime
+= message
.waitTime
?? 0
513 this.workerChoiceStrategyContext
.getTaskStatistics().avgWaitTime
&&
514 workerTasksUsage
.ran
!== 0
516 workerTasksUsage
.avgWaitTime
=
517 workerTasksUsage
.waitTime
/ workerTasksUsage
.ran
520 this.workerChoiceStrategyContext
.getTaskStatistics().medWaitTime
&&
521 message
.waitTime
!= null
523 workerTasksUsage
.waitTimeHistory
.push(message
.waitTime
)
524 workerTasksUsage
.medWaitTime
= median(workerTasksUsage
.waitTimeHistory
)
529 private updateEluTasksUsage (
530 workerTasksUsage
: TasksUsage
,
531 message
: MessageValue
<Response
>
533 if (this.workerChoiceStrategyContext
.getTaskStatistics().elu
) {
534 if (workerTasksUsage
.elu
!= null && message
.elu
!= null) {
535 workerTasksUsage
.elu
= {
536 idle
: workerTasksUsage
.elu
.idle
+ message
.elu
.idle
,
537 active
: workerTasksUsage
.elu
.active
+ message
.elu
.active
,
539 (workerTasksUsage
.elu
.utilization
+ message
.elu
.utilization
) / 2
541 } else if (message
.elu
!= null) {
542 workerTasksUsage
.elu
= message
.elu
548 * Chooses a worker node for the next task.
550 * The default worker choice strategy uses a round robin algorithm to distribute the load.
552 * @returns The worker node key
554 protected chooseWorkerNode (): number {
555 let workerNodeKey
: number
556 if (this.type === PoolTypes
.dynamic
&& !this.full
&& this.internalBusy()) {
557 const workerCreated
= this.createAndSetupWorker()
558 this.registerWorkerMessageListener(workerCreated
, message
=> {
559 const currentWorkerNodeKey
= this.getWorkerNodeKey(workerCreated
)
561 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
562 (message
.kill
!= null &&
563 this.workerNodes
[currentWorkerNodeKey
].tasksUsage
.running
=== 0)
565 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
566 this.flushTasksQueue(currentWorkerNodeKey
)
567 // FIXME: wait for tasks to be finished
568 void (this.destroyWorker(workerCreated
) as Promise
<void>)
571 workerNodeKey
= this.getWorkerNodeKey(workerCreated
)
573 workerNodeKey
= this.workerChoiceStrategyContext
.execute()
579 * Sends a message to the given worker.
581 * @param worker - The worker which should receive the message.
582 * @param message - The message.
584 protected abstract sendToWorker (
586 message
: MessageValue
<Data
>
590 * Registers a listener callback on the given worker.
592 * @param worker - The worker which should register a listener.
593 * @param listener - The message listener callback.
595 protected abstract registerWorkerMessageListener
<
596 Message
extends Data
| Response
597 >(worker
: Worker
, listener
: (message
: MessageValue
<Message
>) => void): void
600 * Returns a newly created worker.
602 protected abstract createWorker (): Worker
605 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
607 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
609 * @param worker - The newly created worker.
611 protected abstract afterWorkerSetup (worker
: Worker
): void
614 * Creates a new worker and sets it up completely in the pool worker nodes.
616 * @returns New, completely set up worker.
618 protected createAndSetupWorker (): Worker
{
619 const worker
= this.createWorker()
621 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
622 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
623 worker
.on('error', error
=> {
624 if (this.emitter
!= null) {
625 this.emitter
.emit(PoolEvents
.error
, error
)
628 worker
.on('error', () => {
629 if (this.opts
.restartWorkerOnError
=== true) {
630 this.createAndSetupWorker()
633 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
634 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
635 worker
.once('exit', () => {
636 this.removeWorkerNode(worker
)
639 this.pushWorkerNode(worker
)
641 this.setWorkerStatistics(worker
)
643 this.afterWorkerSetup(worker
)
649 * This function is the listener registered for each worker message.
651 * @returns The listener function to execute when a message is received from a worker.
653 protected workerListener (): (message
: MessageValue
<Response
>) => void {
655 if (message
.id
!= null) {
656 // Task execution response received
657 const promiseResponse
= this.promiseResponseMap
.get(message
.id
)
658 if (promiseResponse
!= null) {
659 if (message
.error
!= null) {
660 promiseResponse
.reject(message
.error
)
661 if (this.emitter
!= null) {
662 this.emitter
.emit(PoolEvents
.taskError
, {
663 error
: message
.error
,
664 errorData
: message
.errorData
668 promiseResponse
.resolve(message
.data
as Response
)
670 this.afterTaskExecutionHook(promiseResponse
.worker
, message
)
671 this.promiseResponseMap
.delete(message
.id
)
672 const workerNodeKey
= this.getWorkerNodeKey(promiseResponse
.worker
)
674 this.opts
.enableTasksQueue
=== true &&
675 this.tasksQueueSize(workerNodeKey
) > 0
679 this.dequeueTask(workerNodeKey
) as Task
<Data
>
687 private checkAndEmitEvents (): void {
688 if (this.emitter
!= null) {
690 this.emitter
?.emit(PoolEvents
.busy
, this.info
)
692 if (this.type === PoolTypes
.dynamic
&& this.full
) {
693 this.emitter
?.emit(PoolEvents
.full
, this.info
)
699 * Sets the given worker node its tasks usage in the pool.
701 * @param workerNode - The worker node.
702 * @param tasksUsage - The worker node tasks usage.
704 private setWorkerNodeTasksUsage (
705 workerNode
: WorkerNode
<Worker
, Data
>,
706 tasksUsage
: TasksUsage
708 workerNode
.tasksUsage
= tasksUsage
712 * Pushes the given worker in the pool worker nodes.
714 * @param worker - The worker.
715 * @returns The worker nodes length.
717 private pushWorkerNode (worker
: Worker
): number {
718 return this.workerNodes
.push({
724 runTimeHistory
: new CircularArray(),
728 waitTimeHistory
: new CircularArray(),
734 tasksQueue
: new Queue
<Task
<Data
>>()
739 * Sets the given worker in the pool worker nodes.
741 * @param workerNodeKey - The worker node key.
742 * @param worker - The worker.
743 * @param tasksUsage - The worker tasks usage.
744 * @param tasksQueue - The worker task queue.
746 private setWorkerNode (
747 workerNodeKey
: number,
749 tasksUsage
: TasksUsage
,
750 tasksQueue
: Queue
<Task
<Data
>>
752 this.workerNodes
[workerNodeKey
] = {
760 * Removes the given worker from the pool worker nodes.
762 * @param worker - The worker.
764 private removeWorkerNode (worker
: Worker
): void {
765 const workerNodeKey
= this.getWorkerNodeKey(worker
)
766 if (workerNodeKey
!== -1) {
767 this.workerNodes
.splice(workerNodeKey
, 1)
768 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
772 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
773 this.beforeTaskExecutionHook(workerNodeKey
)
774 this.sendToWorker(this.workerNodes
[workerNodeKey
].worker
, task
)
777 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
778 return this.workerNodes
[workerNodeKey
].tasksQueue
.enqueue(task
)
781 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
782 return this.workerNodes
[workerNodeKey
].tasksQueue
.dequeue()
785 private tasksQueueSize (workerNodeKey
: number): number {
786 return this.workerNodes
[workerNodeKey
].tasksQueue
.size
789 private flushTasksQueue (workerNodeKey
: number): void {
790 if (this.tasksQueueSize(workerNodeKey
) > 0) {
791 for (let i
= 0; i
< this.tasksQueueSize(workerNodeKey
); i
++) {
794 this.dequeueTask(workerNodeKey
) as Task
<Data
>
800 private flushTasksQueues (): void {
801 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
802 this.flushTasksQueue(workerNodeKey
)
806 private setWorkerStatistics (worker
: Worker
): void {
807 this.sendToWorker(worker
, {
809 runTime
: this.workerChoiceStrategyContext
.getTaskStatistics().runTime
,
810 waitTime
: this.workerChoiceStrategyContext
.getTaskStatistics().waitTime
,
811 elu
: this.workerChoiceStrategyContext
.getTaskStatistics().elu