1 import crypto from
'node:crypto'
2 import type { MessageValue
, PromiseResponseWrapper
} from
'../utility-types'
3 import { EMPTY_FUNCTION
} from
'../utils'
4 import { KillBehaviors
, isKillBehavior
} from
'../worker/worker-options'
5 import 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'
17 * Base class that implements some shared logic for all poolifier pools.
19 * @typeParam Worker - Type of worker which manages this pool.
20 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
21 * @typeParam Response - Type of response of execution. This can only be serializable data.
23 export abstract class AbstractPool
<
24 Worker
extends IPoolWorker
,
27 > implements IPoolInternal
<Worker
, Data
, Response
> {
29 public readonly workers
: Array<WorkerType
<Worker
>> = []
32 public readonly emitter
?: PoolEmitter
35 * The promise response map.
37 * - `key`: The message id of each submitted task.
38 * - `value`: An object that contains the worker, the promise resolve and reject callbacks.
40 * When we receive a message from the worker we get a map entry with the promise resolve/reject bound to the message.
42 protected promiseResponseMap
: Map
<
44 PromiseResponseWrapper
<Worker
, Response
>
45 > = new Map
<string, PromiseResponseWrapper
<Worker
, Response
>>()
48 * Worker choice strategy context referencing a worker choice algorithm implementation.
50 * Default to a round robin algorithm.
52 protected workerChoiceStrategyContext
: WorkerChoiceStrategyContext
<
59 * Constructs a new poolifier pool.
61 * @param numberOfWorkers - Number of workers that this pool should manage.
62 * @param filePath - Path to the worker-file.
63 * @param opts - Options for the pool.
66 public readonly numberOfWorkers
: number,
67 public readonly filePath
: string,
68 public readonly opts
: PoolOptions
<Worker
>
71 throw new Error('Cannot start a pool from a worker!')
73 this.checkNumberOfWorkers(this.numberOfWorkers
)
74 this.checkFilePath(this.filePath
)
75 this.checkPoolOptions(this.opts
)
77 this.chooseWorker
.bind(this)
78 this.internalExecute
.bind(this)
79 this.checkAndEmitFull
.bind(this)
80 this.checkAndEmitBusy
.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
<
99 const createdWorker
= this.createAndSetupWorker()
100 this.registerWorkerMessageListener(createdWorker
, message
=> {
102 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
103 this.getWorkerTasksUsage(createdWorker
)?.running
=== 0
105 // Kill received from the worker, means that no new tasks are submitted to that worker for a while ( > maxInactiveTime)
106 void this.destroyWorker(createdWorker
)
109 return this.getWorkerKey(createdWorker
)
111 this.opts
.workerChoiceStrategy
115 private checkFilePath (filePath
: string): void {
118 (typeof filePath
=== 'string' && filePath
.trim().length
=== 0)
120 throw new Error('Please specify a file with a worker implementation')
124 private checkNumberOfWorkers (numberOfWorkers
: number): void {
125 if (numberOfWorkers
== null) {
127 'Cannot instantiate a pool without specifying the number of workers'
129 } else if (!Number.isSafeInteger(numberOfWorkers
)) {
131 'Cannot instantiate a pool with a non integer number of workers'
133 } else if (numberOfWorkers
< 0) {
134 throw new RangeError(
135 'Cannot instantiate a pool with a negative number of workers'
137 } else if (this.type === PoolType
.FIXED
&& numberOfWorkers
=== 0) {
138 throw new Error('Cannot instantiate a fixed pool with no worker')
142 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
143 this.opts
.workerChoiceStrategy
=
144 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
146 !Object.values(WorkerChoiceStrategies
).includes(
147 this.opts
.workerChoiceStrategy
151 `Invalid worker choice strategy '${this.opts.workerChoiceStrategy}'`
154 this.opts
.enableEvents
= opts
.enableEvents
?? true
158 public abstract get
type (): PoolType
161 * Number of tasks concurrently running in the pool.
163 private get
numberOfRunningTasks (): number {
164 return this.promiseResponseMap
.size
168 * Gets the given worker key.
170 * @param worker - The worker.
171 * @returns The worker key if the worker is found in the pool, `-1` otherwise.
173 private getWorkerKey (worker
: Worker
): number {
174 return this.workers
.findIndex(workerItem
=> workerItem
.worker
=== worker
)
178 public setWorkerChoiceStrategy (
179 workerChoiceStrategy
: WorkerChoiceStrategy
181 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
182 for (const [index
, workerItem
] of this.workers
.entries()) {
183 this.setWorker(index
, workerItem
.worker
, {
191 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
198 public abstract get
full (): boolean
201 public abstract get
busy (): boolean
203 protected internalBusy (): boolean {
205 this.numberOfRunningTasks
>= this.numberOfWorkers
&&
206 this.findFreeWorkerKey() === -1
211 public findFreeWorkerKey (): number {
212 return this.workers
.findIndex(workerItem
=> {
213 return workerItem
.tasksUsage
.running
=== 0
218 public async execute (data
: Data
): Promise
<Response
> {
219 const [workerKey
, worker
] = this.chooseWorker()
220 const messageId
= crypto
.randomUUID()
221 const res
= this.internalExecute(workerKey
, worker
, messageId
)
222 this.checkAndEmitFull()
223 this.checkAndEmitBusy()
224 this.sendToWorker(worker
, {
225 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
226 data
: data
?? ({} as Data
),
229 // eslint-disable-next-line @typescript-eslint/return-await
234 public async destroy (): Promise
<void> {
236 this.workers
.map(async workerItem
=> {
237 await this.destroyWorker(workerItem
.worker
)
243 * Shutdowns given worker.
245 * @param worker - A worker within `workers`.
247 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
250 * Setup hook that can be overridden by a Poolifier pool implementation
251 * to run code before workers are created in the abstract constructor.
253 protected setupHook (): void {
258 * Should return whether the worker is the main worker or not.
260 protected abstract isMain (): boolean
263 * Hook executed before the worker task promise resolution.
266 * @param workerKey - The worker key.
268 protected beforePromiseResponseHook (workerKey
: number): void {
269 ++this.workers
[workerKey
].tasksUsage
.running
273 * Hook executed after the worker task promise resolution.
276 * @param worker - The worker.
277 * @param message - The received message.
279 protected afterPromiseResponseHook (
281 message
: MessageValue
<Response
>
283 const workerTasksUsage
= this.getWorkerTasksUsage(worker
) as TasksUsage
284 --workerTasksUsage
.running
285 ++workerTasksUsage
.run
286 if (message
.error
!= null) {
287 ++workerTasksUsage
.error
289 if (this.workerChoiceStrategyContext
.getRequiredStatistics().runTime
) {
290 workerTasksUsage
.runTime
+= message
.taskRunTime
?? 0
292 this.workerChoiceStrategyContext
.getRequiredStatistics().avgRunTime
&&
293 workerTasksUsage
.run
!== 0
295 workerTasksUsage
.avgRunTime
=
296 workerTasksUsage
.runTime
/ workerTasksUsage
.run
302 * Chooses a worker for the next task.
304 * The default uses a round robin algorithm to distribute the load.
306 * @returns [worker key, worker].
308 protected chooseWorker (): [number, Worker
] {
309 const workerKey
= this.workerChoiceStrategyContext
.execute()
310 return [workerKey
, this.workers
[workerKey
].worker
]
314 * Sends a message to the given worker.
316 * @param worker - The worker which should receive the message.
317 * @param message - The message.
319 protected abstract sendToWorker (
321 message
: MessageValue
<Data
>
325 * Registers a listener callback on a given worker.
327 * @param worker - The worker which should register a listener.
328 * @param listener - The message listener callback.
330 protected abstract registerWorkerMessageListener
<
331 Message
extends Data
| Response
332 >(worker
: Worker
, listener
: (message
: MessageValue
<Message
>) => void): void
335 * Returns a newly created worker.
337 protected abstract createWorker (): Worker
340 * Function that can be hooked up when a worker has been newly created and moved to the workers registry.
342 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
344 * @param worker - The newly created worker.
346 protected abstract afterWorkerSetup (worker
: Worker
): void
349 * Creates a new worker for this pool and sets it up completely.
351 * @returns New, completely set up worker.
353 protected createAndSetupWorker (): Worker
{
354 const worker
= this.createWorker()
356 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
357 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
358 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
359 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
360 worker
.once('exit', () => {
361 this.removeWorker(worker
)
364 this.pushWorker(worker
, {
372 this.afterWorkerSetup(worker
)
378 * This function is the listener registered for each worker.
380 * @returns The listener function to execute when a message is received from a worker.
382 protected workerListener (): (message
: MessageValue
<Response
>) => void {
384 if (message
.id
!== undefined) {
385 const promiseResponse
= this.promiseResponseMap
.get(message
.id
)
386 if (promiseResponse
!== undefined) {
387 if (message
.error
!= null) {
388 promiseResponse
.reject(message
.error
)
390 promiseResponse
.resolve(message
.data
as Response
)
392 this.afterPromiseResponseHook(promiseResponse
.worker
, message
)
393 this.promiseResponseMap
.delete(message
.id
)
399 private async internalExecute (
403 ): Promise
<Response
> {
404 this.beforePromiseResponseHook(workerKey
)
405 return await new Promise
<Response
>((resolve
, reject
) => {
406 this.promiseResponseMap
.set(messageId
, { resolve
, reject
, worker
})
410 private checkAndEmitBusy (): void {
411 if (this.opts
.enableEvents
=== true && this.busy
) {
412 this.emitter
?.emit('busy')
416 private checkAndEmitFull (): void {
418 this.type === PoolType
.DYNAMIC
&&
419 this.opts
.enableEvents
=== true &&
422 this.emitter
?.emit('full')
427 * Gets worker tasks usage.
429 * @param worker - The worker.
430 * @returns The worker tasks usage.
432 private getWorkerTasksUsage (worker
: Worker
): TasksUsage
| undefined {
433 const workerKey
= this.getWorkerKey(worker
)
434 if (workerKey
!== -1) {
435 return this.workers
[workerKey
].tasksUsage
437 throw new Error('Worker could not be found in the pool')
441 * Pushes the given worker in the pool.
443 * @param worker - The worker.
444 * @param tasksUsage - The worker tasks usage.
446 private pushWorker (worker
: Worker
, tasksUsage
: TasksUsage
): void {
454 * Sets the given worker in the pool.
456 * @param workerKey - The worker key.
457 * @param worker - The worker.
458 * @param tasksUsage - The worker tasks usage.
463 tasksUsage
: TasksUsage
465 this.workers
[workerKey
] = {
472 * Removes the given worker from the pool.
474 * @param worker - The worker that will be removed.
476 protected removeWorker (worker
: Worker
): void {
477 const workerKey
= this.getWorkerKey(worker
)
478 this.workers
.splice(workerKey
, 1)
479 this.workerChoiceStrategyContext
.remove(workerKey
)