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