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 // FIXME: wait for tasks to be finished
414 await this.destroyWorker(workerNode
.worker
)
420 * Shutdowns the given worker.
422 * @param worker - A worker within `workerNodes`.
424 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
427 * Setup hook to execute code before worker node are created in the abstract constructor.
432 protected setupHook (): void {
433 // Intentionally empty
437 * Should return whether the worker is the main worker or not.
439 protected abstract isMain (): boolean
442 * Hook executed before the worker task execution.
445 * @param workerNodeKey - The worker node key.
447 protected beforeTaskExecutionHook (workerNodeKey
: number): void {
448 ++this.workerNodes
[workerNodeKey
].tasksUsage
.running
452 * Hook executed after the worker task execution.
455 * @param worker - The worker.
456 * @param message - The received message.
458 protected afterTaskExecutionHook (
460 message
: MessageValue
<Response
>
462 const workerTasksUsage
=
463 this.workerNodes
[this.getWorkerNodeKey(worker
)].tasksUsage
464 --workerTasksUsage
.running
465 ++workerTasksUsage
.run
466 if (message
.error
!= null) {
467 ++workerTasksUsage
.error
469 this.updateRunTimeTasksUsage(workerTasksUsage
, message
)
470 this.updateWaitTimeTasksUsage(workerTasksUsage
, message
)
473 private updateRunTimeTasksUsage (
474 workerTasksUsage
: TasksUsage
,
475 message
: MessageValue
<Response
>
477 if (this.workerChoiceStrategyContext
.getRequiredStatistics().runTime
) {
478 workerTasksUsage
.runTime
+= message
.runTime
?? 0
480 this.workerChoiceStrategyContext
.getRequiredStatistics().avgRunTime
&&
481 workerTasksUsage
.run
!== 0
483 workerTasksUsage
.avgRunTime
=
484 workerTasksUsage
.runTime
/ workerTasksUsage
.run
487 this.workerChoiceStrategyContext
.getRequiredStatistics().medRunTime
&&
488 message
.runTime
!= null
490 workerTasksUsage
.runTimeHistory
.push(message
.runTime
)
491 workerTasksUsage
.medRunTime
= median(workerTasksUsage
.runTimeHistory
)
496 private updateWaitTimeTasksUsage (
497 workerTasksUsage
: TasksUsage
,
498 message
: MessageValue
<Response
>
500 if (this.workerChoiceStrategyContext
.getRequiredStatistics().waitTime
) {
501 workerTasksUsage
.waitTime
+= message
.waitTime
?? 0
503 this.workerChoiceStrategyContext
.getRequiredStatistics().avgWaitTime
&&
504 workerTasksUsage
.run
!== 0
506 workerTasksUsage
.avgWaitTime
=
507 workerTasksUsage
.waitTime
/ workerTasksUsage
.run
510 this.workerChoiceStrategyContext
.getRequiredStatistics().medWaitTime
&&
511 message
.waitTime
!= null
513 workerTasksUsage
.waitTimeHistory
.push(message
.waitTime
)
514 workerTasksUsage
.medWaitTime
= median(workerTasksUsage
.waitTimeHistory
)
520 * Chooses a worker node for the next task.
522 * The default worker choice strategy uses a round robin algorithm to distribute the load.
524 * @returns The worker node key
526 protected chooseWorkerNode (): number {
527 let workerNodeKey
: number
528 if (this.type === PoolTypes
.dynamic
&& !this.full
&& this.internalBusy()) {
529 const workerCreated
= this.createAndSetupWorker()
530 this.registerWorkerMessageListener(workerCreated
, message
=> {
531 const currentWorkerNodeKey
= this.getWorkerNodeKey(workerCreated
)
533 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
534 (message
.kill
!= null &&
535 this.workerNodes
[currentWorkerNodeKey
].tasksUsage
.running
=== 0)
537 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
538 this.flushTasksQueue(currentWorkerNodeKey
)
539 // FIXME: wait for tasks to be finished
540 void (this.destroyWorker(workerCreated
) as Promise
<void>)
543 workerNodeKey
= this.getWorkerNodeKey(workerCreated
)
545 workerNodeKey
= this.workerChoiceStrategyContext
.execute()
551 * Sends a message to the given worker.
553 * @param worker - The worker which should receive the message.
554 * @param message - The message.
556 protected abstract sendToWorker (
558 message
: MessageValue
<Data
>
562 * Registers a listener callback on the given worker.
564 * @param worker - The worker which should register a listener.
565 * @param listener - The message listener callback.
567 protected abstract registerWorkerMessageListener
<
568 Message
extends Data
| Response
569 >(worker
: Worker
, listener
: (message
: MessageValue
<Message
>) => void): void
572 * Returns a newly created worker.
574 protected abstract createWorker (): Worker
577 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
579 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
581 * @param worker - The newly created worker.
583 protected abstract afterWorkerSetup (worker
: Worker
): void
586 * Creates a new worker and sets it up completely in the pool worker nodes.
588 * @returns New, completely set up worker.
590 protected createAndSetupWorker (): Worker
{
591 const worker
= this.createWorker()
593 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
594 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
595 worker
.on('error', error
=> {
596 if (this.emitter
!= null) {
597 this.emitter
.emit(PoolEvents
.error
, error
)
600 if (this.opts
.restartWorkerOnError
=== true) {
601 worker
.on('error', () => {
602 this.createAndSetupWorker()
605 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
606 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
607 worker
.once('exit', () => {
608 this.removeWorkerNode(worker
)
611 this.pushWorkerNode(worker
)
613 this.afterWorkerSetup(worker
)
619 * This function is the listener registered for each worker message.
621 * @returns The listener function to execute when a message is received from a worker.
623 protected workerListener (): (message
: MessageValue
<Response
>) => void {
625 if (message
.id
!= null) {
626 // Task execution response received
627 const promiseResponse
= this.promiseResponseMap
.get(message
.id
)
628 if (promiseResponse
!= null) {
629 if (message
.error
!= null) {
630 promiseResponse
.reject(message
.error
)
631 if (this.emitter
!= null) {
632 this.emitter
.emit(PoolEvents
.taskError
, {
633 error
: message
.error
,
634 errorData
: message
.errorData
638 promiseResponse
.resolve(message
.data
as Response
)
640 this.afterTaskExecutionHook(promiseResponse
.worker
, message
)
641 this.promiseResponseMap
.delete(message
.id
)
642 const workerNodeKey
= this.getWorkerNodeKey(promiseResponse
.worker
)
644 this.opts
.enableTasksQueue
=== true &&
645 this.tasksQueueSize(workerNodeKey
) > 0
649 this.dequeueTask(workerNodeKey
) as Task
<Data
>
657 private checkAndEmitEvents (): void {
658 if (this.emitter
!= null) {
660 this.emitter
?.emit(PoolEvents
.busy
, this.info
)
662 if (this.type === PoolTypes
.dynamic
&& this.full
) {
663 this.emitter
?.emit(PoolEvents
.full
, this.info
)
669 * Sets the given worker node its tasks usage in the pool.
671 * @param workerNode - The worker node.
672 * @param tasksUsage - The worker node tasks usage.
674 private setWorkerNodeTasksUsage (
675 workerNode
: WorkerNode
<Worker
, Data
>,
676 tasksUsage
: TasksUsage
678 workerNode
.tasksUsage
= tasksUsage
682 * Pushes the given worker in the pool worker nodes.
684 * @param worker - The worker.
685 * @returns The worker nodes length.
687 private pushWorkerNode (worker
: Worker
): number {
688 return this.workerNodes
.push({
694 runTimeHistory
: new CircularArray(),
698 waitTimeHistory
: new CircularArray(),
703 tasksQueue
: new Queue
<Task
<Data
>>()
708 * Sets the given worker in the pool worker nodes.
710 * @param workerNodeKey - The worker node key.
711 * @param worker - The worker.
712 * @param tasksUsage - The worker tasks usage.
713 * @param tasksQueue - The worker task queue.
715 private setWorkerNode (
716 workerNodeKey
: number,
718 tasksUsage
: TasksUsage
,
719 tasksQueue
: Queue
<Task
<Data
>>
721 this.workerNodes
[workerNodeKey
] = {
729 * Removes the given worker from the pool worker nodes.
731 * @param worker - The worker.
733 private removeWorkerNode (worker
: Worker
): void {
734 const workerNodeKey
= this.getWorkerNodeKey(worker
)
735 if (workerNodeKey
!== -1) {
736 this.workerNodes
.splice(workerNodeKey
, 1)
737 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
741 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
742 this.beforeTaskExecutionHook(workerNodeKey
)
743 this.sendToWorker(this.workerNodes
[workerNodeKey
].worker
, task
)
746 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
747 return this.workerNodes
[workerNodeKey
].tasksQueue
.enqueue(task
)
750 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
751 return this.workerNodes
[workerNodeKey
].tasksQueue
.dequeue()
754 private tasksQueueSize (workerNodeKey
: number): number {
755 return this.workerNodes
[workerNodeKey
].tasksQueue
.size
758 private flushTasksQueue (workerNodeKey
: number): void {
759 if (this.tasksQueueSize(workerNodeKey
) > 0) {
760 for (let i
= 0; i
< this.tasksQueueSize(workerNodeKey
); i
++) {
763 this.dequeueTask(workerNodeKey
) as Task
<Data
>
769 private flushTasksQueues (): void {
770 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
771 this.flushTasksQueue(workerNodeKey
)