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