3 PromiseWorkerResponseWrapper
4 } from
'../utility-types'
5 import { EMPTY_FUNCTION
} from
'../utils'
6 import { isKillBehavior
, KillBehaviors
} from
'../worker/worker-options'
7 import type { IPoolInternal
} from
'./pool-internal'
8 import { PoolEmitter
, PoolType
} from
'./pool-internal'
9 import type { WorkerChoiceStrategy
} from
'./selection-strategies'
11 WorkerChoiceStrategies
,
12 WorkerChoiceStrategyContext
13 } from
'./selection-strategies'
16 * Callback invoked if the worker raised an error.
18 export type ErrorHandler
<Worker
> = (this: Worker
, e
: Error) => void
21 * Callback invoked when the worker has started successfully.
23 export type OnlineHandler
<Worker
> = (this: Worker
) => void
26 * Callback invoked when the worker exits successfully.
28 export type ExitHandler
<Worker
> = (this: Worker
, code
: number) => void
31 * Basic interface that describes the minimum required implementation of listener events for a pool-worker.
33 export interface IWorker
{
35 * Register a listener to the error event.
37 * @param event `'error'`.
38 * @param handler The error handler.
40 on(event
: 'error', handler
: ErrorHandler
<this>): void
42 * Register a listener to the online event.
44 * @param event `'online'`.
45 * @param handler The online handler.
47 on(event
: 'online', handler
: OnlineHandler
<this>): void
49 * Register a listener to the exit event.
51 * @param event `'exit'`.
52 * @param handler The exit handler.
54 on(event
: 'exit', handler
: ExitHandler
<this>): void
56 * Register a listener to the exit event that will only performed once.
58 * @param event `'exit'`.
59 * @param handler The exit handler.
61 once(event
: 'exit', handler
: ExitHandler
<this>): void
65 * Options for a poolifier pool.
67 export interface PoolOptions
<Worker
> {
69 * A function that will listen for error event on each worker.
71 errorHandler
?: ErrorHandler
<Worker
>
73 * A function that will listen for online event on each worker.
75 onlineHandler
?: OnlineHandler
<Worker
>
77 * A function that will listen for exit event on each worker.
79 exitHandler
?: ExitHandler
<Worker
>
81 * The work choice strategy to use in this pool.
83 workerChoiceStrategy
?: WorkerChoiceStrategy
85 * Pool events emission.
89 enableEvents
?: boolean
93 * Base class containing some shared logic for all poolifier pools.
95 * @template Worker Type of worker which manages this pool.
96 * @template Data Type of data sent to the worker. This can only be serializable data.
97 * @template Response Type of response of execution. This can only be serializable data.
99 export abstract class AbstractPool
<
100 Worker
extends IWorker
,
103 > implements IPoolInternal
<Worker
, Data
, Response
> {
105 public readonly workers
: Worker
[] = []
108 public readonly tasks
: Map
<Worker
, number> = new Map
<Worker
, number>()
111 public readonly emitter
?: PoolEmitter
114 public readonly max
?: number
119 * - `key`: This is the message ID of each submitted task.
120 * - `value`: An object that contains the worker, the resolve function and the reject function.
122 * When we receive a message from the worker we get a map entry and resolve/reject the promise based on the message.
124 protected promiseMap
: Map
<
126 PromiseWorkerResponseWrapper
<Worker
, Response
>
127 > = new Map
<number, PromiseWorkerResponseWrapper
<Worker
, Response
>>()
130 * ID of the next message.
132 protected nextMessageId
: number = 0
135 * Worker choice strategy instance implementing the worker choice algorithm.
137 * Default to a strategy implementing a round robin algorithm.
139 protected workerChoiceStrategyContext
: WorkerChoiceStrategyContext
<
146 * Constructs a new poolifier pool.
148 * @param numberOfWorkers Number of workers that this pool should manage.
149 * @param filePath Path to the worker-file.
150 * @param opts Options for the pool.
153 public readonly numberOfWorkers
: number,
154 public readonly filePath
: string,
155 public readonly opts
: PoolOptions
<Worker
>
157 if (!this.isMain()) {
158 throw new Error('Cannot start a pool from a worker!')
160 this.checkNumberOfWorkers(this.numberOfWorkers
)
161 this.checkFilePath(this.filePath
)
162 this.checkPoolOptions(this.opts
)
165 for (let i
= 1; i
<= this.numberOfWorkers
; i
++) {
166 this.createAndSetupWorker()
169 if (this.opts
.enableEvents
) {
170 this.emitter
= new PoolEmitter()
172 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext(
175 const workerCreated
= this.createAndSetupWorker()
176 this.registerWorkerMessageListener(workerCreated
, async message
=> {
177 const tasksInProgress
= this.tasks
.get(workerCreated
)
179 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
180 tasksInProgress
=== 0
182 // Kill received from the worker, means that no new tasks are submitted to that worker for a while ( > maxInactiveTime)
183 await this.destroyWorker(workerCreated
)
188 this.opts
.workerChoiceStrategy
192 private checkFilePath (filePath
: string): void {
194 throw new Error('Please specify a file with a worker implementation')
198 private checkNumberOfWorkers (numberOfWorkers
: number): void {
199 if (numberOfWorkers
== null) {
201 'Cannot instantiate a pool without specifying the number of workers'
203 } else if (!Number.isSafeInteger(numberOfWorkers
)) {
205 'Cannot instantiate a pool with a non integer number of workers'
207 } else if (numberOfWorkers
< 0) {
209 'Cannot instantiate a pool with a negative number of workers'
211 } else if (this.type === PoolType
.FIXED
&& numberOfWorkers
=== 0) {
212 throw new Error('Cannot instantiate a fixed pool with no worker')
216 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
217 this.opts
.workerChoiceStrategy
=
218 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
219 this.opts
.enableEvents
= opts
.enableEvents
?? true
223 public abstract get
type (): PoolType
226 public get
numberOfRunningTasks (): number {
227 return this.promiseMap
.size
231 public setWorkerChoiceStrategy (
232 workerChoiceStrategy
: WorkerChoiceStrategy
234 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
235 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
241 public abstract get
busy (): boolean
243 protected internalGetBusyStatus (): boolean {
245 this.numberOfRunningTasks
>= this.numberOfWorkers
&&
246 this.findFreeTasksMapEntry() === false
251 public findFreeTasksMapEntry (): [Worker
, number] | false {
252 for (const [worker
, numberOfTasks
] of this.tasks
) {
253 if (numberOfTasks
=== 0) {
254 // A worker is free, return the matching tasks map entry
255 return [worker
, numberOfTasks
]
262 public execute (data
: Data
): Promise
<Response
> {
263 // Configure worker to handle message with the specified task
264 const worker
= this.chooseWorker()
265 const messageId
= ++this.nextMessageId
266 const res
= this.internalExecute(worker
, messageId
)
267 this.checkAndEmitBusy()
268 this.sendToWorker(worker
, { data
: data
|| ({} as Data
), id
: messageId
})
273 public async destroy (): Promise
<void> {
274 await Promise
.all(this.workers
.map(worker
=> this.destroyWorker(worker
)))
278 * Shut down given worker.
280 * @param worker A worker within `workers`.
282 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
285 * Setup hook that can be overridden by a Poolifier pool implementation
286 * to run code before workers are created in the abstract constructor.
288 protected setupHook (): void {
293 * Should return whether the worker is the main worker or not.
295 protected abstract isMain (): boolean
298 * Increase the number of tasks that the given workers has applied.
300 * @param worker Worker whose tasks are increased.
302 protected increaseWorkersTask (worker
: Worker
): void {
303 this.stepWorkerNumberOfTasks(worker
, 1)
307 * Decrease the number of tasks that the given workers has applied.
309 * @param worker Worker whose tasks are decreased.
311 protected decreaseWorkersTasks (worker
: Worker
): void {
312 this.stepWorkerNumberOfTasks(worker
, -1)
316 * Step the number of tasks that the given workers has applied.
318 * @param worker Worker whose tasks are set.
319 * @param step Worker number of tasks step.
321 private stepWorkerNumberOfTasks (worker
: Worker
, step
: number): void {
322 const numberOfTasksInProgress
= this.tasks
.get(worker
)
323 if (numberOfTasksInProgress
!== undefined) {
324 this.tasks
.set(worker
, numberOfTasksInProgress
+ step
)
326 throw Error('Worker could not be found in tasks map')
331 * Removes the given worker from the pool.
333 * @param worker Worker that will be removed.
335 protected removeWorker (worker
: Worker
): void {
336 // Clean worker from data structure
337 const workerIndex
= this.workers
.indexOf(worker
)
338 this.workers
.splice(workerIndex
, 1)
339 this.tasks
.delete(worker
)
343 * Choose a worker for the next task.
345 * The default implementation uses a round robin algorithm to distribute the load.
349 protected chooseWorker (): Worker
{
350 return this.workerChoiceStrategyContext
.execute()
354 * Send a message to the given worker.
356 * @param worker The worker which should receive the message.
357 * @param message The message.
359 protected abstract sendToWorker (
361 message
: MessageValue
<Data
>
365 * Register a listener callback on a given worker.
367 * @param worker A worker.
368 * @param listener A message listener callback.
370 protected abstract registerWorkerMessageListener
<
371 Message
extends Data
| Response
372 > (worker
: Worker
, listener
: (message
: MessageValue
<Message
>) => void): void
374 protected internalExecute (
377 ): Promise
<Response
> {
378 this.increaseWorkersTask(worker
)
379 return new Promise
<Response
>((resolve
, reject
) => {
380 this.promiseMap
.set(messageId
, { resolve
, reject
, worker
})
385 * Returns a newly created worker.
387 protected abstract createWorker (): Worker
390 * Function that can be hooked up when a worker has been newly created and moved to the workers registry.
392 * Can be used to update the `maxListeners` or binding the `main-worker`<->`worker` connection if not bind by default.
394 * @param worker The newly created worker.
396 protected abstract afterWorkerSetup (worker
: Worker
): void
399 * Creates a new worker for this pool and sets it up completely.
401 * @returns New, completely set up worker.
403 protected createAndSetupWorker (): Worker
{
404 const worker
: Worker
= this.createWorker()
406 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
407 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
408 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
409 worker
.once('exit', () => this.removeWorker(worker
))
411 this.workers
.push(worker
)
414 this.tasks
.set(worker
, 0)
416 this.afterWorkerSetup(worker
)
422 * This function is the listener registered for each worker.
424 * @returns The listener function to execute when a message is sent from a worker.
426 protected workerListener (): (message
: MessageValue
<Response
>) => void {
429 const value
= this.promiseMap
.get(message
.id
)
431 this.decreaseWorkersTasks(value
.worker
)
432 if (message
.error
) value
.reject(message
.error
)
433 else value
.resolve(message
.data
as Response
)
434 this.promiseMap
.delete(message
.id
)
440 private checkAndEmitBusy (): void {
441 if (this.opts
.enableEvents
&& this.busy
) {
442 this.emitter
?.emit('busy')