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
27 once(event
: 'exit', handler
: ExitHandler
<this>): void
31 * Options for a poolifier pool.
33 export interface PoolOptions
<Worker
> {
35 * A function that will listen for error event on each worker.
37 errorHandler
?: ErrorHandler
<Worker
>
39 * A function that will listen for online event on each worker.
41 onlineHandler
?: OnlineHandler
<Worker
>
43 * A function that will listen for exit event on each worker.
45 exitHandler
?: ExitHandler
<Worker
>
47 * This is just to avoid non-useful warning messages.
49 * Will be used to set `maxListeners` on event emitters (workers are event emitters).
52 * @see [Node events emitter.setMaxListeners(n)](https://nodejs.org/api/events.html#events_emitter_setmaxlisteners_n)
58 * Internal poolifier pool emitter.
60 class PoolEmitter
extends EventEmitter
{}
63 * Base class containing some shared logic for all poolifier pools.
65 * @template Worker Type of worker which manages this pool.
66 * @template Data Type of data sent to the worker.
67 * @template Response Type of response of execution.
69 export abstract class AbstractPool
<
70 Worker
extends IWorker
,
73 > implements IPool
<Data
, Response
> {
75 * List of currently available workers.
77 public readonly workers
: Worker
[] = []
80 * Index for the next worker.
82 public nextWorkerIndex
: number = 0
85 * - `key`: The `Worker`
86 * - `value`: Number of tasks that has been assigned to that worker since it started
88 public readonly tasks
: Map
<Worker
, number> = new Map
<Worker
, number>()
91 * Emitter on which events can be listened to.
93 * Events that can currently be listened to:
97 public readonly emitter
: PoolEmitter
100 * ID of the next message.
102 protected nextMessageId
: number = 0
105 * Constructs a new poolifier pool.
107 * @param numberOfWorkers Number of workers that this pool should manage.
108 * @param filePath Path to the worker-file.
109 * @param opts Options for the pool. Default: `{ maxTasks: 1000 }`
112 public readonly numberOfWorkers
: number,
113 public readonly filePath
: string,
114 public readonly opts
: PoolOptions
<Worker
> = { maxTasks
: 1000 }
116 if (!this.isMain()) {
117 throw new Error('Cannot start a pool from a worker!')
119 // TODO christopher 2021-02-07: Improve this check e.g. with a pattern or blank check
120 if (!this.filePath
) {
121 throw new Error('Please specify a file with a worker implementation')
126 for (let i
= 1; i
<= this.numberOfWorkers
; i
++) {
127 this.createAndSetupWorker()
130 this.emitter
= new PoolEmitter()
134 * Number of workers that this pool should manage.
136 * @returns Number of workers that this pool manages.
137 * @deprecated Only here for backward compatibility.
139 // eslint-disable-next-line spellcheck/spell-checker
140 public get
numWorkers (): number {
141 return this.numberOfWorkers
145 * Index for the next worker.
147 * @returns Index for the next worker.
148 * @deprecated Only here for backward compatibility.
150 public get
nextWorker (): number {
151 return this.nextWorkerIndex
154 public execute (data
: Data
): Promise
<Response
> {
155 // Configure worker to handle message with the specified task
156 const worker
= this.chooseWorker()
157 this.increaseWorkersTask(worker
)
158 const messageId
= ++this.nextMessageId
159 const res
= this.internalExecute(worker
, messageId
)
160 this.sendToWorker(worker
, { data
: data
|| ({} as Data
), id
: messageId
})
164 public async destroy (): Promise
<void> {
165 await Promise
.all(this.workers
.map(worker
=> this.destroyWorker(worker
)))
169 * Shut down given worker.
171 * @param worker A worker within `workers`.
173 protected abstract destroyWorker (worker
: Worker
): void | Promise
<void>
176 * Setup hook that can be overridden by a Poolifier pool implementation
177 * to run code before workers are created in the abstract constructor.
179 protected setupHook (): void {
184 * Should return whether the worker is the main worker or not.
186 protected abstract isMain (): boolean
189 * Increase the number of tasks that the given workers has done.
191 * @param worker Workers whose tasks are increased.
193 protected increaseWorkersTask (worker
: Worker
): void {
194 const numberOfTasksTheWorkerHas
= this.tasks
.get(worker
)
195 if (numberOfTasksTheWorkerHas
!== undefined) {
196 this.tasks
.set(worker
, numberOfTasksTheWorkerHas
+ 1)
198 throw Error('Worker could not be found in tasks map')
203 * Removes the given worker from the pool.
205 * @param worker Worker that will be removed.
207 protected removeWorker (worker
: Worker
): void {
208 // Clean worker from data structure
209 const workerIndex
= this.workers
.indexOf(worker
)
210 this.workers
.splice(workerIndex
, 1)
211 this.tasks
.delete(worker
)
215 * Choose a worker for the next task.
217 * The default implementation uses a round robin algorithm to distribute the load.
221 protected chooseWorker (): Worker
{
222 const chosenWorker
= this.workers
[this.nextWorkerIndex
]
223 this.nextWorkerIndex
=
224 this.workers
.length
- 1 === this.nextWorkerIndex
226 : this.nextWorkerIndex
+ 1
231 * Send a message to the given worker.
233 * @param worker The worker which should receive the message.
234 * @param message The message.
236 protected abstract sendToWorker (
238 message
: MessageValue
<Data
>
241 protected abstract registerWorkerMessageListener
<
242 Message
extends Data
| Response
243 > (worker
: Worker
, listener
: (message
: MessageValue
<Message
>) => void): void
245 protected abstract unregisterWorkerMessageListener
<
246 Message
extends Data
| Response
247 > (worker
: Worker
, listener
: (message
: MessageValue
<Message
>) => void): void
249 protected internalExecute (
252 ): Promise
<Response
> {
253 return new Promise((resolve
, reject
) => {
254 const listener
: (message
: MessageValue
<Response
>) => void = message
=> {
255 if (message
.id
=== messageId
) {
256 this.unregisterWorkerMessageListener(worker
, listener
)
257 this.increaseWorkersTask(worker
)
258 if (message
.error
) reject(message
.error
)
259 else resolve(message
.data
as Response
)
262 this.registerWorkerMessageListener(worker
, listener
)
267 * Returns a newly created worker.
269 protected abstract createWorker (): Worker
272 * Function that can be hooked up when a worker has been newly created and moved to the workers registry.
274 * Can be used to update the `maxListeners` or binding the `main-worker`<->`worker` connection if not bind by default.
276 * @param worker The newly created worker.
278 protected abstract afterWorkerSetup (worker
: Worker
): void
281 * Creates a new worker for this pool and sets it up completely.
283 * @returns New, completely set up worker.
285 protected createAndSetupWorker (): Worker
{
286 const worker
: Worker
= this.createWorker()
288 worker
.on('error', this.opts
.errorHandler
?? (() => {}))
289 worker
.on('online', this.opts
.onlineHandler
?? (() => {}))
290 worker
.on('exit', this.opts
.exitHandler
?? (() => {}))
291 worker
.once('exit', () => this.removeWorker(worker
))
293 this.workers
.push(worker
)
296 this.tasks
.set(worker
, 0)
298 this.afterWorkerSetup(worker
)