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 get
info (): PoolInfo
{
219 minSize
: this.minSize
,
220 maxSize
: this.maxSize
,
221 workerNodes
: this.workerNodes
.length
,
222 idleWorkerNodes
: this.workerNodes
.reduce(
223 (accumulator
, workerNode
) =>
224 workerNode
.tasksUsage
.running
=== 0 ? accumulator
+ 1 : accumulator
,
227 busyWorkerNodes
: this.workerNodes
.reduce(
228 (accumulator
, workerNode
) =>
229 workerNode
.tasksUsage
.running
> 0 ? accumulator
+ 1 : accumulator
,
232 runningTasks
: this.workerNodes
.reduce(
233 (accumulator
, workerNode
) =>
234 accumulator
+ workerNode
.tasksUsage
.running
,
237 queuedTasks
: this.workerNodes
.reduce(
238 (accumulator
, workerNode
) => accumulator
+ workerNode
.tasksQueue
.size
,
241 maxQueuedTasks
: this.workerNodes
.reduce(
242 (accumulator
, workerNode
) =>
243 accumulator
+ workerNode
.tasksQueue
.maxSize
,
252 * If it is `'dynamic'`, it provides the `max` property.
254 protected abstract get
type (): PoolType
257 * Gets the worker type.
259 protected abstract get
worker (): WorkerType
264 protected abstract get
minSize (): number
269 protected abstract get
maxSize (): number
272 * Gets the given worker its worker node key.
274 * @param worker - The worker.
275 * @returns The worker node key if the worker is found in the pool worker nodes, `-1` otherwise.
277 private getWorkerNodeKey (worker
: Worker
): number {
278 return this.workerNodes
.findIndex(
279 workerNode
=> workerNode
.worker
=== worker
284 public setWorkerChoiceStrategy (
285 workerChoiceStrategy
: WorkerChoiceStrategy
,
286 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
288 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
289 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
290 for (const workerNode
of this.workerNodes
) {
291 this.setWorkerNodeTasksUsage(workerNode
, {
295 runTimeHistory
: new CircularArray(),
299 waitTimeHistory
: new CircularArray(),
305 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
306 this.opts
.workerChoiceStrategy
308 if (workerChoiceStrategyOptions
!= null) {
309 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
314 public setWorkerChoiceStrategyOptions (
315 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
317 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
318 this.opts
.workerChoiceStrategyOptions
= workerChoiceStrategyOptions
319 this.workerChoiceStrategyContext
.setOptions(
320 this.opts
.workerChoiceStrategyOptions
325 public enableTasksQueue (
327 tasksQueueOptions
?: TasksQueueOptions
329 if (this.opts
.enableTasksQueue
=== true && !enable
) {
330 this.flushTasksQueues()
332 this.opts
.enableTasksQueue
= enable
333 this.setTasksQueueOptions(tasksQueueOptions
as TasksQueueOptions
)
337 public setTasksQueueOptions (tasksQueueOptions
: TasksQueueOptions
): void {
338 if (this.opts
.enableTasksQueue
=== true) {
339 this.checkValidTasksQueueOptions(tasksQueueOptions
)
340 this.opts
.tasksQueueOptions
=
341 this.buildTasksQueueOptions(tasksQueueOptions
)
343 delete this.opts
.tasksQueueOptions
347 private buildTasksQueueOptions (
348 tasksQueueOptions
: TasksQueueOptions
349 ): TasksQueueOptions
{
351 concurrency
: tasksQueueOptions
?.concurrency
?? 1
356 * Whether the pool is full or not.
358 * The pool filling boolean status.
360 protected abstract get
full (): boolean
363 * Whether the pool is busy or not.
365 * The pool busyness boolean status.
367 protected abstract get
busy (): boolean
369 protected internalBusy (): boolean {
371 this.workerNodes
.findIndex(workerNode
=> {
372 return workerNode
.tasksUsage
.running
=== 0
378 public async execute (data
?: Data
, name
?: string): Promise
<Response
> {
379 const submissionTimestamp
= performance
.now()
380 const workerNodeKey
= this.chooseWorkerNode()
381 const submittedTask
: Task
<Data
> = {
383 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
384 data
: data
?? ({} as Data
),
386 id
: crypto
.randomUUID()
388 const res
= new Promise
<Response
>((resolve
, reject
) => {
389 this.promiseResponseMap
.set(submittedTask
.id
as string, {
392 worker
: this.workerNodes
[workerNodeKey
].worker
396 this.opts
.enableTasksQueue
=== true &&
398 this.workerNodes
[workerNodeKey
].tasksUsage
.running
>=
399 ((this.opts
.tasksQueueOptions
as TasksQueueOptions
)
400 .concurrency
as number))
402 this.enqueueTask(workerNodeKey
, submittedTask
)
404 this.executeTask(workerNodeKey
, submittedTask
)
406 this.workerChoiceStrategyContext
.update(workerNodeKey
)
407 this.checkAndEmitEvents()
408 // eslint-disable-next-line @typescript-eslint/return-await
413 public async destroy (): Promise
<void> {
415 this.workerNodes
.map(async (workerNode
, workerNodeKey
) => {
416 this.flushTasksQueue(workerNodeKey
)
417 // FIXME: wait for tasks to be finished
418 await this.destroyWorker(workerNode
.worker
)
424 * Shutdowns the given worker.
426 * @param worker - A worker within `workerNodes`.
428 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
431 * Setup hook to execute code before worker node are created in the abstract constructor.
436 protected setupHook (): void {
437 // Intentionally empty
441 * Should return whether the worker is the main worker or not.
443 protected abstract isMain (): boolean
446 * Hook executed before the worker task execution.
449 * @param workerNodeKey - The worker node key.
451 protected beforeTaskExecutionHook (workerNodeKey
: number): void {
452 ++this.workerNodes
[workerNodeKey
].tasksUsage
.running
456 * Hook executed after the worker task execution.
459 * @param worker - The worker.
460 * @param message - The received message.
462 protected afterTaskExecutionHook (
464 message
: MessageValue
<Response
>
466 const workerTasksUsage
=
467 this.workerNodes
[this.getWorkerNodeKey(worker
)].tasksUsage
468 --workerTasksUsage
.running
469 ++workerTasksUsage
.run
470 if (message
.error
!= null) {
471 ++workerTasksUsage
.error
473 this.updateRunTimeTasksUsage(workerTasksUsage
, message
)
474 this.updateWaitTimeTasksUsage(workerTasksUsage
, message
)
477 private updateRunTimeTasksUsage (
478 workerTasksUsage
: TasksUsage
,
479 message
: MessageValue
<Response
>
481 if (this.workerChoiceStrategyContext
.getRequiredStatistics().runTime
) {
482 workerTasksUsage
.runTime
+= message
.runTime
?? 0
484 this.workerChoiceStrategyContext
.getRequiredStatistics().avgRunTime
&&
485 workerTasksUsage
.run
!== 0
487 workerTasksUsage
.avgRunTime
=
488 workerTasksUsage
.runTime
/ workerTasksUsage
.run
491 this.workerChoiceStrategyContext
.getRequiredStatistics().medRunTime
&&
492 message
.runTime
!= null
494 workerTasksUsage
.runTimeHistory
.push(message
.runTime
)
495 workerTasksUsage
.medRunTime
= median(workerTasksUsage
.runTimeHistory
)
500 private updateWaitTimeTasksUsage (
501 workerTasksUsage
: TasksUsage
,
502 message
: MessageValue
<Response
>
504 if (this.workerChoiceStrategyContext
.getRequiredStatistics().waitTime
) {
505 workerTasksUsage
.waitTime
+= message
.waitTime
?? 0
507 this.workerChoiceStrategyContext
.getRequiredStatistics().avgWaitTime
&&
508 workerTasksUsage
.run
!== 0
510 workerTasksUsage
.avgWaitTime
=
511 workerTasksUsage
.waitTime
/ workerTasksUsage
.run
514 this.workerChoiceStrategyContext
.getRequiredStatistics().medWaitTime
&&
515 message
.waitTime
!= null
517 workerTasksUsage
.waitTimeHistory
.push(message
.waitTime
)
518 workerTasksUsage
.medWaitTime
= median(workerTasksUsage
.waitTimeHistory
)
524 * Chooses a worker node for the next task.
526 * The default worker choice strategy uses a round robin algorithm to distribute the load.
528 * @returns The worker node key
530 protected chooseWorkerNode (): number {
531 let workerNodeKey
: number
532 if (this.type === PoolTypes
.dynamic
&& !this.full
&& this.internalBusy()) {
533 const workerCreated
= this.createAndSetupWorker()
534 this.registerWorkerMessageListener(workerCreated
, message
=> {
535 const currentWorkerNodeKey
= this.getWorkerNodeKey(workerCreated
)
537 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
538 (message
.kill
!= null &&
539 this.workerNodes
[currentWorkerNodeKey
].tasksUsage
.running
=== 0)
541 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
542 this.flushTasksQueue(currentWorkerNodeKey
)
543 // FIXME: wait for tasks to be finished
544 void (this.destroyWorker(workerCreated
) as Promise
<void>)
547 workerNodeKey
= this.getWorkerNodeKey(workerCreated
)
549 workerNodeKey
= this.workerChoiceStrategyContext
.execute()
555 * Sends a message to the given worker.
557 * @param worker - The worker which should receive the message.
558 * @param message - The message.
560 protected abstract sendToWorker (
562 message
: MessageValue
<Data
>
566 * Registers a listener callback on the given worker.
568 * @param worker - The worker which should register a listener.
569 * @param listener - The message listener callback.
571 protected abstract registerWorkerMessageListener
<
572 Message
extends Data
| Response
573 >(worker
: Worker
, listener
: (message
: MessageValue
<Message
>) => void): void
576 * Returns a newly created worker.
578 protected abstract createWorker (): Worker
581 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
583 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
585 * @param worker - The newly created worker.
587 protected abstract afterWorkerSetup (worker
: Worker
): void
590 * Creates a new worker and sets it up completely in the pool worker nodes.
592 * @returns New, completely set up worker.
594 protected createAndSetupWorker (): Worker
{
595 const worker
= this.createWorker()
597 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
598 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
599 worker
.on('error', error
=> {
600 if (this.emitter
!= null) {
601 this.emitter
.emit(PoolEvents
.error
, error
)
604 if (this.opts
.restartWorkerOnError
=== true) {
605 worker
.on('error', () => {
606 this.createAndSetupWorker()
609 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
610 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
611 worker
.once('exit', () => {
612 this.removeWorkerNode(worker
)
615 this.pushWorkerNode(worker
)
617 this.afterWorkerSetup(worker
)
623 * This function is the listener registered for each worker message.
625 * @returns The listener function to execute when a message is received from a worker.
627 protected workerListener (): (message
: MessageValue
<Response
>) => void {
629 if (message
.id
!= null) {
630 // Task execution response received
631 const promiseResponse
= this.promiseResponseMap
.get(message
.id
)
632 if (promiseResponse
!= null) {
633 if (message
.error
!= null) {
634 promiseResponse
.reject(message
.error
)
635 if (this.emitter
!= null) {
636 this.emitter
.emit(PoolEvents
.taskError
, {
637 error
: message
.error
,
638 errorData
: message
.errorData
642 promiseResponse
.resolve(message
.data
as Response
)
644 this.afterTaskExecutionHook(promiseResponse
.worker
, message
)
645 this.promiseResponseMap
.delete(message
.id
)
646 const workerNodeKey
= this.getWorkerNodeKey(promiseResponse
.worker
)
648 this.opts
.enableTasksQueue
=== true &&
649 this.tasksQueueSize(workerNodeKey
) > 0
653 this.dequeueTask(workerNodeKey
) as Task
<Data
>
661 private checkAndEmitEvents (): void {
662 if (this.emitter
!= null) {
664 this.emitter
?.emit(PoolEvents
.busy
, this.info
)
666 if (this.type === PoolTypes
.dynamic
&& this.full
) {
667 this.emitter
?.emit(PoolEvents
.full
, this.info
)
673 * Sets the given worker node its tasks usage in the pool.
675 * @param workerNode - The worker node.
676 * @param tasksUsage - The worker node tasks usage.
678 private setWorkerNodeTasksUsage (
679 workerNode
: WorkerNode
<Worker
, Data
>,
680 tasksUsage
: TasksUsage
682 workerNode
.tasksUsage
= tasksUsage
686 * Pushes the given worker in the pool worker nodes.
688 * @param worker - The worker.
689 * @returns The worker nodes length.
691 private pushWorkerNode (worker
: Worker
): number {
692 return this.workerNodes
.push({
698 runTimeHistory
: new CircularArray(),
702 waitTimeHistory
: new CircularArray(),
707 tasksQueue
: new Queue
<Task
<Data
>>()
712 * Sets the given worker in the pool worker nodes.
714 * @param workerNodeKey - The worker node key.
715 * @param worker - The worker.
716 * @param tasksUsage - The worker tasks usage.
717 * @param tasksQueue - The worker task queue.
719 private setWorkerNode (
720 workerNodeKey
: number,
722 tasksUsage
: TasksUsage
,
723 tasksQueue
: Queue
<Task
<Data
>>
725 this.workerNodes
[workerNodeKey
] = {
733 * Removes the given worker from the pool worker nodes.
735 * @param worker - The worker.
737 private removeWorkerNode (worker
: Worker
): void {
738 const workerNodeKey
= this.getWorkerNodeKey(worker
)
739 if (workerNodeKey
!== -1) {
740 this.workerNodes
.splice(workerNodeKey
, 1)
741 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
745 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
746 this.beforeTaskExecutionHook(workerNodeKey
)
747 this.sendToWorker(this.workerNodes
[workerNodeKey
].worker
, task
)
750 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
751 return this.workerNodes
[workerNodeKey
].tasksQueue
.enqueue(task
)
754 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
755 return this.workerNodes
[workerNodeKey
].tasksQueue
.dequeue()
758 private tasksQueueSize (workerNodeKey
: number): number {
759 return this.workerNodes
[workerNodeKey
].tasksQueue
.size
762 private flushTasksQueue (workerNodeKey
: number): void {
763 if (this.tasksQueueSize(workerNodeKey
) > 0) {
764 for (let i
= 0; i
< this.tasksQueueSize(workerNodeKey
); i
++) {
767 this.dequeueTask(workerNodeKey
) as Task
<Data
>
773 private flushTasksQueues (): void {
774 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
775 this.flushTasksQueue(workerNodeKey
)