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 instance implementing the worker choice algorithm.
50 * Default to a strategy implementing 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
)
78 for (let i
= 1; i
<= this.numberOfWorkers
; i
++) {
79 this.createAndSetupWorker()
82 if (this.opts
.enableEvents
=== true) {
83 this.emitter
= new PoolEmitter()
85 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext(
88 const createdWorker
= this.createAndSetupWorker()
89 this.registerWorkerMessageListener(createdWorker
, message
=> {
91 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
92 this.getWorkerTasksUsage(createdWorker
)?.running
=== 0
94 // Kill received from the worker, means that no new tasks are submitted to that worker for a while ( > maxInactiveTime)
95 void this.destroyWorker(createdWorker
)
98 return this.getWorkerKey(createdWorker
)
100 this.opts
.workerChoiceStrategy
104 private checkFilePath (filePath
: string): void {
107 (typeof filePath
=== 'string' && filePath
.trim().length
=== 0)
109 throw new Error('Please specify a file with a worker implementation')
113 private checkNumberOfWorkers (numberOfWorkers
: number): void {
114 if (numberOfWorkers
== null) {
116 'Cannot instantiate a pool without specifying the number of workers'
118 } else if (!Number.isSafeInteger(numberOfWorkers
)) {
120 'Cannot instantiate a pool with a non integer number of workers'
122 } else if (numberOfWorkers
< 0) {
123 throw new RangeError(
124 'Cannot instantiate a pool with a negative number of workers'
126 } else if (this.type === PoolType
.FIXED
&& numberOfWorkers
=== 0) {
127 throw new Error('Cannot instantiate a fixed pool with no worker')
131 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
132 this.opts
.workerChoiceStrategy
=
133 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
134 this.opts
.enableEvents
= opts
.enableEvents
?? true
138 public abstract get
type (): PoolType
141 public get
numberOfRunningTasks (): number {
142 return this.promiseResponseMap
.size
146 * Gets the given worker key.
148 * @param worker - The worker.
149 * @returns The worker key if the worker is found in the pool, `-1` otherwise.
151 private getWorkerKey (worker
: Worker
): number {
152 return this.workers
.findIndex(workerItem
=> workerItem
.worker
=== worker
)
156 public setWorkerChoiceStrategy (
157 workerChoiceStrategy
: WorkerChoiceStrategy
159 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
160 for (const [index
, workerItem
] of this.workers
.entries()) {
161 this.setWorker(index
, workerItem
.worker
, {
169 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
175 public abstract get
busy (): boolean
177 protected internalGetBusyStatus (): boolean {
179 this.numberOfRunningTasks
>= this.numberOfWorkers
&&
180 this.findFreeWorkerKey() === -1
185 public findFreeWorkerKey (): number {
186 return this.workers
.findIndex(workerItem
=> {
187 return workerItem
.tasksUsage
.running
=== 0
192 public async execute (data
: Data
): Promise
<Response
> {
193 const [workerKey
, worker
] = this.chooseWorker()
194 const messageId
= crypto
.randomUUID()
195 const res
= this.internalExecute(workerKey
, worker
, messageId
)
196 this.checkAndEmitBusy()
197 this.sendToWorker(worker
, {
198 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
199 data
: data
?? ({} as Data
),
202 // eslint-disable-next-line @typescript-eslint/return-await
207 public async destroy (): Promise
<void> {
209 this.workers
.map(async workerItem
=> {
210 await this.destroyWorker(workerItem
.worker
)
216 * Shutdowns given worker.
218 * @param worker - A worker within `workers`.
220 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
223 * Setup hook that can be overridden by a Poolifier pool implementation
224 * to run code before workers are created in the abstract constructor.
226 protected setupHook (): void {
231 * Should return whether the worker is the main worker or not.
233 protected abstract isMain (): boolean
236 * Hook executed before the worker task promise resolution.
239 * @param workerKey - The worker key.
241 protected beforePromiseResponseHook (workerKey
: number): void {
242 ++this.workers
[workerKey
].tasksUsage
.running
246 * Hook executed after the worker task promise resolution.
249 * @param worker - The worker.
250 * @param message - The received message.
252 protected afterPromiseResponseHook (
254 message
: MessageValue
<Response
>
256 const workerTasksUsage
= this.getWorkerTasksUsage(worker
) as TasksUsage
257 --workerTasksUsage
.running
258 ++workerTasksUsage
.run
259 if (message
.error
!= null) {
260 ++workerTasksUsage
.error
262 if (this.workerChoiceStrategyContext
.getRequiredStatistics().runTime
) {
263 workerTasksUsage
.runTime
+= message
.taskRunTime
?? 0
265 this.workerChoiceStrategyContext
.getRequiredStatistics().avgRunTime
&&
266 workerTasksUsage
.run
!== 0
268 workerTasksUsage
.avgRunTime
=
269 workerTasksUsage
.runTime
/ workerTasksUsage
.run
275 * Removes the given worker from the pool.
277 * @param worker - The worker that will be removed.
279 protected removeWorker (worker
: Worker
): void {
280 const workerKey
= this.getWorkerKey(worker
)
281 this.workers
.splice(workerKey
, 1)
282 this.workerChoiceStrategyContext
.remove(workerKey
)
286 * Chooses a worker for the next task.
288 * The default implementation uses a round robin algorithm to distribute the load.
290 * @returns [worker key, worker].
292 protected chooseWorker (): [number, Worker
] {
293 const workerKey
= this.workerChoiceStrategyContext
.execute()
294 return [workerKey
, this.workers
[workerKey
].worker
]
298 * Sends a message to the given worker.
300 * @param worker - The worker which should receive the message.
301 * @param message - The message.
303 protected abstract sendToWorker (
305 message
: MessageValue
<Data
>
309 * Registers a listener callback on a given worker.
311 * @param worker - The worker which should register a listener.
312 * @param listener - The message listener callback.
314 protected abstract registerWorkerMessageListener
<
315 Message
extends Data
| Response
316 >(worker
: Worker
, listener
: (message
: MessageValue
<Message
>) => void): void
319 * Returns a newly created worker.
321 protected abstract createWorker (): Worker
324 * Function that can be hooked up when a worker has been newly created and moved to the workers registry.
326 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
328 * @param worker - The newly created worker.
330 protected abstract afterWorkerSetup (worker
: Worker
): void
333 * Creates a new worker for this pool and sets it up completely.
335 * @returns New, completely set up worker.
337 protected createAndSetupWorker (): Worker
{
338 const worker
= this.createWorker()
340 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
341 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
342 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
343 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
344 worker
.once('exit', () => {
345 this.removeWorker(worker
)
348 this.pushWorker(worker
, {
356 this.afterWorkerSetup(worker
)
362 * This function is the listener registered for each worker.
364 * @returns The listener function to execute when a message is received from a worker.
366 protected workerListener (): (message
: MessageValue
<Response
>) => void {
368 if (message
.id
!== undefined) {
369 const promiseResponse
= this.promiseResponseMap
.get(message
.id
)
370 if (promiseResponse
!== undefined) {
371 if (message
.error
!= null) {
372 promiseResponse
.reject(message
.error
)
374 promiseResponse
.resolve(message
.data
as Response
)
376 this.afterPromiseResponseHook(promiseResponse
.worker
, message
)
377 this.promiseResponseMap
.delete(message
.id
)
383 private async internalExecute (
387 ): Promise
<Response
> {
388 this.beforePromiseResponseHook(workerKey
)
389 return await new Promise
<Response
>((resolve
, reject
) => {
390 this.promiseResponseMap
.set(messageId
, { resolve
, reject
, worker
})
394 private checkAndEmitBusy (): void {
395 if (this.opts
.enableEvents
=== true && this.busy
) {
396 this.emitter
?.emit('busy')
401 * Gets worker tasks usage.
403 * @param worker - The worker.
404 * @returns The worker tasks usage.
406 private getWorkerTasksUsage (worker
: Worker
): TasksUsage
| undefined {
407 const workerKey
= this.getWorkerKey(worker
)
408 if (workerKey
!== -1) {
409 return this.workers
[workerKey
].tasksUsage
411 throw new Error('Worker could not be found in the pool')
415 * Pushes the given worker.
417 * @param worker - The worker.
418 * @param tasksUsage - The worker tasks usage.
420 private pushWorker (worker
: Worker
, tasksUsage
: TasksUsage
): void {
428 * Sets the given worker.
430 * @param workerKey - The worker key.
431 * @param worker - The worker.
432 * @param tasksUsage - The worker tasks usage.
437 tasksUsage
: TasksUsage
439 this.workers
[workerKey
] = {