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 { PoolEvents
, type PoolOptions
, type TasksQueueOptions
} from
'./pool'
10 import { PoolEmitter
} from
'./pool'
11 import type { IPoolInternal
} from
'./pool-internal'
12 import { PoolType
} from
'./pool-internal'
13 import type { IWorker
, Task
, TasksUsage
, WorkerNode
} from
'./worker'
15 WorkerChoiceStrategies
,
16 type WorkerChoiceStrategy
17 } from
'./selection-strategies/selection-strategies-types'
18 import { WorkerChoiceStrategyContext
} from
'./selection-strategies/worker-choice-strategy-context'
19 import { CircularArray
} from
'../circular-array'
22 * Base class that implements some shared logic for all poolifier pools.
24 * @typeParam Worker - Type of worker which manages this pool.
25 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
26 * @typeParam Response - Type of response of execution. This can only be serializable data.
28 export abstract class AbstractPool
<
29 Worker
extends IWorker
,
32 > implements IPoolInternal
<Worker
, Data
, Response
> {
34 public readonly workerNodes
: Array<WorkerNode
<Worker
, Data
>> = []
37 public readonly emitter
?: PoolEmitter
40 * The execution response promise map.
42 * - `key`: The message id of each submitted task.
43 * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks.
45 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
47 protected promiseResponseMap
: Map
<
49 PromiseResponseWrapper
<Worker
, Response
>
50 > = new Map
<string, PromiseResponseWrapper
<Worker
, Response
>>()
53 * Worker choice strategy context referencing a worker choice algorithm implementation.
55 * Default to a round robin algorithm.
57 protected workerChoiceStrategyContext
: WorkerChoiceStrategyContext
<
64 * Constructs a new poolifier pool.
66 * @param numberOfWorkers - Number of workers that this pool should manage.
67 * @param filePath - Path to the worker-file.
68 * @param opts - Options for the pool.
71 public readonly numberOfWorkers
: number,
72 public readonly filePath
: string,
73 public readonly opts
: PoolOptions
<Worker
>
76 throw new Error('Cannot start a pool from a worker!')
78 this.checkNumberOfWorkers(this.numberOfWorkers
)
79 this.checkFilePath(this.filePath
)
80 this.checkPoolOptions(this.opts
)
82 this.chooseWorkerNode
.bind(this)
83 this.executeTask
.bind(this)
84 this.enqueueTask
.bind(this)
85 this.checkAndEmitEvents
.bind(this)
89 for (let i
= 1; i
<= this.numberOfWorkers
; i
++) {
90 this.createAndSetupWorker()
93 if (this.opts
.enableEvents
=== true) {
94 this.emitter
= new PoolEmitter()
96 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext
<
102 this.opts
.workerChoiceStrategy
,
103 this.opts
.workerChoiceStrategyOptions
107 private checkFilePath (filePath
: string): void {
110 (typeof filePath
=== 'string' && filePath
.trim().length
=== 0)
112 throw new Error('Please specify a file with a worker implementation')
116 private checkNumberOfWorkers (numberOfWorkers
: number): void {
117 if (numberOfWorkers
== null) {
119 'Cannot instantiate a pool without specifying the number of workers'
121 } else if (!Number.isSafeInteger(numberOfWorkers
)) {
123 'Cannot instantiate a pool with a non integer number of workers'
125 } else if (numberOfWorkers
< 0) {
126 throw new RangeError(
127 'Cannot instantiate a pool with a negative number of workers'
129 } else if (this.type === PoolType
.FIXED
&& numberOfWorkers
=== 0) {
130 throw new Error('Cannot instantiate a fixed pool with no worker')
134 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
135 this.opts
.workerChoiceStrategy
=
136 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
137 this.checkValidWorkerChoiceStrategy(this.opts
.workerChoiceStrategy
)
138 this.opts
.workerChoiceStrategyOptions
=
139 opts
.workerChoiceStrategyOptions
?? DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
140 this.opts
.enableEvents
= opts
.enableEvents
?? true
141 this.opts
.enableTasksQueue
= opts
.enableTasksQueue
?? false
142 if (this.opts
.enableTasksQueue
) {
143 if ((opts
.tasksQueueOptions
?.concurrency
as number) <= 0) {
145 `Invalid tasks queue concurrency '${
146 (opts.tasksQueueOptions as TasksQueueOptions).concurrency as number
150 this.opts
.tasksQueueOptions
= {
151 concurrency
: opts
.tasksQueueOptions
?.concurrency
?? 1
156 private checkValidWorkerChoiceStrategy (
157 workerChoiceStrategy
: WorkerChoiceStrategy
159 if (!Object.values(WorkerChoiceStrategies
).includes(workerChoiceStrategy
)) {
161 `Invalid worker choice strategy '${workerChoiceStrategy}'`
167 public abstract get
type (): PoolType
170 * Number of tasks running in the pool.
172 private get
numberOfRunningTasks (): number {
173 return this.workerNodes
.reduce(
174 (accumulator
, workerNode
) => accumulator
+ workerNode
.tasksUsage
.running
,
180 * Number of tasks queued in the pool.
182 private get
numberOfQueuedTasks (): number {
183 if (this.opts
.enableTasksQueue
=== false) {
186 return this.workerNodes
.reduce(
187 (accumulator
, workerNode
) => accumulator
+ workerNode
.tasksQueue
.length
,
193 * Gets the given worker its worker node key.
195 * @param worker - The worker.
196 * @returns The worker node key if the worker is found in the pool worker nodes, `-1` otherwise.
198 private getWorkerNodeKey (worker
: Worker
): number {
199 return this.workerNodes
.findIndex(
200 workerNode
=> workerNode
.worker
=== worker
205 public setWorkerChoiceStrategy (
206 workerChoiceStrategy
: WorkerChoiceStrategy
208 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
209 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
210 for (const workerNode
of this.workerNodes
) {
211 this.setWorkerNodeTasksUsage(workerNode
, {
215 runTimeHistory
: new CircularArray(),
221 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
227 public abstract get
full (): boolean
230 public abstract get
busy (): boolean
232 protected internalBusy (): boolean {
233 return this.findFreeWorkerNodeKey() === -1
237 public findFreeWorkerNodeKey (): number {
238 return this.workerNodes
.findIndex(workerNode
=> {
239 return workerNode
.tasksUsage
?.running
=== 0
244 public async execute (data
: Data
): Promise
<Response
> {
245 const [workerNodeKey
, workerNode
] = this.chooseWorkerNode()
246 const submittedTask
: Task
<Data
> = {
247 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
248 data
: data
?? ({} as Data
),
249 id
: crypto
.randomUUID()
251 const res
= new Promise
<Response
>((resolve
, reject
) => {
252 this.promiseResponseMap
.set(submittedTask
.id
, {
255 worker
: workerNode
.worker
259 this.opts
.enableTasksQueue
=== true &&
261 this.workerNodes
[workerNodeKey
].tasksUsage
.running
>
262 ((this.opts
.tasksQueueOptions
as TasksQueueOptions
)
263 .concurrency
as number) -
266 this.enqueueTask(workerNodeKey
, submittedTask
)
268 this.executeTask(workerNodeKey
, submittedTask
)
270 this.checkAndEmitEvents()
271 // eslint-disable-next-line @typescript-eslint/return-await
276 public async destroy (): Promise
<void> {
278 this.workerNodes
.map(async (workerNode
, workerNodeKey
) => {
279 this.flushTasksQueue(workerNodeKey
)
280 await this.destroyWorker(workerNode
.worker
)
286 * Shutdowns the given worker.
288 * @param worker - A worker within `workerNodes`.
290 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
293 * Setup hook to execute code before worker node are created in the abstract constructor.
298 protected setupHook (): void {
299 // Intentionally empty
303 * Should return whether the worker is the main worker or not.
305 protected abstract isMain (): boolean
308 * Hook executed before the worker task execution.
311 * @param workerNodeKey - The worker node key.
313 protected beforeTaskExecutionHook (workerNodeKey
: number): void {
314 ++this.workerNodes
[workerNodeKey
].tasksUsage
.running
318 * Hook executed after the worker task execution.
321 * @param worker - The worker.
322 * @param message - The received message.
324 protected afterTaskExecutionHook (
326 message
: MessageValue
<Response
>
328 const workerTasksUsage
= this.getWorkerTasksUsage(worker
) as TasksUsage
329 --workerTasksUsage
.running
330 ++workerTasksUsage
.run
331 if (message
.error
!= null) {
332 ++workerTasksUsage
.error
334 if (this.workerChoiceStrategyContext
.getRequiredStatistics().runTime
) {
335 workerTasksUsage
.runTime
+= message
.runTime
?? 0
337 this.workerChoiceStrategyContext
.getRequiredStatistics().avgRunTime
&&
338 workerTasksUsage
.run
!== 0
340 workerTasksUsage
.avgRunTime
=
341 workerTasksUsage
.runTime
/ workerTasksUsage
.run
343 if (this.workerChoiceStrategyContext
.getRequiredStatistics().medRunTime
) {
344 workerTasksUsage
.runTimeHistory
.push(message
.runTime
?? 0)
345 workerTasksUsage
.medRunTime
= median(workerTasksUsage
.runTimeHistory
)
351 * Chooses a worker node for the next task.
353 * The default uses a round robin algorithm to distribute the load.
355 * @returns [worker node key, worker node].
357 protected chooseWorkerNode (): [number, WorkerNode
<Worker
, Data
>] {
358 let workerNodeKey
: number
359 if (this.type === PoolType
.DYNAMIC
&& !this.full
&& this.internalBusy()) {
360 const workerCreated
= this.createAndSetupWorker()
361 this.registerWorkerMessageListener(workerCreated
, message
=> {
363 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
364 (message
.kill
!= null &&
365 this.getWorkerTasksUsage(workerCreated
)?.running
=== 0)
367 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
368 this.flushTasksQueueByWorker(workerCreated
)
369 void this.destroyWorker(workerCreated
)
372 workerNodeKey
= this.getWorkerNodeKey(workerCreated
)
374 workerNodeKey
= this.workerChoiceStrategyContext
.execute()
376 return [workerNodeKey
, this.workerNodes
[workerNodeKey
]]
380 * Sends a message to the given worker.
382 * @param worker - The worker which should receive the message.
383 * @param message - The message.
385 protected abstract sendToWorker (
387 message
: MessageValue
<Data
>
391 * Registers a listener callback on the given worker.
393 * @param worker - The worker which should register a listener.
394 * @param listener - The message listener callback.
396 protected abstract registerWorkerMessageListener
<
397 Message
extends Data
| Response
398 >(worker
: Worker
, listener
: (message
: MessageValue
<Message
>) => void): void
401 * Returns a newly created worker.
403 protected abstract createWorker (): Worker
406 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
408 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
410 * @param worker - The newly created worker.
412 protected abstract afterWorkerSetup (worker
: Worker
): void
415 * Creates a new worker and sets it up completely in the pool worker nodes.
417 * @returns New, completely set up worker.
419 protected createAndSetupWorker (): Worker
{
420 const worker
= this.createWorker()
422 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
423 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
424 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
425 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
426 worker
.once('exit', () => {
427 this.removeWorkerNode(worker
)
430 this.pushWorkerNode(worker
)
432 this.afterWorkerSetup(worker
)
438 * This function is the listener registered for each worker message.
440 * @returns The listener function to execute when a message is received from a worker.
442 protected workerListener (): (message
: MessageValue
<Response
>) => void {
444 if (message
.id
!= null) {
445 // Task execution response received
446 const promiseResponse
= this.promiseResponseMap
.get(message
.id
)
447 if (promiseResponse
!= null) {
448 if (message
.error
!= null) {
449 promiseResponse
.reject(message
.error
)
451 promiseResponse
.resolve(message
.data
as Response
)
453 this.afterTaskExecutionHook(promiseResponse
.worker
, message
)
454 this.promiseResponseMap
.delete(message
.id
)
455 const workerNodeKey
= this.getWorkerNodeKey(promiseResponse
.worker
)
457 this.opts
.enableTasksQueue
=== true &&
458 this.tasksQueueSize(workerNodeKey
) > 0
462 this.dequeueTask(workerNodeKey
) as Task
<Data
>
470 private checkAndEmitEvents (): void {
471 if (this.opts
.enableEvents
=== true) {
473 this.emitter
?.emit(PoolEvents
.busy
)
475 if (this.type === PoolType
.DYNAMIC
&& this.full
) {
476 this.emitter
?.emit(PoolEvents
.full
)
482 * Sets the given worker node its tasks usage in the pool.
484 * @param workerNode - The worker node.
485 * @param tasksUsage - The worker node tasks usage.
487 private setWorkerNodeTasksUsage (
488 workerNode
: WorkerNode
<Worker
, Data
>,
489 tasksUsage
: TasksUsage
491 workerNode
.tasksUsage
= tasksUsage
495 * Gets the given worker its tasks usage in the pool.
497 * @param worker - The worker.
498 * @returns The worker tasks usage.
500 private getWorkerTasksUsage (worker
: Worker
): TasksUsage
| undefined {
501 const workerNodeKey
= this.getWorkerNodeKey(worker
)
502 if (workerNodeKey
!== -1) {
503 return this.workerNodes
[workerNodeKey
].tasksUsage
505 throw new Error('Worker could not be found in the pool worker nodes')
509 * Pushes the given worker in the pool worker nodes.
511 * @param worker - The worker.
512 * @returns The worker nodes length.
514 private pushWorkerNode (worker
: Worker
): number {
515 return this.workerNodes
.push({
521 runTimeHistory
: new CircularArray(),
531 * Sets the given worker in the pool worker nodes.
533 * @param workerNodeKey - The worker node key.
534 * @param worker - The worker.
535 * @param tasksUsage - The worker tasks usage.
536 * @param tasksQueue - The worker task queue.
538 private setWorkerNode (
539 workerNodeKey
: number,
541 tasksUsage
: TasksUsage
,
542 tasksQueue
: Array<Task
<Data
>>
544 this.workerNodes
[workerNodeKey
] = {
552 * Removes the given worker from the pool worker nodes.
554 * @param worker - The worker.
556 private removeWorkerNode (worker
: Worker
): void {
557 const workerNodeKey
= this.getWorkerNodeKey(worker
)
558 this.workerNodes
.splice(workerNodeKey
, 1)
559 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
562 private executeTask (workerNodeKey
: number, task
: Task
<Data
>): void {
563 this.beforeTaskExecutionHook(workerNodeKey
)
564 this.sendToWorker(this.workerNodes
[workerNodeKey
].worker
, task
)
567 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): number {
568 return this.workerNodes
[workerNodeKey
].tasksQueue
.push(task
)
571 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
572 return this.workerNodes
[workerNodeKey
].tasksQueue
.shift()
575 private tasksQueueSize (workerNodeKey
: number): number {
576 return this.workerNodes
[workerNodeKey
].tasksQueue
.length
579 private flushTasksQueue (workerNodeKey
: number): void {
580 if (this.tasksQueueSize(workerNodeKey
) > 0) {
581 for (const task
of this.workerNodes
[workerNodeKey
].tasksQueue
) {
582 this.executeTask(workerNodeKey
, task
)
587 private flushTasksQueueByWorker (worker
: Worker
): void {
588 const workerNodeKey
= this.getWorkerNodeKey(worker
)
589 this.flushTasksQueue(workerNodeKey
)