1 import crypto from
'node:crypto'
2 import type { MessageValue
, PromiseResponseWrapper
} from
'../utility-types'
4 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
,
8 import { KillBehaviors
, isKillBehavior
} from
'../worker/worker-options'
9 import { CircularArray
} from
'../circular-array'
16 type TasksQueueOptions
18 import type { IWorker
, Task
, TasksUsage
, WorkerNode
} from
'./worker'
20 WorkerChoiceStrategies
,
21 type WorkerChoiceStrategy
,
22 type WorkerChoiceStrategyOptions
23 } from
'./selection-strategies/selection-strategies-types'
24 import { WorkerChoiceStrategyContext
} from
'./selection-strategies/worker-choice-strategy-context'
27 * Base class that implements some shared logic for all poolifier pools.
29 * @typeParam Worker - Type of worker which manages this pool.
30 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
31 * @typeParam Response - Type of execution response. This can only be serializable data.
33 export abstract class AbstractPool
<
34 Worker
extends IWorker
,
37 > implements IPool
<Worker
, Data
, Response
> {
39 public readonly workerNodes
: Array<WorkerNode
<Worker
, Data
>> = []
42 public readonly emitter
?: PoolEmitter
45 * The execution response promise map.
47 * - `key`: The message id of each submitted task.
48 * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks.
50 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
52 protected promiseResponseMap
: Map
<
54 PromiseResponseWrapper
<Worker
, Response
>
55 > = new Map
<string, PromiseResponseWrapper
<Worker
, Response
>>()
58 * Worker choice strategy context referencing a worker choice algorithm implementation.
60 * Default to a round robin algorithm.
62 protected workerChoiceStrategyContext
: WorkerChoiceStrategyContext
<
69 * Constructs a new poolifier pool.
71 * @param numberOfWorkers - Number of workers that this pool should manage.
72 * @param filePath - Path to the worker file.
73 * @param opts - Options for the pool.
76 public readonly numberOfWorkers
: number,
77 public readonly filePath
: string,
78 public readonly opts
: PoolOptions
<Worker
>
81 throw new Error('Cannot start a pool from a worker!')
83 this.checkNumberOfWorkers(this.numberOfWorkers
)
84 this.checkFilePath(this.filePath
)
85 this.checkPoolOptions(this.opts
)
87 this.chooseWorkerNode
= this.chooseWorkerNode
.bind(this)
88 this.executeTask
= this.executeTask
.bind(this)
89 this.enqueueTask
= this.enqueueTask
.bind(this)
90 this.checkAndEmitEvents
= this.checkAndEmitEvents
.bind(this)
94 for (let i
= 1; i
<= this.numberOfWorkers
; i
++) {
95 this.createAndSetupWorker()
98 if (this.opts
.enableEvents
=== true) {
99 this.emitter
= new PoolEmitter()
101 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext
<
107 this.opts
.workerChoiceStrategy
,
108 this.opts
.workerChoiceStrategyOptions
112 private checkFilePath (filePath
: string): void {
115 (typeof filePath
=== 'string' && filePath
.trim().length
=== 0)
117 throw new Error('Please specify a file with a worker implementation')
121 private checkNumberOfWorkers (numberOfWorkers
: number): void {
122 if (numberOfWorkers
== null) {
124 'Cannot instantiate a pool without specifying the number of workers'
126 } else if (!Number.isSafeInteger(numberOfWorkers
)) {
128 'Cannot instantiate a pool with a non integer number of workers'
130 } else if (numberOfWorkers
< 0) {
131 throw new RangeError(
132 'Cannot instantiate a pool with a negative number of workers'
134 } else if (this.type === PoolType
.FIXED
&& numberOfWorkers
=== 0) {
135 throw new Error('Cannot instantiate a fixed pool with no worker')
139 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
140 this.opts
.workerChoiceStrategy
=
141 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
142 this.checkValidWorkerChoiceStrategy(this.opts
.workerChoiceStrategy
)
143 this.opts
.workerChoiceStrategyOptions
=
144 opts
.workerChoiceStrategyOptions
?? DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
145 this.opts
.enableEvents
= opts
.enableEvents
?? true
146 this.opts
.enableTasksQueue
= opts
.enableTasksQueue
?? false
147 if (this.opts
.enableTasksQueue
) {
148 this.checkValidTasksQueueOptions(
149 opts
.tasksQueueOptions
as TasksQueueOptions
151 this.opts
.tasksQueueOptions
= this.buildTasksQueueOptions(
152 opts
.tasksQueueOptions
as TasksQueueOptions
157 private checkValidWorkerChoiceStrategy (
158 workerChoiceStrategy
: WorkerChoiceStrategy
160 if (!Object.values(WorkerChoiceStrategies
).includes(workerChoiceStrategy
)) {
162 `Invalid worker choice strategy '${workerChoiceStrategy}'`
167 private checkValidTasksQueueOptions (
168 tasksQueueOptions
: TasksQueueOptions
170 if ((tasksQueueOptions
?.concurrency
as number) <= 0) {
172 `Invalid worker tasks concurrency '${
173 tasksQueueOptions.concurrency as number
180 public abstract get
type (): PoolType
183 * Number of tasks running in the pool.
185 private get
numberOfRunningTasks (): number {
186 return this.workerNodes
.reduce(
187 (accumulator
, workerNode
) => accumulator
+ workerNode
.tasksUsage
.running
,
193 * Number of tasks queued in the pool.
195 private get
numberOfQueuedTasks (): number {
196 if (this.opts
.enableTasksQueue
=== false) {
199 return this.workerNodes
.reduce(
200 (accumulator
, workerNode
) => accumulator
+ workerNode
.tasksQueue
.length
,
206 * Gets the given worker its worker node key.
208 * @param worker - The worker.
209 * @returns The worker node key if the worker is found in the pool worker nodes, `-1` otherwise.
211 private getWorkerNodeKey (worker
: Worker
): number {
212 return this.workerNodes
.findIndex(
213 workerNode
=> workerNode
.worker
=== worker
218 public setWorkerChoiceStrategy (
219 workerChoiceStrategy
: WorkerChoiceStrategy
,
220 workerChoiceStrategyOptions
?: WorkerChoiceStrategyOptions
222 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
223 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
224 for (const workerNode
of this.workerNodes
) {
225 this.setWorkerNodeTasksUsage(workerNode
, {
229 runTimeHistory
: new CircularArray(),
235 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
236 this.opts
.workerChoiceStrategy
238 if (workerChoiceStrategyOptions
!= null) {
239 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions
)
244 public setWorkerChoiceStrategyOptions (
245 workerChoiceStrategyOptions
: WorkerChoiceStrategyOptions
247 this.opts
.workerChoiceStrategyOptions
= workerChoiceStrategyOptions
248 this.workerChoiceStrategyContext
.setOptions(
249 this.opts
.workerChoiceStrategyOptions
254 public enableTasksQueue (
256 tasksQueueOptions
?: TasksQueueOptions
258 if (this.opts
.enableTasksQueue
=== true && !enable
) {
259 this.flushTasksQueues()
261 this.opts
.enableTasksQueue
= enable
262 this.setTasksQueueOptions(tasksQueueOptions
as TasksQueueOptions
)
266 public setTasksQueueOptions (tasksQueueOptions
: TasksQueueOptions
): void {
267 if (this.opts
.enableTasksQueue
=== true) {
268 this.checkValidTasksQueueOptions(tasksQueueOptions
)
269 this.opts
.tasksQueueOptions
=
270 this.buildTasksQueueOptions(tasksQueueOptions
)
272 delete this.opts
.tasksQueueOptions
276 private buildTasksQueueOptions (
277 tasksQueueOptions
: TasksQueueOptions
278 ): TasksQueueOptions
{
280 concurrency
: tasksQueueOptions
?.concurrency
?? 1
285 * Whether the pool is full or not.
287 * The pool filling boolean status.
289 protected abstract get
full (): boolean
292 * Whether the pool is busy or not.
294 * The pool busyness boolean status.
296 protected abstract get
busy (): boolean
298 protected internalBusy (): boolean {
300 this.workerNodes
.findIndex(workerNode
=> {
301 return workerNode
.tasksUsage
?.running
=== 0
307 public async execute (data
?: Data
): Promise
<Response
> {
308 const [workerNodeKey
, workerNode
] = this.chooseWorkerNode()
309 const submittedTask
: Task
<Data
> = {
310 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
311 data
: data
?? ({} as Data
),
312 id
: crypto
.randomUUID()
314 const res
= new Promise
<Response
>((resolve
, reject
) => {
315 this.promiseResponseMap
.set(submittedTask
.id
as string, {
318 worker
: workerNode
.worker
322 this.opts
.enableTasksQueue
=== true &&
324 this.workerNodes
[workerNodeKey
].tasksUsage
.running
>=
325 ((this.opts
.tasksQueueOptions
as TasksQueueOptions
)
326 .concurrency
as number))
328 this.enqueueTask(workerNodeKey
, submittedTask
)
330 this.executeTask(workerNodeKey
, submittedTask
)
332 this.checkAndEmitEvents()
333 // eslint-disable-next-line @typescript-eslint/return-await
338 public async destroy (): Promise
<void> {
340 this.workerNodes
.map(async (workerNode
, workerNodeKey
) => {
341 this.flushTasksQueue(workerNodeKey
)
342 await this.destroyWorker(workerNode
.worker
)
348 * Shutdowns the given worker.
350 * @param worker - A worker within `workerNodes`.
352 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
355 * Setup hook to execute code before worker node are created in the abstract constructor.
360 protected setupHook (): void {
361 // Intentionally empty
365 * Should return whether the worker is the main worker or not.
367 protected abstract isMain (): boolean
370 * Hook executed before the worker task execution.
373 * @param workerNodeKey - The worker node key.
375 protected beforeTaskExecutionHook (workerNodeKey
: number): void {
376 ++this.workerNodes
[workerNodeKey
].tasksUsage
.running
380 * Hook executed after the worker task execution.
383 * @param worker - The worker.
384 * @param message - The received message.
386 protected afterTaskExecutionHook (
388 message
: MessageValue
<Response
>
390 const workerTasksUsage
= this.getWorkerTasksUsage(worker
)
391 --workerTasksUsage
.running
392 ++workerTasksUsage
.run
393 if (message
.error
!= null) {
394 ++workerTasksUsage
.error
396 if (this.workerChoiceStrategyContext
.getRequiredStatistics().runTime
) {
397 workerTasksUsage
.runTime
+= message
.runTime
?? 0
399 this.workerChoiceStrategyContext
.getRequiredStatistics().avgRunTime
&&
400 workerTasksUsage
.run
!== 0
402 workerTasksUsage
.avgRunTime
=
403 workerTasksUsage
.runTime
/ workerTasksUsage
.run
405 if (this.workerChoiceStrategyContext
.getRequiredStatistics().medRunTime
) {
406 workerTasksUsage
.runTimeHistory
.push(message
.runTime
?? 0)
407 workerTasksUsage
.medRunTime
= median(workerTasksUsage
.runTimeHistory
)
413 * Chooses a worker node for the next task.
415 * The default uses a round robin algorithm to distribute the load.
417 * @returns [worker node key, worker node].
419 protected chooseWorkerNode (): [number, WorkerNode
<Worker
, Data
>] {
420 let workerNodeKey
: number
421 if (this.type === PoolType
.DYNAMIC
&& !this.full
&& this.internalBusy()) {
422 const workerCreated
= this.createAndSetupWorker()
423 this.registerWorkerMessageListener(workerCreated
, message
=> {
425 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
426 (message
.kill
!= null &&
427 this.getWorkerTasksUsage(workerCreated
)?.running
=== 0)
429 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
430 this.flushTasksQueueByWorker(workerCreated
)
431 void (this.destroyWorker(workerCreated
) as Promise
<void>)
434 workerNodeKey
= this.getWorkerNodeKey(workerCreated
)
436 workerNodeKey
= this.workerChoiceStrategyContext
.execute()
438 return [workerNodeKey
, this.workerNodes
[workerNodeKey
]]
442 * Sends a message to the given worker.
444 * @param worker - The worker which should receive the message.
445 * @param message - The message.
447 protected abstract sendToWorker (
449 message
: MessageValue
<Data
>
453 * Registers a listener callback on the given worker.
455 * @param worker - The worker which should register a listener.
456 * @param listener - The message listener callback.
458 protected abstract registerWorkerMessageListener
<
459 Message
extends Data
| Response
460 >(worker
: Worker
, listener
: (message
: MessageValue
<Message
>) => void): void
463 * Returns a newly created worker.
465 protected abstract createWorker (): Worker
468 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
470 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
472 * @param worker - The newly created worker.
474 protected abstract afterWorkerSetup (worker
: Worker
): void
477 * Creates a new worker and sets it up completely in the pool worker nodes.
479 * @returns New, completely set up worker.
481 protected createAndSetupWorker (): Worker
{
482 const worker
= this.createWorker()
484 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
485 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
486 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
487 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
488 worker
.once('exit', () => {
489 this.removeWorkerNode(worker
)
492 this.pushWorkerNode(worker
)
494 this.afterWorkerSetup(worker
)
500 * This function is the listener registered for each worker message.
502 * @returns The listener function to execute when a message is received from a worker.
504 protected workerListener (): (message
: MessageValue
<Response
>) => void {
506 if (message
.id
!= null) {
507 // Task execution response received
508 const promiseResponse
= this.promiseResponseMap
.get(message
.id
)
509 if (promiseResponse
!= null) {
510 if (message
.error
!= null) {
511 promiseResponse
.reject(message
.error
)
513 promiseResponse
.resolve(message
.data
as Response
)
515 this.afterTaskExecutionHook(promiseResponse
.worker
, message
)
516 this.promiseResponseMap
.delete(message
.id
)
517 const workerNodeKey
= this.getWorkerNodeKey(promiseResponse
.worker
)
519 this.opts
.enableTasksQueue
=== true &&
520 this.tasksQueueSize(workerNodeKey
) > 0
524 this.dequeueTask(workerNodeKey
) as Task
<Data
>
532 private checkAndEmitEvents (): void {
533 if (this.opts
.enableEvents
=== true) {
535 this.emitter
?.emit(PoolEvents
.busy
)
537 if (this.type === PoolType
.DYNAMIC
&& this.full
) {
538 this.emitter
?.emit(PoolEvents
.full
)
544 * Sets the given worker node its tasks usage in the pool.
546 * @param workerNode - The worker node.
547 * @param tasksUsage - The worker node tasks usage.
549 private setWorkerNodeTasksUsage (
550 workerNode
: WorkerNode
<Worker
, Data
>,
551 tasksUsage
: TasksUsage
553 workerNode
.tasksUsage
= tasksUsage
557 * Gets the given worker its tasks usage in the pool.
559 * @param worker - The worker.
560 * @throws Error if the worker is not found in the pool worker nodes.
561 * @returns The worker tasks usage.
563 private getWorkerTasksUsage (worker
: Worker
): TasksUsage
{
564 const workerNodeKey
= this.getWorkerNodeKey(worker
)
565 if (workerNodeKey
!== -1) {
566 return this.workerNodes
[workerNodeKey
].tasksUsage
568 throw new Error('Worker could not be found in the pool worker nodes')
572 * Pushes the given worker in the pool worker nodes.
574 * @param worker - The worker.
575 * @returns The worker nodes length.
577 private pushWorkerNode (worker
: Worker
): number {
578 return this.workerNodes
.push({
584 runTimeHistory
: new CircularArray(),
594 * Sets the given worker in the pool worker nodes.
596 * @param workerNodeKey - The worker node key.
597 * @param worker - The worker.
598 * @param tasksUsage - The worker tasks usage.
599 * @param tasksQueue - The worker task queue.
601 private setWorkerNode (
602 workerNodeKey
: number,
604 tasksUsage
: TasksUsage
,
605 tasksQueue
: Array<Task
<Data
>>
607 this.workerNodes
[workerNodeKey
] = {
615 * Removes the given worker from the pool worker nodes.
617 * @param worker - The worker.
619 private removeWorkerNode (worker
: Worker
): void {
620 const workerNodeKey
= this.getWorkerNodeKey(worker
)
621 this.workerNodes
.splice(workerNodeKey
, 1)
622 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
625 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
626 this.beforeTaskExecutionHook(workerNodeKey
)
627 this.sendToWorker(this.workerNodes
[workerNodeKey
].worker
, task
)
630 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
631 return this.workerNodes
[workerNodeKey
].tasksQueue
.push(task
)
634 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
635 return this.workerNodes
[workerNodeKey
].tasksQueue
.shift()
638 private tasksQueueSize (workerNodeKey
: number): number {
639 return this.workerNodes
[workerNodeKey
].tasksQueue
.length
642 private flushTasksQueue (workerNodeKey
: number): void {
643 if (this.tasksQueueSize(workerNodeKey
) > 0) {
644 for (const task
of this.workerNodes
[workerNodeKey
].tasksQueue
) {
645 this.executeTask(workerNodeKey
, task
)
650 private flushTasksQueueByWorker (worker
: Worker
): void {
651 const workerNodeKey
= this.getWorkerNodeKey(worker
)
652 this.flushTasksQueue(workerNodeKey
)
655 private flushTasksQueues (): void {
656 for (const [workerNodeKey
] of this.workerNodes
.entries()) {
657 this.flushTasksQueue(workerNodeKey
)