1 import crypto from
'node:crypto'
2 import type { MessageValue
, PromiseResponseWrapper
} from
'../utility-types'
3 import { EMPTY_FUNCTION
, median
} from
'../utils'
4 import { KillBehaviors
, isKillBehavior
} from
'../worker/worker-options'
5 import { PoolEvents
, type PoolOptions
} from
'./pool'
6 import { PoolEmitter
} from
'./pool'
7 import type { IPoolInternal
} from
'./pool-internal'
8 import { PoolType
} from
'./pool-internal'
9 import type { IWorker
, Task
, TasksUsage
, WorkerNode
} from
'./worker'
11 WorkerChoiceStrategies
,
12 type WorkerChoiceStrategy
13 } from
'./selection-strategies/selection-strategies-types'
14 import { WorkerChoiceStrategyContext
} from
'./selection-strategies/worker-choice-strategy-context'
15 import { CircularArray
} from
'../circular-array'
18 * Base class that implements some shared logic for all poolifier pools.
20 * @typeParam Worker - Type of worker which manages this pool.
21 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
22 * @typeParam Response - Type of response of execution. This can only be serializable data.
24 export abstract class AbstractPool
<
25 Worker
extends IWorker
,
28 > implements IPoolInternal
<Worker
, Data
, Response
> {
30 public readonly workerNodes
: Array<WorkerNode
<Worker
, Data
>> = []
33 public readonly emitter
?: PoolEmitter
36 * The execution response promise map.
38 * - `key`: The message id of each submitted task.
39 * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks.
41 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
43 protected promiseResponseMap
: Map
<
45 PromiseResponseWrapper
<Worker
, Response
>
46 > = new Map
<string, PromiseResponseWrapper
<Worker
, Response
>>()
49 * Worker choice strategy context referencing a worker choice algorithm implementation.
51 * Default to a round robin algorithm.
53 protected workerChoiceStrategyContext
: WorkerChoiceStrategyContext
<
60 * Constructs a new poolifier pool.
62 * @param numberOfWorkers - Number of workers that this pool should manage.
63 * @param filePath - Path to the worker-file.
64 * @param opts - Options for the pool.
67 public readonly numberOfWorkers
: number,
68 public readonly filePath
: string,
69 public readonly opts
: PoolOptions
<Worker
>
72 throw new Error('Cannot start a pool from a worker!')
74 this.checkNumberOfWorkers(this.numberOfWorkers
)
75 this.checkFilePath(this.filePath
)
76 this.checkPoolOptions(this.opts
)
78 this.chooseWorkerNode
.bind(this)
79 this.internalExecute
.bind(this)
80 this.checkAndEmitEvents
.bind(this)
81 this.sendToWorker
.bind(this)
85 for (let i
= 1; i
<= this.numberOfWorkers
; i
++) {
86 this.createAndSetupWorker()
89 if (this.opts
.enableEvents
=== true) {
90 this.emitter
= new PoolEmitter()
92 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext
<
98 this.opts
.workerChoiceStrategy
,
99 this.opts
.workerChoiceStrategyOptions
103 private checkFilePath (filePath
: string): void {
106 (typeof filePath
=== 'string' && filePath
.trim().length
=== 0)
108 throw new Error('Please specify a file with a worker implementation')
112 private checkNumberOfWorkers (numberOfWorkers
: number): void {
113 if (numberOfWorkers
== null) {
115 'Cannot instantiate a pool without specifying the number of workers'
117 } else if (!Number.isSafeInteger(numberOfWorkers
)) {
119 'Cannot instantiate a pool with a non integer number of workers'
121 } else if (numberOfWorkers
< 0) {
122 throw new RangeError(
123 'Cannot instantiate a pool with a negative number of workers'
125 } else if (this.type === PoolType
.FIXED
&& numberOfWorkers
=== 0) {
126 throw new Error('Cannot instantiate a fixed pool with no worker')
130 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
131 this.opts
.workerChoiceStrategy
=
132 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
133 this.checkValidWorkerChoiceStrategy(this.opts
.workerChoiceStrategy
)
134 this.opts
.workerChoiceStrategyOptions
=
135 opts
.workerChoiceStrategyOptions
?? { medRunTime
: false }
136 this.opts
.enableEvents
= opts
.enableEvents
?? true
137 this.opts
.enableTasksQueue
= opts
.enableTasksQueue
?? false
140 private checkValidWorkerChoiceStrategy (
141 workerChoiceStrategy
: WorkerChoiceStrategy
143 if (!Object.values(WorkerChoiceStrategies
).includes(workerChoiceStrategy
)) {
145 `Invalid worker choice strategy '${workerChoiceStrategy}'`
151 public abstract get
type (): PoolType
154 * Number of tasks running in the pool.
156 private get
numberOfRunningTasks (): number {
157 return this.workerNodes
.reduce(
158 (accumulator
, workerNode
) => accumulator
+ workerNode
.tasksUsage
.running
,
164 * Number of tasks queued in the pool.
166 private get
numberOfQueuedTasks (): number {
167 if (this.opts
.enableTasksQueue
=== false) {
170 return this.workerNodes
.reduce(
171 (accumulator
, workerNode
) => accumulator
+ workerNode
.tasksQueue
.length
,
177 * Gets the given worker its worker node key.
179 * @param worker - The worker.
180 * @returns The worker node key if the worker is found in the pool worker nodes, `-1` otherwise.
182 private getWorkerNodeKey (worker
: Worker
): number {
183 return this.workerNodes
.findIndex(
184 workerNode
=> workerNode
.worker
=== worker
189 public setWorkerChoiceStrategy (
190 workerChoiceStrategy
: WorkerChoiceStrategy
192 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
193 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
194 for (const workerNode
of this.workerNodes
) {
195 this.setWorkerNodeTasksUsage(workerNode
, {
199 runTimeHistory
: new CircularArray(),
205 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
211 public abstract get
full (): boolean
214 public abstract get
busy (): boolean
216 protected internalBusy (): boolean {
218 this.numberOfRunningTasks
>= this.numberOfWorkers
&&
219 this.findFreeWorkerNodeKey() === -1
224 public findFreeWorkerNodeKey (): number {
225 return this.workerNodes
.findIndex(workerNode
=> {
226 return workerNode
.tasksUsage
?.running
=== 0
231 public async execute (data
: Data
): Promise
<Response
> {
232 const [workerNodeKey
, workerNode
] = this.chooseWorkerNode()
233 const submittedTask
: Task
<Data
> = {
234 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
235 data
: data
?? ({} as Data
),
236 id
: crypto
.randomUUID()
238 const res
= this.internalExecute(workerNodeKey
, workerNode
, submittedTask
)
239 let currentTask
: Task
<Data
> = submittedTask
241 this.opts
.enableTasksQueue
=== true &&
242 (this.busy
|| this.tasksQueueSize(workerNodeKey
) > 0)
244 currentTask
= this.enqueueDequeueTask(
249 this.sendToWorker(workerNode
.worker
, currentTask
)
250 this.checkAndEmitEvents()
251 // eslint-disable-next-line @typescript-eslint/return-await
256 public async destroy (): Promise
<void> {
258 this.workerNodes
.map(async workerNode
=> {
259 this.flushTasksQueueByWorker(workerNode
.worker
)
260 await this.destroyWorker(workerNode
.worker
)
266 * Shutdowns the given worker.
268 * @param worker - A worker within `workerNodes`.
270 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
273 * Setup hook to run code before worker node are created in the abstract constructor.
278 protected setupHook (): void {
279 // Intentionally empty
283 * Should return whether the worker is the main worker or not.
285 protected abstract isMain (): boolean
288 * Hook executed before the worker task promise resolution.
291 * @param workerNodeKey - The worker node key.
293 protected beforePromiseResponseHook (workerNodeKey
: number): void {
294 ++this.workerNodes
[workerNodeKey
].tasksUsage
.running
298 * Hook executed after the worker task promise resolution.
301 * @param worker - The worker.
302 * @param message - The received message.
304 protected afterPromiseResponseHook (
306 message
: MessageValue
<Response
>
308 const workerTasksUsage
= this.getWorkerTasksUsage(worker
) as TasksUsage
309 --workerTasksUsage
.running
310 ++workerTasksUsage
.run
311 if (message
.error
!= null) {
312 ++workerTasksUsage
.error
314 if (this.workerChoiceStrategyContext
.getRequiredStatistics().runTime
) {
315 workerTasksUsage
.runTime
+= message
.runTime
?? 0
317 this.workerChoiceStrategyContext
.getRequiredStatistics().avgRunTime
&&
318 workerTasksUsage
.run
!== 0
320 workerTasksUsage
.avgRunTime
=
321 workerTasksUsage
.runTime
/ workerTasksUsage
.run
323 if (this.workerChoiceStrategyContext
.getRequiredStatistics().medRunTime
) {
324 workerTasksUsage
.runTimeHistory
.push(message
.runTime
?? 0)
325 workerTasksUsage
.medRunTime
= median(workerTasksUsage
.runTimeHistory
)
331 * Chooses a worker node for the next task.
333 * The default uses a round robin algorithm to distribute the load.
335 * @returns [worker node key, worker node].
337 protected chooseWorkerNode (): [number, WorkerNode
<Worker
, Data
>] {
338 let workerNodeKey
: number
340 this.type === PoolType
.DYNAMIC
&&
342 this.findFreeWorkerNodeKey() === -1
344 const workerCreated
= this.createAndSetupWorker()
345 this.registerWorkerMessageListener(workerCreated
, message
=> {
347 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
348 (message
.kill
!= null &&
349 this.getWorkerTasksUsage(workerCreated
)?.running
=== 0)
351 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
352 this.flushTasksQueueByWorker(workerCreated
)
353 void this.destroyWorker(workerCreated
)
356 workerNodeKey
= this.getWorkerNodeKey(workerCreated
)
358 workerNodeKey
= this.workerChoiceStrategyContext
.execute()
360 return [workerNodeKey
, this.workerNodes
[workerNodeKey
]]
364 * Sends a message to the given worker.
366 * @param worker - The worker which should receive the message.
367 * @param message - The message.
369 protected abstract sendToWorker (
371 message
: MessageValue
<Data
>
375 * Registers a listener callback on the given worker.
377 * @param worker - The worker which should register a listener.
378 * @param listener - The message listener callback.
380 protected abstract registerWorkerMessageListener
<
381 Message
extends Data
| Response
382 >(worker
: Worker
, listener
: (message
: MessageValue
<Message
>) => void): void
385 * Returns a newly created worker.
387 protected abstract createWorker (): Worker
390 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
392 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
394 * @param worker - The newly created worker.
396 protected abstract afterWorkerSetup (worker
: Worker
): void
399 * Creates a new worker and sets it up completely in the pool worker nodes.
401 * @returns New, completely set up worker.
403 protected createAndSetupWorker (): Worker
{
404 const worker
= this.createWorker()
406 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
407 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
408 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
409 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
410 worker
.once('exit', () => {
411 this.removeWorkerNode(worker
)
414 this.pushWorkerNode(worker
)
416 this.afterWorkerSetup(worker
)
422 * This function is the listener registered for each worker message.
424 * @returns The listener function to execute when a message is received from a worker.
426 protected workerListener (): (message
: MessageValue
<Response
>) => void {
428 if (message
.id
!= null) {
429 // Task execution response received
430 const promiseResponse
= this.promiseResponseMap
.get(message
.id
)
431 if (promiseResponse
!= null) {
432 if (message
.error
!= null) {
433 promiseResponse
.reject(message
.error
)
435 promiseResponse
.resolve(message
.data
as Response
)
437 this.afterPromiseResponseHook(promiseResponse
.worker
, message
)
438 this.promiseResponseMap
.delete(message
.id
)
439 const workerNodeKey
= this.getWorkerNodeKey(promiseResponse
.worker
)
441 this.opts
.enableTasksQueue
=== true &&
442 this.tasksQueueSize(workerNodeKey
) > 0
445 promiseResponse
.worker
,
446 this.dequeueTask(workerNodeKey
) as Task
<Data
>
454 private async internalExecute (
455 workerNodeKey
: number,
456 workerNode
: WorkerNode
<Worker
, Data
>,
458 ): Promise
<Response
> {
459 this.beforePromiseResponseHook(workerNodeKey
)
460 return await new Promise
<Response
>((resolve
, reject
) => {
461 this.promiseResponseMap
.set(task
.id
, {
464 worker
: workerNode
.worker
469 private checkAndEmitEvents (): void {
470 if (this.opts
.enableEvents
=== true) {
472 this.emitter
?.emit(PoolEvents
.busy
)
474 if (this.type === PoolType
.DYNAMIC
&& this.full
) {
475 this.emitter
?.emit(PoolEvents
.full
)
481 * Sets the given worker node its tasks usage in the pool.
483 * @param workerNode - The worker node.
484 * @param tasksUsage - The worker node tasks usage.
486 private setWorkerNodeTasksUsage (
487 workerNode
: WorkerNode
<Worker
, Data
>,
488 tasksUsage
: TasksUsage
490 workerNode
.tasksUsage
= tasksUsage
494 * Gets the given worker its tasks usage in the pool.
496 * @param worker - The worker.
497 * @returns The worker tasks usage.
499 private getWorkerTasksUsage (worker
: Worker
): TasksUsage
| undefined {
500 const workerNodeKey
= this.getWorkerNodeKey(worker
)
501 if (workerNodeKey
!== -1) {
502 return this.workerNodes
[workerNodeKey
].tasksUsage
504 throw new Error('Worker could not be found in the pool worker nodes')
508 * Pushes the given worker in the pool worker nodes.
510 * @param worker - The worker.
511 * @returns The worker nodes length.
513 private pushWorkerNode (worker
: Worker
): number {
514 return this.workerNodes
.push({
520 runTimeHistory
: new CircularArray(),
530 * Sets the given worker in the pool worker nodes.
532 * @param workerNodeKey - The worker node key.
533 * @param worker - The worker.
534 * @param tasksUsage - The worker tasks usage.
535 * @param tasksQueue - The worker task queue.
537 private setWorkerNode (
538 workerNodeKey
: number,
540 tasksUsage
: TasksUsage
,
541 tasksQueue
: Array<Task
<Data
>>
543 this.workerNodes
[workerNodeKey
] = {
551 * Removes the given worker from the pool worker nodes.
553 * @param worker - The worker.
555 private removeWorkerNode (worker
: Worker
): void {
556 const workerNodeKey
= this.getWorkerNodeKey(worker
)
557 this.workerNodes
.splice(workerNodeKey
, 1)
558 this.workerChoiceStrategyContext
.remove(workerNodeKey
)
561 private enqueueDequeueTask (
562 workerNodeKey
: number,
564 ): Task
<Data
> | undefined {
565 this.enqueueTask(workerNodeKey
, task
)
566 return this.dequeueTask(workerNodeKey
)
569 private enqueueTask (workerNodeKey
: number, task
: Task
<Data
>): void {
570 this.workerNodes
[workerNodeKey
].tasksQueue
.push(task
)
573 private dequeueTask (workerNodeKey
: number): Task
<Data
> | undefined {
574 return this.workerNodes
[workerNodeKey
].tasksQueue
.shift()
577 private tasksQueueSize (workerNodeKey
: number): number {
578 return this.workerNodes
[workerNodeKey
].tasksQueue
.length
581 private flushTasksQueue (workerNodeKey
: number): void {
582 if (this.tasksQueueSize(workerNodeKey
) > 0) {
583 for (const task
of this.workerNodes
[workerNodeKey
].tasksQueue
) {
584 this.sendToWorker(this.workerNodes
[workerNodeKey
].worker
, task
)
586 this.workerNodes
[workerNodeKey
].tasksQueue
= []
590 private flushTasksQueueByWorker (worker
: Worker
): void {
591 const workerNodeKey
= this.getWorkerNodeKey(worker
)
592 this.flushTasksQueue(workerNodeKey
)