1 import EventEmitter from
'events'
2 import type { MessageValue
} from
'../utility-types'
3 import type { IPool
} from
'./pool'
6 * Callback invoked if the worker raised an error.
8 export type ErrorHandler
<Worker
> = (this: Worker
, e
: Error) => void
11 * Callback invoked when the worker has started successfully.
13 export type OnlineHandler
<Worker
> = (this: Worker
) => void
16 * Callback invoked when the worker exits successfully.
18 export type ExitHandler
<Worker
> = (this: Worker
, code
: number) => void
21 * Basic interface that describes the minimum required implementation of listener events for a pool-worker.
23 export interface IWorker
{
24 on(event
: 'error', handler
: ErrorHandler
<this>): void
25 on(event
: 'online', handler
: OnlineHandler
<this>): void
26 on(event
: 'exit', handler
: ExitHandler
<this>): void
30 * Options for a poolifier pool.
32 export interface PoolOptions
<Worker
> {
34 * A function that will listen for error event on each worker.
36 errorHandler
?: ErrorHandler
<Worker
>
38 * A function that will listen for online event on each worker.
40 onlineHandler
?: OnlineHandler
<Worker
>
42 * A function that will listen for exit event on each worker.
44 exitHandler
?: ExitHandler
<Worker
>
46 * This is just to avoid non-useful warning messages.
48 * Will be used to set `maxListeners` on event emitters (workers are event emitters).
51 * @see [Node events emitter.setMaxListeners(n)](https://nodejs.org/api/events.html#events_emitter_setmaxlisteners_n)
57 * Internal poolifier pool emitter.
59 class PoolEmitter
extends EventEmitter
{}
62 * Base class containing some shared logic for all poolifier pools.
64 * @template Worker Type of worker which manages this pool.
65 * @template Data Type of data sent to the worker.
66 * @template Response Type of response of execution.
68 export abstract class AbstractPool
<
69 Worker
extends IWorker
,
72 > implements IPool
<Data
, Response
> {
74 * List of currently available workers.
76 public readonly workers
: Worker
[] = []
79 * Index for the next worker.
81 public nextWorkerIndex
: number = 0
84 * - `key`: The `Worker`
85 * - `value`: Number of tasks that has been assigned to that worker since it started
87 public readonly tasks
: Map
<Worker
, number> = new Map
<Worker
, number>()
90 * Emitter on which events can be listened to.
92 * Events that can currently be listened to:
96 public readonly emitter
: PoolEmitter
99 * ID of the next message.
101 protected nextMessageId
: number = 0
104 * Constructs a new poolifier pool.
106 * @param numberOfWorkers Number of workers that this pool should manage.
107 * @param filePath Path to the worker-file.
108 * @param opts Options for the pool. Default: `{ maxTasks: 1000 }`
111 public readonly numberOfWorkers
: number,
112 public readonly filePath
: string,
113 public readonly opts
: PoolOptions
<Worker
> = { maxTasks
: 1000 }
115 if (!this.isMain()) {
116 throw new Error('Cannot start a pool from a worker!')
118 // TODO christopher 2021-02-07: Improve this check e.g. with a pattern or blank check
119 if (!this.filePath
) {
120 throw new Error('Please specify a file with a worker implementation')
125 for (let i
= 1; i
<= this.numberOfWorkers
; i
++) {
126 this.createAndSetupWorker()
129 this.emitter
= new PoolEmitter()
133 * Number of workers that this pool should manage.
135 * @returns Number of workers that this pool manages.
136 * @deprecated Only here for backward compatibility.
138 // eslint-disable-next-line spellcheck/spell-checker
139 public get
numWorkers (): number {
140 return this.numberOfWorkers
144 * Index for the next worker.
146 * @returns Index for the next worker.
147 * @deprecated Only here for backward compatibility.
149 public get
nextWorker (): number {
150 return this.nextWorkerIndex
153 public execute (data
: Data
): Promise
<Response
> {
154 // Configure worker to handle message with the specified task
155 const worker
= this.chooseWorker()
156 this.increaseWorkersTask(worker
)
157 const messageId
= ++this.nextMessageId
158 const res
= this.internalExecute(worker
, messageId
)
159 this.sendToWorker(worker
, { data
: data
|| ({} as Data
), id
: messageId
})
163 public async destroy (): Promise
<void> {
164 for (const worker
of this.workers
) {
165 await this.destroyWorker(worker
)
170 * Shut down given worker.
172 * @param worker A worker within `workers`.
174 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
177 * Setup hook that can be overridden by a Poolifier pool implementation
178 * to run code before workers are created in the abstract constructor.
180 protected setupHook (): void {
185 * Should return whether the worker is the main worker or not.
187 protected abstract isMain (): boolean
190 * Increase the number of tasks that the given workers has done.
192 * @param worker Workers whose tasks are increased.
194 protected increaseWorkersTask (worker
: Worker
): void {
195 const numberOfTasksTheWorkerHas
= this.tasks
.get(worker
)
196 if (numberOfTasksTheWorkerHas
!== undefined) {
197 this.tasks
.set(worker
, numberOfTasksTheWorkerHas
+ 1)
199 throw Error('Worker could not be found in tasks map')
204 * Removes the given worker from the pool.
206 * @param worker Worker that will be removed.
208 protected removeWorker (worker
: Worker
): void {
209 // Clean worker from data structure
210 const workerIndex
= this.workers
.indexOf(worker
)
211 this.workers
.splice(workerIndex
, 1)
212 this.tasks
.delete(worker
)
216 * Choose a worker for the next task.
218 * The default implementation uses a round robin algorithm to distribute the load.
222 protected chooseWorker (): Worker
{
223 const chosenWorker
= this.workers
[this.nextWorkerIndex
]
224 this.nextWorkerIndex
++
225 this.nextWorkerIndex
%= this.workers
.length
230 * Send a message to the given worker.
232 * @param worker The worker which should receive the message.
233 * @param message The message.
235 protected abstract sendToWorker (
237 message
: MessageValue
<Data
>
240 protected abstract registerWorkerMessageListener (
242 listener
: (message
: MessageValue
<Response
>) => void
245 protected abstract unregisterWorkerMessageListener (
247 listener
: (message
: MessageValue
<Response
>) => void
250 protected internalExecute (
253 ): Promise
<Response
> {
254 return new Promise((resolve
, reject
) => {
255 const listener
: (message
: MessageValue
<Response
>) => void = message
=> {
256 if (message
.id
=== messageId
) {
257 this.unregisterWorkerMessageListener(worker
, listener
)
258 this.increaseWorkersTask(worker
)
259 if (message
.error
) reject(message
.error
)
260 else resolve(message
.data
as Response
)
263 this.registerWorkerMessageListener(worker
, listener
)
268 * Returns a newly created worker.
270 protected abstract createWorker (): Worker
273 * Function that can be hooked up when a worker has been newly created and moved to the workers registry.
275 * Can be used to update the `maxListeners` or binding the `main-worker`<->`worker` connection if not bind by default.
277 * @param worker The newly created worker.
279 protected abstract afterWorkerSetup (worker
: Worker
): void
282 * Creates a new worker for this pool and sets it up completely.
284 * @returns New, completely set up worker.
286 protected createAndSetupWorker (): Worker
{
287 const worker
: Worker
= this.createWorker()
289 worker
.on('error', this.opts
.errorHandler
?? (() => {}))
290 worker
.on('online', this.opts
.onlineHandler
?? (() => {}))
291 // TODO handle properly when a worker exit
292 worker
.on('exit', this.opts
.exitHandler
?? (() => {}))
294 this.workers
.push(worker
)
297 this.tasks
.set(worker
, 0)
299 this.afterWorkerSetup(worker
)