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
, TasksUsage
, WorkerType
} from
'./pool-internal'
8 import { PoolType
} from
'./pool-internal'
9 import type { IPoolWorker
} from
'./pool-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 IPoolWorker
,
28 > implements IPoolInternal
<Worker
, Data
, Response
> {
30 public readonly workers
: Array<WorkerType
<Worker
>> = []
33 public readonly emitter
?: PoolEmitter
36 * The promise response map.
38 * - `key`: The message id of each submitted task.
39 * - `value`: An object that contains the worker, the 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.
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.chooseWorker
.bind(this)
79 this.internalExecute
.bind(this)
80 this.checkAndEmitFull
.bind(this)
81 this.checkAndEmitBusy
.bind(this)
82 this.sendToWorker
.bind(this)
86 for (let i
= 1; i
<= this.numberOfWorkers
; i
++) {
87 this.createAndSetupWorker()
90 if (this.opts
.enableEvents
=== true) {
91 this.emitter
= new PoolEmitter()
93 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext
<
97 >(this, this.opts
.workerChoiceStrategy
)
100 private checkFilePath (filePath
: string): void {
103 (typeof filePath
=== 'string' && filePath
.trim().length
=== 0)
105 throw new Error('Please specify a file with a worker implementation')
109 private checkNumberOfWorkers (numberOfWorkers
: number): void {
110 if (numberOfWorkers
== null) {
112 'Cannot instantiate a pool without specifying the number of workers'
114 } else if (!Number.isSafeInteger(numberOfWorkers
)) {
116 'Cannot instantiate a pool with a non integer number of workers'
118 } else if (numberOfWorkers
< 0) {
119 throw new RangeError(
120 'Cannot instantiate a pool with a negative number of workers'
122 } else if (this.type === PoolType
.FIXED
&& numberOfWorkers
=== 0) {
123 throw new Error('Cannot instantiate a fixed pool with no worker')
127 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
128 this.opts
.workerChoiceStrategy
=
129 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
130 this.checkValidWorkerChoiceStrategy(this.opts
.workerChoiceStrategy
)
131 this.opts
.enableEvents
= opts
.enableEvents
?? true
134 private checkValidWorkerChoiceStrategy (
135 workerChoiceStrategy
: WorkerChoiceStrategy
137 if (!Object.values(WorkerChoiceStrategies
).includes(workerChoiceStrategy
)) {
139 `Invalid worker choice strategy '${workerChoiceStrategy}'`
145 public abstract get
type (): PoolType
148 * Number of tasks concurrently running in the pool.
150 private get
numberOfRunningTasks (): number {
151 return this.promiseResponseMap
.size
155 * Gets the given worker key.
157 * @param worker - The worker.
158 * @returns The worker key if the worker is found in the pool, `-1` otherwise.
160 private getWorkerKey (worker
: Worker
): number {
161 return this.workers
.findIndex(workerItem
=> workerItem
.worker
=== worker
)
165 public setWorkerChoiceStrategy (
166 workerChoiceStrategy
: WorkerChoiceStrategy
168 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy
)
169 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
170 for (const [index
, workerItem
] of this.workers
.entries()) {
171 this.setWorker(index
, workerItem
.worker
, {
175 runTimeHistory
: new CircularArray(),
181 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
187 public abstract get
full (): boolean
190 public abstract get
busy (): boolean
192 protected internalBusy (): boolean {
194 this.numberOfRunningTasks
>= this.numberOfWorkers
&&
195 this.findFreeWorkerKey() === -1
200 public findFreeWorkerKey (): number {
201 return this.workers
.findIndex(workerItem
=> {
202 return workerItem
.tasksUsage
.running
=== 0
207 public async execute (data
: Data
): Promise
<Response
> {
208 const [workerKey
, worker
] = this.chooseWorker()
209 const messageId
= crypto
.randomUUID()
210 const res
= this.internalExecute(workerKey
, worker
, messageId
)
211 this.checkAndEmitFull()
212 this.checkAndEmitBusy()
213 this.sendToWorker(worker
, {
214 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
215 data
: data
?? ({} as Data
),
218 // eslint-disable-next-line @typescript-eslint/return-await
223 public async destroy (): Promise
<void> {
225 this.workers
.map(async workerItem
=> {
226 await this.destroyWorker(workerItem
.worker
)
232 * Shutdowns given worker in the pool.
234 * @param worker - A worker within `workers`.
236 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
239 * Setup hook that can be overridden by a Poolifier pool implementation
240 * to run code before workers are created in the abstract constructor.
245 protected setupHook (): void {
246 // Intentionally empty
250 * Should return whether the worker is the main worker or not.
252 protected abstract isMain (): boolean
255 * Hook executed before the worker task promise resolution.
258 * @param workerKey - The worker key.
260 protected beforePromiseResponseHook (workerKey
: number): void {
261 ++this.workers
[workerKey
].tasksUsage
.running
265 * Hook executed after the worker task promise resolution.
268 * @param worker - The worker.
269 * @param message - The received message.
271 protected afterPromiseResponseHook (
273 message
: MessageValue
<Response
>
275 const workerTasksUsage
= this.getWorkerTasksUsage(worker
) as TasksUsage
276 --workerTasksUsage
.running
277 ++workerTasksUsage
.run
278 if (message
.error
!= null) {
279 ++workerTasksUsage
.error
281 if (this.workerChoiceStrategyContext
.getRequiredStatistics().runTime
) {
282 workerTasksUsage
.runTime
+= message
.runTime
?? 0
284 this.workerChoiceStrategyContext
.getRequiredStatistics().avgRunTime
&&
285 workerTasksUsage
.run
!== 0
287 workerTasksUsage
.avgRunTime
=
288 workerTasksUsage
.runTime
/ workerTasksUsage
.run
290 if (this.workerChoiceStrategyContext
.getRequiredStatistics().medRunTime
) {
291 workerTasksUsage
.runTimeHistory
.push(message
.runTime
?? 0)
292 workerTasksUsage
.medRunTime
= median(workerTasksUsage
.runTimeHistory
)
298 * Chooses a worker for the next task.
300 * The default uses a round robin algorithm to distribute the load.
302 * @returns [worker key, worker].
304 protected chooseWorker (): [number, Worker
] {
305 let workerKey
: number
307 this.type === PoolType
.DYNAMIC
&&
309 this.findFreeWorkerKey() === -1
311 const createdWorker
= this.createAndSetupWorker()
312 this.registerWorkerMessageListener(createdWorker
, message
=> {
314 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
315 (message
.kill
!= null &&
316 this.getWorkerTasksUsage(createdWorker
)?.running
=== 0)
318 // Kill message received from the worker, means that no new tasks are submitted to that worker for a while ( > maxInactiveTime)
319 void this.destroyWorker(createdWorker
)
322 workerKey
= this.getWorkerKey(createdWorker
)
324 workerKey
= this.workerChoiceStrategyContext
.execute()
326 return [workerKey
, this.workers
[workerKey
].worker
]
330 * Sends a message to the given worker.
332 * @param worker - The worker which should receive the message.
333 * @param message - The message.
335 protected abstract sendToWorker (
337 message
: MessageValue
<Data
>
341 * Registers a listener callback on a given worker.
343 * @param worker - The worker which should register a listener.
344 * @param listener - The message listener callback.
346 protected abstract registerWorkerMessageListener
<
347 Message
extends Data
| Response
348 >(worker
: Worker
, listener
: (message
: MessageValue
<Message
>) => void): void
351 * Returns a newly created worker.
353 protected abstract createWorker (): Worker
356 * Function that can be hooked up when a worker has been newly created and moved to the workers registry.
358 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
360 * @param worker - The newly created worker.
363 protected abstract afterWorkerSetup (worker
: Worker
): void
366 * Creates a new worker for this pool and sets it up completely.
368 * @returns New, completely set up worker.
370 protected createAndSetupWorker (): Worker
{
371 const worker
= this.createWorker()
373 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
374 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
375 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
376 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
377 worker
.once('exit', () => {
378 this.removeWorker(worker
)
381 this.pushWorker(worker
, {
385 runTimeHistory
: new CircularArray(),
391 this.afterWorkerSetup(worker
)
397 * This function is the listener registered for each worker.
399 * @returns The listener function to execute when a message is received from a worker.
401 protected workerListener (): (message
: MessageValue
<Response
>) => void {
403 if (message
.id
!= null) {
404 // Task response received
405 const promiseResponse
= this.promiseResponseMap
.get(message
.id
)
406 if (promiseResponse
!= null) {
407 if (message
.error
!= null) {
408 promiseResponse
.reject(message
.error
)
410 promiseResponse
.resolve(message
.data
as Response
)
412 this.afterPromiseResponseHook(promiseResponse
.worker
, message
)
413 this.promiseResponseMap
.delete(message
.id
)
419 private async internalExecute (
423 ): Promise
<Response
> {
424 this.beforePromiseResponseHook(workerKey
)
425 return await new Promise
<Response
>((resolve
, reject
) => {
426 this.promiseResponseMap
.set(messageId
, { resolve
, reject
, worker
})
430 private checkAndEmitBusy (): void {
431 if (this.opts
.enableEvents
=== true && this.busy
) {
432 this.emitter
?.emit(PoolEvents
.busy
)
436 private checkAndEmitFull (): void {
438 this.type === PoolType
.DYNAMIC
&&
439 this.opts
.enableEvents
=== true &&
442 this.emitter
?.emit(PoolEvents
.full
)
447 * Gets the given worker tasks usage in the pool.
449 * @param worker - The worker.
450 * @returns The worker tasks usage.
452 private getWorkerTasksUsage (worker
: Worker
): TasksUsage
| undefined {
453 const workerKey
= this.getWorkerKey(worker
)
454 if (workerKey
!== -1) {
455 return this.workers
[workerKey
].tasksUsage
457 throw new Error('Worker could not be found in the pool')
461 * Pushes the given worker in the pool.
463 * @param worker - The worker.
464 * @param tasksUsage - The worker tasks usage.
466 private pushWorker (worker
: Worker
, tasksUsage
: TasksUsage
): void {
474 * Sets the given worker in the pool.
476 * @param workerKey - The worker key.
477 * @param worker - The worker.
478 * @param tasksUsage - The worker tasks usage.
483 tasksUsage
: TasksUsage
485 this.workers
[workerKey
] = {
492 * Removes the given worker from the pool.
494 * @param worker - The worker that will be removed.
496 protected removeWorker (worker
: Worker
): void {
497 const workerKey
= this.getWorkerKey(worker
)
498 this.workers
.splice(workerKey
, 1)
499 this.workerChoiceStrategyContext
.remove(workerKey
)