feat: add pool runtime setters
[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 ): void {
221 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy)
222 this.opts.workerChoiceStrategy = workerChoiceStrategy
223 for (const workerNode of this.workerNodes) {
224 this.setWorkerNodeTasksUsage(workerNode, {
225 run: 0,
226 running: 0,
227 runTime: 0,
228 runTimeHistory: new CircularArray(),
229 avgRunTime: 0,
230 medRunTime: 0,
231 error: 0
232 })
233 }
234 this.workerChoiceStrategyContext.setWorkerChoiceStrategy(
235 this.opts.workerChoiceStrategy
236 )
237 }
238
239 /** @inheritDoc */
240 public setWorkerChoiceStrategyOptions (
241 workerChoiceStrategyOptions: WorkerChoiceStrategyOptions
242 ): void {
243 this.opts.workerChoiceStrategyOptions = workerChoiceStrategyOptions
244 this.workerChoiceStrategyContext.setOptions(
245 this.opts.workerChoiceStrategyOptions
246 )
247 }
248
249 /** @inheritDoc */
250 public enableTasksQueue (enable: boolean, opts?: TasksQueueOptions): void {
251 if (this.opts.enableTasksQueue === true && !enable) {
252 for (const [workerNodeKey] of this.workerNodes.entries()) {
253 this.flushTasksQueue(workerNodeKey)
254 }
255 }
256 this.opts.enableTasksQueue = enable
257 this.setTasksQueueOptions(opts as TasksQueueOptions)
258 }
259
260 /** @inheritDoc */
261 public setTasksQueueOptions (opts: TasksQueueOptions): void {
262 if (this.opts.enableTasksQueue === true) {
263 this.checkValidTasksQueueOptions(opts)
264 this.opts.tasksQueueOptions = this.buildTasksQueueOptions(opts)
265 } else {
266 delete this.opts.tasksQueueOptions
267 }
268 }
269
270 private buildTasksQueueOptions (
271 tasksQueueOptions: TasksQueueOptions
272 ): TasksQueueOptions {
273 return {
274 concurrency: tasksQueueOptions?.concurrency ?? 1
275 }
276 }
277
278 /**
279 * Whether the pool is full or not.
280 *
281 * The pool filling boolean status.
282 */
283 protected abstract get full (): boolean
284
285 /**
286 * Whether the pool is busy or not.
287 *
288 * The pool busyness boolean status.
289 */
290 protected abstract get busy (): boolean
291
292 protected internalBusy (): boolean {
293 return this.findFreeWorkerNodeKey() === -1
294 }
295
296 /** @inheritDoc */
297 public findFreeWorkerNodeKey (): number {
298 return this.workerNodes.findIndex(workerNode => {
299 return workerNode.tasksUsage?.running === 0
300 })
301 }
302
303 /** @inheritDoc */
304 public async execute (data: Data): Promise<Response> {
305 const [workerNodeKey, workerNode] = this.chooseWorkerNode()
306 const submittedTask: Task<Data> = {
307 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
308 data: data ?? ({} as Data),
309 id: crypto.randomUUID()
310 }
311 const res = new Promise<Response>((resolve, reject) => {
312 this.promiseResponseMap.set(submittedTask.id as string, {
313 resolve,
314 reject,
315 worker: workerNode.worker
316 })
317 })
318 if (
319 this.opts.enableTasksQueue === true &&
320 (this.busy ||
321 this.workerNodes[workerNodeKey].tasksUsage.running >=
322 ((this.opts.tasksQueueOptions as TasksQueueOptions)
323 .concurrency as number))
324 ) {
325 this.enqueueTask(workerNodeKey, submittedTask)
326 } else {
327 this.executeTask(workerNodeKey, submittedTask)
328 }
329 this.checkAndEmitEvents()
330 // eslint-disable-next-line @typescript-eslint/return-await
331 return res
332 }
333
334 /** @inheritDoc */
335 public async destroy (): Promise<void> {
336 await Promise.all(
337 this.workerNodes.map(async (workerNode, workerNodeKey) => {
338 this.flushTasksQueue(workerNodeKey)
339 await this.destroyWorker(workerNode.worker)
340 })
341 )
342 }
343
344 /**
345 * Shutdowns the given worker.
346 *
347 * @param worker - A worker within `workerNodes`.
348 */
349 protected abstract destroyWorker (worker: Worker): void | Promise<void>
350
351 /**
352 * Setup hook to execute code before worker node are created in the abstract constructor.
353 * Can be overridden
354 *
355 * @virtual
356 */
357 protected setupHook (): void {
358 // Intentionally empty
359 }
360
361 /**
362 * Should return whether the worker is the main worker or not.
363 */
364 protected abstract isMain (): boolean
365
366 /**
367 * Hook executed before the worker task execution.
368 * Can be overridden.
369 *
370 * @param workerNodeKey - The worker node key.
371 */
372 protected beforeTaskExecutionHook (workerNodeKey: number): void {
373 ++this.workerNodes[workerNodeKey].tasksUsage.running
374 }
375
376 /**
377 * Hook executed after the worker task execution.
378 * Can be overridden.
379 *
380 * @param worker - The worker.
381 * @param message - The received message.
382 */
383 protected afterTaskExecutionHook (
384 worker: Worker,
385 message: MessageValue<Response>
386 ): void {
387 const workerTasksUsage = this.getWorkerTasksUsage(worker) as TasksUsage
388 --workerTasksUsage.running
389 ++workerTasksUsage.run
390 if (message.error != null) {
391 ++workerTasksUsage.error
392 }
393 if (this.workerChoiceStrategyContext.getRequiredStatistics().runTime) {
394 workerTasksUsage.runTime += message.runTime ?? 0
395 if (
396 this.workerChoiceStrategyContext.getRequiredStatistics().avgRunTime &&
397 workerTasksUsage.run !== 0
398 ) {
399 workerTasksUsage.avgRunTime =
400 workerTasksUsage.runTime / workerTasksUsage.run
401 }
402 if (this.workerChoiceStrategyContext.getRequiredStatistics().medRunTime) {
403 workerTasksUsage.runTimeHistory.push(message.runTime ?? 0)
404 workerTasksUsage.medRunTime = median(workerTasksUsage.runTimeHistory)
405 }
406 }
407 }
408
409 /**
410 * Chooses a worker node for the next task.
411 *
412 * The default uses a round robin algorithm to distribute the load.
413 *
414 * @returns [worker node key, worker node].
415 */
416 protected chooseWorkerNode (): [number, WorkerNode<Worker, Data>] {
417 let workerNodeKey: number
418 if (this.type === PoolType.DYNAMIC && !this.full && this.internalBusy()) {
419 const workerCreated = this.createAndSetupWorker()
420 this.registerWorkerMessageListener(workerCreated, message => {
421 if (
422 isKillBehavior(KillBehaviors.HARD, message.kill) ||
423 (message.kill != null &&
424 this.getWorkerTasksUsage(workerCreated)?.running === 0)
425 ) {
426 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
427 this.flushTasksQueueByWorker(workerCreated)
428 void this.destroyWorker(workerCreated)
429 }
430 })
431 workerNodeKey = this.getWorkerNodeKey(workerCreated)
432 } else {
433 workerNodeKey = this.workerChoiceStrategyContext.execute()
434 }
435 return [workerNodeKey, this.workerNodes[workerNodeKey]]
436 }
437
438 /**
439 * Sends a message to the given worker.
440 *
441 * @param worker - The worker which should receive the message.
442 * @param message - The message.
443 */
444 protected abstract sendToWorker (
445 worker: Worker,
446 message: MessageValue<Data>
447 ): void
448
449 /**
450 * Registers a listener callback on the given worker.
451 *
452 * @param worker - The worker which should register a listener.
453 * @param listener - The message listener callback.
454 */
455 protected abstract registerWorkerMessageListener<
456 Message extends Data | Response
457 >(worker: Worker, listener: (message: MessageValue<Message>) => void): void
458
459 /**
460 * Returns a newly created worker.
461 */
462 protected abstract createWorker (): Worker
463
464 /**
465 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
466 *
467 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
468 *
469 * @param worker - The newly created worker.
470 */
471 protected abstract afterWorkerSetup (worker: Worker): void
472
473 /**
474 * Creates a new worker and sets it up completely in the pool worker nodes.
475 *
476 * @returns New, completely set up worker.
477 */
478 protected createAndSetupWorker (): Worker {
479 const worker = this.createWorker()
480
481 worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION)
482 worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION)
483 worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION)
484 worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION)
485 worker.once('exit', () => {
486 this.removeWorkerNode(worker)
487 })
488
489 this.pushWorkerNode(worker)
490
491 this.afterWorkerSetup(worker)
492
493 return worker
494 }
495
496 /**
497 * This function is the listener registered for each worker message.
498 *
499 * @returns The listener function to execute when a message is received from a worker.
500 */
501 protected workerListener (): (message: MessageValue<Response>) => void {
502 return message => {
503 if (message.id != null) {
504 // Task execution response received
505 const promiseResponse = this.promiseResponseMap.get(message.id)
506 if (promiseResponse != null) {
507 if (message.error != null) {
508 promiseResponse.reject(message.error)
509 } else {
510 promiseResponse.resolve(message.data as Response)
511 }
512 this.afterTaskExecutionHook(promiseResponse.worker, message)
513 this.promiseResponseMap.delete(message.id)
514 const workerNodeKey = this.getWorkerNodeKey(promiseResponse.worker)
515 if (
516 this.opts.enableTasksQueue === true &&
517 this.tasksQueueSize(workerNodeKey) > 0
518 ) {
519 this.executeTask(
520 workerNodeKey,
521 this.dequeueTask(workerNodeKey) as Task<Data>
522 )
523 }
524 }
525 }
526 }
527 }
528
529 private checkAndEmitEvents (): void {
530 if (this.opts.enableEvents === true) {
531 if (this.busy) {
532 this.emitter?.emit(PoolEvents.busy)
533 }
534 if (this.type === PoolType.DYNAMIC && this.full) {
535 this.emitter?.emit(PoolEvents.full)
536 }
537 }
538 }
539
540 /**
541 * Sets the given worker node its tasks usage in the pool.
542 *
543 * @param workerNode - The worker node.
544 * @param tasksUsage - The worker node tasks usage.
545 */
546 private setWorkerNodeTasksUsage (
547 workerNode: WorkerNode<Worker, Data>,
548 tasksUsage: TasksUsage
549 ): void {
550 workerNode.tasksUsage = tasksUsage
551 }
552
553 /**
554 * Gets the given worker its tasks usage in the pool.
555 *
556 * @param worker - The worker.
557 * @throws {@link Error} if the worker is not found in the pool worker nodes.
558 * @returns The worker tasks usage.
559 */
560 private getWorkerTasksUsage (worker: Worker): TasksUsage | undefined {
561 const workerNodeKey = this.getWorkerNodeKey(worker)
562 if (workerNodeKey !== -1) {
563 return this.workerNodes[workerNodeKey].tasksUsage
564 }
565 throw new Error('Worker could not be found in the pool worker nodes')
566 }
567
568 /**
569 * Pushes the given worker in the pool worker nodes.
570 *
571 * @param worker - The worker.
572 * @returns The worker nodes length.
573 */
574 private pushWorkerNode (worker: Worker): number {
575 return this.workerNodes.push({
576 worker,
577 tasksUsage: {
578 run: 0,
579 running: 0,
580 runTime: 0,
581 runTimeHistory: new CircularArray(),
582 avgRunTime: 0,
583 medRunTime: 0,
584 error: 0
585 },
586 tasksQueue: []
587 })
588 }
589
590 /**
591 * Sets the given worker in the pool worker nodes.
592 *
593 * @param workerNodeKey - The worker node key.
594 * @param worker - The worker.
595 * @param tasksUsage - The worker tasks usage.
596 * @param tasksQueue - The worker task queue.
597 */
598 private setWorkerNode (
599 workerNodeKey: number,
600 worker: Worker,
601 tasksUsage: TasksUsage,
602 tasksQueue: Array<Task<Data>>
603 ): void {
604 this.workerNodes[workerNodeKey] = {
605 worker,
606 tasksUsage,
607 tasksQueue
608 }
609 }
610
611 /**
612 * Removes the given worker from the pool worker nodes.
613 *
614 * @param worker - The worker.
615 */
616 private removeWorkerNode (worker: Worker): void {
617 const workerNodeKey = this.getWorkerNodeKey(worker)
618 this.workerNodes.splice(workerNodeKey, 1)
619 this.workerChoiceStrategyContext.remove(workerNodeKey)
620 }
621
622 private executeTask (workerNodeKey: number, task: Task<Data>): void {
623 this.beforeTaskExecutionHook(workerNodeKey)
624 this.sendToWorker(this.workerNodes[workerNodeKey].worker, task)
625 }
626
627 private enqueueTask (workerNodeKey: number, task: Task<Data>): number {
628 return this.workerNodes[workerNodeKey].tasksQueue.push(task)
629 }
630
631 private dequeueTask (workerNodeKey: number): Task<Data> | undefined {
632 return this.workerNodes[workerNodeKey].tasksQueue.shift()
633 }
634
635 private tasksQueueSize (workerNodeKey: number): number {
636 return this.workerNodes[workerNodeKey].tasksQueue.length
637 }
638
639 private flushTasksQueue (workerNodeKey: number): void {
640 if (this.tasksQueueSize(workerNodeKey) > 0) {
641 for (const task of this.workerNodes[workerNodeKey].tasksQueue) {
642 this.executeTask(workerNodeKey, task)
643 }
644 }
645 }
646
647 private flushTasksQueueByWorker (worker: Worker): void {
648 const workerNodeKey = this.getWorkerNodeKey(worker)
649 this.flushTasksQueue(workerNodeKey)
650 }
651 }