3 PromiseWorkerResponseWrapper
4 } from
'../utility-types'
5 import { EMPTY_FUNCTION
} from
'../utils'
6 import { isKillBehavior
, KillBehaviors
} from
'../worker/worker-options'
7 import type { PoolOptions
} from
'./pool'
8 import type { IPoolInternal
, TasksUsage
} from
'./pool-internal'
9 import { PoolEmitter
, PoolType
} from
'./pool-internal'
10 import type { IPoolWorker
} from
'./pool-worker'
12 WorkerChoiceStrategies
,
14 } from
'./selection-strategies/selection-strategies-types'
15 import { WorkerChoiceStrategyContext
} from
'./selection-strategies/worker-choice-strategy-context'
18 * Base class that implements some shared logic for all poolifier pools.
20 * @template Worker Type of worker which manages this pool.
21 * @template Data Type of data sent to the worker. This can only be serializable data.
22 * @template 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
: Worker
[] = []
33 public readonly workersTasksUsage
: Map
<Worker
, TasksUsage
> = new Map
<
39 public readonly emitter
?: PoolEmitter
42 public readonly max
?: number
47 * - `key`: This is the message Id of each submitted task.
48 * - `value`: An object that contains the worker, the resolve function and the reject function.
50 * When we receive a message from the worker we get a map entry and resolve/reject the promise based on the message.
52 protected promiseMap
: Map
<
54 PromiseWorkerResponseWrapper
<Worker
, Response
>
55 > = new Map
<number, PromiseWorkerResponseWrapper
<Worker
, Response
>>()
58 * Id of the next message.
60 protected nextMessageId
: number = 0
63 * Worker choice strategy instance implementing the worker choice algorithm.
65 * Default to a strategy implementing a round robin algorithm.
67 protected workerChoiceStrategyContext
: WorkerChoiceStrategyContext
<
74 * Constructs a new poolifier pool.
76 * @param numberOfWorkers Number of workers that this pool should manage.
77 * @param filePath Path to the worker-file.
78 * @param opts Options for the pool.
81 public readonly numberOfWorkers
: number,
82 public readonly filePath
: string,
83 public readonly opts
: PoolOptions
<Worker
>
85 if (this.isMain() === false) {
86 throw new Error('Cannot start a pool from a worker!')
88 this.checkNumberOfWorkers(this.numberOfWorkers
)
89 this.checkFilePath(this.filePath
)
90 this.checkPoolOptions(this.opts
)
93 for (let i
= 1; i
<= this.numberOfWorkers
; i
++) {
94 this.createAndSetupWorker()
97 if (this.opts
.enableEvents
=== true) {
98 this.emitter
= new PoolEmitter()
100 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext(
103 const workerCreated
= this.createAndSetupWorker()
104 this.registerWorkerMessageListener(workerCreated
, message
=> {
106 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
107 this.getWorkerRunningTasks(workerCreated
) === 0
109 // Kill received from the worker, means that no new tasks are submitted to that worker for a while ( > maxInactiveTime)
110 this.destroyWorker(workerCreated
) as void
115 this.opts
.workerChoiceStrategy
119 private checkFilePath (filePath
: string): void {
121 throw new Error('Please specify a file with a worker implementation')
125 private checkNumberOfWorkers (numberOfWorkers
: number): void {
126 if (numberOfWorkers
== null) {
128 'Cannot instantiate a pool without specifying the number of workers'
130 } else if (Number.isSafeInteger(numberOfWorkers
) === false) {
132 'Cannot instantiate a pool with a non integer number of workers'
134 } else if (numberOfWorkers
< 0) {
136 'Cannot instantiate a pool with a negative number of workers'
138 } else if (this.type === PoolType
.FIXED
&& numberOfWorkers
=== 0) {
139 throw new Error('Cannot instantiate a fixed pool with no worker')
143 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
144 this.opts
.workerChoiceStrategy
=
145 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
146 this.opts
.enableEvents
= opts
.enableEvents
?? true
150 public abstract get
type (): PoolType
153 public get
numberOfRunningTasks (): number {
154 return this.promiseMap
.size
158 public getWorkerIndex (worker
: Worker
): number {
159 return this.workers
.indexOf(worker
)
163 public getWorkerRunningTasks (worker
: Worker
): number | undefined {
164 return this.workersTasksUsage
.get(worker
)?.running
168 public getWorkerAverageTasksRunTime (worker
: Worker
): number | undefined {
169 return this.workersTasksUsage
.get(worker
)?.avgRunTime
173 public setWorkerChoiceStrategy (
174 workerChoiceStrategy
: WorkerChoiceStrategy
176 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
177 for (const worker
of this.workers
) {
178 this.resetWorkerTasksUsage(worker
)
180 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
186 public abstract get
busy (): boolean
188 protected internalGetBusyStatus (): boolean {
190 this.numberOfRunningTasks
>= this.numberOfWorkers
&&
191 this.findFreeWorker() === false
196 public findFreeWorker (): Worker
| false {
197 for (const worker
of this.workers
) {
198 if (this.getWorkerRunningTasks(worker
) === 0) {
199 // A worker is free, return the matching worker
207 public execute (data
: Data
): Promise
<Response
> {
208 // Configure worker to handle message with the specified task
209 const worker
= this.chooseWorker()
210 const res
= this.internalExecute(worker
, this.nextMessageId
)
211 this.checkAndEmitBusy()
212 this.sendToWorker(worker
, {
213 data
: data
?? ({} as Data
),
214 id
: this.nextMessageId
221 public async destroy (): Promise
<void> {
222 await Promise
.all(this.workers
.map(worker
=> this.destroyWorker(worker
)))
226 * Shutdowns given worker.
228 * @param worker A worker within `workers`.
230 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
233 * Setup hook that can be overridden by a Poolifier pool implementation
234 * to run code before workers are created in the abstract constructor.
236 protected setupHook (): void {
241 * Should return whether the worker is the main worker or not.
243 protected abstract isMain (): boolean
246 * Hook executed before the worker task promise resolution.
249 * @param worker The worker.
251 protected beforePromiseWorkerResponseHook (worker
: Worker
): void {
252 this.increaseWorkerRunningTasks(worker
)
256 * Hook executed after the worker task promise resolution.
259 * @param message The received message.
260 * @param promise The Promise response.
262 protected afterPromiseWorkerResponseHook (
263 message
: MessageValue
<Response
>,
264 promise
: PromiseWorkerResponseWrapper
<Worker
, Response
>
266 this.decreaseWorkerRunningTasks(promise
.worker
)
267 this.stepWorkerRunTasks(promise
.worker
, 1)
268 this.updateWorkerTasksRunTime(promise
.worker
, message
.taskRunTime
)
272 * Removes the given worker from the pool.
274 * @param worker The worker that will be removed.
276 protected removeWorker (worker
: Worker
): void {
277 // Clean worker from data structure
278 this.workers
.splice(this.getWorkerIndex(worker
), 1)
279 this.removeWorkerTasksUsage(worker
)
283 * Chooses a worker for the next task.
285 * The default implementation uses a round robin algorithm to distribute the load.
289 protected chooseWorker (): Worker
{
290 return this.workerChoiceStrategyContext
.execute()
294 * Sends a message to the given worker.
296 * @param worker The worker which should receive the message.
297 * @param message The message.
299 protected abstract sendToWorker (
301 message
: MessageValue
<Data
>
305 * Registers a listener callback on a given worker.
307 * @param worker The worker which should register a listener.
308 * @param listener The message listener callback.
310 protected abstract registerWorkerMessageListener
<
311 Message
extends Data
| Response
312 > (worker
: Worker
, listener
: (message
: MessageValue
<Message
>) => void): void
314 protected internalExecute (
317 ): Promise
<Response
> {
318 this.beforePromiseWorkerResponseHook(worker
)
319 return new Promise
<Response
>((resolve
, reject
) => {
320 this.promiseMap
.set(messageId
, { resolve
, reject
, worker
})
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', () => this.removeWorker(worker
))
352 this.workers
.push(worker
)
354 // Init worker tasks usage map
355 this.initWorkerTasksUsage(worker
)
357 this.afterWorkerSetup(worker
)
363 * This function is the listener registered for each worker.
365 * @returns The listener function to execute when a message is received from a worker.
367 protected workerListener (): (message
: MessageValue
<Response
>) => void {
369 if (message
.id
!== undefined) {
370 const promise
= this.promiseMap
.get(message
.id
)
371 if (promise
!== undefined) {
373 promise
.reject(message
.error
)
375 promise
.resolve(message
.data
as Response
)
377 this.afterPromiseWorkerResponseHook(message
, promise
)
378 this.promiseMap
.delete(message
.id
)
384 private checkAndEmitBusy (): void {
385 if (this.opts
.enableEvents
=== true && this.busy
=== true) {
386 this.emitter
?.emit('busy')
391 * Increases the number of tasks that the given worker has applied.
393 * @param worker Worker which running tasks is increased.
395 private increaseWorkerRunningTasks (worker
: Worker
): void {
396 this.stepWorkerRunningTasks(worker
, 1)
400 * Decreases the number of tasks that the given worker has applied.
402 * @param worker Worker which running tasks is decreased.
404 private decreaseWorkerRunningTasks (worker
: Worker
): void {
405 this.stepWorkerRunningTasks(worker
, -1)
409 * Steps the number of tasks that the given worker has applied.
411 * @param worker Worker which running tasks are stepped.
412 * @param step Number of running tasks step.
414 private stepWorkerRunningTasks (worker
: Worker
, step
: number): void {
415 if (this.checkWorkerTasksUsage(worker
) === true) {
416 const tasksUsage
= this.workersTasksUsage
.get(worker
) as TasksUsage
417 tasksUsage
.running
= tasksUsage
.running
+ step
418 this.workersTasksUsage
.set(worker
, tasksUsage
)
423 * Steps the number of tasks that the given worker has run.
425 * @param worker Worker which has run tasks.
426 * @param step Number of run tasks step.
428 private stepWorkerRunTasks (worker
: Worker
, step
: number): void {
429 if (this.checkWorkerTasksUsage(worker
) === true) {
430 const tasksUsage
= this.workersTasksUsage
.get(worker
) as TasksUsage
431 tasksUsage
.run
= tasksUsage
.run
+ step
432 this.workersTasksUsage
.set(worker
, tasksUsage
)
437 * Updates tasks runtime for the given worker.
439 * @param worker Worker which run the task.
440 * @param taskRunTime Worker task runtime.
442 private updateWorkerTasksRunTime (
444 taskRunTime
: number | undefined
447 this.workerChoiceStrategyContext
.getWorkerChoiceStrategy()
448 .requiredStatistics
.runTime
=== true &&
449 this.checkWorkerTasksUsage(worker
) === true
451 const tasksUsage
= this.workersTasksUsage
.get(worker
) as TasksUsage
452 tasksUsage
.runTime
+= taskRunTime
?? 0
453 if (tasksUsage
.run
!== 0) {
454 tasksUsage
.avgRunTime
= tasksUsage
.runTime
/ tasksUsage
.run
456 this.workersTasksUsage
.set(worker
, tasksUsage
)
461 * Checks if the given worker is registered in the workers tasks usage map.
463 * @param worker Worker to check.
464 * @returns `true` if the worker is registered in the workers tasks usage map. `false` otherwise.
466 private checkWorkerTasksUsage (worker
: Worker
): boolean {
467 const hasTasksUsage
= this.workersTasksUsage
.has(worker
)
468 if (hasTasksUsage
=== false) {
469 throw new Error('Worker could not be found in workers tasks usage map')
475 * Initializes tasks usage statistics.
477 * @param worker The worker.
479 initWorkerTasksUsage (worker
: Worker
): void {
480 this.workersTasksUsage
.set(worker
, {
489 * Removes worker tasks usage statistics.
491 * @param worker The worker.
493 private removeWorkerTasksUsage (worker
: Worker
): void {
494 this.workersTasksUsage
.delete(worker
)
498 * Resets worker tasks usage statistics.
500 * @param worker The worker.
502 private resetWorkerTasksUsage (worker
: Worker
): void {
503 this.removeWorkerTasksUsage(worker
)
504 this.initWorkerTasksUsage(worker
)