3 PromiseWorkerResponseWrapper
4 } from
'../utility-types'
5 import { EMPTY_FUNCTION
} from
'../utils'
6 import { KillBehaviors
, isKillBehavior
} from
'../worker/worker-options'
7 import type { PoolOptions
} from
'./pool'
8 import { PoolEmitter
} from
'./pool'
9 import type { IPoolInternal
, TasksUsage
} from
'./pool-internal'
10 import { PoolType
} from
'./pool-internal'
11 import type { IPoolWorker
} from
'./pool-worker'
13 WorkerChoiceStrategies
,
14 type WorkerChoiceStrategy
15 } from
'./selection-strategies/selection-strategies-types'
16 import { WorkerChoiceStrategyContext
} from
'./selection-strategies/worker-choice-strategy-context'
19 * Base class that implements some shared logic for all poolifier pools.
21 * @typeParam Worker - Type of worker which manages this pool.
22 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
23 * @typeParam Response - Type of response of execution. This can only be serializable data.
25 export abstract class AbstractPool
<
26 Worker
extends IPoolWorker
,
29 > implements IPoolInternal
<Worker
, Data
, Response
> {
31 public readonly workers
: Worker
[] = []
34 public readonly workersTasksUsage
: Map
<Worker
, TasksUsage
> = new Map
<
40 public readonly emitter
?: PoolEmitter
45 * - `key`: This is the message Id of each submitted task.
46 * - `value`: An object that contains the worker, the resolve function and the reject function.
48 * When we receive a message from the worker we get a map entry and resolve/reject the promise based on the message.
50 protected promiseMap
: Map
<
52 PromiseWorkerResponseWrapper
<Worker
, Response
>
53 > = new Map
<number, PromiseWorkerResponseWrapper
<Worker
, Response
>>()
56 * Id of the next message.
58 protected nextMessageId
: number = 0
61 * Worker choice strategy instance implementing the worker choice algorithm.
63 * Default to a strategy implementing a round robin algorithm.
65 protected workerChoiceStrategyContext
: WorkerChoiceStrategyContext
<
72 * Constructs a new poolifier pool.
74 * @param numberOfWorkers - Number of workers that this pool should manage.
75 * @param filePath - Path to the worker-file.
76 * @param opts - Options for the pool.
79 public readonly numberOfWorkers
: number,
80 public readonly filePath
: string,
81 public readonly opts
: PoolOptions
<Worker
>
84 throw new Error('Cannot start a pool from a worker!')
86 this.checkNumberOfWorkers(this.numberOfWorkers
)
87 this.checkFilePath(this.filePath
)
88 this.checkPoolOptions(this.opts
)
91 for (let i
= 1; i
<= this.numberOfWorkers
; i
++) {
92 this.createAndSetupWorker()
95 if (this.opts
.enableEvents
=== true) {
96 this.emitter
= new PoolEmitter()
98 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext(
101 const workerCreated
= this.createAndSetupWorker()
102 this.registerWorkerMessageListener(workerCreated
, message
=> {
104 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
105 this.getWorkerRunningTasks(workerCreated
) === 0
107 // Kill received from the worker, means that no new tasks are submitted to that worker for a while ( > maxInactiveTime)
108 void (this.destroyWorker(workerCreated
) as Promise
<void>)
113 this.opts
.workerChoiceStrategy
117 private checkFilePath (filePath
: string): void {
118 if (filePath
== null || filePath
.length
=== 0) {
119 throw new Error('Please specify a file with a worker implementation')
123 private checkNumberOfWorkers (numberOfWorkers
: number): void {
124 if (numberOfWorkers
== null) {
126 'Cannot instantiate a pool without specifying the number of workers'
128 } else if (!Number.isSafeInteger(numberOfWorkers
)) {
130 'Cannot instantiate a pool with a non integer number of workers'
132 } else if (numberOfWorkers
< 0) {
133 throw new RangeError(
134 'Cannot instantiate a pool with a negative number of workers'
136 } else if (this.type === PoolType
.FIXED
&& numberOfWorkers
=== 0) {
137 throw new Error('Cannot instantiate a fixed pool with no worker')
141 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
142 this.opts
.workerChoiceStrategy
=
143 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
144 this.opts
.enableEvents
= opts
.enableEvents
?? true
148 public abstract get
type (): PoolType
151 public get
numberOfRunningTasks (): number {
152 return this.promiseMap
.size
156 public getWorkerIndex (worker
: Worker
): number {
157 return this.workers
.indexOf(worker
)
161 public getWorkerRunningTasks (worker
: Worker
): number | undefined {
162 return this.workersTasksUsage
.get(worker
)?.running
166 public getWorkerAverageTasksRunTime (worker
: Worker
): number | undefined {
167 return this.workersTasksUsage
.get(worker
)?.avgRunTime
171 public setWorkerChoiceStrategy (
172 workerChoiceStrategy
: WorkerChoiceStrategy
174 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
175 for (const worker
of this.workers
) {
176 this.resetWorkerTasksUsage(worker
)
178 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
184 public abstract get
busy (): boolean
186 protected internalGetBusyStatus (): boolean {
188 this.numberOfRunningTasks
>= this.numberOfWorkers
&&
189 this.findFreeWorker() === false
194 public findFreeWorker (): Worker
| false {
195 for (const worker
of this.workers
) {
196 if (this.getWorkerRunningTasks(worker
) === 0) {
197 // A worker is free, return the matching worker
205 public async execute (data
: Data
): Promise
<Response
> {
206 // Configure worker to handle message with the specified task
207 const worker
= this.chooseWorker()
208 const res
= this.internalExecute(worker
, this.nextMessageId
)
209 this.checkAndEmitBusy()
210 this.sendToWorker(worker
, {
211 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
212 data
: data
?? ({} as Data
),
213 id
: this.nextMessageId
216 // eslint-disable-next-line @typescript-eslint/return-await
221 public async destroy (): Promise
<void> {
223 this.workers
.map(async worker
=> {
224 await this.destroyWorker(worker
)
230 * Shutdowns given worker.
232 * @param worker - A worker within `workers`.
234 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
237 * Setup hook that can be overridden by a Poolifier pool implementation
238 * to run code before workers are created in the abstract constructor.
240 protected setupHook (): void {
245 * Should return whether the worker is the main worker or not.
247 protected abstract isMain (): boolean
250 * Hook executed before the worker task promise resolution.
253 * @param worker - The worker.
255 protected beforePromiseWorkerResponseHook (worker
: Worker
): void {
256 this.increaseWorkerRunningTasks(worker
)
260 * Hook executed after the worker task promise resolution.
263 * @param message - The received message.
264 * @param promise - The Promise response.
266 protected afterPromiseWorkerResponseHook (
267 message
: MessageValue
<Response
>,
268 promise
: PromiseWorkerResponseWrapper
<Worker
, Response
>
270 this.decreaseWorkerRunningTasks(promise
.worker
)
271 this.stepWorkerRunTasks(promise
.worker
, 1)
272 this.updateWorkerTasksRunTime(promise
.worker
, message
.taskRunTime
)
276 * Removes the given worker from the pool.
278 * @param worker - The worker that will be removed.
280 protected removeWorker (worker
: Worker
): void {
281 // Clean worker from data structure
282 this.workers
.splice(this.getWorkerIndex(worker
), 1)
283 this.removeWorkerTasksUsage(worker
)
287 * Chooses a worker for the next task.
289 * The default implementation uses a round robin algorithm to distribute the load.
293 protected chooseWorker (): Worker
{
294 return this.workerChoiceStrategyContext
.execute()
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.workers
.push(worker
)
350 // Init worker tasks usage map
351 this.initWorkerTasksUsage(worker
)
353 this.afterWorkerSetup(worker
)
359 * This function is the listener registered for each worker.
361 * @returns The listener function to execute when a message is received from a worker.
363 protected workerListener (): (message
: MessageValue
<Response
>) => void {
365 if (message
.id
!== undefined) {
366 const promise
= this.promiseMap
.get(message
.id
)
367 if (promise
!== undefined) {
368 if (message
.error
!= null) {
369 promise
.reject(message
.error
)
371 promise
.resolve(message
.data
as Response
)
373 this.afterPromiseWorkerResponseHook(message
, promise
)
374 this.promiseMap
.delete(message
.id
)
380 private async internalExecute (
383 ): Promise
<Response
> {
384 this.beforePromiseWorkerResponseHook(worker
)
385 return await new Promise
<Response
>((resolve
, reject
) => {
386 this.promiseMap
.set(messageId
, { resolve
, reject
, worker
})
390 private checkAndEmitBusy (): void {
391 if (this.opts
.enableEvents
=== true && this.busy
) {
392 this.emitter
?.emit('busy')
397 * Increases the number of tasks that the given worker has applied.
399 * @param worker - Worker which running tasks is increased.
401 private increaseWorkerRunningTasks (worker
: Worker
): void {
402 this.stepWorkerRunningTasks(worker
, 1)
406 * Decreases the number of tasks that the given worker has applied.
408 * @param worker - Worker which running tasks is decreased.
410 private decreaseWorkerRunningTasks (worker
: Worker
): void {
411 this.stepWorkerRunningTasks(worker
, -1)
415 * Steps the number of tasks that the given worker has applied.
417 * @param worker - Worker which running tasks are stepped.
418 * @param step - Number of running tasks step.
420 private stepWorkerRunningTasks (worker
: Worker
, step
: number): void {
421 if (this.checkWorkerTasksUsage(worker
)) {
422 const tasksUsage
= this.workersTasksUsage
.get(worker
) as TasksUsage
423 tasksUsage
.running
= tasksUsage
.running
+ step
424 this.workersTasksUsage
.set(worker
, tasksUsage
)
429 * Steps the number of tasks that the given worker has run.
431 * @param worker - Worker which has run tasks.
432 * @param step - Number of run tasks step.
434 private stepWorkerRunTasks (worker
: Worker
, step
: number): void {
435 if (this.checkWorkerTasksUsage(worker
)) {
436 const tasksUsage
= this.workersTasksUsage
.get(worker
) as TasksUsage
437 tasksUsage
.run
= tasksUsage
.run
+ step
438 this.workersTasksUsage
.set(worker
, tasksUsage
)
443 * Updates tasks runtime for the given worker.
445 * @param worker - Worker which run the task.
446 * @param taskRunTime - Worker task runtime.
448 private updateWorkerTasksRunTime (
450 taskRunTime
: number | undefined
453 this.workerChoiceStrategyContext
.getWorkerChoiceStrategy()
454 .requiredStatistics
.runTime
&&
455 this.checkWorkerTasksUsage(worker
)
457 const tasksUsage
= this.workersTasksUsage
.get(worker
) as TasksUsage
458 tasksUsage
.runTime
+= taskRunTime
?? 0
459 if (tasksUsage
.run
!== 0) {
460 tasksUsage
.avgRunTime
= tasksUsage
.runTime
/ tasksUsage
.run
462 this.workersTasksUsage
.set(worker
, tasksUsage
)
467 * Checks if the given worker is registered in the workers tasks usage map.
469 * @param worker - Worker to check.
470 * @returns `true` if the worker is registered in the workers tasks usage map. `false` otherwise.
472 private checkWorkerTasksUsage (worker
: Worker
): boolean {
473 const hasTasksUsage
= this.workersTasksUsage
.has(worker
)
474 if (!hasTasksUsage
) {
475 throw new Error('Worker could not be found in workers tasks usage map')
481 * Initializes tasks usage statistics.
483 * @param worker - The worker.
485 private initWorkerTasksUsage (worker
: Worker
): void {
486 this.workersTasksUsage
.set(worker
, {
495 * Removes worker tasks usage statistics.
497 * @param worker - The worker.
499 private removeWorkerTasksUsage (worker
: Worker
): void {
500 this.workersTasksUsage
.delete(worker
)
504 * Resets worker tasks usage statistics.
506 * @param worker - The worker.
508 private resetWorkerTasksUsage (worker
: Worker
): void {
509 this.removeWorkerTasksUsage(worker
)
510 this.initWorkerTasksUsage(worker
)