c1e6ddc09a9a41ce18d34ced63a162225f66818f
[poolifier.git] / src / pools / abstract-pool.ts
1 import crypto from 'node:crypto'
2 import type { MessageValue, PromiseResponseWrapper } from '../utility-types'
3 import { EMPTY_FUNCTION } from '../utils'
4 import { KillBehaviors, isKillBehavior } from '../worker/worker-options'
5 import type { PoolOptions } from './pool'
6 import { PoolEmitter } from './pool'
7 import type { IPoolInternal, TasksUsage, WorkerType } from './pool-internal'
8 import { PoolType } from './pool-internal'
9 import type { IPoolWorker } from './pool-worker'
10 import {
11 WorkerChoiceStrategies,
12 type WorkerChoiceStrategy
13 } from './selection-strategies/selection-strategies-types'
14 import { WorkerChoiceStrategyContext } from './selection-strategies/worker-choice-strategy-context'
15
16 /**
17 * Base class that implements some shared logic for all poolifier pools.
18 *
19 * @typeParam Worker - Type of worker which manages this pool.
20 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
21 * @typeParam Response - Type of response of execution. This can only be serializable data.
22 */
23 export abstract class AbstractPool<
24 Worker extends IPoolWorker,
25 Data = unknown,
26 Response = unknown
27 > implements IPoolInternal<Worker, Data, Response> {
28 /** {@inheritDoc} */
29 public readonly workers: Array<WorkerType<Worker>> = []
30
31 /** {@inheritDoc} */
32 public readonly emitter?: PoolEmitter
33
34 /**
35 * The promise response map.
36 *
37 * - `key`: The message id of each submitted task.
38 * - `value`: An object that contains the worker, the promise resolve and reject callbacks.
39 *
40 * When we receive a message from the worker we get a map entry with the promise resolve/reject bound to the message.
41 */
42 protected promiseResponseMap: Map<
43 string,
44 PromiseResponseWrapper<Worker, Response>
45 > = new Map<string, PromiseResponseWrapper<Worker, Response>>()
46
47 /**
48 * Worker choice strategy instance implementing the worker choice algorithm.
49 *
50 * Default to a strategy implementing a round robin algorithm.
51 */
52 protected workerChoiceStrategyContext: WorkerChoiceStrategyContext<
53 Worker,
54 Data,
55 Response
56 >
57
58 /**
59 * Constructs a new poolifier pool.
60 *
61 * @param numberOfWorkers - Number of workers that this pool should manage.
62 * @param filePath - Path to the worker-file.
63 * @param opts - Options for the pool.
64 */
65 public constructor (
66 public readonly numberOfWorkers: number,
67 public readonly filePath: string,
68 public readonly opts: PoolOptions<Worker>
69 ) {
70 if (!this.isMain()) {
71 throw new Error('Cannot start a pool from a worker!')
72 }
73 this.checkNumberOfWorkers(this.numberOfWorkers)
74 this.checkFilePath(this.filePath)
75 this.checkPoolOptions(this.opts)
76
77 this.chooseWorker.bind(this)
78 this.internalExecute.bind(this)
79 this.checkAndEmitBusy.bind(this)
80 this.sendToWorker.bind(this)
81
82 this.setupHook()
83
84 for (let i = 1; i <= this.numberOfWorkers; i++) {
85 this.createAndSetupWorker()
86 }
87
88 if (this.opts.enableEvents === true) {
89 this.emitter = new PoolEmitter()
90 }
91 this.workerChoiceStrategyContext = new WorkerChoiceStrategyContext<
92 Worker,
93 Data,
94 Response
95 >(
96 this,
97 () => {
98 const createdWorker = this.createAndSetupWorker()
99 this.registerWorkerMessageListener(createdWorker, message => {
100 if (
101 isKillBehavior(KillBehaviors.HARD, message.kill) ||
102 this.getWorkerTasksUsage(createdWorker)?.running === 0
103 ) {
104 // Kill received from the worker, means that no new tasks are submitted to that worker for a while ( > maxInactiveTime)
105 void this.destroyWorker(createdWorker)
106 }
107 })
108 return this.getWorkerKey(createdWorker)
109 },
110 this.opts.workerChoiceStrategy
111 )
112 }
113
114 private checkFilePath (filePath: string): void {
115 if (
116 filePath == null ||
117 (typeof filePath === 'string' && filePath.trim().length === 0)
118 ) {
119 throw new Error('Please specify a file with a worker implementation')
120 }
121 }
122
123 private checkNumberOfWorkers (numberOfWorkers: number): void {
124 if (numberOfWorkers == null) {
125 throw new Error(
126 'Cannot instantiate a pool without specifying the number of workers'
127 )
128 } else if (!Number.isSafeInteger(numberOfWorkers)) {
129 throw new TypeError(
130 'Cannot instantiate a pool with a non integer number of workers'
131 )
132 } else if (numberOfWorkers < 0) {
133 throw new RangeError(
134 'Cannot instantiate a pool with a negative number of workers'
135 )
136 } else if (this.type === PoolType.FIXED && numberOfWorkers === 0) {
137 throw new Error('Cannot instantiate a fixed pool with no worker')
138 }
139 }
140
141 private checkPoolOptions (opts: PoolOptions<Worker>): void {
142 this.opts.workerChoiceStrategy =
143 opts.workerChoiceStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN
144 this.opts.enableEvents = opts.enableEvents ?? true
145 }
146
147 /** {@inheritDoc} */
148 public abstract get type (): PoolType
149
150 /**
151 * Number of tasks concurrently running.
152 */
153 private get numberOfRunningTasks (): number {
154 return this.promiseResponseMap.size
155 }
156
157 /**
158 * Gets the given worker key.
159 *
160 * @param worker - The worker.
161 * @returns The worker key if the worker is found in the pool, `-1` otherwise.
162 */
163 private getWorkerKey (worker: Worker): number {
164 return this.workers.findIndex(workerItem => workerItem.worker === worker)
165 }
166
167 /** {@inheritDoc} */
168 public setWorkerChoiceStrategy (
169 workerChoiceStrategy: WorkerChoiceStrategy
170 ): void {
171 this.opts.workerChoiceStrategy = workerChoiceStrategy
172 for (const [index, workerItem] of this.workers.entries()) {
173 this.setWorker(index, workerItem.worker, {
174 run: 0,
175 running: 0,
176 runTime: 0,
177 avgRunTime: 0,
178 error: 0
179 })
180 }
181 this.workerChoiceStrategyContext.setWorkerChoiceStrategy(
182 this,
183 workerChoiceStrategy
184 )
185 }
186
187 /** {@inheritDoc} */
188 public abstract get full (): boolean
189
190 /** {@inheritDoc} */
191 public abstract get busy (): boolean
192
193 protected internalBusy (): boolean {
194 return (
195 this.numberOfRunningTasks >= this.numberOfWorkers &&
196 this.findFreeWorkerKey() === -1
197 )
198 }
199
200 /** {@inheritDoc} */
201 public findFreeWorkerKey (): number {
202 return this.workers.findIndex(workerItem => {
203 return workerItem.tasksUsage.running === 0
204 })
205 }
206
207 /** {@inheritDoc} */
208 public async execute (data: Data): Promise<Response> {
209 const [workerKey, worker] = this.chooseWorker()
210 const messageId = crypto.randomUUID()
211 const res = this.internalExecute(workerKey, worker, messageId)
212 this.checkAndEmitBusy()
213 this.sendToWorker(worker, {
214 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
215 data: data ?? ({} as Data),
216 id: messageId
217 })
218 // eslint-disable-next-line @typescript-eslint/return-await
219 return res
220 }
221
222 /** {@inheritDoc} */
223 public async destroy (): Promise<void> {
224 await Promise.all(
225 this.workers.map(async workerItem => {
226 await this.destroyWorker(workerItem.worker)
227 })
228 )
229 }
230
231 /**
232 * Shutdowns given worker.
233 *
234 * @param worker - A worker within `workers`.
235 */
236 protected abstract destroyWorker (worker: Worker): void | Promise<void>
237
238 /**
239 * Setup hook that can be overridden by a Poolifier pool implementation
240 * to run code before workers are created in the abstract constructor.
241 */
242 protected setupHook (): void {
243 // Can be overridden
244 }
245
246 /**
247 * Should return whether the worker is the main worker or not.
248 */
249 protected abstract isMain (): boolean
250
251 /**
252 * Hook executed before the worker task promise resolution.
253 * Can be overridden.
254 *
255 * @param workerKey - The worker key.
256 */
257 protected beforePromiseResponseHook (workerKey: number): void {
258 ++this.workers[workerKey].tasksUsage.running
259 }
260
261 /**
262 * Hook executed after the worker task promise resolution.
263 * Can be overridden.
264 *
265 * @param worker - The worker.
266 * @param message - The received message.
267 */
268 protected afterPromiseResponseHook (
269 worker: Worker,
270 message: MessageValue<Response>
271 ): void {
272 const workerTasksUsage = this.getWorkerTasksUsage(worker) as TasksUsage
273 --workerTasksUsage.running
274 ++workerTasksUsage.run
275 if (message.error != null) {
276 ++workerTasksUsage.error
277 }
278 if (this.workerChoiceStrategyContext.getRequiredStatistics().runTime) {
279 workerTasksUsage.runTime += message.taskRunTime ?? 0
280 if (
281 this.workerChoiceStrategyContext.getRequiredStatistics().avgRunTime &&
282 workerTasksUsage.run !== 0
283 ) {
284 workerTasksUsage.avgRunTime =
285 workerTasksUsage.runTime / workerTasksUsage.run
286 }
287 }
288 }
289
290 /**
291 * Removes the given worker from the pool.
292 *
293 * @param worker - The worker that will be removed.
294 */
295 protected removeWorker (worker: Worker): void {
296 const workerKey = this.getWorkerKey(worker)
297 this.workers.splice(workerKey, 1)
298 this.workerChoiceStrategyContext.remove(workerKey)
299 }
300
301 /**
302 * Chooses a worker for the next task.
303 *
304 * The default implementation uses a round robin algorithm to distribute the load.
305 *
306 * @returns [worker key, worker].
307 */
308 protected chooseWorker (): [number, Worker] {
309 const workerKey = this.workerChoiceStrategyContext.execute()
310 return [workerKey, this.workers[workerKey].worker]
311 }
312
313 /**
314 * Sends a message to the given worker.
315 *
316 * @param worker - The worker which should receive the message.
317 * @param message - The message.
318 */
319 protected abstract sendToWorker (
320 worker: Worker,
321 message: MessageValue<Data>
322 ): void
323
324 /**
325 * Registers a listener callback on a given worker.
326 *
327 * @param worker - The worker which should register a listener.
328 * @param listener - The message listener callback.
329 */
330 protected abstract registerWorkerMessageListener<
331 Message extends Data | Response
332 >(worker: Worker, listener: (message: MessageValue<Message>) => void): void
333
334 /**
335 * Returns a newly created worker.
336 */
337 protected abstract createWorker (): Worker
338
339 /**
340 * Function that can be hooked up when a worker has been newly created and moved to the workers registry.
341 *
342 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
343 *
344 * @param worker - The newly created worker.
345 */
346 protected abstract afterWorkerSetup (worker: Worker): void
347
348 /**
349 * Creates a new worker for this pool and sets it up completely.
350 *
351 * @returns New, completely set up worker.
352 */
353 protected createAndSetupWorker (): Worker {
354 const worker = this.createWorker()
355
356 worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION)
357 worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION)
358 worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION)
359 worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION)
360 worker.once('exit', () => {
361 this.removeWorker(worker)
362 })
363
364 this.pushWorker(worker, {
365 run: 0,
366 running: 0,
367 runTime: 0,
368 avgRunTime: 0,
369 error: 0
370 })
371
372 this.afterWorkerSetup(worker)
373
374 return worker
375 }
376
377 /**
378 * This function is the listener registered for each worker.
379 *
380 * @returns The listener function to execute when a message is received from a worker.
381 */
382 protected workerListener (): (message: MessageValue<Response>) => void {
383 return message => {
384 if (message.id !== undefined) {
385 const promiseResponse = this.promiseResponseMap.get(message.id)
386 if (promiseResponse !== undefined) {
387 if (message.error != null) {
388 promiseResponse.reject(message.error)
389 } else {
390 promiseResponse.resolve(message.data as Response)
391 }
392 this.afterPromiseResponseHook(promiseResponse.worker, message)
393 this.promiseResponseMap.delete(message.id)
394 }
395 }
396 }
397 }
398
399 private async internalExecute (
400 workerKey: number,
401 worker: Worker,
402 messageId: string
403 ): Promise<Response> {
404 this.beforePromiseResponseHook(workerKey)
405 return await new Promise<Response>((resolve, reject) => {
406 this.promiseResponseMap.set(messageId, { resolve, reject, worker })
407 })
408 }
409
410 private checkAndEmitBusy (): void {
411 if (this.opts.enableEvents === true && this.busy) {
412 this.emitter?.emit('busy')
413 }
414 }
415
416 /**
417 * Gets worker tasks usage.
418 *
419 * @param worker - The worker.
420 * @returns The worker tasks usage.
421 */
422 private getWorkerTasksUsage (worker: Worker): TasksUsage | undefined {
423 const workerKey = this.getWorkerKey(worker)
424 if (workerKey !== -1) {
425 return this.workers[workerKey].tasksUsage
426 }
427 throw new Error('Worker could not be found in the pool')
428 }
429
430 /**
431 * Pushes the given worker.
432 *
433 * @param worker - The worker.
434 * @param tasksUsage - The worker tasks usage.
435 */
436 private pushWorker (worker: Worker, tasksUsage: TasksUsage): void {
437 this.workers.push({
438 worker,
439 tasksUsage
440 })
441 }
442
443 /**
444 * Sets the given worker.
445 *
446 * @param workerKey - The worker key.
447 * @param worker - The worker.
448 * @param tasksUsage - The worker tasks usage.
449 */
450 private setWorker (
451 workerKey: number,
452 worker: Worker,
453 tasksUsage: TasksUsage
454 ): void {
455 this.workers[workerKey] = {
456 worker,
457 tasksUsage
458 }
459 }
460 }