Add eslint-plugin-jsdoc (#142)
[poolifier.git] / src / pools / abstract-pool.ts
1 import EventEmitter from 'events'
2 import type { MessageValue } from '../utility-types'
3 import type { IPool } from './pool'
4
5 /**
6 * Callback invoked if the worker raised an error.
7 */
8 export type ErrorHandler<Worker> = (this: Worker, e: Error) => void
9
10 /**
11 * Callback invoked when the worker has started successfully.
12 */
13 export type OnlineHandler<Worker> = (this: Worker) => void
14
15 /**
16 * Callback invoked when the worker exits successfully.
17 */
18 export type ExitHandler<Worker> = (this: Worker, code: number) => void
19
20 /**
21 * Basic interface that describes the minimum required implementation of listener events for a pool-worker.
22 */
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 }
28
29 /**
30 * Options for a poolifier pool.
31 */
32 export interface PoolOptions<Worker> {
33 /**
34 * A function that will listen for error event on each worker.
35 */
36 errorHandler?: ErrorHandler<Worker>
37 /**
38 * A function that will listen for online event on each worker.
39 */
40 onlineHandler?: OnlineHandler<Worker>
41 /**
42 * A function that will listen for exit event on each worker.
43 */
44 exitHandler?: ExitHandler<Worker>
45 /**
46 * This is just to avoid non-useful warning messages.
47 *
48 * Will be used to set `maxListeners` on event emitters (workers are event emitters).
49 *
50 * @default 1000
51 * @see [Node events emitter.setMaxListeners(n)](https://nodejs.org/api/events.html#events_emitter_setmaxlisteners_n)
52 */
53 maxTasks?: number
54 }
55
56 /**
57 * Internal poolifier pool emitter.
58 */
59 class PoolEmitter extends EventEmitter {}
60
61 /**
62 * Base class containing some shared logic for all poolifier pools.
63 *
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.
67 */
68 export abstract class AbstractPool<
69 Worker extends IWorker,
70 Data = unknown,
71 Response = unknown
72 > implements IPool<Data, Response> {
73 /**
74 * List of currently available workers.
75 */
76 public readonly workers: Worker[] = []
77
78 /**
79 * ID for the next worker.
80 */
81 public nextWorker: number = 0
82
83 /**
84 * - `key`: The `Worker`
85 * - `value`: Number of tasks that has been assigned to that worker since it started
86 */
87 public readonly tasks: Map<Worker, number> = new Map<Worker, number>()
88
89 /**
90 * Emitter on which events can be listened to.
91 *
92 * Events that can currently be listened to:
93 *
94 * - `'FullPool'`
95 */
96 public readonly emitter: PoolEmitter
97
98 /**
99 * ID of the next message.
100 */
101 protected id: number = 0
102
103 /**
104 * Constructs a new poolifier pool.
105 *
106 * @param numWorkers 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 }`
109 */
110 public constructor (
111 public readonly numWorkers: number,
112 public readonly filePath: string,
113 public readonly opts: PoolOptions<Worker> = { maxTasks: 1000 }
114 ) {
115 if (!this.isMain()) {
116 throw new Error('Cannot start a pool from a worker!')
117 }
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')
121 }
122
123 this.setupHook()
124
125 for (let i = 1; i <= this.numWorkers; i++) {
126 this.internalNewWorker()
127 }
128
129 this.emitter = new PoolEmitter()
130 }
131
132 /**
133 * Setup hook that can be overridden by a Poolifer pool implementation
134 * to run code before workers are created in the abstract constructor.
135 */
136 protected setupHook (): void {
137 // Can be overridden
138 }
139
140 /**
141 * Should return whether the worker is the main worker or not.
142 */
143 protected abstract isMain (): boolean
144
145 public async destroy (): Promise<void> {
146 for (const worker of this.workers) {
147 await this.destroyWorker(worker)
148 }
149 }
150
151 /**
152 * Shut down given worker.
153 *
154 * @param worker A worker within `workers`.
155 */
156 protected abstract destroyWorker (worker: Worker): void | Promise<void>
157
158 /**
159 * Send a message to the given worker.
160 *
161 * @param worker The worker which should receive the message.
162 * @param message The message.
163 */
164 protected abstract sendToWorker (
165 worker: Worker,
166 message: MessageValue<Data>
167 ): void
168
169 /**
170 * Adds the given worker to the pool.
171 *
172 * @param worker Worker that will be added.
173 */
174 protected addWorker (worker: Worker): void {
175 const previousWorkerIndex = this.tasks.get(worker)
176 if (previousWorkerIndex !== undefined) {
177 this.tasks.set(worker, previousWorkerIndex + 1)
178 } else {
179 throw Error('Worker could not be found in tasks map')
180 }
181 }
182
183 /**
184 * Removes the given worker from the pool.
185 *
186 * @param worker Worker that will be removed.
187 */
188 protected removeWorker (worker: Worker): void {
189 // Clean worker from data structure
190 const workerIndex = this.workers.indexOf(worker)
191 this.workers.splice(workerIndex, 1)
192 this.tasks.delete(worker)
193 }
194
195 public execute (data: Data): Promise<Response> {
196 // Configure worker to handle message with the specified task
197 const worker = this.chooseWorker()
198 this.addWorker(worker)
199 const id = ++this.id
200 const res = this.internalExecute(worker, id)
201 this.sendToWorker(worker, { data: data || ({} as Data), id: id })
202 return res
203 }
204
205 protected abstract registerWorkerMessageListener (
206 port: Worker,
207 listener: (message: MessageValue<Response>) => void
208 ): void
209
210 protected abstract unregisterWorkerMessageListener (
211 port: Worker,
212 listener: (message: MessageValue<Response>) => void
213 ): void
214
215 protected internalExecute (worker: Worker, id: number): Promise<Response> {
216 return new Promise((resolve, reject) => {
217 const listener: (message: MessageValue<Response>) => void = message => {
218 if (message.id === id) {
219 this.unregisterWorkerMessageListener(worker, listener)
220 this.addWorker(worker)
221 if (message.error) reject(message.error)
222 else resolve(message.data as Response)
223 }
224 }
225 this.registerWorkerMessageListener(worker, listener)
226 })
227 }
228
229 /**
230 * Choose a worker for the next task.
231 *
232 * The default implementation uses a round robin algorithm to distribute the load.
233 *
234 * @returns Worker.
235 */
236 protected chooseWorker (): Worker {
237 this.nextWorker =
238 this.nextWorker === this.workers.length - 1 ? 0 : this.nextWorker + 1
239 return this.workers[this.nextWorker]
240 }
241
242 /**
243 * Returns a newly created worker.
244 */
245 protected abstract newWorker (): Worker
246
247 /**
248 * Function that can be hooked up when a worker has been newly created and moved to the workers registry.
249 *
250 * Can be used to update the `maxListeners` or binding the `main-worker`<->`worker` connection if not bind by default.
251 *
252 * @param worker The newly created worker.
253 */
254 protected abstract afterNewWorkerPushed (worker: Worker): void
255
256 /**
257 * Creates a new worker for this pool and sets it up completely.
258 *
259 * @returns New, completely set up worker.
260 */
261 protected internalNewWorker (): Worker {
262 const worker: Worker = this.newWorker()
263 worker.on('error', this.opts.errorHandler ?? (() => {}))
264 worker.on('online', this.opts.onlineHandler ?? (() => {}))
265 // TODO handle properly when a worker exit
266 worker.on('exit', this.opts.exitHandler ?? (() => {}))
267 this.workers.push(worker)
268 this.afterNewWorkerPushed(worker)
269 // init tasks map
270 this.tasks.set(worker, 0)
271 return worker
272 }
273 }