fix: fix TS type definitions
[poolifier.git] / src / pools / abstract-pool.ts
1 import crypto from 'node:crypto'
2 import type { MessageValue, PromiseResponseWrapper } from '../utility-types'
3 import {
4 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS,
5 EMPTY_FUNCTION,
6 median
7 } from '../utils'
8 import { KillBehaviors, isKillBehavior } from '../worker/worker-options'
9 import {
10 PoolEvents,
11 type IPool,
12 type PoolOptions,
13 type TasksQueueOptions,
14 PoolType
15 } from './pool'
16 import { PoolEmitter } from './pool'
17 import type { IWorker, Task, TasksUsage, WorkerNode } from './worker'
18 import {
19 WorkerChoiceStrategies,
20 type WorkerChoiceStrategy,
21 type WorkerChoiceStrategyOptions
22 } from './selection-strategies/selection-strategies-types'
23 import { WorkerChoiceStrategyContext } from './selection-strategies/worker-choice-strategy-context'
24 import { CircularArray } from '../circular-array'
25
26 /**
27 * Base class that implements some shared logic for all poolifier pools.
28 *
29 * @typeParam Worker - Type of worker which manages this pool.
30 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
31 * @typeParam Response - Type of execution response. This can only be serializable data.
32 */
33 export abstract class AbstractPool<
34 Worker extends IWorker,
35 Data = unknown,
36 Response = unknown
37 > implements IPool<Worker, Data, Response> {
38 /** @inheritDoc */
39 public readonly workerNodes: Array<WorkerNode<Worker, Data>> = []
40
41 /** @inheritDoc */
42 public readonly emitter?: PoolEmitter
43
44 /**
45 * The execution response promise map.
46 *
47 * - `key`: The message id of each submitted task.
48 * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks.
49 *
50 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
51 */
52 protected promiseResponseMap: Map<
53 string,
54 PromiseResponseWrapper<Worker, Response>
55 > = new Map<string, PromiseResponseWrapper<Worker, Response>>()
56
57 /**
58 * Worker choice strategy context referencing a worker choice algorithm implementation.
59 *
60 * Default to a round robin algorithm.
61 */
62 protected workerChoiceStrategyContext: WorkerChoiceStrategyContext<
63 Worker,
64 Data,
65 Response
66 >
67
68 /**
69 * Constructs a new poolifier pool.
70 *
71 * @param numberOfWorkers - Number of workers that this pool should manage.
72 * @param filePath - Path to the worker file.
73 * @param opts - Options for the pool.
74 */
75 public constructor (
76 public readonly numberOfWorkers: number,
77 public readonly filePath: string,
78 public readonly opts: PoolOptions<Worker>
79 ) {
80 if (!this.isMain()) {
81 throw new Error('Cannot start a pool from a worker!')
82 }
83 this.checkNumberOfWorkers(this.numberOfWorkers)
84 this.checkFilePath(this.filePath)
85 this.checkPoolOptions(this.opts)
86
87 this.chooseWorkerNode.bind(this)
88 this.executeTask.bind(this)
89 this.enqueueTask.bind(this)
90 this.checkAndEmitEvents.bind(this)
91
92 this.setupHook()
93
94 for (let i = 1; i <= this.numberOfWorkers; i++) {
95 this.createAndSetupWorker()
96 }
97
98 if (this.opts.enableEvents === true) {
99 this.emitter = new PoolEmitter()
100 }
101 this.workerChoiceStrategyContext = new WorkerChoiceStrategyContext<
102 Worker,
103 Data,
104 Response
105 >(
106 this,
107 this.opts.workerChoiceStrategy,
108 this.opts.workerChoiceStrategyOptions
109 )
110 }
111
112 private checkFilePath (filePath: string): void {
113 if (
114 filePath == null ||
115 (typeof filePath === 'string' && filePath.trim().length === 0)
116 ) {
117 throw new Error('Please specify a file with a worker implementation')
118 }
119 }
120
121 private checkNumberOfWorkers (numberOfWorkers: number): void {
122 if (numberOfWorkers == null) {
123 throw new Error(
124 'Cannot instantiate a pool without specifying the number of workers'
125 )
126 } else if (!Number.isSafeInteger(numberOfWorkers)) {
127 throw new TypeError(
128 'Cannot instantiate a pool with a non integer number of workers'
129 )
130 } else if (numberOfWorkers < 0) {
131 throw new RangeError(
132 'Cannot instantiate a pool with a negative number of workers'
133 )
134 } else if (this.type === PoolType.FIXED && numberOfWorkers === 0) {
135 throw new Error('Cannot instantiate a fixed pool with no worker')
136 }
137 }
138
139 private checkPoolOptions (opts: PoolOptions<Worker>): void {
140 this.opts.workerChoiceStrategy =
141 opts.workerChoiceStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN
142 this.checkValidWorkerChoiceStrategy(this.opts.workerChoiceStrategy)
143 this.opts.workerChoiceStrategyOptions =
144 opts.workerChoiceStrategyOptions ?? DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
145 this.opts.enableEvents = opts.enableEvents ?? true
146 this.opts.enableTasksQueue = opts.enableTasksQueue ?? false
147 if (this.opts.enableTasksQueue) {
148 this.checkValidTasksQueueOptions(
149 opts.tasksQueueOptions as TasksQueueOptions
150 )
151 this.opts.tasksQueueOptions = this.buildTasksQueueOptions(
152 opts.tasksQueueOptions as TasksQueueOptions
153 )
154 }
155 }
156
157 private checkValidWorkerChoiceStrategy (
158 workerChoiceStrategy: WorkerChoiceStrategy
159 ): void {
160 if (!Object.values(WorkerChoiceStrategies).includes(workerChoiceStrategy)) {
161 throw new Error(
162 `Invalid worker choice strategy '${workerChoiceStrategy}'`
163 )
164 }
165 }
166
167 private checkValidTasksQueueOptions (
168 tasksQueueOptions: TasksQueueOptions
169 ): void {
170 if ((tasksQueueOptions?.concurrency as number) <= 0) {
171 throw new Error(
172 `Invalid worker tasks concurrency '${
173 tasksQueueOptions.concurrency as number
174 }'`
175 )
176 }
177 }
178
179 /** @inheritDoc */
180 public abstract get type (): PoolType
181
182 /**
183 * Number of tasks running in the pool.
184 */
185 private get numberOfRunningTasks (): number {
186 return this.workerNodes.reduce(
187 (accumulator, workerNode) => accumulator + workerNode.tasksUsage.running,
188 0
189 )
190 }
191
192 /**
193 * Number of tasks queued in the pool.
194 */
195 private get numberOfQueuedTasks (): number {
196 if (this.opts.enableTasksQueue === false) {
197 return 0
198 }
199 return this.workerNodes.reduce(
200 (accumulator, workerNode) => accumulator + workerNode.tasksQueue.length,
201 0
202 )
203 }
204
205 /**
206 * Gets the given worker its worker node key.
207 *
208 * @param worker - The worker.
209 * @returns The worker node key if the worker is found in the pool worker nodes, `-1` otherwise.
210 */
211 private getWorkerNodeKey (worker: Worker): number {
212 return this.workerNodes.findIndex(
213 workerNode => workerNode.worker === worker
214 )
215 }
216
217 /** @inheritDoc */
218 public setWorkerChoiceStrategy (
219 workerChoiceStrategy: WorkerChoiceStrategy,
220 workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions
221 ): void {
222 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy)
223 this.opts.workerChoiceStrategy = workerChoiceStrategy
224 for (const workerNode of this.workerNodes) {
225 this.setWorkerNodeTasksUsage(workerNode, {
226 run: 0,
227 running: 0,
228 runTime: 0,
229 runTimeHistory: new CircularArray(),
230 avgRunTime: 0,
231 medRunTime: 0,
232 error: 0
233 })
234 }
235 this.workerChoiceStrategyContext.setWorkerChoiceStrategy(
236 this.opts.workerChoiceStrategy
237 )
238 if (workerChoiceStrategyOptions != null) {
239 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions)
240 }
241 }
242
243 /** @inheritDoc */
244 public setWorkerChoiceStrategyOptions (
245 workerChoiceStrategyOptions: WorkerChoiceStrategyOptions
246 ): void {
247 this.opts.workerChoiceStrategyOptions = workerChoiceStrategyOptions
248 this.workerChoiceStrategyContext.setOptions(
249 this.opts.workerChoiceStrategyOptions
250 )
251 }
252
253 /** @inheritDoc */
254 public enableTasksQueue (
255 enable: boolean,
256 tasksQueueOptions?: TasksQueueOptions
257 ): void {
258 if (this.opts.enableTasksQueue === true && !enable) {
259 this.flushTasksQueues()
260 }
261 this.opts.enableTasksQueue = enable
262 this.setTasksQueueOptions(tasksQueueOptions as TasksQueueOptions)
263 }
264
265 /** @inheritDoc */
266 public setTasksQueueOptions (tasksQueueOptions: TasksQueueOptions): void {
267 if (this.opts.enableTasksQueue === true) {
268 this.checkValidTasksQueueOptions(tasksQueueOptions)
269 this.opts.tasksQueueOptions =
270 this.buildTasksQueueOptions(tasksQueueOptions)
271 } else {
272 delete this.opts.tasksQueueOptions
273 }
274 }
275
276 private buildTasksQueueOptions (
277 tasksQueueOptions: TasksQueueOptions
278 ): TasksQueueOptions {
279 return {
280 concurrency: tasksQueueOptions?.concurrency ?? 1
281 }
282 }
283
284 /**
285 * Whether the pool is full or not.
286 *
287 * The pool filling boolean status.
288 */
289 protected abstract get full (): boolean
290
291 /**
292 * Whether the pool is busy or not.
293 *
294 * The pool busyness boolean status.
295 */
296 protected abstract get busy (): boolean
297
298 protected internalBusy (): boolean {
299 return this.findFreeWorkerNodeKey() === -1
300 }
301
302 /** @inheritDoc */
303 public findFreeWorkerNodeKey (): number {
304 return this.workerNodes.findIndex(workerNode => {
305 return workerNode.tasksUsage?.running === 0
306 })
307 }
308
309 /** @inheritDoc */
310 public async execute (data?: Data): Promise<Response> {
311 const [workerNodeKey, workerNode] = this.chooseWorkerNode()
312 const submittedTask: Task<Data> = {
313 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
314 data: data ?? ({} as Data),
315 id: crypto.randomUUID()
316 }
317 const res = new Promise<Response>((resolve, reject) => {
318 this.promiseResponseMap.set(submittedTask.id as string, {
319 resolve,
320 reject,
321 worker: workerNode.worker
322 })
323 })
324 if (
325 this.opts.enableTasksQueue === true &&
326 (this.busy ||
327 this.workerNodes[workerNodeKey].tasksUsage.running >=
328 ((this.opts.tasksQueueOptions as TasksQueueOptions)
329 .concurrency as number))
330 ) {
331 this.enqueueTask(workerNodeKey, submittedTask)
332 } else {
333 this.executeTask(workerNodeKey, submittedTask)
334 }
335 this.checkAndEmitEvents()
336 // eslint-disable-next-line @typescript-eslint/return-await
337 return res
338 }
339
340 /** @inheritDoc */
341 public async destroy (): Promise<void> {
342 await Promise.all(
343 this.workerNodes.map(async (workerNode, workerNodeKey) => {
344 this.flushTasksQueue(workerNodeKey)
345 await this.destroyWorker(workerNode.worker)
346 })
347 )
348 }
349
350 /**
351 * Shutdowns the given worker.
352 *
353 * @param worker - A worker within `workerNodes`.
354 */
355 protected abstract destroyWorker (worker: Worker): void | Promise<void>
356
357 /**
358 * Setup hook to execute code before worker node are created in the abstract constructor.
359 * Can be overridden
360 *
361 * @virtual
362 */
363 protected setupHook (): void {
364 // Intentionally empty
365 }
366
367 /**
368 * Should return whether the worker is the main worker or not.
369 */
370 protected abstract isMain (): boolean
371
372 /**
373 * Hook executed before the worker task execution.
374 * Can be overridden.
375 *
376 * @param workerNodeKey - The worker node key.
377 */
378 protected beforeTaskExecutionHook (workerNodeKey: number): void {
379 ++this.workerNodes[workerNodeKey].tasksUsage.running
380 }
381
382 /**
383 * Hook executed after the worker task execution.
384 * Can be overridden.
385 *
386 * @param worker - The worker.
387 * @param message - The received message.
388 */
389 protected afterTaskExecutionHook (
390 worker: Worker,
391 message: MessageValue<Response>
392 ): void {
393 const workerTasksUsage = this.getWorkerTasksUsage(worker) as TasksUsage
394 --workerTasksUsage.running
395 ++workerTasksUsage.run
396 if (message.error != null) {
397 ++workerTasksUsage.error
398 }
399 if (this.workerChoiceStrategyContext.getRequiredStatistics().runTime) {
400 workerTasksUsage.runTime += message.runTime ?? 0
401 if (
402 this.workerChoiceStrategyContext.getRequiredStatistics().avgRunTime &&
403 workerTasksUsage.run !== 0
404 ) {
405 workerTasksUsage.avgRunTime =
406 workerTasksUsage.runTime / workerTasksUsage.run
407 }
408 if (this.workerChoiceStrategyContext.getRequiredStatistics().medRunTime) {
409 workerTasksUsage.runTimeHistory.push(message.runTime ?? 0)
410 workerTasksUsage.medRunTime = median(workerTasksUsage.runTimeHistory)
411 }
412 }
413 }
414
415 /**
416 * Chooses a worker node for the next task.
417 *
418 * The default uses a round robin algorithm to distribute the load.
419 *
420 * @returns [worker node key, worker node].
421 */
422 protected chooseWorkerNode (): [number, WorkerNode<Worker, Data>] {
423 let workerNodeKey: number
424 if (this.type === PoolType.DYNAMIC && !this.full && this.internalBusy()) {
425 const workerCreated = this.createAndSetupWorker()
426 this.registerWorkerMessageListener(workerCreated, message => {
427 if (
428 isKillBehavior(KillBehaviors.HARD, message.kill) ||
429 (message.kill != null &&
430 this.getWorkerTasksUsage(workerCreated)?.running === 0)
431 ) {
432 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
433 this.flushTasksQueueByWorker(workerCreated)
434 void this.destroyWorker(workerCreated)
435 }
436 })
437 workerNodeKey = this.getWorkerNodeKey(workerCreated)
438 } else {
439 workerNodeKey = this.workerChoiceStrategyContext.execute()
440 }
441 return [workerNodeKey, this.workerNodes[workerNodeKey]]
442 }
443
444 /**
445 * Sends a message to the given worker.
446 *
447 * @param worker - The worker which should receive the message.
448 * @param message - The message.
449 */
450 protected abstract sendToWorker (
451 worker: Worker,
452 message: MessageValue<Data>
453 ): void
454
455 /**
456 * Registers a listener callback on the given worker.
457 *
458 * @param worker - The worker which should register a listener.
459 * @param listener - The message listener callback.
460 */
461 protected abstract registerWorkerMessageListener<
462 Message extends Data | Response
463 >(worker: Worker, listener: (message: MessageValue<Message>) => void): void
464
465 /**
466 * Returns a newly created worker.
467 */
468 protected abstract createWorker (): Worker
469
470 /**
471 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
472 *
473 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
474 *
475 * @param worker - The newly created worker.
476 */
477 protected abstract afterWorkerSetup (worker: Worker): void
478
479 /**
480 * Creates a new worker and sets it up completely in the pool worker nodes.
481 *
482 * @returns New, completely set up worker.
483 */
484 protected createAndSetupWorker (): Worker {
485 const worker = this.createWorker()
486
487 worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION)
488 worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION)
489 worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION)
490 worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION)
491 worker.once('exit', () => {
492 this.removeWorkerNode(worker)
493 })
494
495 this.pushWorkerNode(worker)
496
497 this.afterWorkerSetup(worker)
498
499 return worker
500 }
501
502 /**
503 * This function is the listener registered for each worker message.
504 *
505 * @returns The listener function to execute when a message is received from a worker.
506 */
507 protected workerListener (): (message: MessageValue<Response>) => void {
508 return message => {
509 if (message.id != null) {
510 // Task execution response received
511 const promiseResponse = this.promiseResponseMap.get(message.id)
512 if (promiseResponse != null) {
513 if (message.error != null) {
514 promiseResponse.reject(message.error)
515 } else {
516 promiseResponse.resolve(message.data as Response)
517 }
518 this.afterTaskExecutionHook(promiseResponse.worker, message)
519 this.promiseResponseMap.delete(message.id)
520 const workerNodeKey = this.getWorkerNodeKey(promiseResponse.worker)
521 if (
522 this.opts.enableTasksQueue === true &&
523 this.tasksQueueSize(workerNodeKey) > 0
524 ) {
525 this.executeTask(
526 workerNodeKey,
527 this.dequeueTask(workerNodeKey) as Task<Data>
528 )
529 }
530 }
531 }
532 }
533 }
534
535 private checkAndEmitEvents (): void {
536 if (this.opts.enableEvents === true) {
537 if (this.busy) {
538 this.emitter?.emit(PoolEvents.busy)
539 }
540 if (this.type === PoolType.DYNAMIC && this.full) {
541 this.emitter?.emit(PoolEvents.full)
542 }
543 }
544 }
545
546 /**
547 * Sets the given worker node its tasks usage in the pool.
548 *
549 * @param workerNode - The worker node.
550 * @param tasksUsage - The worker node tasks usage.
551 */
552 private setWorkerNodeTasksUsage (
553 workerNode: WorkerNode<Worker, Data>,
554 tasksUsage: TasksUsage
555 ): void {
556 workerNode.tasksUsage = tasksUsage
557 }
558
559 /**
560 * Gets the given worker its tasks usage in the pool.
561 *
562 * @param worker - The worker.
563 * @throws Error if the worker is not found in the pool worker nodes.
564 * @returns The worker tasks usage.
565 */
566 private getWorkerTasksUsage (worker: Worker): TasksUsage | undefined {
567 const workerNodeKey = this.getWorkerNodeKey(worker)
568 if (workerNodeKey !== -1) {
569 return this.workerNodes[workerNodeKey].tasksUsage
570 }
571 throw new Error('Worker could not be found in the pool worker nodes')
572 }
573
574 /**
575 * Pushes the given worker in the pool worker nodes.
576 *
577 * @param worker - The worker.
578 * @returns The worker nodes length.
579 */
580 private pushWorkerNode (worker: Worker): number {
581 return this.workerNodes.push({
582 worker,
583 tasksUsage: {
584 run: 0,
585 running: 0,
586 runTime: 0,
587 runTimeHistory: new CircularArray(),
588 avgRunTime: 0,
589 medRunTime: 0,
590 error: 0
591 },
592 tasksQueue: []
593 })
594 }
595
596 /**
597 * Sets the given worker in the pool worker nodes.
598 *
599 * @param workerNodeKey - The worker node key.
600 * @param worker - The worker.
601 * @param tasksUsage - The worker tasks usage.
602 * @param tasksQueue - The worker task queue.
603 */
604 private setWorkerNode (
605 workerNodeKey: number,
606 worker: Worker,
607 tasksUsage: TasksUsage,
608 tasksQueue: Array<Task<Data>>
609 ): void {
610 this.workerNodes[workerNodeKey] = {
611 worker,
612 tasksUsage,
613 tasksQueue
614 }
615 }
616
617 /**
618 * Removes the given worker from the pool worker nodes.
619 *
620 * @param worker - The worker.
621 */
622 private removeWorkerNode (worker: Worker): void {
623 const workerNodeKey = this.getWorkerNodeKey(worker)
624 this.workerNodes.splice(workerNodeKey, 1)
625 this.workerChoiceStrategyContext.remove(workerNodeKey)
626 }
627
628 private executeTask (workerNodeKey: number, task: Task<Data>): void {
629 this.beforeTaskExecutionHook(workerNodeKey)
630 this.sendToWorker(this.workerNodes[workerNodeKey].worker, task)
631 }
632
633 private enqueueTask (workerNodeKey: number, task: Task<Data>): number {
634 return this.workerNodes[workerNodeKey].tasksQueue.push(task)
635 }
636
637 private dequeueTask (workerNodeKey: number): Task<Data> | undefined {
638 return this.workerNodes[workerNodeKey].tasksQueue.shift()
639 }
640
641 private tasksQueueSize (workerNodeKey: number): number {
642 return this.workerNodes[workerNodeKey].tasksQueue.length
643 }
644
645 private flushTasksQueue (workerNodeKey: number): void {
646 if (this.tasksQueueSize(workerNodeKey) > 0) {
647 for (const task of this.workerNodes[workerNodeKey].tasksQueue) {
648 this.executeTask(workerNodeKey, task)
649 }
650 }
651 }
652
653 private flushTasksQueueByWorker (worker: Worker): void {
654 const workerNodeKey = this.getWorkerNodeKey(worker)
655 this.flushTasksQueue(workerNodeKey)
656 }
657
658 private flushTasksQueues (): void {
659 for (const [workerNodeKey] of this.workerNodes.entries()) {
660 this.flushTasksQueue(workerNodeKey)
661 }
662 }
663 }