1 import crypto from
'node:crypto'
2 import type { MessageValue
, PromiseResponseWrapper
} from
'../utility-types'
4 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
,
9 import { KillBehaviors
, isKillBehavior
} from
'../worker/worker-options'
10 import { CircularArray
} from
'../circular-array'
11 import { Queue
} from
'../queue'
20 type TasksQueueOptions
,
23 import type { IWorker
, Task
, TasksUsage
, WorkerNode
} from
'./worker'
25 WorkerChoiceStrategies
,
26 type WorkerChoiceStrategy
,
27 type WorkerChoiceStrategyOptions
28 } from
'./selection-strategies/selection-strategies-types'
29 import { WorkerChoiceStrategyContext
} from
'./selection-strategies/worker-choice-strategy-context'
32 * Base class that implements some shared logic for all poolifier pools.
34 * @typeParam Worker - Type of worker which manages this pool.
35 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
36 * @typeParam Response - Type of execution response. This can only be serializable data.
38 export abstract class AbstractPool
<
39 Worker
extends IWorker
,
42 > implements IPool
<Worker
, Data
, Response
> {
44 public readonly workerNodes
: Array<WorkerNode
<Worker
, Data
>> = []
47 public readonly emitter
?: PoolEmitter
50 * The execution response promise map.
52 * - `key`: The message id of each submitted task.
53 * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks.
55 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
57 protected promiseResponseMap
: Map
<
59 PromiseResponseWrapper
<Worker
, Response
>
60 > = new Map
<string, PromiseResponseWrapper
<Worker
, Response
>>()
63 * Worker choice strategy context referencing a worker choice algorithm implementation.
65 * Default to a round robin algorithm.
67 protected workerChoiceStrategyContext
: WorkerChoiceStrategyContext
<
74 * Constructs a new poolifier pool.
76 * @param numberOfWorkers - Number of workers that this pool should manage.
77 * @param filePath - Path to the worker file.
78 * @param opts - Options for the pool.
81 public readonly numberOfWorkers
: number,
82 public readonly filePath
: string,
83 public readonly opts
: PoolOptions
<Worker
>
86 throw new Error('Cannot start a pool from a worker!')
88 this.checkNumberOfWorkers(this.numberOfWorkers
)
89 this.checkFilePath(this.filePath
)
90 this.checkPoolOptions(this.opts
)
92 this.chooseWorkerNode
= this.chooseWorkerNode
.bind(this)
93 this.executeTask
= this.executeTask
.bind(this)
94 this.enqueueTask
= this.enqueueTask
.bind(this)
95 this.checkAndEmitEvents
= this.checkAndEmitEvents
.bind(this)
99 for (let i
= 1; i
<= this.numberOfWorkers
; i
++) {
100 this.createAndSetupWorker()
103 if (this.opts
.enableEvents
=== true) {
104 this.emitter
= new PoolEmitter()
106 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext
<
112 this.opts
.workerChoiceStrategy
,
113 this.opts
.workerChoiceStrategyOptions
117 private checkFilePath (filePath
: string): void {
120 (typeof filePath
=== 'string' && filePath
.trim().length
=== 0)
122 throw new Error('Please specify a file with a worker implementation')
126 private checkNumberOfWorkers (numberOfWorkers
: number): void {
127 if (numberOfWorkers
== null) {
129 'Cannot instantiate a pool without specifying the number of workers'
131 } else if (!Number.isSafeInteger(numberOfWorkers
)) {
133 'Cannot instantiate a pool with a non safe integer number of workers'
135 } else if (numberOfWorkers
< 0) {
136 throw new RangeError(
137 'Cannot instantiate a pool with a negative number of workers'
139 } else if (this.type === PoolTypes
.fixed
&& numberOfWorkers
=== 0) {
140 throw new Error('Cannot instantiate a fixed pool with no worker')
144 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
145 if (isPlainObject(opts
)) {
146 this.opts
.workerChoiceStrategy
=
147 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
148 this.checkValidWorkerChoiceStrategy(this.opts
.workerChoiceStrategy
)
149 this.opts
.workerChoiceStrategyOptions
=
150 opts
.workerChoiceStrategyOptions
??
151 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
152 this.checkValidWorkerChoiceStrategyOptions(
153 this.opts
.workerChoiceStrategyOptions
155 this.opts
.restartWorkerOnError
= opts
.restartWorkerOnError
?? true
156 this.opts
.enableEvents
= opts
.enableEvents
?? true
157 this.opts
.enableTasksQueue
= opts
.enableTasksQueue
?? false
158 if (this.opts
.enableTasksQueue
) {
159 this.checkValidTasksQueueOptions(
160 opts
.tasksQueueOptions
as TasksQueueOptions
162 this.opts
.tasksQueueOptions
= this.buildTasksQueueOptions(
163 opts
.tasksQueueOptions
as TasksQueueOptions
167 throw new TypeError('Invalid pool options: must be a plain object')
171 private checkValidWorkerChoiceStrategy (
172 workerChoiceStrategy
: WorkerChoiceStrategy
174 if (!Object.values(WorkerChoiceStrategies
).includes(workerChoiceStrategy
)) {
176 `Invalid worker choice strategy '${workerChoiceStrategy}'`
181 private checkValidWorkerChoiceStrategyOptions (
182 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
184 if (!isPlainObject(workerChoiceStrategyOptions
)) {
186 'Invalid worker choice strategy options: must be a plain object'
190 workerChoiceStrategyOptions
.weights
!= null &&
191 Object.keys(workerChoiceStrategyOptions
.weights
).length
!== this.maxSize
194 'Invalid worker choice strategy options: must have a weight for each worker node'
199 private checkValidTasksQueueOptions (
200 tasksQueueOptions
: TasksQueueOptions
202 if (tasksQueueOptions
!= null && !isPlainObject(tasksQueueOptions
)) {
203 throw new TypeError('Invalid tasks queue options: must be a plain object')
205 if ((tasksQueueOptions
?.concurrency
as number) <= 0) {
207 `Invalid worker tasks concurrency '${
208 tasksQueueOptions.concurrency as number
215 public abstract get
type (): PoolType
218 public get
info (): PoolInfo
{
222 minSize
: this.minSize
,
223 maxSize
: this.maxSize
,
224 workerNodes
: this.workerNodes
.length
,
225 idleWorkerNodes
: this.workerNodes
.reduce(
226 (accumulator
, workerNode
) =>
227 workerNode
.tasksUsage
.running
=== 0 ? accumulator
+ 1 : accumulator
,
230 busyWorkerNodes
: this.workerNodes
.reduce(
231 (accumulator
, workerNode
) =>
232 workerNode
.tasksUsage
.running
> 0 ? accumulator
+ 1 : accumulator
,
235 runningTasks
: this.workerNodes
.reduce(
236 (accumulator
, workerNode
) =>
237 accumulator
+ workerNode
.tasksUsage
.running
,
240 queuedTasks
: this.workerNodes
.reduce(
241 (accumulator
, workerNode
) => accumulator
+ workerNode
.tasksQueue
.size
,
244 maxQueuedTasks
: this.workerNodes
.reduce(
245 (accumulator
, workerNode
) =>
246 accumulator
+ workerNode
.tasksQueue
.maxSize
,
253 * Gets the worker type.
255 protected abstract get
worker (): WorkerType
260 protected abstract get
minSize (): number
265 protected abstract get
maxSize (): number
268 * Gets the given worker its worker node key.
270 * @param worker - The worker.
271 * @returns The worker node key if the worker is found in the pool worker nodes, `-1` otherwise.
273 private getWorkerNodeKey (worker
: Worker
): number {
274 return this.workerNodes
.findIndex(
275 workerNode
=> workerNode
.worker
=== worker
280 public setWorkerChoiceStrategy (
281 workerChoiceStrategy
: WorkerChoiceStrategy
,
282 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
284 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
285 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
286 for (const workerNode
of this.workerNodes
) {
287 this.setWorkerNodeTasksUsage(workerNode
, {
291 runTimeHistory
: new CircularArray(),
295 waitTimeHistory
: new CircularArray(),
301 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
302 this.opts
.workerChoiceStrategy
304 if (workerChoiceStrategyOptions
!= null) {
305 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
310 public setWorkerChoiceStrategyOptions (
311 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
313 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
314 this.opts
.workerChoiceStrategyOptions
= workerChoiceStrategyOptions
315 this.workerChoiceStrategyContext
.setOptions(
316 this.opts
.workerChoiceStrategyOptions
321 public enableTasksQueue (
323 tasksQueueOptions
?: TasksQueueOptions
325 if (this.opts
.enableTasksQueue
=== true && !enable
) {
326 this.flushTasksQueues()
328 this.opts
.enableTasksQueue
= enable
329 this.setTasksQueueOptions(tasksQueueOptions
as TasksQueueOptions
)
333 public setTasksQueueOptions (tasksQueueOptions
: TasksQueueOptions
): void {
334 if (this.opts
.enableTasksQueue
=== true) {
335 this.checkValidTasksQueueOptions(tasksQueueOptions
)
336 this.opts
.tasksQueueOptions
=
337 this.buildTasksQueueOptions(tasksQueueOptions
)
339 delete this.opts
.tasksQueueOptions
343 private buildTasksQueueOptions (
344 tasksQueueOptions
: TasksQueueOptions
345 ): TasksQueueOptions
{
347 concurrency
: tasksQueueOptions
?.concurrency
?? 1
352 * Whether the pool is full or not.
354 * The pool filling boolean status.
356 protected abstract get
full (): boolean
359 * Whether the pool is busy or not.
361 * The pool busyness boolean status.
363 protected abstract get
busy (): boolean
365 protected internalBusy (): boolean {
367 this.workerNodes
.findIndex(workerNode
=> {
368 return workerNode
.tasksUsage
.running
=== 0
374 public async execute (data
?: Data
, name
?: string): Promise
<Response
> {
375 const submissionTimestamp
= performance
.now()
376 const workerNodeKey
= this.chooseWorkerNode()
377 const submittedTask
: Task
<Data
> = {
379 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
380 data
: data
?? ({} as Data
),
382 id
: crypto
.randomUUID()
384 const res
= new Promise
<Response
>((resolve
, reject
) => {
385 this.promiseResponseMap
.set(submittedTask
.id
as string, {
388 worker
: this.workerNodes
[workerNodeKey
].worker
392 this.opts
.enableTasksQueue
=== true &&
394 this.workerNodes
[workerNodeKey
].tasksUsage
.running
>=
395 ((this.opts
.tasksQueueOptions
as TasksQueueOptions
)
396 .concurrency
as number))
398 this.enqueueTask(workerNodeKey
, submittedTask
)
400 this.executeTask(workerNodeKey
, submittedTask
)
402 this.workerChoiceStrategyContext
.update(workerNodeKey
)
403 this.checkAndEmitEvents()
404 // eslint-disable-next-line @typescript-eslint/return-await
409 public async destroy (): Promise
<void> {
411 this.workerNodes
.map(async (workerNode
, workerNodeKey
) => {
412 this.flushTasksQueue(workerNodeKey
)
413 await this.destroyWorker(workerNode
.worker
)
419 * Shutdowns the given worker.
421 * @param worker - A worker within `workerNodes`.
423 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
426 * Setup hook to execute code before worker node are created in the abstract constructor.
431 protected setupHook (): void {
432 // Intentionally empty
436 * Should return whether the worker is the main worker or not.
438 protected abstract isMain (): boolean
441 * Hook executed before the worker task execution.
444 * @param workerNodeKey - The worker node key.
446 protected beforeTaskExecutionHook (workerNodeKey
: number): void {
447 ++this.workerNodes
[workerNodeKey
].tasksUsage
.running
451 * Hook executed after the worker task execution.
454 * @param worker - The worker.
455 * @param message - The received message.
457 protected afterTaskExecutionHook (
459 message
: MessageValue
<Response
>
461 const workerTasksUsage
=
462 this.workerNodes
[this.getWorkerNodeKey(worker
)].tasksUsage
463 --workerTasksUsage
.running
464 ++workerTasksUsage
.run
465 if (message
.error
!= null) {
466 ++workerTasksUsage
.error
468 this.updateRunTimeTasksUsage(workerTasksUsage
, message
)
469 this.updateWaitTimeTasksUsage(workerTasksUsage
, message
)
472 private updateRunTimeTasksUsage (
473 workerTasksUsage
: TasksUsage
,
474 message
: MessageValue
<Response
>
476 if (this.workerChoiceStrategyContext
.getRequiredStatistics().runTime
) {
477 workerTasksUsage
.runTime
+= message
.runTime
?? 0
479 this.workerChoiceStrategyContext
.getRequiredStatistics().avgRunTime
&&
480 workerTasksUsage
.run
!== 0
482 workerTasksUsage
.avgRunTime
=
483 workerTasksUsage
.runTime
/ workerTasksUsage
.run
486 this.workerChoiceStrategyContext
.getRequiredStatistics().medRunTime
&&
487 message
.runTime
!= null
489 workerTasksUsage
.runTimeHistory
.push(message
.runTime
)
490 workerTasksUsage
.medRunTime
= median(workerTasksUsage
.runTimeHistory
)
495 private updateWaitTimeTasksUsage (
496 workerTasksUsage
: TasksUsage
,
497 message
: MessageValue
<Response
>
499 if (this.workerChoiceStrategyContext
.getRequiredStatistics().waitTime
) {
500 workerTasksUsage
.waitTime
+= message
.waitTime
?? 0
502 this.workerChoiceStrategyContext
.getRequiredStatistics().avgWaitTime
&&
503 workerTasksUsage
.run
!== 0
505 workerTasksUsage
.avgWaitTime
=
506 workerTasksUsage
.waitTime
/ workerTasksUsage
.run
509 this.workerChoiceStrategyContext
.getRequiredStatistics().medWaitTime
&&
510 message
.waitTime
!= null
512 workerTasksUsage
.waitTimeHistory
.push(message
.waitTime
)
513 workerTasksUsage
.medWaitTime
= median(workerTasksUsage
.waitTimeHistory
)
519 * Chooses a worker node for the next task.
521 * The default worker choice strategy uses a round robin algorithm to distribute the load.
523 * @returns The worker node key
525 protected chooseWorkerNode (): number {
526 let workerNodeKey
: number
527 if (this.type === PoolTypes
.dynamic
&& !this.full
&& this.internalBusy()) {
528 const workerCreated
= this.createAndSetupWorker()
529 this.registerWorkerMessageListener(workerCreated
, message
=> {
530 const currentWorkerNodeKey
= this.getWorkerNodeKey(workerCreated
)
532 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
533 (message
.kill
!= null &&
534 this.workerNodes
[currentWorkerNodeKey
].tasksUsage
.running
=== 0)
536 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
537 this.flushTasksQueue(currentWorkerNodeKey
)
538 void (this.destroyWorker(workerCreated
) as Promise
<void>)
541 workerNodeKey
= this.getWorkerNodeKey(workerCreated
)
543 workerNodeKey
= this.workerChoiceStrategyContext
.execute()
549 * Sends a message to the given worker.
551 * @param worker - The worker which should receive the message.
552 * @param message - The message.
554 protected abstract sendToWorker (
556 message
: MessageValue
<Data
>
560 * Registers a listener callback on the given worker.
562 * @param worker - The worker which should register a listener.
563 * @param listener - The message listener callback.
565 protected abstract registerWorkerMessageListener
<
566 Message
extends Data
| Response
567 >(worker
: Worker
, listener
: (message
: MessageValue
<Message
>) => void): void
570 * Returns a newly created worker.
572 protected abstract createWorker (): Worker
575 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
577 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
579 * @param worker - The newly created worker.
581 protected abstract afterWorkerSetup (worker
: Worker
): void
584 * Creates a new worker and sets it up completely in the pool worker nodes.
586 * @returns New, completely set up worker.
588 protected createAndSetupWorker (): Worker
{
589 const worker
= this.createWorker()
591 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
592 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
593 worker
.on('error', error
=> {
594 if (this.emitter
!= null) {
595 this.emitter
.emit(PoolEvents
.error
, error
)
598 if (this.opts
.restartWorkerOnError
=== true) {
599 worker
.on('error', () => {
600 this.createAndSetupWorker()
603 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
604 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
605 worker
.once('exit', () => {
606 this.removeWorkerNode(worker
)
609 this.pushWorkerNode(worker
)
611 this.afterWorkerSetup(worker
)
617 * This function is the listener registered for each worker message.
619 * @returns The listener function to execute when a message is received from a worker.
621 protected workerListener (): (message
: MessageValue
<Response
>) => void {
623 if (message
.id
!= null) {
624 // Task execution response received
625 const promiseResponse
= this.promiseResponseMap
.get(message
.id
)
626 if (promiseResponse
!= null) {
627 if (message
.error
!= null) {
628 promiseResponse
.reject(message
.error
)
629 if (this.emitter
!= null) {
630 this.emitter
.emit(PoolEvents
.taskError
, {
631 error
: message
.error
,
632 errorData
: message
.errorData
636 promiseResponse
.resolve(message
.data
as Response
)
638 this.afterTaskExecutionHook(promiseResponse
.worker
, message
)
639 this.promiseResponseMap
.delete(message
.id
)
640 const workerNodeKey
= this.getWorkerNodeKey(promiseResponse
.worker
)
642 this.opts
.enableTasksQueue
=== true &&
643 this.tasksQueueSize(workerNodeKey
) > 0
647 this.dequeueTask(workerNodeKey
) as Task
<Data
>
655 private checkAndEmitEvents (): void {
656 if (this.emitter
!= null) {
658 this.emitter
?.emit(PoolEvents
.busy
, this.info
)
660 if (this.type === PoolTypes
.dynamic
&& this.full
) {
661 this.emitter
?.emit(PoolEvents
.full
, this.info
)
667 * Sets the given worker node its tasks usage in the pool.
669 * @param workerNode - The worker node.
670 * @param tasksUsage - The worker node tasks usage.
672 private setWorkerNodeTasksUsage (
673 workerNode
: WorkerNode
<Worker
, Data
>,
674 tasksUsage
: TasksUsage
676 workerNode
.tasksUsage
= tasksUsage
680 * Pushes the given worker in the pool worker nodes.
682 * @param worker - The worker.
683 * @returns The worker nodes length.
685 private pushWorkerNode (worker
: Worker
): number {
686 return this.workerNodes
.push({
692 runTimeHistory
: new CircularArray(),
696 waitTimeHistory
: new CircularArray(),
701 tasksQueue
: new Queue
<Task
<Data
>>()
706 * Sets the given worker in the pool worker nodes.
708 * @param workerNodeKey - The worker node key.
709 * @param worker - The worker.
710 * @param tasksUsage - The worker tasks usage.
711 * @param tasksQueue - The worker task queue.
713 private setWorkerNode (
714 workerNodeKey
: number,
716 tasksUsage
: TasksUsage
,
717 tasksQueue
: Queue
<Task
<Data
>>
719 this.workerNodes
[workerNodeKey
] = {
727 * Removes the given worker from the pool worker nodes.
729 * @param worker - The worker.
731 private removeWorkerNode (worker
: Worker
): void {
732 const workerNodeKey
= this.getWorkerNodeKey(worker
)
733 if (workerNodeKey
!== -1) {
734 this.workerNodes
.splice(workerNodeKey
, 1)
735 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
739 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
740 this.beforeTaskExecutionHook(workerNodeKey
)
741 this.sendToWorker(this.workerNodes
[workerNodeKey
].worker
, task
)
744 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
745 return this.workerNodes
[workerNodeKey
].tasksQueue
.enqueue(task
)
748 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
749 return this.workerNodes
[workerNodeKey
].tasksQueue
.dequeue()
752 private tasksQueueSize (workerNodeKey
: number): number {
753 return this.workerNodes
[workerNodeKey
].tasksQueue
.size
756 private flushTasksQueue (workerNodeKey
: number): void {
757 if (this.tasksQueueSize(workerNodeKey
) > 0) {
758 for (let i
= 0; i
< this.tasksQueueSize(workerNodeKey
); i
++) {
761 this.dequeueTask(workerNodeKey
) as Task
<Data
>
767 private flushTasksQueues (): void {
768 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
769 this.flushTasksQueue(workerNodeKey
)