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'
18 type TasksQueueOptions
20 import type { IWorker
, Task
, TasksUsage
, WorkerNode
} from
'./worker'
22 WorkerChoiceStrategies
,
23 type WorkerChoiceStrategy
,
24 type WorkerChoiceStrategyOptions
25 } from
'./selection-strategies/selection-strategies-types'
26 import { WorkerChoiceStrategyContext
} from
'./selection-strategies/worker-choice-strategy-context'
29 * Base class that implements some shared logic for all poolifier pools.
31 * @typeParam Worker - Type of worker which manages this pool.
32 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
33 * @typeParam Response - Type of execution response. This can only be serializable data.
35 export abstract class AbstractPool
<
36 Worker
extends IWorker
,
39 > implements IPool
<Worker
, Data
, Response
> {
41 public readonly workerNodes
: Array<WorkerNode
<Worker
, Data
>> = []
44 public readonly emitter
?: PoolEmitter
47 * The execution response promise map.
49 * - `key`: The message id of each submitted task.
50 * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks.
52 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
54 protected promiseResponseMap
: Map
<
56 PromiseResponseWrapper
<Worker
, Response
>
57 > = new Map
<string, PromiseResponseWrapper
<Worker
, Response
>>()
60 * Worker choice strategy context referencing a worker choice algorithm implementation.
62 * Default to a round robin algorithm.
64 protected workerChoiceStrategyContext
: WorkerChoiceStrategyContext
<
71 * Constructs a new poolifier pool.
73 * @param numberOfWorkers - Number of workers that this pool should manage.
74 * @param filePath - Path to the worker file.
75 * @param opts - Options for the pool.
78 public readonly numberOfWorkers
: number,
79 public readonly filePath
: string,
80 public readonly opts
: PoolOptions
<Worker
>
83 throw new Error('Cannot start a pool from a worker!')
85 this.checkNumberOfWorkers(this.numberOfWorkers
)
86 this.checkFilePath(this.filePath
)
87 this.checkPoolOptions(this.opts
)
89 this.chooseWorkerNode
= this.chooseWorkerNode
.bind(this)
90 this.executeTask
= this.executeTask
.bind(this)
91 this.enqueueTask
= this.enqueueTask
.bind(this)
92 this.checkAndEmitEvents
= this.checkAndEmitEvents
.bind(this)
96 for (let i
= 1; i
<= this.numberOfWorkers
; i
++) {
97 this.createAndSetupWorker()
100 if (this.opts
.enableEvents
=== true) {
101 this.emitter
= new PoolEmitter()
103 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext
<
109 this.opts
.workerChoiceStrategy
,
110 this.opts
.workerChoiceStrategyOptions
114 private checkFilePath (filePath
: string): void {
117 (typeof filePath
=== 'string' && filePath
.trim().length
=== 0)
119 throw new Error('Please specify a file with a worker implementation')
123 private checkNumberOfWorkers (numberOfWorkers
: number): void {
124 if (numberOfWorkers
== null) {
126 'Cannot instantiate a pool without specifying the number of workers'
128 } else if (!Number.isSafeInteger(numberOfWorkers
)) {
130 'Cannot instantiate a pool with a non safe integer number of workers'
132 } else if (numberOfWorkers
< 0) {
133 throw new RangeError(
134 'Cannot instantiate a pool with a negative number of workers'
136 } else if (this.type === PoolType
.FIXED
&& numberOfWorkers
=== 0) {
137 throw new Error('Cannot instantiate a fixed pool with no worker')
141 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
142 if (isPlainObject(opts
)) {
143 this.opts
.workerChoiceStrategy
=
144 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
145 this.checkValidWorkerChoiceStrategy(this.opts
.workerChoiceStrategy
)
146 this.opts
.workerChoiceStrategyOptions
=
147 opts
.workerChoiceStrategyOptions
??
148 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
149 this.checkValidWorkerChoiceStrategyOptions(
150 this.opts
.workerChoiceStrategyOptions
152 this.opts
.enableEvents
= opts
.enableEvents
?? true
153 this.opts
.enableTasksQueue
= opts
.enableTasksQueue
?? false
154 if (this.opts
.enableTasksQueue
) {
155 this.checkValidTasksQueueOptions(
156 opts
.tasksQueueOptions
as TasksQueueOptions
158 this.opts
.tasksQueueOptions
= this.buildTasksQueueOptions(
159 opts
.tasksQueueOptions
as TasksQueueOptions
163 throw new TypeError('Invalid pool options: must be a plain object')
167 private checkValidWorkerChoiceStrategy (
168 workerChoiceStrategy
: WorkerChoiceStrategy
170 if (!Object.values(WorkerChoiceStrategies
).includes(workerChoiceStrategy
)) {
172 `Invalid worker choice strategy '${workerChoiceStrategy}'`
177 private checkValidWorkerChoiceStrategyOptions (
178 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
180 if (!isPlainObject(workerChoiceStrategyOptions
)) {
182 'Invalid worker choice strategy options: must be a plain object'
186 workerChoiceStrategyOptions
.weights
!= null &&
187 Object.keys(workerChoiceStrategyOptions
.weights
).length
!== this.size
190 'Invalid worker choice strategy options: must have a weight for each worker node'
195 private checkValidTasksQueueOptions (
196 tasksQueueOptions
: TasksQueueOptions
198 if (tasksQueueOptions
!= null && !isPlainObject(tasksQueueOptions
)) {
199 throw new TypeError('Invalid tasks queue options: must be a plain object')
201 if ((tasksQueueOptions
?.concurrency
as number) <= 0) {
203 `Invalid worker tasks concurrency '${
204 tasksQueueOptions.concurrency as number
211 public abstract get
type (): PoolType
214 public abstract get
size (): number
217 * Number of tasks running in the pool.
219 private get
numberOfRunningTasks (): number {
220 return this.workerNodes
.reduce(
221 (accumulator
, workerNode
) => accumulator
+ workerNode
.tasksUsage
.running
,
227 * Number of tasks queued in the pool.
229 private get
numberOfQueuedTasks (): number {
230 if (this.opts
.enableTasksQueue
=== false) {
233 return this.workerNodes
.reduce(
234 (accumulator
, workerNode
) => accumulator
+ workerNode
.tasksQueue
.size
,
240 * Gets the given worker its worker node key.
242 * @param worker - The worker.
243 * @returns The worker node key if the worker is found in the pool worker nodes, `-1` otherwise.
245 private getWorkerNodeKey (worker
: Worker
): number {
246 return this.workerNodes
.findIndex(
247 workerNode
=> workerNode
.worker
=== worker
252 public setWorkerChoiceStrategy (
253 workerChoiceStrategy
: WorkerChoiceStrategy
,
254 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
256 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
257 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
258 for (const workerNode
of this.workerNodes
) {
259 this.setWorkerNodeTasksUsage(workerNode
, {
263 runTimeHistory
: new CircularArray(),
267 waitTimeHistory
: new CircularArray(),
273 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
274 this.opts
.workerChoiceStrategy
276 if (workerChoiceStrategyOptions
!= null) {
277 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
282 public setWorkerChoiceStrategyOptions (
283 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
285 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
286 this.opts
.workerChoiceStrategyOptions
= workerChoiceStrategyOptions
287 this.workerChoiceStrategyContext
.setOptions(
288 this.opts
.workerChoiceStrategyOptions
293 public enableTasksQueue (
295 tasksQueueOptions
?: TasksQueueOptions
297 if (this.opts
.enableTasksQueue
=== true && !enable
) {
298 this.flushTasksQueues()
300 this.opts
.enableTasksQueue
= enable
301 this.setTasksQueueOptions(tasksQueueOptions
as TasksQueueOptions
)
305 public setTasksQueueOptions (tasksQueueOptions
: TasksQueueOptions
): void {
306 if (this.opts
.enableTasksQueue
=== true) {
307 this.checkValidTasksQueueOptions(tasksQueueOptions
)
308 this.opts
.tasksQueueOptions
=
309 this.buildTasksQueueOptions(tasksQueueOptions
)
311 delete this.opts
.tasksQueueOptions
315 private buildTasksQueueOptions (
316 tasksQueueOptions
: TasksQueueOptions
317 ): TasksQueueOptions
{
319 concurrency
: tasksQueueOptions
?.concurrency
?? 1
324 * Whether the pool is full or not.
326 * The pool filling boolean status.
328 protected abstract get
full (): boolean
331 * Whether the pool is busy or not.
333 * The pool busyness boolean status.
335 protected abstract get
busy (): boolean
337 protected internalBusy (): boolean {
339 this.workerNodes
.findIndex(workerNode
=> {
340 return workerNode
.tasksUsage
.running
=== 0
346 public async execute (data
?: Data
, name
?: string): Promise
<Response
> {
347 const submissionTimestamp
= performance
.now()
348 const workerNodeKey
= this.chooseWorkerNode()
349 const submittedTask
: Task
<Data
> = {
351 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
352 data
: data
?? ({} as Data
),
354 id
: crypto
.randomUUID()
356 const res
= new Promise
<Response
>((resolve
, reject
) => {
357 this.promiseResponseMap
.set(submittedTask
.id
as string, {
360 worker
: this.workerNodes
[workerNodeKey
].worker
364 this.opts
.enableTasksQueue
=== true &&
366 this.workerNodes
[workerNodeKey
].tasksUsage
.running
>=
367 ((this.opts
.tasksQueueOptions
as TasksQueueOptions
)
368 .concurrency
as number))
370 this.enqueueTask(workerNodeKey
, submittedTask
)
372 this.executeTask(workerNodeKey
, submittedTask
)
374 this.workerChoiceStrategyContext
.update(workerNodeKey
)
375 this.checkAndEmitEvents()
376 // eslint-disable-next-line @typescript-eslint/return-await
381 public async destroy (): Promise
<void> {
383 this.workerNodes
.map(async (workerNode
, workerNodeKey
) => {
384 this.flushTasksQueue(workerNodeKey
)
385 await this.destroyWorker(workerNode
.worker
)
391 * Shutdowns the given worker.
393 * @param worker - A worker within `workerNodes`.
395 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
398 * Setup hook to execute code before worker node are created in the abstract constructor.
403 protected setupHook (): void {
404 // Intentionally empty
408 * Should return whether the worker is the main worker or not.
410 protected abstract isMain (): boolean
413 * Hook executed before the worker task execution.
416 * @param workerNodeKey - The worker node key.
418 protected beforeTaskExecutionHook (workerNodeKey
: number): void {
419 ++this.workerNodes
[workerNodeKey
].tasksUsage
.running
423 * Hook executed after the worker task execution.
426 * @param worker - The worker.
427 * @param message - The received message.
429 protected afterTaskExecutionHook (
431 message
: MessageValue
<Response
>
433 const workerTasksUsage
=
434 this.workerNodes
[this.getWorkerNodeKey(worker
)].tasksUsage
435 --workerTasksUsage
.running
436 ++workerTasksUsage
.run
437 if (message
.error
!= null) {
438 ++workerTasksUsage
.error
440 this.updateRunTimeTasksUsage(workerTasksUsage
, message
)
441 this.updateWaitTasksUsage(workerTasksUsage
, message
)
444 private updateRunTimeTasksUsage (
445 workerTasksUsage
: TasksUsage
,
446 message
: MessageValue
<Response
>
448 if (this.workerChoiceStrategyContext
.getRequiredStatistics().runTime
) {
449 workerTasksUsage
.runTime
+= message
.runTime
?? 0
451 this.workerChoiceStrategyContext
.getRequiredStatistics().avgRunTime
&&
452 workerTasksUsage
.run
!== 0
454 workerTasksUsage
.avgRunTime
=
455 workerTasksUsage
.runTime
/ workerTasksUsage
.run
458 this.workerChoiceStrategyContext
.getRequiredStatistics().medRunTime
&&
459 message
.runTime
!= null
461 workerTasksUsage
.runTimeHistory
.push(message
.runTime
)
462 workerTasksUsage
.medRunTime
= median(workerTasksUsage
.runTimeHistory
)
467 private updateWaitTasksUsage (
468 workerTasksUsage
: TasksUsage
,
469 message
: MessageValue
<Response
>
471 if (this.workerChoiceStrategyContext
.getRequiredStatistics().waitTime
) {
472 workerTasksUsage
.waitTime
+= message
.waitTime
?? 0
474 this.workerChoiceStrategyContext
.getRequiredStatistics().avgWaitTime
&&
475 workerTasksUsage
.run
!== 0
477 workerTasksUsage
.avgWaitTime
=
478 workerTasksUsage
.waitTime
/ workerTasksUsage
.run
481 this.workerChoiceStrategyContext
.getRequiredStatistics().medWaitTime
&&
482 message
.waitTime
!= null
484 workerTasksUsage
.waitTimeHistory
.push(message
.waitTime
)
485 workerTasksUsage
.medWaitTime
= median(workerTasksUsage
.waitTimeHistory
)
491 * Chooses a worker node for the next task.
493 * The default worker choice strategy uses a round robin algorithm to distribute the load.
495 * @returns The worker node key
497 protected chooseWorkerNode (): number {
498 let workerNodeKey
: number
499 if (this.type === PoolType
.DYNAMIC
&& !this.full
&& this.internalBusy()) {
500 const workerCreated
= this.createAndSetupWorker()
501 this.registerWorkerMessageListener(workerCreated
, message
=> {
502 const currentWorkerNodeKey
= this.getWorkerNodeKey(workerCreated
)
504 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
505 (message
.kill
!= null &&
506 this.workerNodes
[currentWorkerNodeKey
].tasksUsage
.running
=== 0)
508 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
509 this.flushTasksQueue(currentWorkerNodeKey
)
510 void (this.destroyWorker(workerCreated
) as Promise
<void>)
513 workerNodeKey
= this.getWorkerNodeKey(workerCreated
)
515 workerNodeKey
= this.workerChoiceStrategyContext
.execute()
521 * Sends a message to the given worker.
523 * @param worker - The worker which should receive the message.
524 * @param message - The message.
526 protected abstract sendToWorker (
528 message
: MessageValue
<Data
>
532 * Registers a listener callback on the given worker.
534 * @param worker - The worker which should register a listener.
535 * @param listener - The message listener callback.
537 protected abstract registerWorkerMessageListener
<
538 Message
extends Data
| Response
539 >(worker
: Worker
, listener
: (message
: MessageValue
<Message
>) => void): void
542 * Returns a newly created worker.
544 protected abstract createWorker (): Worker
547 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
549 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
551 * @param worker - The newly created worker.
553 protected abstract afterWorkerSetup (worker
: Worker
): void
556 * Creates a new worker and sets it up completely in the pool worker nodes.
558 * @returns New, completely set up worker.
560 protected createAndSetupWorker (): Worker
{
561 const worker
= this.createWorker()
563 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
564 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
565 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
566 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
567 worker
.once('exit', () => {
568 this.removeWorkerNode(worker
)
571 this.pushWorkerNode(worker
)
573 this.afterWorkerSetup(worker
)
579 * This function is the listener registered for each worker message.
581 * @returns The listener function to execute when a message is received from a worker.
583 protected workerListener (): (message
: MessageValue
<Response
>) => void {
585 if (message
.id
!= null) {
586 // Task execution response received
587 const promiseResponse
= this.promiseResponseMap
.get(message
.id
)
588 if (promiseResponse
!= null) {
589 if (message
.error
!= null) {
590 promiseResponse
.reject(message
.error
)
592 promiseResponse
.resolve(message
.data
as Response
)
594 this.afterTaskExecutionHook(promiseResponse
.worker
, message
)
595 this.promiseResponseMap
.delete(message
.id
)
596 const workerNodeKey
= this.getWorkerNodeKey(promiseResponse
.worker
)
598 this.opts
.enableTasksQueue
=== true &&
599 this.tasksQueueSize(workerNodeKey
) > 0
603 this.dequeueTask(workerNodeKey
) as Task
<Data
>
611 private checkAndEmitEvents (): void {
612 if (this.opts
.enableEvents
=== true) {
614 this.emitter
?.emit(PoolEvents
.busy
)
616 if (this.type === PoolType
.DYNAMIC
&& this.full
) {
617 this.emitter
?.emit(PoolEvents
.full
)
623 * Sets the given worker node its tasks usage in the pool.
625 * @param workerNode - The worker node.
626 * @param tasksUsage - The worker node tasks usage.
628 private setWorkerNodeTasksUsage (
629 workerNode
: WorkerNode
<Worker
, Data
>,
630 tasksUsage
: TasksUsage
632 workerNode
.tasksUsage
= tasksUsage
636 * Pushes the given worker in the pool worker nodes.
638 * @param worker - The worker.
639 * @returns The worker nodes length.
641 private pushWorkerNode (worker
: Worker
): number {
642 return this.workerNodes
.push({
648 runTimeHistory
: new CircularArray(),
652 waitTimeHistory
: new CircularArray(),
657 tasksQueue
: new Queue
<Task
<Data
>>()
662 * Sets the given worker in the pool worker nodes.
664 * @param workerNodeKey - The worker node key.
665 * @param worker - The worker.
666 * @param tasksUsage - The worker tasks usage.
667 * @param tasksQueue - The worker task queue.
669 private setWorkerNode (
670 workerNodeKey
: number,
672 tasksUsage
: TasksUsage
,
673 tasksQueue
: Queue
<Task
<Data
>>
675 this.workerNodes
[workerNodeKey
] = {
683 * Removes the given worker from the pool worker nodes.
685 * @param worker - The worker.
687 private removeWorkerNode (worker
: Worker
): void {
688 const workerNodeKey
= this.getWorkerNodeKey(worker
)
689 this.workerNodes
.splice(workerNodeKey
, 1)
690 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
693 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
694 this.beforeTaskExecutionHook(workerNodeKey
)
695 this.sendToWorker(this.workerNodes
[workerNodeKey
].worker
, task
)
698 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
699 return this.workerNodes
[workerNodeKey
].tasksQueue
.enqueue(task
)
702 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
703 return this.workerNodes
[workerNodeKey
].tasksQueue
.dequeue()
706 private tasksQueueSize (workerNodeKey
: number): number {
707 return this.workerNodes
[workerNodeKey
].tasksQueue
.size
710 private flushTasksQueue (workerNodeKey
: number): void {
711 if (this.tasksQueueSize(workerNodeKey
) > 0) {
712 for (let i
= 0; i
< this.tasksQueueSize(workerNodeKey
); i
++) {
715 this.dequeueTask(workerNodeKey
) as Task
<Data
>
721 private flushTasksQueues (): void {
722 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
723 this.flushTasksQueue(workerNodeKey
)