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
)
77 this.chooseWorker
.bind(this)
78 this.internalExecute
.bind(this)
79 this.checkAndEmitBusy
.bind(this)
80 this.sendToWorker
.bind(this)
84 for (let i
= 1; i
<= this.numberOfWorkers
; i
++) {
85 this.createAndSetupWorker()
88 if (this.opts
.enableEvents
=== true) {
89 this.emitter
= new PoolEmitter()
91 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext(
94 const createdWorker
= this.createAndSetupWorker()
95 this.registerWorkerMessageListener(createdWorker
, message
=> {
97 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
98 this.getWorkerTasksUsage(createdWorker
)?.running
=== 0
100 // Kill received from the worker, means that no new tasks are submitted to that worker for a while ( > maxInactiveTime)
101 void this.destroyWorker(createdWorker
)
104 return this.getWorkerKey(createdWorker
)
106 this.opts
.workerChoiceStrategy
110 private checkFilePath (filePath
: string): void {
113 (typeof filePath
=== 'string' && filePath
.trim().length
=== 0)
115 throw new Error('Please specify a file with a worker implementation')
119 private checkNumberOfWorkers (numberOfWorkers
: number): void {
120 if (numberOfWorkers
== null) {
122 'Cannot instantiate a pool without specifying the number of workers'
124 } else if (!Number.isSafeInteger(numberOfWorkers
)) {
126 'Cannot instantiate a pool with a non integer number of workers'
128 } else if (numberOfWorkers
< 0) {
129 throw new RangeError(
130 'Cannot instantiate a pool with a negative number of workers'
132 } else if (this.type === PoolType
.FIXED
&& numberOfWorkers
=== 0) {
133 throw new Error('Cannot instantiate a fixed pool with no worker')
137 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
138 this.opts
.workerChoiceStrategy
=
139 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
140 this.opts
.enableEvents
= opts
.enableEvents
?? true
144 public abstract get
type (): PoolType
147 public get
numberOfRunningTasks (): number {
148 return this.promiseResponseMap
.size
152 * Gets the given worker key.
154 * @param worker - The worker.
155 * @returns The worker key if the worker is found in the pool, `-1` otherwise.
157 private getWorkerKey (worker
: Worker
): number {
158 return this.workers
.findIndex(workerItem
=> workerItem
.worker
=== worker
)
162 public setWorkerChoiceStrategy (
163 workerChoiceStrategy
: WorkerChoiceStrategy
165 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
166 for (const [index
, workerItem
] of this.workers
.entries()) {
167 this.setWorker(index
, workerItem
.worker
, {
175 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
181 public abstract get
busy (): boolean
183 protected internalGetBusyStatus (): boolean {
185 this.numberOfRunningTasks
>= this.numberOfWorkers
&&
186 this.findFreeWorkerKey() === -1
191 public findFreeWorkerKey (): number {
192 return this.workers
.findIndex(workerItem
=> {
193 return workerItem
.tasksUsage
.running
=== 0
198 public async execute (data
: Data
): Promise
<Response
> {
199 const [workerKey
, worker
] = this.chooseWorker()
200 const messageId
= crypto
.randomUUID()
201 const res
= this.internalExecute(workerKey
, worker
, messageId
)
202 this.checkAndEmitBusy()
203 this.sendToWorker(worker
, {
204 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
205 data
: data
?? ({} as Data
),
208 // eslint-disable-next-line @typescript-eslint/return-await
213 public async destroy (): Promise
<void> {
215 this.workers
.map(async workerItem
=> {
216 await this.destroyWorker(workerItem
.worker
)
222 * Shutdowns given worker.
224 * @param worker - A worker within `workers`.
226 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
229 * Setup hook that can be overridden by a Poolifier pool implementation
230 * to run code before workers are created in the abstract constructor.
232 protected setupHook (): void {
237 * Should return whether the worker is the main worker or not.
239 protected abstract isMain (): boolean
242 * Hook executed before the worker task promise resolution.
245 * @param workerKey - The worker key.
247 protected beforePromiseResponseHook (workerKey
: number): void {
248 ++this.workers
[workerKey
].tasksUsage
.running
252 * Hook executed after the worker task promise resolution.
255 * @param worker - The worker.
256 * @param message - The received message.
258 protected afterPromiseResponseHook (
260 message
: MessageValue
<Response
>
262 const workerTasksUsage
= this.getWorkerTasksUsage(worker
) as TasksUsage
263 --workerTasksUsage
.running
264 ++workerTasksUsage
.run
265 if (message
.error
!= null) {
266 ++workerTasksUsage
.error
268 if (this.workerChoiceStrategyContext
.getRequiredStatistics().runTime
) {
269 workerTasksUsage
.runTime
+= message
.taskRunTime
?? 0
271 this.workerChoiceStrategyContext
.getRequiredStatistics().avgRunTime
&&
272 workerTasksUsage
.run
!== 0
274 workerTasksUsage
.avgRunTime
=
275 workerTasksUsage
.runTime
/ workerTasksUsage
.run
281 * Removes the given worker from the pool.
283 * @param worker - The worker that will be removed.
285 protected removeWorker (worker
: Worker
): void {
286 const workerKey
= this.getWorkerKey(worker
)
287 this.workers
.splice(workerKey
, 1)
288 this.workerChoiceStrategyContext
.remove(workerKey
)
292 * Chooses a worker for the next task.
294 * The default implementation uses a round robin algorithm to distribute the load.
296 * @returns [worker key, worker].
298 protected chooseWorker (): [number, Worker
] {
299 const workerKey
= this.workerChoiceStrategyContext
.execute()
300 return [workerKey
, this.workers
[workerKey
].worker
]
304 * Sends a message to the given worker.
306 * @param worker - The worker which should receive the message.
307 * @param message - The message.
309 protected abstract sendToWorker (
311 message
: MessageValue
<Data
>
315 * Registers a listener callback on a given worker.
317 * @param worker - The worker which should register a listener.
318 * @param listener - The message listener callback.
320 protected abstract registerWorkerMessageListener
<
321 Message
extends Data
| Response
322 >(worker
: Worker
, listener
: (message
: MessageValue
<Message
>) => void): void
325 * Returns a newly created worker.
327 protected abstract createWorker (): Worker
330 * Function that can be hooked up when a worker has been newly created and moved to the workers registry.
332 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
334 * @param worker - The newly created worker.
336 protected abstract afterWorkerSetup (worker
: Worker
): void
339 * Creates a new worker for this pool and sets it up completely.
341 * @returns New, completely set up worker.
343 protected createAndSetupWorker (): Worker
{
344 const worker
= this.createWorker()
346 worker
.on('message', this.opts
.messageHandler
?? EMPTY_FUNCTION
)
347 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
348 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
349 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
350 worker
.once('exit', () => {
351 this.removeWorker(worker
)
354 this.pushWorker(worker
, {
362 this.afterWorkerSetup(worker
)
368 * This function is the listener registered for each worker.
370 * @returns The listener function to execute when a message is received from a worker.
372 protected workerListener (): (message
: MessageValue
<Response
>) => void {
374 if (message
.id
!== undefined) {
375 const promiseResponse
= this.promiseResponseMap
.get(message
.id
)
376 if (promiseResponse
!== undefined) {
377 if (message
.error
!= null) {
378 promiseResponse
.reject(message
.error
)
380 promiseResponse
.resolve(message
.data
as Response
)
382 this.afterPromiseResponseHook(promiseResponse
.worker
, message
)
383 this.promiseResponseMap
.delete(message
.id
)
389 private async internalExecute (
393 ): Promise
<Response
> {
394 this.beforePromiseResponseHook(workerKey
)
395 return await new Promise
<Response
>((resolve
, reject
) => {
396 this.promiseResponseMap
.set(messageId
, { resolve
, reject
, worker
})
400 private checkAndEmitBusy (): void {
401 if (this.opts
.enableEvents
=== true && this.busy
) {
402 this.emitter
?.emit('busy')
407 * Gets worker tasks usage.
409 * @param worker - The worker.
410 * @returns The worker tasks usage.
412 private getWorkerTasksUsage (worker
: Worker
): TasksUsage
| undefined {
413 const workerKey
= this.getWorkerKey(worker
)
414 if (workerKey
!== -1) {
415 return this.workers
[workerKey
].tasksUsage
417 throw new Error('Worker could not be found in the pool')
421 * Pushes the given worker.
423 * @param worker - The worker.
424 * @param tasksUsage - The worker tasks usage.
426 private pushWorker (worker
: Worker
, tasksUsage
: TasksUsage
): void {
434 * Sets the given worker.
436 * @param workerKey - The worker key.
437 * @param worker - The worker.
438 * @param tasksUsage - The worker tasks usage.
443 tasksUsage
: TasksUsage
445 this.workers
[workerKey
] = {