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)
100 for (let i
= 1; i
<= this.numberOfWorkers
; i
++) {
101 this.createAndSetupWorker()
104 if (this.opts
.enableEvents
=== true) {
105 this.emitter
= new PoolEmitter()
107 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext
<
113 this.opts
.workerChoiceStrategy
,
114 this.opts
.workerChoiceStrategyOptions
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 for (const workerNode
of this.workerNodes
) {
292 this.setWorkerNodeTasksUsage(workerNode
, {
296 runTimeHistory
: new CircularArray(),
300 waitTimeHistory
: new CircularArray(),
307 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
308 this.opts
.workerChoiceStrategy
310 if (workerChoiceStrategyOptions
!= null) {
311 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
316 public setWorkerChoiceStrategyOptions (
317 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
319 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
320 this.opts
.workerChoiceStrategyOptions
= workerChoiceStrategyOptions
321 this.workerChoiceStrategyContext
.setOptions(
322 this.opts
.workerChoiceStrategyOptions
327 public enableTasksQueue (
329 tasksQueueOptions
?: TasksQueueOptions
331 if (this.opts
.enableTasksQueue
=== true && !enable
) {
332 this.flushTasksQueues()
334 this.opts
.enableTasksQueue
= enable
335 this.setTasksQueueOptions(tasksQueueOptions
as TasksQueueOptions
)
339 public setTasksQueueOptions (tasksQueueOptions
: TasksQueueOptions
): void {
340 if (this.opts
.enableTasksQueue
=== true) {
341 this.checkValidTasksQueueOptions(tasksQueueOptions
)
342 this.opts
.tasksQueueOptions
=
343 this.buildTasksQueueOptions(tasksQueueOptions
)
345 delete this.opts
.tasksQueueOptions
349 private buildTasksQueueOptions (
350 tasksQueueOptions
: TasksQueueOptions
351 ): TasksQueueOptions
{
353 concurrency
: tasksQueueOptions
?.concurrency
?? 1
358 * Whether the pool is full or not.
360 * The pool filling boolean status.
362 protected get
full (): boolean {
363 return this.workerNodes
.length
>= this.maxSize
367 * Whether the pool is busy or not.
369 * The pool busyness boolean status.
371 protected abstract get
busy (): boolean
373 protected internalBusy (): boolean {
375 this.workerNodes
.findIndex(workerNode
=> {
376 return workerNode
.tasksUsage
.running
=== 0
382 public async execute (data
?: Data
, name
?: string): Promise
<Response
> {
383 const submissionTimestamp
= performance
.now()
384 const workerNodeKey
= this.chooseWorkerNode()
385 const submittedTask
: Task
<Data
> = {
387 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
388 data
: data
?? ({} as Data
),
390 id
: crypto
.randomUUID()
392 const res
= new Promise
<Response
>((resolve
, reject
) => {
393 this.promiseResponseMap
.set(submittedTask
.id
as string, {
396 worker
: this.workerNodes
[workerNodeKey
].worker
400 this.opts
.enableTasksQueue
=== true &&
402 this.workerNodes
[workerNodeKey
].tasksUsage
.running
>=
403 ((this.opts
.tasksQueueOptions
as TasksQueueOptions
)
404 .concurrency
as number))
406 this.enqueueTask(workerNodeKey
, submittedTask
)
408 this.executeTask(workerNodeKey
, submittedTask
)
410 this.workerChoiceStrategyContext
.update(workerNodeKey
)
411 this.checkAndEmitEvents()
412 // eslint-disable-next-line @typescript-eslint/return-await
417 public async destroy (): Promise
<void> {
419 this.workerNodes
.map(async (workerNode
, workerNodeKey
) => {
420 this.flushTasksQueue(workerNodeKey
)
421 // FIXME: wait for tasks to be finished
422 await this.destroyWorker(workerNode
.worker
)
428 * Shutdowns the given worker.
430 * @param worker - A worker within `workerNodes`.
432 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
435 * Setup hook to execute code before worker node are created in the abstract constructor.
440 protected setupHook (): void {
441 // Intentionally empty
445 * Should return whether the worker is the main worker or not.
447 protected abstract isMain (): boolean
450 * Hook executed before the worker task execution.
453 * @param workerNodeKey - The worker node key.
455 protected beforeTaskExecutionHook (workerNodeKey
: number): void {
456 ++this.workerNodes
[workerNodeKey
].tasksUsage
.running
460 * Hook executed after the worker task execution.
463 * @param worker - The worker.
464 * @param message - The received message.
466 protected afterTaskExecutionHook (
468 message
: MessageValue
<Response
>
470 const workerTasksUsage
=
471 this.workerNodes
[this.getWorkerNodeKey(worker
)].tasksUsage
472 --workerTasksUsage
.running
473 ++workerTasksUsage
.ran
474 if (message
.error
!= null) {
475 ++workerTasksUsage
.error
477 this.updateRunTimeTasksUsage(workerTasksUsage
, message
)
478 this.updateWaitTimeTasksUsage(workerTasksUsage
, message
)
479 this.updateEluTasksUsage(workerTasksUsage
, message
)
482 private updateRunTimeTasksUsage (
483 workerTasksUsage
: TasksUsage
,
484 message
: MessageValue
<Response
>
486 if (this.workerChoiceStrategyContext
.getRequiredStatistics().runTime
) {
487 workerTasksUsage
.runTime
+= message
.runTime
?? 0
489 this.workerChoiceStrategyContext
.getRequiredStatistics().avgRunTime
&&
490 workerTasksUsage
.ran
!== 0
492 workerTasksUsage
.avgRunTime
=
493 workerTasksUsage
.runTime
/ workerTasksUsage
.ran
496 this.workerChoiceStrategyContext
.getRequiredStatistics().medRunTime
&&
497 message
.runTime
!= null
499 workerTasksUsage
.runTimeHistory
.push(message
.runTime
)
500 workerTasksUsage
.medRunTime
= median(workerTasksUsage
.runTimeHistory
)
505 private updateWaitTimeTasksUsage (
506 workerTasksUsage
: TasksUsage
,
507 message
: MessageValue
<Response
>
509 if (this.workerChoiceStrategyContext
.getRequiredStatistics().waitTime
) {
510 workerTasksUsage
.waitTime
+= message
.waitTime
?? 0
512 this.workerChoiceStrategyContext
.getRequiredStatistics().avgWaitTime
&&
513 workerTasksUsage
.ran
!== 0
515 workerTasksUsage
.avgWaitTime
=
516 workerTasksUsage
.waitTime
/ workerTasksUsage
.ran
519 this.workerChoiceStrategyContext
.getRequiredStatistics().medWaitTime
&&
520 message
.waitTime
!= null
522 workerTasksUsage
.waitTimeHistory
.push(message
.waitTime
)
523 workerTasksUsage
.medWaitTime
= median(workerTasksUsage
.waitTimeHistory
)
528 private updateEluTasksUsage (
529 workerTasksUsage
: TasksUsage
,
530 message
: MessageValue
<Response
>
532 if (this.workerChoiceStrategyContext
.getRequiredStatistics().elu
) {
533 if (workerTasksUsage
.elu
!= null && message
.elu
!= null) {
534 // TODO: cumulative or delta?
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
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 if (this.opts
.restartWorkerOnError
=== true) {
629 worker
.on('error', () => {
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.afterWorkerSetup(worker
)
647 * This function is the listener registered for each worker message.
649 * @returns The listener function to execute when a message is received from a worker.
651 protected workerListener (): (message
: MessageValue
<Response
>) => void {
653 if (message
.id
!= null) {
654 // Task execution response received
655 const promiseResponse
= this.promiseResponseMap
.get(message
.id
)
656 if (promiseResponse
!= null) {
657 if (message
.error
!= null) {
658 promiseResponse
.reject(message
.error
)
659 if (this.emitter
!= null) {
660 this.emitter
.emit(PoolEvents
.taskError
, {
661 error
: message
.error
,
662 errorData
: message
.errorData
666 promiseResponse
.resolve(message
.data
as Response
)
668 this.afterTaskExecutionHook(promiseResponse
.worker
, message
)
669 this.promiseResponseMap
.delete(message
.id
)
670 const workerNodeKey
= this.getWorkerNodeKey(promiseResponse
.worker
)
672 this.opts
.enableTasksQueue
=== true &&
673 this.tasksQueueSize(workerNodeKey
) > 0
677 this.dequeueTask(workerNodeKey
) as Task
<Data
>
685 private checkAndEmitEvents (): void {
686 if (this.emitter
!= null) {
688 this.emitter
?.emit(PoolEvents
.busy
, this.info
)
690 if (this.type === PoolTypes
.dynamic
&& this.full
) {
691 this.emitter
?.emit(PoolEvents
.full
, this.info
)
697 * Sets the given worker node its tasks usage in the pool.
699 * @param workerNode - The worker node.
700 * @param tasksUsage - The worker node tasks usage.
702 private setWorkerNodeTasksUsage (
703 workerNode
: WorkerNode
<Worker
, Data
>,
704 tasksUsage
: TasksUsage
706 workerNode
.tasksUsage
= tasksUsage
710 * Pushes the given worker in the pool worker nodes.
712 * @param worker - The worker.
713 * @returns The worker nodes length.
715 private pushWorkerNode (worker
: Worker
): number {
716 return this.workerNodes
.push({
722 runTimeHistory
: new CircularArray(),
726 waitTimeHistory
: new CircularArray(),
732 tasksQueue
: new Queue
<Task
<Data
>>()
737 * Sets the given worker in the pool worker nodes.
739 * @param workerNodeKey - The worker node key.
740 * @param worker - The worker.
741 * @param tasksUsage - The worker tasks usage.
742 * @param tasksQueue - The worker task queue.
744 private setWorkerNode (
745 workerNodeKey
: number,
747 tasksUsage
: TasksUsage
,
748 tasksQueue
: Queue
<Task
<Data
>>
750 this.workerNodes
[workerNodeKey
] = {
758 * Removes the given worker from the pool worker nodes.
760 * @param worker - The worker.
762 private removeWorkerNode (worker
: Worker
): void {
763 const workerNodeKey
= this.getWorkerNodeKey(worker
)
764 if (workerNodeKey
!== -1) {
765 this.workerNodes
.splice(workerNodeKey
, 1)
766 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
770 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
771 this.beforeTaskExecutionHook(workerNodeKey
)
772 this.sendToWorker(this.workerNodes
[workerNodeKey
].worker
, task
)
775 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
776 return this.workerNodes
[workerNodeKey
].tasksQueue
.enqueue(task
)
779 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
780 return this.workerNodes
[workerNodeKey
].tasksQueue
.dequeue()
783 private tasksQueueSize (workerNodeKey
: number): number {
784 return this.workerNodes
[workerNodeKey
].tasksQueue
.size
787 private flushTasksQueue (workerNodeKey
: number): void {
788 if (this.tasksQueueSize(workerNodeKey
) > 0) {
789 for (let i
= 0; i
< this.tasksQueueSize(workerNodeKey
); i
++) {
792 this.dequeueTask(workerNodeKey
) as Task
<Data
>
798 private flushTasksQueues (): void {
799 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
800 this.flushTasksQueue(workerNodeKey
)