Factor out worker tasks number in/de-crement. (#182)
[poolifier.git] / src / pools / abstract-pool.ts
CommitLineData
c97c7edb
S
1import EventEmitter from 'events'
2import type { MessageValue } from '../utility-types'
3import type { IPool } from './pool'
4
729c563d
S
5/**
6 * Callback invoked if the worker raised an error.
7 */
c97c7edb 8export type ErrorHandler<Worker> = (this: Worker, e: Error) => void
729c563d
S
9
10/**
11 * Callback invoked when the worker has started successfully.
12 */
c97c7edb 13export type OnlineHandler<Worker> = (this: Worker) => void
729c563d
S
14
15/**
16 * Callback invoked when the worker exits successfully.
17 */
c97c7edb
S
18export type ExitHandler<Worker> = (this: Worker, code: number) => void
19
729c563d
S
20/**
21 * Basic interface that describes the minimum required implementation of listener events for a pool-worker.
22 */
c97c7edb 23export interface IWorker {
3832ad95
S
24 /**
25 * Register a listener to the error event.
26 *
27 * @param event `'error'`.
28 * @param handler The error handler.
29 */
c97c7edb 30 on(event: 'error', handler: ErrorHandler<this>): void
3832ad95
S
31 /**
32 * Register a listener to the online event.
33 *
34 * @param event `'online'`.
35 * @param handler The online handler.
36 */
c97c7edb 37 on(event: 'online', handler: OnlineHandler<this>): void
3832ad95
S
38 /**
39 * Register a listener to the exit event.
40 *
41 * @param event `'exit'`.
42 * @param handler The exit handler.
43 */
c97c7edb 44 on(event: 'exit', handler: ExitHandler<this>): void
3832ad95
S
45 /**
46 * Register a listener to the exit event that will only performed once.
47 *
48 * @param event `'exit'`.
49 * @param handler The exit handler.
50 */
45dbbb14 51 once(event: 'exit', handler: ExitHandler<this>): void
c97c7edb
S
52}
53
729c563d
S
54/**
55 * Options for a poolifier pool.
56 */
c97c7edb
S
57export interface PoolOptions<Worker> {
58 /**
59 * A function that will listen for error event on each worker.
60 */
61 errorHandler?: ErrorHandler<Worker>
62 /**
63 * A function that will listen for online event on each worker.
64 */
65 onlineHandler?: OnlineHandler<Worker>
66 /**
67 * A function that will listen for exit event on each worker.
68 */
69 exitHandler?: ExitHandler<Worker>
70 /**
729c563d
S
71 * This is just to avoid non-useful warning messages.
72 *
73 * Will be used to set `maxListeners` on event emitters (workers are event emitters).
c97c7edb
S
74 *
75 * @default 1000
729c563d 76 * @see [Node events emitter.setMaxListeners(n)](https://nodejs.org/api/events.html#events_emitter_setmaxlisteners_n)
c97c7edb
S
77 */
78 maxTasks?: number
79}
80
729c563d
S
81/**
82 * Internal poolifier pool emitter.
83 */
c97c7edb
S
84class PoolEmitter extends EventEmitter {}
85
729c563d
S
86/**
87 * Base class containing some shared logic for all poolifier pools.
88 *
89 * @template Worker Type of worker which manages this pool.
90 * @template Data Type of data sent to the worker.
91 * @template Response Type of response of execution.
92 */
c97c7edb
S
93export abstract class AbstractPool<
94 Worker extends IWorker,
d3c8a1a8
S
95 Data = unknown,
96 Response = unknown
c97c7edb 97> implements IPool<Data, Response> {
729c563d
S
98 /**
99 * List of currently available workers.
100 */
c97c7edb 101 public readonly workers: Worker[] = []
729c563d
S
102
103 /**
280c2a77 104 * Index for the next worker.
729c563d 105 */
280c2a77 106 public nextWorkerIndex: number = 0
c97c7edb
S
107
108 /**
3832ad95
S
109 * The tasks map.
110 *
729c563d 111 * - `key`: The `Worker`
c01733f1 112 * - `value`: Number of tasks currently in progress on the worker.
c97c7edb
S
113 */
114 public readonly tasks: Map<Worker, number> = new Map<Worker, number>()
115
729c563d
S
116 /**
117 * Emitter on which events can be listened to.
118 *
119 * Events that can currently be listened to:
120 *
121 * - `'FullPool'`
122 */
c97c7edb
S
123 public readonly emitter: PoolEmitter
124
729c563d
S
125 /**
126 * ID of the next message.
127 */
280c2a77 128 protected nextMessageId: number = 0
c97c7edb 129
729c563d
S
130 /**
131 * Constructs a new poolifier pool.
132 *
5c5a1fb7 133 * @param numberOfWorkers Number of workers that this pool should manage.
729c563d
S
134 * @param filePath Path to the worker-file.
135 * @param opts Options for the pool. Default: `{ maxTasks: 1000 }`
136 */
c97c7edb 137 public constructor (
5c5a1fb7 138 public readonly numberOfWorkers: number,
c97c7edb
S
139 public readonly filePath: string,
140 public readonly opts: PoolOptions<Worker> = { maxTasks: 1000 }
141 ) {
142 if (!this.isMain()) {
143 throw new Error('Cannot start a pool from a worker!')
144 }
145 // TODO christopher 2021-02-07: Improve this check e.g. with a pattern or blank check
146 if (!this.filePath) {
147 throw new Error('Please specify a file with a worker implementation')
148 }
c97c7edb
S
149 this.setupHook()
150
5c5a1fb7 151 for (let i = 1; i <= this.numberOfWorkers; i++) {
280c2a77 152 this.createAndSetupWorker()
c97c7edb
S
153 }
154
155 this.emitter = new PoolEmitter()
156 }
157
3832ad95
S
158 /**
159 * Perform the task specified in the constructor with the data parameter.
160 *
161 * @param data The input for the specified task.
162 * @returns Promise that will be resolved when the task is successfully completed.
163 */
280c2a77
S
164 public execute (data: Data): Promise<Response> {
165 // Configure worker to handle message with the specified task
166 const worker = this.chooseWorker()
167 this.increaseWorkersTask(worker)
168 const messageId = ++this.nextMessageId
169 const res = this.internalExecute(worker, messageId)
170 this.sendToWorker(worker, { data: data || ({} as Data), id: messageId })
171 return res
172 }
c97c7edb 173
3832ad95
S
174 /**
175 * Shut down every current worker in this pool.
176 */
c97c7edb 177 public async destroy (): Promise<void> {
45dbbb14 178 await Promise.all(this.workers.map(worker => this.destroyWorker(worker)))
c97c7edb
S
179 }
180
729c563d
S
181 /**
182 * Shut down given worker.
183 *
184 * @param worker A worker within `workers`.
185 */
c97c7edb
S
186 protected abstract destroyWorker (worker: Worker): void | Promise<void>
187
729c563d 188 /**
280c2a77
S
189 * Setup hook that can be overridden by a Poolifier pool implementation
190 * to run code before workers are created in the abstract constructor.
729c563d 191 */
280c2a77
S
192 protected setupHook (): void {
193 // Can be overridden
194 }
c97c7edb 195
729c563d 196 /**
280c2a77
S
197 * Should return whether the worker is the main worker or not.
198 */
199 protected abstract isMain (): boolean
200
201 /**
202 * Increase the number of tasks that the given workers has done.
729c563d 203 *
f416c098 204 * @param worker Worker whose tasks are increased.
729c563d 205 */
280c2a77 206 protected increaseWorkersTask (worker: Worker): void {
f416c098 207 this.stepWorkerNumberOfTasks(worker, 1)
c97c7edb
S
208 }
209
c01733f1 210 /**
d63d3be3 211 * Decrease the number of tasks that the given workers has done.
c01733f1 212 *
f416c098 213 * @param worker Worker whose tasks are decreased.
c01733f1 214 */
215 protected decreaseWorkersTasks (worker: Worker): void {
f416c098
JB
216 this.stepWorkerNumberOfTasks(worker, -1)
217 }
218
219 /**
220 * Step the number of tasks that the given workers has done.
221 *
222 * @param worker Worker whose tasks are set.
223 * @param step Worker number of tasks step.
224 */
225 private stepWorkerNumberOfTasks (worker: Worker, step: number) {
d63d3be3 226 const numberOfTasksInProgress = this.tasks.get(worker)
227 if (numberOfTasksInProgress !== undefined) {
f416c098 228 this.tasks.set(worker, numberOfTasksInProgress + step)
c01733f1 229 } else {
230 throw Error('Worker could not be found in tasks map')
231 }
232 }
233
729c563d
S
234 /**
235 * Removes the given worker from the pool.
236 *
237 * @param worker Worker that will be removed.
238 */
f2fdaa86
JB
239 protected removeWorker (worker: Worker): void {
240 // Clean worker from data structure
241 const workerIndex = this.workers.indexOf(worker)
242 this.workers.splice(workerIndex, 1)
243 this.tasks.delete(worker)
244 }
245
280c2a77
S
246 /**
247 * Choose a worker for the next task.
248 *
249 * The default implementation uses a round robin algorithm to distribute the load.
250 *
251 * @returns Worker.
252 */
253 protected chooseWorker (): Worker {
254 const chosenWorker = this.workers[this.nextWorkerIndex]
aacd8188
S
255 this.nextWorkerIndex =
256 this.workers.length - 1 === this.nextWorkerIndex
257 ? 0
258 : this.nextWorkerIndex + 1
280c2a77 259 return chosenWorker
c97c7edb
S
260 }
261
280c2a77
S
262 /**
263 * Send a message to the given worker.
264 *
265 * @param worker The worker which should receive the message.
266 * @param message The message.
267 */
268 protected abstract sendToWorker (
269 worker: Worker,
270 message: MessageValue<Data>
271 ): void
272
4f7fa42a
S
273 protected abstract registerWorkerMessageListener<
274 Message extends Data | Response
275 > (worker: Worker, listener: (message: MessageValue<Message>) => void): void
c97c7edb 276
4f7fa42a
S
277 protected abstract unregisterWorkerMessageListener<
278 Message extends Data | Response
279 > (worker: Worker, listener: (message: MessageValue<Message>) => void): void
c97c7edb 280
280c2a77
S
281 protected internalExecute (
282 worker: Worker,
283 messageId: number
284 ): Promise<Response> {
c97c7edb
S
285 return new Promise((resolve, reject) => {
286 const listener: (message: MessageValue<Response>) => void = message => {
280c2a77 287 if (message.id === messageId) {
c97c7edb 288 this.unregisterWorkerMessageListener(worker, listener)
c01733f1 289 this.decreaseWorkersTasks(worker)
c97c7edb
S
290 if (message.error) reject(message.error)
291 else resolve(message.data as Response)
292 }
293 }
294 this.registerWorkerMessageListener(worker, listener)
295 })
296 }
297
729c563d
S
298 /**
299 * Returns a newly created worker.
300 */
280c2a77 301 protected abstract createWorker (): Worker
c97c7edb 302
729c563d
S
303 /**
304 * Function that can be hooked up when a worker has been newly created and moved to the workers registry.
305 *
306 * Can be used to update the `maxListeners` or binding the `main-worker`<->`worker` connection if not bind by default.
307 *
308 * @param worker The newly created worker.
309 */
280c2a77 310 protected abstract afterWorkerSetup (worker: Worker): void
c97c7edb 311
729c563d
S
312 /**
313 * Creates a new worker for this pool and sets it up completely.
50eceb07
S
314 *
315 * @returns New, completely set up worker.
729c563d 316 */
280c2a77
S
317 protected createAndSetupWorker (): Worker {
318 const worker: Worker = this.createWorker()
319
c97c7edb
S
320 worker.on('error', this.opts.errorHandler ?? (() => {}))
321 worker.on('online', this.opts.onlineHandler ?? (() => {}))
c97c7edb 322 worker.on('exit', this.opts.exitHandler ?? (() => {}))
45dbbb14 323 worker.once('exit', () => this.removeWorker(worker))
280c2a77 324
c97c7edb 325 this.workers.push(worker)
280c2a77
S
326
327 // Init tasks map
c97c7edb 328 this.tasks.set(worker, 0)
280c2a77
S
329
330 this.afterWorkerSetup(worker)
331
c97c7edb
S
332 return worker
333 }
334}