3 PromiseWorkerResponseWrapper
4 } from
'../utility-types'
5 import { isKillBehavior
, KillBehaviors
} from
'../worker/worker-options'
6 import type { IPoolInternal
} from
'./pool-internal'
7 import { PoolEmitter
, PoolType
} from
'./pool-internal'
8 import type { WorkerChoiceStrategy
} from
'./selection-strategies'
10 WorkerChoiceStrategies
,
11 WorkerChoiceStrategyContext
12 } from
'./selection-strategies'
15 * An intentional empty function.
17 const EMPTY_FUNCTION
: () => void = () => {
18 /* Intentionally empty */
22 * Callback invoked if the worker raised an error.
24 export type ErrorHandler
<Worker
> = (this: Worker
, e
: Error) => void
27 * Callback invoked when the worker has started successfully.
29 export type OnlineHandler
<Worker
> = (this: Worker
) => void
32 * Callback invoked when the worker exits successfully.
34 export type ExitHandler
<Worker
> = (this: Worker
, code
: number) => void
37 * Basic interface that describes the minimum required implementation of listener events for a pool-worker.
39 export interface IWorker
{
41 * Register a listener to the error event.
43 * @param event `'error'`.
44 * @param handler The error handler.
46 on(event
: 'error', handler
: ErrorHandler
<this>): void
48 * Register a listener to the online event.
50 * @param event `'online'`.
51 * @param handler The online handler.
53 on(event
: 'online', handler
: OnlineHandler
<this>): void
55 * Register a listener to the exit event.
57 * @param event `'exit'`.
58 * @param handler The exit handler.
60 on(event
: 'exit', handler
: ExitHandler
<this>): void
62 * Register a listener to the exit event that will only performed once.
64 * @param event `'exit'`.
65 * @param handler The exit handler.
67 once(event
: 'exit', handler
: ExitHandler
<this>): void
71 * Options for a poolifier pool.
73 export interface PoolOptions
<Worker
> {
75 * A function that will listen for error event on each worker.
77 errorHandler
?: ErrorHandler
<Worker
>
79 * A function that will listen for online event on each worker.
81 onlineHandler
?: OnlineHandler
<Worker
>
83 * A function that will listen for exit event on each worker.
85 exitHandler
?: ExitHandler
<Worker
>
87 * The work choice strategy to use in this pool.
89 workerChoiceStrategy
?: WorkerChoiceStrategy
91 * Pool events emission.
95 enableEvents
?: boolean
99 * Base class containing some shared logic for all poolifier pools.
101 * @template Worker Type of worker which manages this pool.
102 * @template Data Type of data sent to the worker. This can only be serializable data.
103 * @template Response Type of response of execution. This can only be serializable data.
105 export abstract class AbstractPool
<
106 Worker
extends IWorker
,
109 > implements IPoolInternal
<Worker
, Data
, Response
> {
111 public readonly workers
: Worker
[] = []
114 public readonly tasks
: Map
<Worker
, number> = new Map
<Worker
, number>()
117 public readonly emitter
?: PoolEmitter
120 public readonly max
?: number
125 * - `key`: This is the message ID of each submitted task.
126 * - `value`: An object that contains the worker, the resolve function and the reject function.
128 * When we receive a message from the worker we get a map entry and resolve/reject the promise based on the message.
130 protected promiseMap
: Map
<
132 PromiseWorkerResponseWrapper
<Worker
, Response
>
133 > = new Map
<number, PromiseWorkerResponseWrapper
<Worker
, Response
>>()
136 * ID of the next message.
138 protected nextMessageId
: number = 0
141 * Worker choice strategy instance implementing the worker choice algorithm.
143 * Default to a strategy implementing a round robin algorithm.
145 protected workerChoiceStrategyContext
: WorkerChoiceStrategyContext
<
152 * Constructs a new poolifier pool.
154 * @param numberOfWorkers Number of workers that this pool should manage.
155 * @param filePath Path to the worker-file.
156 * @param opts Options for the pool.
159 public readonly numberOfWorkers
: number,
160 public readonly filePath
: string,
161 public readonly opts
: PoolOptions
<Worker
>
163 if (!this.isMain()) {
164 throw new Error('Cannot start a pool from a worker!')
166 this.checkNumberOfWorkers(this.numberOfWorkers
)
167 this.checkFilePath(this.filePath
)
168 this.checkPoolOptions(this.opts
)
171 for (let i
= 1; i
<= this.numberOfWorkers
; i
++) {
172 this.createAndSetupWorker()
175 if (this.opts
.enableEvents
) {
176 this.emitter
= new PoolEmitter()
178 this.workerChoiceStrategyContext
= new WorkerChoiceStrategyContext(
181 const workerCreated
= this.createAndSetupWorker()
182 this.registerWorkerMessageListener(workerCreated
, message
=> {
183 const tasksInProgress
= this.tasks
.get(workerCreated
)
185 isKillBehavior(KillBehaviors
.HARD
, message
.kill
) ||
186 tasksInProgress
=== 0
188 // Kill received from the worker, means that no new tasks are submitted to that worker for a while ( > maxInactiveTime)
189 void this.destroyWorker(workerCreated
)
194 opts
.workerChoiceStrategy
?? WorkerChoiceStrategies
.ROUND_ROBIN
198 private checkFilePath (filePath
: string): void {
200 throw new Error('Please specify a file with a worker implementation')
204 private checkNumberOfWorkers (numberOfWorkers
: number): void {
205 if (numberOfWorkers
== null) {
207 'Cannot instantiate a pool without specifying the number of workers'
209 } else if (!Number.isSafeInteger(numberOfWorkers
)) {
211 'Cannot instantiate a pool with a non integer number of workers'
213 } else if (numberOfWorkers
< 0) {
215 'Cannot instantiate a pool with a negative number of workers'
217 } else if (this.type === PoolType
.FIXED
&& numberOfWorkers
=== 0) {
218 throw new Error('Cannot instantiate a fixed pool with no worker')
222 private checkPoolOptions (opts
: PoolOptions
<Worker
>): void {
223 this.opts
.enableEvents
= opts
.enableEvents
?? true
227 public abstract get
type (): PoolType
230 public get
numberOfRunningTasks (): number {
231 return this.promiseMap
.size
235 public setWorkerChoiceStrategy (
236 workerChoiceStrategy
: WorkerChoiceStrategy
238 this.opts
.workerChoiceStrategy
= workerChoiceStrategy
239 this.workerChoiceStrategyContext
.setWorkerChoiceStrategy(
245 public abstract get
busy (): boolean
247 protected internalGetBusyStatus (): boolean {
249 this.numberOfRunningTasks
>= this.numberOfWorkers
&&
250 this.findFreeTasksMapEntry() === false
255 public findFreeTasksMapEntry (): [Worker
, number] | false {
256 for (const [worker
, numberOfTasks
] of this.tasks
) {
257 if (numberOfTasks
=== 0) {
258 // A worker is free, return the matching tasks map entry
259 return [worker
, numberOfTasks
]
266 public execute (data
: Data
): Promise
<Response
> {
267 // Configure worker to handle message with the specified task
268 const worker
= this.chooseWorker()
269 this.increaseWorkersTask(worker
)
270 this.checkAndEmitBusy()
271 const messageId
= ++this.nextMessageId
272 const res
= this.internalExecute(worker
, messageId
)
273 this.sendToWorker(worker
, { data
: data
|| ({} as Data
), id
: messageId
})
278 public async destroy (): Promise
<void> {
279 await Promise
.all(this.workers
.map(worker
=> this.destroyWorker(worker
)))
283 * Shut down given worker.
285 * @param worker A worker within `workers`.
287 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
290 * Setup hook that can be overridden by a Poolifier pool implementation
291 * to run code before workers are created in the abstract constructor.
293 protected setupHook (): void {
298 * Should return whether the worker is the main worker or not.
300 protected abstract isMain (): boolean
303 * Increase the number of tasks that the given workers has applied.
305 * @param worker Worker whose tasks are increased.
307 protected increaseWorkersTask (worker
: Worker
): void {
308 this.stepWorkerNumberOfTasks(worker
, 1)
312 * Decrease the number of tasks that the given workers has applied.
314 * @param worker Worker whose tasks are decreased.
316 protected decreaseWorkersTasks (worker
: Worker
): void {
317 this.stepWorkerNumberOfTasks(worker
, -1)
321 * Step the number of tasks that the given workers has applied.
323 * @param worker Worker whose tasks are set.
324 * @param step Worker number of tasks step.
326 private stepWorkerNumberOfTasks (worker
: Worker
, step
: number): void {
327 const numberOfTasksInProgress
= this.tasks
.get(worker
)
328 if (numberOfTasksInProgress
!== undefined) {
329 this.tasks
.set(worker
, numberOfTasksInProgress
+ step
)
331 throw Error('Worker could not be found in tasks map')
336 * Removes the given worker from the pool.
338 * @param worker Worker that will be removed.
340 protected removeWorker (worker
: Worker
): void {
341 // Clean worker from data structure
342 const workerIndex
= this.workers
.indexOf(worker
)
343 this.workers
.splice(workerIndex
, 1)
344 this.tasks
.delete(worker
)
348 * Choose a worker for the next task.
350 * The default implementation uses a round robin algorithm to distribute the load.
354 protected chooseWorker (): Worker
{
355 return this.workerChoiceStrategyContext
.execute()
359 * Send a message to the given worker.
361 * @param worker The worker which should receive the message.
362 * @param message The message.
364 protected abstract sendToWorker (
366 message
: MessageValue
<Data
>
370 * Register a listener callback on a given worker.
372 * @param worker A worker.
373 * @param listener A message listener callback.
375 protected abstract registerWorkerMessageListener
<
376 Message
extends Data
| Response
377 > (worker
: Worker
, listener
: (message
: MessageValue
<Message
>) => void): void
379 protected internalExecute (
382 ): Promise
<Response
> {
383 return new Promise
<Response
>((resolve
, reject
) => {
384 this.promiseMap
.set(messageId
, { resolve
, reject
, worker
})
389 * Returns a newly created worker.
391 protected abstract createWorker (): Worker
394 * Function that can be hooked up when a worker has been newly created and moved to the workers registry.
396 * Can be used to update the `maxListeners` or binding the `main-worker`<->`worker` connection if not bind by default.
398 * @param worker The newly created worker.
400 protected abstract afterWorkerSetup (worker
: Worker
): void
403 * Creates a new worker for this pool and sets it up completely.
405 * @returns New, completely set up worker.
407 protected createAndSetupWorker (): Worker
{
408 const worker
: Worker
= this.createWorker()
410 worker
.on('error', this.opts
.errorHandler
?? EMPTY_FUNCTION
)
411 worker
.on('online', this.opts
.onlineHandler
?? EMPTY_FUNCTION
)
412 worker
.on('exit', this.opts
.exitHandler
?? EMPTY_FUNCTION
)
413 worker
.once('exit', () => this.removeWorker(worker
))
415 this.workers
.push(worker
)
418 this.tasks
.set(worker
, 0)
420 this.afterWorkerSetup(worker
)
426 * This function is the listener registered for each worker.
428 * @returns The listener function to execute when a message is sent from a worker.
430 protected workerListener (): (message
: MessageValue
<Response
>) => void {
433 const value
= this.promiseMap
.get(message
.id
)
435 this.decreaseWorkersTasks(value
.worker
)
436 if (message
.error
) value
.reject(message
.error
)
437 else value
.resolve(message
.data
as Response
)
438 this.promiseMap
.delete(message
.id
)
444 private checkAndEmitBusy (): void {
445 if (this.opts
.enableEvents
&& this.busy
) {
446 this.emitter
?.emit('busy')