3 PromiseWorkerResponseWrapper
4 } from
'../utility-types'
5 import type { IPoolInternal
} from
'./pool-internal'
6 import { PoolEmitter
} from
'./pool-internal'
7 import type { WorkerChoiceStrategy
} from
'./selection-strategies'
9 WorkerChoiceStrategies
,
10 WorkerChoiceStrategyContext
11 } from
'./selection-strategies'
14 * An intentional empty function.
16 const EMPTY_FUNCTION
: () => void = () => {
17 /* Intentionally empty */
21 * Callback invoked if the worker raised an error.
23 export type ErrorHandler
<Worker
> = (this: Worker
, e
: Error) => void
26 * Callback invoked when the worker has started successfully.
28 export type OnlineHandler
<Worker
> = (this: Worker
) => void
31 * Callback invoked when the worker exits successfully.
33 export type ExitHandler
<Worker
> = (this: Worker
, code
: number) => void
36 * Basic interface that describes the minimum required implementation of listener events for a pool-worker.
38 export interface IWorker
{
40 * Register a listener to the error event.
42 * @param event `'error'`.
43 * @param handler The error handler.
45 on(event
: 'error', handler
: ErrorHandler
<this>): void
47 * Register a listener to the online event.
49 * @param event `'online'`.
50 * @param handler The online handler.
52 on(event
: 'online', handler
: OnlineHandler
<this>): void
54 * Register a listener to the exit event.
56 * @param event `'exit'`.
57 * @param handler The exit handler.
59 on(event
: 'exit', handler
: ExitHandler
<this>): void
61 * Register a listener to the exit event that will only performed once.
63 * @param event `'exit'`.
64 * @param handler The exit handler.
66 once(event
: 'exit', handler
: ExitHandler
<this>): void
70 * Options for a poolifier pool.
72 export interface PoolOptions
<Worker
> {
74 * A function that will listen for error event on each worker.
76 errorHandler
?: ErrorHandler
<Worker
>
78 * A function that will listen for online event on each worker.
80 onlineHandler
?: OnlineHandler
<Worker
>
82 * A function that will listen for exit event on each worker.
84 exitHandler
?: ExitHandler
<Worker
>
86 * The work choice strategy to use in this pool.
88 workerChoiceStrategy
?: WorkerChoiceStrategy
92 * Base class containing some shared logic for all poolifier pools.
94 * @template Worker Type of worker which manages this pool.
95 * @template Data Type of data sent to the worker. This can only be serializable data.
96 * @template Response Type of response of execution. This can only be serializable data.
98 export abstract class AbstractPool
<
99 Worker
extends IWorker
,
102 > implements IPoolInternal
<Worker
, Data
, Response
> {
106 * - `key`: This is the message ID of each submitted task.
107 * - `value`: An object that contains the worker, the resolve function and the reject function.
109 * When we receive a message from the worker we get a map entry and resolve/reject the promise based on the message.
111 protected promiseMap
: Map
<
113 PromiseWorkerResponseWrapper
<Worker
, Response
>
114 > = new Map
<number, PromiseWorkerResponseWrapper
<Worker
, Response
>>()
117 public readonly workers
: Worker
[] = []
120 public readonly tasks
: Map
<Worker
, number> = new Map
<Worker
, number>()
123 public readonly emitter
: PoolEmitter
126 * ID of the next message.
128 protected nextMessageId
: number = 0
131 * Worker choice strategy instance implementing the worker choice algorithm.
133 * Default to a strategy implementing a round robin algorithm.
135 protected workerChoiceStrategyContext
: WorkerChoiceStrategyContext
<
142 * Constructs a new poolifier pool.
144 * @param numberOfWorkers Number of workers that this pool should manage.
145 * @param filePath Path to the worker-file.
146 * @param opts Options for the pool.
149 public readonly numberOfWorkers
: number,
150 public readonly filePath
: string,
151 public readonly opts
: PoolOptions
<Worker
>
153 if (!this.isMain()) {
154 throw new Error('Cannot start a pool from a worker!')
156 this.checkNumberOfWorkers(this.numberOfWorkers
)
157 this.checkFilePath(this.filePath
)
160 for (let i
= 1; i
<= this.numberOfWorkers
; i
++) {
161 this.createAndSetupWorker()
164 this.emitter
= new PoolEmitter()
165 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext(
167 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
171 private checkFilePath (filePath
: string): void {
173 throw new Error('Please specify a file with a worker implementation')
177 private checkNumberOfWorkers (numberOfWorkers
: number): void {
178 if (numberOfWorkers
== null) {
180 'Cannot instantiate a pool without specifying the number of workers'
182 } else if (!Number.isSafeInteger(numberOfWorkers
)) {
184 'Cannot instantiate a pool with a non integer number of workers'
186 } else if (numberOfWorkers
< 0) {
188 'Cannot instantiate a pool with a negative number of workers'
190 } else if (!this.dynamic
&& numberOfWorkers
=== 0) {
191 throw new Error('Cannot instantiate a fixed pool with no worker')
196 public get
dynamic (): boolean {
201 public setWorkerChoiceStrategy (
202 workerChoiceStrategy
: WorkerChoiceStrategy
204 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
205 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
211 public execute (data
: Data
): Promise
<Response
> {
212 // Configure worker to handle message with the specified task
213 const worker
= this.chooseWorker()
214 this.increaseWorkersTask(worker
)
215 const messageId
= ++this.nextMessageId
216 const res
= this.internalExecute(worker
, messageId
)
217 this.sendToWorker(worker
, { data
: data
|| ({} as Data
), id
: messageId
})
222 public async destroy (): Promise
<void> {
223 await Promise
.all(this.workers
.map(worker
=> this.destroyWorker(worker
)))
227 public abstract destroyWorker (worker
: Worker
): void | Promise
<void>
230 * Setup hook that can be overridden by a Poolifier pool implementation
231 * to run code before workers are created in the abstract constructor.
233 protected setupHook (): void {
238 * Should return whether the worker is the main worker or not.
240 protected abstract isMain (): boolean
243 * Increase the number of tasks that the given workers has done.
245 * @param worker Worker whose tasks are increased.
247 protected increaseWorkersTask (worker
: Worker
): void {
248 this.stepWorkerNumberOfTasks(worker
, 1)
252 * Decrease the number of tasks that the given workers has done.
254 * @param worker Worker whose tasks are decreased.
256 protected decreaseWorkersTasks (worker
: Worker
): void {
257 this.stepWorkerNumberOfTasks(worker
, -1)
261 * Step the number of tasks that the given workers has done.
263 * @param worker Worker whose tasks are set.
264 * @param step Worker number of tasks step.
266 private stepWorkerNumberOfTasks (worker
: Worker
, step
: number): void {
267 const numberOfTasksInProgress
= this.tasks
.get(worker
)
268 if (numberOfTasksInProgress
!== undefined) {
269 this.tasks
.set(worker
, numberOfTasksInProgress
+ step
)
271 throw Error('Worker could not be found in tasks map')
276 * Removes the given worker from the pool.
278 * @param worker Worker that will be removed.
280 protected removeWorker (worker
: Worker
): void {
281 // Clean worker from data structure
282 const workerIndex
= this.workers
.indexOf(worker
)
283 this.workers
.splice(workerIndex
, 1)
284 this.tasks
.delete(worker
)
288 * Choose a worker for the next task.
290 * The default implementation uses a round robin algorithm to distribute the load.
294 protected chooseWorker (): Worker
{
295 return this.workerChoiceStrategyContext
.execute()
299 * Send a message to the given worker.
301 * @param worker The worker which should receive the message.
302 * @param message The message.
304 protected abstract sendToWorker (
306 message
: MessageValue
<Data
>
310 public abstract registerWorkerMessageListener
<
311 Message
extends Data
| Response
312 > (worker
: Worker
, listener
: (message
: MessageValue
<Message
>) => void): void
314 protected internalExecute (
317 ): Promise
<Response
> {
318 return new Promise
<Response
>((resolve
, reject
) => {
319 this.promiseMap
.set(messageId
, { resolve
, reject
, worker
})
324 * Returns a newly created worker.
326 protected abstract createWorker (): Worker
329 * Function that can be hooked up when a worker has been newly created and moved to the workers registry.
331 * Can be used to update the `maxListeners` or binding the `main-worker`<->`worker` connection if not bind by default.
333 * @param worker The newly created worker.
335 protected abstract afterWorkerSetup (worker
: Worker
): void
338 public createAndSetupWorker (): Worker
{
339 const worker
: Worker
= this.createWorker()
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', () => this.removeWorker(worker
))
346 this.workers
.push(worker
)
349 this.tasks
.set(worker
, 0)
351 this.afterWorkerSetup(worker
)
357 * This function is the listener registered for each worker.
359 * @returns The listener function to execute when a message is sent from a worker.
361 protected workerListener (): (message
: MessageValue
<Response
>) => void {
362 const listener
: (message
: MessageValue
<Response
>) => void = message
=> {
364 const value
= this.promiseMap
.get(message
.id
)
366 this.decreaseWorkersTasks(value
.worker
)
367 if (message
.error
) value
.reject(message
.error
)
368 else value
.resolve(message
.data
as Response
)
369 this.promiseMap
.delete(message
.id
)