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