a23c7983bfc652fbfcb8ece4a75853dbed270ac5
[poolifier.git] / src / pools / abstract-pool.ts
1 import { AsyncResource } from 'node:async_hooks'
2 import { randomUUID } from 'node:crypto'
3 import { EventEmitterAsyncResource } from 'node:events'
4 import { performance } from 'node:perf_hooks'
5 import type { TransferListItem } from 'node:worker_threads'
6
7 import type {
8 MessageValue,
9 PromiseResponseWrapper,
10 Task,
11 TaskFunctionProperties
12 } from '../utility-types.js'
13 import {
14 average,
15 buildTaskFunctionProperties,
16 DEFAULT_TASK_NAME,
17 EMPTY_FUNCTION,
18 exponentialDelay,
19 isKillBehavior,
20 isPlainObject,
21 max,
22 median,
23 min,
24 round,
25 sleep
26 } from '../utils.js'
27 import type {
28 TaskFunction,
29 TaskFunctionObject
30 } from '../worker/task-functions.js'
31 import { KillBehaviors } from '../worker/worker-options.js'
32 import {
33 type IPool,
34 PoolEvents,
35 type PoolInfo,
36 type PoolOptions,
37 type PoolType,
38 PoolTypes,
39 type TasksQueueOptions
40 } from './pool.js'
41 import {
42 Measurements,
43 WorkerChoiceStrategies,
44 type WorkerChoiceStrategy,
45 type WorkerChoiceStrategyOptions
46 } from './selection-strategies/selection-strategies-types.js'
47 import { WorkerChoiceStrategiesContext } from './selection-strategies/worker-choice-strategies-context.js'
48 import {
49 checkFilePath,
50 checkValidPriority,
51 checkValidTasksQueueOptions,
52 checkValidWorkerChoiceStrategy,
53 getDefaultTasksQueueOptions,
54 updateEluWorkerUsage,
55 updateRunTimeWorkerUsage,
56 updateTaskStatisticsWorkerUsage,
57 updateWaitTimeWorkerUsage,
58 waitWorkerNodeEvents
59 } from './utils.js'
60 import { version } from './version.js'
61 import type {
62 IWorker,
63 IWorkerNode,
64 WorkerInfo,
65 WorkerNodeEventDetail,
66 WorkerType
67 } from './worker.js'
68 import { WorkerNode } from './worker-node.js'
69
70 /**
71 * Base class that implements some shared logic for all poolifier pools.
72 *
73 * @typeParam Worker - Type of worker which manages this pool.
74 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
75 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
76 */
77 export abstract class AbstractPool<
78 Worker extends IWorker,
79 Data = unknown,
80 Response = unknown
81 > implements IPool<Worker, Data, Response> {
82 /** @inheritDoc */
83 public readonly workerNodes: Array<IWorkerNode<Worker, Data>> = []
84
85 /** @inheritDoc */
86 public emitter?: EventEmitterAsyncResource
87
88 /**
89 * The task execution response promise map:
90 * - `key`: The message id of each submitted task.
91 * - `value`: An object that contains task's worker node key, execution response promise resolve and reject callbacks, async resource.
92 *
93 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
94 */
95 protected promiseResponseMap: Map<
96 `${string}-${string}-${string}-${string}-${string}`,
97 PromiseResponseWrapper<Response>
98 > = new Map<
99 `${string}-${string}-${string}-${string}-${string}`,
100 PromiseResponseWrapper<Response>
101 >()
102
103 /**
104 * Worker choice strategies context referencing worker choice algorithms implementation.
105 */
106 protected workerChoiceStrategiesContext?: WorkerChoiceStrategiesContext<
107 Worker,
108 Data,
109 Response
110 >
111
112 /**
113 * The task functions added at runtime map:
114 * - `key`: The task function name.
115 * - `value`: The task function object.
116 */
117 private readonly taskFunctions: Map<
118 string,
119 TaskFunctionObject<Data, Response>
120 >
121
122 /**
123 * Whether the pool is started or not.
124 */
125 private started: boolean
126 /**
127 * Whether the pool is starting or not.
128 */
129 private starting: boolean
130 /**
131 * Whether the pool is destroying or not.
132 */
133 private destroying: boolean
134 /**
135 * Whether the minimum number of workers is starting or not.
136 */
137 private startingMinimumNumberOfWorkers: boolean
138 /**
139 * Whether the pool ready event has been emitted or not.
140 */
141 private readyEventEmitted: boolean
142 /**
143 * The start timestamp of the pool.
144 */
145 private startTimestamp?: number
146
147 /**
148 * Constructs a new poolifier pool.
149 *
150 * @param minimumNumberOfWorkers - Minimum number of workers that this pool manages.
151 * @param filePath - Path to the worker file.
152 * @param opts - Options for the pool.
153 * @param maximumNumberOfWorkers - Maximum number of workers that this pool manages.
154 */
155 public constructor (
156 protected readonly minimumNumberOfWorkers: number,
157 protected readonly filePath: string,
158 protected readonly opts: PoolOptions<Worker>,
159 protected readonly maximumNumberOfWorkers?: number
160 ) {
161 if (!this.isMain()) {
162 throw new Error(
163 'Cannot start a pool from a worker with the same type as the pool'
164 )
165 }
166 this.checkPoolType()
167 checkFilePath(this.filePath)
168 this.checkMinimumNumberOfWorkers(this.minimumNumberOfWorkers)
169 this.checkPoolOptions(this.opts)
170
171 this.chooseWorkerNode = this.chooseWorkerNode.bind(this)
172 this.executeTask = this.executeTask.bind(this)
173 this.enqueueTask = this.enqueueTask.bind(this)
174
175 if (this.opts.enableEvents === true) {
176 this.initEventEmitter()
177 }
178 this.workerChoiceStrategiesContext = new WorkerChoiceStrategiesContext<
179 Worker,
180 Data,
181 Response
182 >(
183 this,
184 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
185 [this.opts.workerChoiceStrategy!],
186 this.opts.workerChoiceStrategyOptions
187 )
188
189 this.setupHook()
190
191 this.taskFunctions = new Map<string, TaskFunctionObject<Data, Response>>()
192
193 this.started = false
194 this.starting = false
195 this.destroying = false
196 this.readyEventEmitted = false
197 this.startingMinimumNumberOfWorkers = false
198 if (this.opts.startWorkers === true) {
199 this.start()
200 }
201 }
202
203 private checkPoolType (): void {
204 if (this.type === PoolTypes.fixed && this.maximumNumberOfWorkers != null) {
205 throw new Error(
206 'Cannot instantiate a fixed pool with a maximum number of workers specified at initialization'
207 )
208 }
209 }
210
211 private checkMinimumNumberOfWorkers (
212 minimumNumberOfWorkers: number | undefined
213 ): void {
214 if (minimumNumberOfWorkers == null) {
215 throw new Error(
216 'Cannot instantiate a pool without specifying the number of workers'
217 )
218 } else if (!Number.isSafeInteger(minimumNumberOfWorkers)) {
219 throw new TypeError(
220 'Cannot instantiate a pool with a non safe integer number of workers'
221 )
222 } else if (minimumNumberOfWorkers < 0) {
223 throw new RangeError(
224 'Cannot instantiate a pool with a negative number of workers'
225 )
226 } else if (this.type === PoolTypes.fixed && minimumNumberOfWorkers === 0) {
227 throw new RangeError('Cannot instantiate a fixed pool with zero worker')
228 }
229 }
230
231 private checkPoolOptions (opts: PoolOptions<Worker>): void {
232 if (isPlainObject(opts)) {
233 this.opts.startWorkers = opts.startWorkers ?? true
234 checkValidWorkerChoiceStrategy(opts.workerChoiceStrategy)
235 this.opts.workerChoiceStrategy =
236 opts.workerChoiceStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN
237 this.checkValidWorkerChoiceStrategyOptions(
238 opts.workerChoiceStrategyOptions
239 )
240 if (opts.workerChoiceStrategyOptions != null) {
241 this.opts.workerChoiceStrategyOptions = opts.workerChoiceStrategyOptions
242 }
243 this.opts.restartWorkerOnError = opts.restartWorkerOnError ?? true
244 this.opts.enableEvents = opts.enableEvents ?? true
245 this.opts.enableTasksQueue = opts.enableTasksQueue ?? false
246 if (this.opts.enableTasksQueue) {
247 checkValidTasksQueueOptions(opts.tasksQueueOptions)
248 this.opts.tasksQueueOptions = this.buildTasksQueueOptions(
249 opts.tasksQueueOptions
250 )
251 }
252 } else {
253 throw new TypeError('Invalid pool options: must be a plain object')
254 }
255 }
256
257 private checkValidWorkerChoiceStrategyOptions (
258 workerChoiceStrategyOptions: WorkerChoiceStrategyOptions | undefined
259 ): void {
260 if (
261 workerChoiceStrategyOptions != null &&
262 !isPlainObject(workerChoiceStrategyOptions)
263 ) {
264 throw new TypeError(
265 'Invalid worker choice strategy options: must be a plain object'
266 )
267 }
268 if (
269 workerChoiceStrategyOptions?.weights != null &&
270 Object.keys(workerChoiceStrategyOptions.weights).length !==
271 (this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers)
272 ) {
273 throw new Error(
274 'Invalid worker choice strategy options: must have a weight for each worker node'
275 )
276 }
277 if (
278 workerChoiceStrategyOptions?.measurement != null &&
279 !Object.values(Measurements).includes(
280 workerChoiceStrategyOptions.measurement
281 )
282 ) {
283 throw new Error(
284 `Invalid worker choice strategy options: invalid measurement '${workerChoiceStrategyOptions.measurement}'`
285 )
286 }
287 }
288
289 private initEventEmitter (): void {
290 this.emitter = new EventEmitterAsyncResource({
291 name: `poolifier:${this.type}-${this.worker}-pool`
292 })
293 }
294
295 /** @inheritDoc */
296 public get info (): PoolInfo {
297 return {
298 version,
299 type: this.type,
300 worker: this.worker,
301 started: this.started,
302 ready: this.ready,
303 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
304 defaultStrategy: this.opts.workerChoiceStrategy!,
305 strategyRetries: this.workerChoiceStrategiesContext?.retriesCount ?? 0,
306 minSize: this.minimumNumberOfWorkers,
307 maxSize: this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers,
308 ...(this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements()
309 .runTime.aggregate === true &&
310 this.workerChoiceStrategiesContext.getTaskStatisticsRequirements()
311 .waitTime.aggregate && {
312 utilization: round(this.utilization)
313 }),
314 workerNodes: this.workerNodes.length,
315 idleWorkerNodes: this.workerNodes.reduce(
316 (accumulator, workerNode) =>
317 workerNode.usage.tasks.executing === 0
318 ? accumulator + 1
319 : accumulator,
320 0
321 ),
322 ...(this.opts.enableTasksQueue === true && {
323 stealingWorkerNodes: this.workerNodes.reduce(
324 (accumulator, workerNode) =>
325 workerNode.info.stealing ? accumulator + 1 : accumulator,
326 0
327 )
328 }),
329 busyWorkerNodes: this.workerNodes.reduce(
330 (accumulator, _, workerNodeKey) =>
331 this.isWorkerNodeBusy(workerNodeKey) ? accumulator + 1 : accumulator,
332 0
333 ),
334 executedTasks: this.workerNodes.reduce(
335 (accumulator, workerNode) =>
336 accumulator + workerNode.usage.tasks.executed,
337 0
338 ),
339 executingTasks: this.workerNodes.reduce(
340 (accumulator, workerNode) =>
341 accumulator + workerNode.usage.tasks.executing,
342 0
343 ),
344 ...(this.opts.enableTasksQueue === true && {
345 queuedTasks: this.workerNodes.reduce(
346 (accumulator, workerNode) =>
347 accumulator + workerNode.usage.tasks.queued,
348 0
349 )
350 }),
351 ...(this.opts.enableTasksQueue === true && {
352 maxQueuedTasks: this.workerNodes.reduce(
353 (accumulator, workerNode) =>
354 accumulator + (workerNode.usage.tasks.maxQueued ?? 0),
355 0
356 )
357 }),
358 ...(this.opts.enableTasksQueue === true && {
359 backPressure: this.hasBackPressure()
360 }),
361 ...(this.opts.enableTasksQueue === true && {
362 stolenTasks: this.workerNodes.reduce(
363 (accumulator, workerNode) =>
364 accumulator + workerNode.usage.tasks.stolen,
365 0
366 )
367 }),
368 failedTasks: this.workerNodes.reduce(
369 (accumulator, workerNode) =>
370 accumulator + workerNode.usage.tasks.failed,
371 0
372 ),
373 ...(this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements()
374 .runTime.aggregate === true && {
375 runTime: {
376 minimum: round(
377 min(
378 ...this.workerNodes.map(
379 workerNode =>
380 workerNode.usage.runTime.minimum ?? Number.POSITIVE_INFINITY
381 )
382 )
383 ),
384 maximum: round(
385 max(
386 ...this.workerNodes.map(
387 workerNode =>
388 workerNode.usage.runTime.maximum ?? Number.NEGATIVE_INFINITY
389 )
390 )
391 ),
392 ...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements()
393 .runTime.average && {
394 average: round(
395 average(
396 this.workerNodes.reduce<number[]>(
397 (accumulator, workerNode) =>
398 accumulator.concat(workerNode.usage.runTime.history),
399 []
400 )
401 )
402 )
403 }),
404 ...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements()
405 .runTime.median && {
406 median: round(
407 median(
408 this.workerNodes.reduce<number[]>(
409 (accumulator, workerNode) =>
410 accumulator.concat(workerNode.usage.runTime.history),
411 []
412 )
413 )
414 )
415 })
416 }
417 }),
418 ...(this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements()
419 .waitTime.aggregate === true && {
420 waitTime: {
421 minimum: round(
422 min(
423 ...this.workerNodes.map(
424 workerNode =>
425 workerNode.usage.waitTime.minimum ?? Number.POSITIVE_INFINITY
426 )
427 )
428 ),
429 maximum: round(
430 max(
431 ...this.workerNodes.map(
432 workerNode =>
433 workerNode.usage.waitTime.maximum ?? Number.NEGATIVE_INFINITY
434 )
435 )
436 ),
437 ...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements()
438 .waitTime.average && {
439 average: round(
440 average(
441 this.workerNodes.reduce<number[]>(
442 (accumulator, workerNode) =>
443 accumulator.concat(workerNode.usage.waitTime.history),
444 []
445 )
446 )
447 )
448 }),
449 ...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements()
450 .waitTime.median && {
451 median: round(
452 median(
453 this.workerNodes.reduce<number[]>(
454 (accumulator, workerNode) =>
455 accumulator.concat(workerNode.usage.waitTime.history),
456 []
457 )
458 )
459 )
460 })
461 }
462 }),
463 ...(this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements()
464 .elu.aggregate === true && {
465 elu: {
466 idle: {
467 minimum: round(
468 min(
469 ...this.workerNodes.map(
470 workerNode =>
471 workerNode.usage.elu.idle.minimum ??
472 Number.POSITIVE_INFINITY
473 )
474 )
475 ),
476 maximum: round(
477 max(
478 ...this.workerNodes.map(
479 workerNode =>
480 workerNode.usage.elu.idle.maximum ??
481 Number.NEGATIVE_INFINITY
482 )
483 )
484 ),
485 ...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements()
486 .elu.average && {
487 average: round(
488 average(
489 this.workerNodes.reduce<number[]>(
490 (accumulator, workerNode) =>
491 accumulator.concat(workerNode.usage.elu.idle.history),
492 []
493 )
494 )
495 )
496 }),
497 ...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements()
498 .elu.median && {
499 median: round(
500 median(
501 this.workerNodes.reduce<number[]>(
502 (accumulator, workerNode) =>
503 accumulator.concat(workerNode.usage.elu.idle.history),
504 []
505 )
506 )
507 )
508 })
509 },
510 active: {
511 minimum: round(
512 min(
513 ...this.workerNodes.map(
514 workerNode =>
515 workerNode.usage.elu.active.minimum ??
516 Number.POSITIVE_INFINITY
517 )
518 )
519 ),
520 maximum: round(
521 max(
522 ...this.workerNodes.map(
523 workerNode =>
524 workerNode.usage.elu.active.maximum ??
525 Number.NEGATIVE_INFINITY
526 )
527 )
528 ),
529 ...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements()
530 .elu.average && {
531 average: round(
532 average(
533 this.workerNodes.reduce<number[]>(
534 (accumulator, workerNode) =>
535 accumulator.concat(workerNode.usage.elu.active.history),
536 []
537 )
538 )
539 )
540 }),
541 ...(this.workerChoiceStrategiesContext.getTaskStatisticsRequirements()
542 .elu.median && {
543 median: round(
544 median(
545 this.workerNodes.reduce<number[]>(
546 (accumulator, workerNode) =>
547 accumulator.concat(workerNode.usage.elu.active.history),
548 []
549 )
550 )
551 )
552 })
553 },
554 utilization: {
555 average: round(
556 average(
557 this.workerNodes.map(
558 workerNode => workerNode.usage.elu.utilization ?? 0
559 )
560 )
561 ),
562 median: round(
563 median(
564 this.workerNodes.map(
565 workerNode => workerNode.usage.elu.utilization ?? 0
566 )
567 )
568 )
569 }
570 }
571 })
572 }
573 }
574
575 /**
576 * The pool readiness boolean status.
577 */
578 private get ready (): boolean {
579 if (this.empty) {
580 return false
581 }
582 return (
583 this.workerNodes.reduce(
584 (accumulator, workerNode) =>
585 !workerNode.info.dynamic && workerNode.info.ready
586 ? accumulator + 1
587 : accumulator,
588 0
589 ) >= this.minimumNumberOfWorkers
590 )
591 }
592
593 /**
594 * The pool emptiness boolean status.
595 */
596 protected get empty (): boolean {
597 return this.minimumNumberOfWorkers === 0 && this.workerNodes.length === 0
598 }
599
600 /**
601 * The approximate pool utilization.
602 *
603 * @returns The pool utilization.
604 */
605 private get utilization (): number {
606 if (this.startTimestamp == null) {
607 return 0
608 }
609 const poolTimeCapacity =
610 (performance.now() - this.startTimestamp) *
611 (this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers)
612 const totalTasksRunTime = this.workerNodes.reduce(
613 (accumulator, workerNode) =>
614 accumulator + (workerNode.usage.runTime.aggregate ?? 0),
615 0
616 )
617 const totalTasksWaitTime = this.workerNodes.reduce(
618 (accumulator, workerNode) =>
619 accumulator + (workerNode.usage.waitTime.aggregate ?? 0),
620 0
621 )
622 return (totalTasksRunTime + totalTasksWaitTime) / poolTimeCapacity
623 }
624
625 /**
626 * The pool type.
627 *
628 * If it is `'dynamic'`, it provides the `max` property.
629 */
630 protected abstract get type (): PoolType
631
632 /**
633 * The worker type.
634 */
635 protected abstract get worker (): WorkerType
636
637 /**
638 * Checks if the worker id sent in the received message from a worker is valid.
639 *
640 * @param message - The received message.
641 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the worker id is invalid.
642 */
643 private checkMessageWorkerId (message: MessageValue<Data | Response>): void {
644 if (message.workerId == null) {
645 throw new Error('Worker message received without worker id')
646 } else if (this.getWorkerNodeKeyByWorkerId(message.workerId) === -1) {
647 throw new Error(
648 `Worker message received from unknown worker '${message.workerId}'`
649 )
650 }
651 }
652
653 /**
654 * Gets the worker node key given its worker id.
655 *
656 * @param workerId - The worker id.
657 * @returns The worker node key if the worker id is found in the pool worker nodes, `-1` otherwise.
658 */
659 private getWorkerNodeKeyByWorkerId (workerId: number | undefined): number {
660 return this.workerNodes.findIndex(
661 workerNode => workerNode.info.id === workerId
662 )
663 }
664
665 /** @inheritDoc */
666 public setWorkerChoiceStrategy (
667 workerChoiceStrategy: WorkerChoiceStrategy,
668 workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions
669 ): void {
670 let requireSync = false
671 checkValidWorkerChoiceStrategy(workerChoiceStrategy)
672 if (workerChoiceStrategyOptions != null) {
673 requireSync = !this.setWorkerChoiceStrategyOptions(
674 workerChoiceStrategyOptions
675 )
676 }
677 if (workerChoiceStrategy !== this.opts.workerChoiceStrategy) {
678 this.opts.workerChoiceStrategy = workerChoiceStrategy
679 this.workerChoiceStrategiesContext?.setDefaultWorkerChoiceStrategy(
680 this.opts.workerChoiceStrategy,
681 this.opts.workerChoiceStrategyOptions
682 )
683 requireSync = true
684 }
685 if (requireSync) {
686 this.workerChoiceStrategiesContext?.syncWorkerChoiceStrategies(
687 this.getWorkerChoiceStrategies(),
688 this.opts.workerChoiceStrategyOptions
689 )
690 for (const workerNodeKey of this.workerNodes.keys()) {
691 this.sendStatisticsMessageToWorker(workerNodeKey)
692 }
693 }
694 }
695
696 /** @inheritDoc */
697 public setWorkerChoiceStrategyOptions (
698 workerChoiceStrategyOptions: WorkerChoiceStrategyOptions | undefined
699 ): boolean {
700 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions)
701 if (workerChoiceStrategyOptions != null) {
702 this.opts.workerChoiceStrategyOptions = workerChoiceStrategyOptions
703 this.workerChoiceStrategiesContext?.setOptions(
704 this.opts.workerChoiceStrategyOptions
705 )
706 this.workerChoiceStrategiesContext?.syncWorkerChoiceStrategies(
707 this.getWorkerChoiceStrategies(),
708 this.opts.workerChoiceStrategyOptions
709 )
710 for (const workerNodeKey of this.workerNodes.keys()) {
711 this.sendStatisticsMessageToWorker(workerNodeKey)
712 }
713 return true
714 }
715 return false
716 }
717
718 /** @inheritDoc */
719 public enableTasksQueue (
720 enable: boolean,
721 tasksQueueOptions?: TasksQueueOptions
722 ): void {
723 if (this.opts.enableTasksQueue === true && !enable) {
724 this.unsetTaskStealing()
725 this.unsetTasksStealingOnBackPressure()
726 this.flushTasksQueues()
727 }
728 this.opts.enableTasksQueue = enable
729 this.setTasksQueueOptions(tasksQueueOptions)
730 }
731
732 /** @inheritDoc */
733 public setTasksQueueOptions (
734 tasksQueueOptions: TasksQueueOptions | undefined
735 ): void {
736 if (this.opts.enableTasksQueue === true) {
737 checkValidTasksQueueOptions(tasksQueueOptions)
738 this.opts.tasksQueueOptions =
739 this.buildTasksQueueOptions(tasksQueueOptions)
740 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
741 this.setTasksQueueSize(this.opts.tasksQueueOptions.size!)
742 if (this.opts.tasksQueueOptions.taskStealing === true) {
743 this.unsetTaskStealing()
744 this.setTaskStealing()
745 } else {
746 this.unsetTaskStealing()
747 }
748 if (this.opts.tasksQueueOptions.tasksStealingOnBackPressure === true) {
749 this.unsetTasksStealingOnBackPressure()
750 this.setTasksStealingOnBackPressure()
751 } else {
752 this.unsetTasksStealingOnBackPressure()
753 }
754 } else if (this.opts.tasksQueueOptions != null) {
755 delete this.opts.tasksQueueOptions
756 }
757 }
758
759 private buildTasksQueueOptions (
760 tasksQueueOptions: TasksQueueOptions | undefined
761 ): TasksQueueOptions {
762 return {
763 ...getDefaultTasksQueueOptions(
764 this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers
765 ),
766 ...tasksQueueOptions
767 }
768 }
769
770 private setTasksQueueSize (size: number): void {
771 for (const workerNode of this.workerNodes) {
772 workerNode.tasksQueueBackPressureSize = size
773 }
774 }
775
776 private setTaskStealing (): void {
777 for (const workerNodeKey of this.workerNodes.keys()) {
778 this.workerNodes[workerNodeKey].on('idle', this.handleWorkerNodeIdleEvent)
779 }
780 }
781
782 private unsetTaskStealing (): void {
783 for (const workerNodeKey of this.workerNodes.keys()) {
784 this.workerNodes[workerNodeKey].off(
785 'idle',
786 this.handleWorkerNodeIdleEvent
787 )
788 }
789 }
790
791 private setTasksStealingOnBackPressure (): void {
792 for (const workerNodeKey of this.workerNodes.keys()) {
793 this.workerNodes[workerNodeKey].on(
794 'backPressure',
795 this.handleWorkerNodeBackPressureEvent
796 )
797 }
798 }
799
800 private unsetTasksStealingOnBackPressure (): void {
801 for (const workerNodeKey of this.workerNodes.keys()) {
802 this.workerNodes[workerNodeKey].off(
803 'backPressure',
804 this.handleWorkerNodeBackPressureEvent
805 )
806 }
807 }
808
809 /**
810 * Whether the pool is full or not.
811 *
812 * The pool filling boolean status.
813 */
814 protected get full (): boolean {
815 return (
816 this.workerNodes.length >=
817 (this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers)
818 )
819 }
820
821 /**
822 * Whether the pool is busy or not.
823 *
824 * The pool busyness boolean status.
825 */
826 protected abstract get busy (): boolean
827
828 /**
829 * Whether worker nodes are executing concurrently their tasks quota or not.
830 *
831 * @returns Worker nodes busyness boolean status.
832 */
833 protected internalBusy (): boolean {
834 if (this.opts.enableTasksQueue === true) {
835 return (
836 this.workerNodes.findIndex(
837 workerNode =>
838 workerNode.info.ready &&
839 workerNode.usage.tasks.executing <
840 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
841 this.opts.tasksQueueOptions!.concurrency!
842 ) === -1
843 )
844 }
845 return (
846 this.workerNodes.findIndex(
847 workerNode =>
848 workerNode.info.ready && workerNode.usage.tasks.executing === 0
849 ) === -1
850 )
851 }
852
853 private isWorkerNodeBusy (workerNodeKey: number): boolean {
854 if (this.opts.enableTasksQueue === true) {
855 return (
856 this.workerNodes[workerNodeKey].usage.tasks.executing >=
857 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
858 this.opts.tasksQueueOptions!.concurrency!
859 )
860 }
861 return this.workerNodes[workerNodeKey].usage.tasks.executing > 0
862 }
863
864 private async sendTaskFunctionOperationToWorker (
865 workerNodeKey: number,
866 message: MessageValue<Data>
867 ): Promise<boolean> {
868 return await new Promise<boolean>((resolve, reject) => {
869 const taskFunctionOperationListener = (
870 message: MessageValue<Response>
871 ): void => {
872 this.checkMessageWorkerId(message)
873 const workerId = this.getWorkerInfo(workerNodeKey)?.id
874 if (
875 message.taskFunctionOperationStatus != null &&
876 message.workerId === workerId
877 ) {
878 if (message.taskFunctionOperationStatus) {
879 resolve(true)
880 } else {
881 reject(
882 new Error(
883 `Task function operation '${message.taskFunctionOperation}' failed on worker ${message.workerId} with error: '${message.workerError?.message}'`
884 )
885 )
886 }
887 this.deregisterWorkerMessageListener(
888 this.getWorkerNodeKeyByWorkerId(message.workerId),
889 taskFunctionOperationListener
890 )
891 }
892 }
893 this.registerWorkerMessageListener(
894 workerNodeKey,
895 taskFunctionOperationListener
896 )
897 this.sendToWorker(workerNodeKey, message)
898 })
899 }
900
901 private async sendTaskFunctionOperationToWorkers (
902 message: MessageValue<Data>
903 ): Promise<boolean> {
904 return await new Promise<boolean>((resolve, reject) => {
905 const responsesReceived = new Array<MessageValue<Response>>()
906 const taskFunctionOperationsListener = (
907 message: MessageValue<Response>
908 ): void => {
909 this.checkMessageWorkerId(message)
910 if (message.taskFunctionOperationStatus != null) {
911 responsesReceived.push(message)
912 if (responsesReceived.length === this.workerNodes.length) {
913 if (
914 responsesReceived.every(
915 message => message.taskFunctionOperationStatus === true
916 )
917 ) {
918 resolve(true)
919 } else if (
920 responsesReceived.some(
921 message => message.taskFunctionOperationStatus === false
922 )
923 ) {
924 const errorResponse = responsesReceived.find(
925 response => response.taskFunctionOperationStatus === false
926 )
927 reject(
928 new Error(
929 `Task function operation '${
930 message.taskFunctionOperation as string
931 }' failed on worker ${errorResponse?.workerId} with error: '${
932 errorResponse?.workerError?.message
933 }'`
934 )
935 )
936 }
937 this.deregisterWorkerMessageListener(
938 this.getWorkerNodeKeyByWorkerId(message.workerId),
939 taskFunctionOperationsListener
940 )
941 }
942 }
943 }
944 for (const workerNodeKey of this.workerNodes.keys()) {
945 this.registerWorkerMessageListener(
946 workerNodeKey,
947 taskFunctionOperationsListener
948 )
949 this.sendToWorker(workerNodeKey, message)
950 }
951 })
952 }
953
954 /** @inheritDoc */
955 public hasTaskFunction (name: string): boolean {
956 return this.listTaskFunctionsProperties().some(
957 taskFunctionProperties => taskFunctionProperties.name === name
958 )
959 }
960
961 /** @inheritDoc */
962 public async addTaskFunction (
963 name: string,
964 fn: TaskFunction<Data, Response> | TaskFunctionObject<Data, Response>
965 ): Promise<boolean> {
966 if (typeof name !== 'string') {
967 throw new TypeError('name argument must be a string')
968 }
969 if (typeof name === 'string' && name.trim().length === 0) {
970 throw new TypeError('name argument must not be an empty string')
971 }
972 if (typeof fn === 'function') {
973 fn = { taskFunction: fn } satisfies TaskFunctionObject<Data, Response>
974 }
975 if (typeof fn.taskFunction !== 'function') {
976 throw new TypeError('taskFunction property must be a function')
977 }
978 checkValidPriority(fn.priority)
979 checkValidWorkerChoiceStrategy(fn.strategy)
980 const opResult = await this.sendTaskFunctionOperationToWorkers({
981 taskFunctionOperation: 'add',
982 taskFunctionProperties: buildTaskFunctionProperties(name, fn),
983 taskFunction: fn.taskFunction.toString()
984 })
985 this.taskFunctions.set(name, fn)
986 this.workerChoiceStrategiesContext?.syncWorkerChoiceStrategies(
987 this.getWorkerChoiceStrategies()
988 )
989 for (const workerNodeKey of this.workerNodes.keys()) {
990 this.sendStatisticsMessageToWorker(workerNodeKey)
991 }
992 return opResult
993 }
994
995 /** @inheritDoc */
996 public async removeTaskFunction (name: string): Promise<boolean> {
997 if (!this.taskFunctions.has(name)) {
998 throw new Error(
999 'Cannot remove a task function not handled on the pool side'
1000 )
1001 }
1002 const opResult = await this.sendTaskFunctionOperationToWorkers({
1003 taskFunctionOperation: 'remove',
1004 taskFunctionProperties: buildTaskFunctionProperties(
1005 name,
1006 this.taskFunctions.get(name)
1007 )
1008 })
1009 for (const workerNode of this.workerNodes) {
1010 workerNode.deleteTaskFunctionWorkerUsage(name)
1011 }
1012 this.taskFunctions.delete(name)
1013 this.workerChoiceStrategiesContext?.syncWorkerChoiceStrategies(
1014 this.getWorkerChoiceStrategies()
1015 )
1016 for (const workerNodeKey of this.workerNodes.keys()) {
1017 this.sendStatisticsMessageToWorker(workerNodeKey)
1018 }
1019 return opResult
1020 }
1021
1022 /** @inheritDoc */
1023 public listTaskFunctionsProperties (): TaskFunctionProperties[] {
1024 for (const workerNode of this.workerNodes) {
1025 if (
1026 Array.isArray(workerNode.info.taskFunctionsProperties) &&
1027 workerNode.info.taskFunctionsProperties.length > 0
1028 ) {
1029 return workerNode.info.taskFunctionsProperties
1030 }
1031 }
1032 return []
1033 }
1034
1035 /**
1036 * Gets task function worker choice strategy, if any.
1037 *
1038 * @param name - The task function name.
1039 * @returns The task function worker choice strategy if the task function worker choice strategy is defined, `undefined` otherwise.
1040 */
1041 private readonly getTaskFunctionWorkerChoiceStrategy = (
1042 name?: string
1043 ): WorkerChoiceStrategy | undefined => {
1044 name = name ?? DEFAULT_TASK_NAME
1045 const taskFunctionsProperties = this.listTaskFunctionsProperties()
1046 if (name === DEFAULT_TASK_NAME) {
1047 name = taskFunctionsProperties[1]?.name
1048 }
1049 return taskFunctionsProperties.find(
1050 (taskFunctionProperties: TaskFunctionProperties) =>
1051 taskFunctionProperties.name === name
1052 )?.strategy
1053 }
1054
1055 /**
1056 * Gets worker node task function worker choice strategy, if any.
1057 *
1058 * @param workerNodeKey - The worker node key.
1059 * @param name - The task function name.
1060 * @returns The worker node task function worker choice strategy if the worker node task function worker choice strategy is defined, `undefined` otherwise.
1061 */
1062 private readonly getWorkerNodeTaskFunctionWorkerChoiceStrategy = (
1063 workerNodeKey: number,
1064 name?: string
1065 ): WorkerChoiceStrategy | undefined => {
1066 const workerInfo = this.getWorkerInfo(workerNodeKey)
1067 if (workerInfo == null) {
1068 return
1069 }
1070 name = name ?? DEFAULT_TASK_NAME
1071 if (name === DEFAULT_TASK_NAME) {
1072 name = workerInfo.taskFunctionsProperties?.[1]?.name
1073 }
1074 return workerInfo.taskFunctionsProperties?.find(
1075 (taskFunctionProperties: TaskFunctionProperties) =>
1076 taskFunctionProperties.name === name
1077 )?.strategy
1078 }
1079
1080 /**
1081 * Gets worker node task function priority, if any.
1082 *
1083 * @param workerNodeKey - The worker node key.
1084 * @param name - The task function name.
1085 * @returns The worker node task function priority if the worker node task function priority is defined, `undefined` otherwise.
1086 */
1087 private readonly getWorkerNodeTaskFunctionPriority = (
1088 workerNodeKey: number,
1089 name?: string
1090 ): number | undefined => {
1091 const workerInfo = this.getWorkerInfo(workerNodeKey)
1092 if (workerInfo == null) {
1093 return
1094 }
1095 name = name ?? DEFAULT_TASK_NAME
1096 if (name === DEFAULT_TASK_NAME) {
1097 name = workerInfo.taskFunctionsProperties?.[1]?.name
1098 }
1099 return workerInfo.taskFunctionsProperties?.find(
1100 (taskFunctionProperties: TaskFunctionProperties) =>
1101 taskFunctionProperties.name === name
1102 )?.priority
1103 }
1104
1105 /**
1106 * Gets the worker choice strategies registered in this pool.
1107 *
1108 * @returns The worker choice strategies.
1109 */
1110 private readonly getWorkerChoiceStrategies =
1111 (): Set<WorkerChoiceStrategy> => {
1112 return new Set([
1113 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1114 this.opts.workerChoiceStrategy!,
1115 ...(this.listTaskFunctionsProperties()
1116 .map(
1117 (taskFunctionProperties: TaskFunctionProperties) =>
1118 taskFunctionProperties.strategy
1119 )
1120 .filter(
1121 (strategy: WorkerChoiceStrategy | undefined) => strategy != null
1122 ) as WorkerChoiceStrategy[])
1123 ])
1124 }
1125
1126 /** @inheritDoc */
1127 public async setDefaultTaskFunction (name: string): Promise<boolean> {
1128 return await this.sendTaskFunctionOperationToWorkers({
1129 taskFunctionOperation: 'default',
1130 taskFunctionProperties: buildTaskFunctionProperties(
1131 name,
1132 this.taskFunctions.get(name)
1133 )
1134 })
1135 }
1136
1137 private shallExecuteTask (workerNodeKey: number): boolean {
1138 return (
1139 this.tasksQueueSize(workerNodeKey) === 0 &&
1140 this.workerNodes[workerNodeKey].usage.tasks.executing <
1141 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1142 this.opts.tasksQueueOptions!.concurrency!
1143 )
1144 }
1145
1146 /** @inheritDoc */
1147 public async execute (
1148 data?: Data,
1149 name?: string,
1150 transferList?: readonly TransferListItem[]
1151 ): Promise<Response> {
1152 return await new Promise<Response>((resolve, reject) => {
1153 if (!this.started) {
1154 reject(new Error('Cannot execute a task on not started pool'))
1155 return
1156 }
1157 if (this.destroying) {
1158 reject(new Error('Cannot execute a task on destroying pool'))
1159 return
1160 }
1161 if (name != null && typeof name !== 'string') {
1162 reject(new TypeError('name argument must be a string'))
1163 return
1164 }
1165 if (
1166 name != null &&
1167 typeof name === 'string' &&
1168 name.trim().length === 0
1169 ) {
1170 reject(new TypeError('name argument must not be an empty string'))
1171 return
1172 }
1173 if (transferList != null && !Array.isArray(transferList)) {
1174 reject(new TypeError('transferList argument must be an array'))
1175 return
1176 }
1177 const timestamp = performance.now()
1178 const workerNodeKey = this.chooseWorkerNode(name)
1179 const task: Task<Data> = {
1180 name: name ?? DEFAULT_TASK_NAME,
1181 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
1182 data: data ?? ({} as Data),
1183 priority: this.getWorkerNodeTaskFunctionPriority(workerNodeKey, name),
1184 strategy: this.getWorkerNodeTaskFunctionWorkerChoiceStrategy(
1185 workerNodeKey,
1186 name
1187 ),
1188 transferList,
1189 timestamp,
1190 taskId: randomUUID()
1191 }
1192 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1193 this.promiseResponseMap.set(task.taskId!, {
1194 resolve,
1195 reject,
1196 workerNodeKey,
1197 ...(this.emitter != null && {
1198 asyncResource: new AsyncResource('poolifier:task', {
1199 triggerAsyncId: this.emitter.asyncId,
1200 requireManualDestroy: true
1201 })
1202 })
1203 })
1204 if (
1205 this.opts.enableTasksQueue === false ||
1206 (this.opts.enableTasksQueue === true &&
1207 this.shallExecuteTask(workerNodeKey))
1208 ) {
1209 this.executeTask(workerNodeKey, task)
1210 } else {
1211 this.enqueueTask(workerNodeKey, task)
1212 }
1213 })
1214 }
1215
1216 /**
1217 * Starts the minimum number of workers.
1218 */
1219 private startMinimumNumberOfWorkers (initWorkerNodeUsage = false): void {
1220 this.startingMinimumNumberOfWorkers = true
1221 while (
1222 this.workerNodes.reduce(
1223 (accumulator, workerNode) =>
1224 !workerNode.info.dynamic ? accumulator + 1 : accumulator,
1225 0
1226 ) < this.minimumNumberOfWorkers
1227 ) {
1228 const workerNodeKey = this.createAndSetupWorkerNode()
1229 initWorkerNodeUsage &&
1230 this.initWorkerNodeUsage(this.workerNodes[workerNodeKey])
1231 }
1232 this.startingMinimumNumberOfWorkers = false
1233 }
1234
1235 /** @inheritdoc */
1236 public start (): void {
1237 if (this.started) {
1238 throw new Error('Cannot start an already started pool')
1239 }
1240 if (this.starting) {
1241 throw new Error('Cannot start an already starting pool')
1242 }
1243 if (this.destroying) {
1244 throw new Error('Cannot start a destroying pool')
1245 }
1246 this.starting = true
1247 this.startMinimumNumberOfWorkers()
1248 this.startTimestamp = performance.now()
1249 this.starting = false
1250 this.started = true
1251 }
1252
1253 /** @inheritDoc */
1254 public async destroy (): Promise<void> {
1255 if (!this.started) {
1256 throw new Error('Cannot destroy an already destroyed pool')
1257 }
1258 if (this.starting) {
1259 throw new Error('Cannot destroy an starting pool')
1260 }
1261 if (this.destroying) {
1262 throw new Error('Cannot destroy an already destroying pool')
1263 }
1264 this.destroying = true
1265 await Promise.all(
1266 this.workerNodes.map(async (_, workerNodeKey) => {
1267 await this.destroyWorkerNode(workerNodeKey)
1268 })
1269 )
1270 this.emitter?.emit(PoolEvents.destroy, this.info)
1271 this.emitter?.emitDestroy()
1272 this.readyEventEmitted = false
1273 delete this.startTimestamp
1274 this.destroying = false
1275 this.started = false
1276 }
1277
1278 private async sendKillMessageToWorker (workerNodeKey: number): Promise<void> {
1279 await new Promise<void>((resolve, reject) => {
1280 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1281 if (this.workerNodes[workerNodeKey] == null) {
1282 resolve()
1283 return
1284 }
1285 const killMessageListener = (message: MessageValue<Response>): void => {
1286 this.checkMessageWorkerId(message)
1287 if (message.kill === 'success') {
1288 resolve()
1289 } else if (message.kill === 'failure') {
1290 reject(
1291 new Error(
1292 `Kill message handling failed on worker ${message.workerId}`
1293 )
1294 )
1295 }
1296 }
1297 // FIXME: should be registered only once
1298 this.registerWorkerMessageListener(workerNodeKey, killMessageListener)
1299 this.sendToWorker(workerNodeKey, { kill: true })
1300 })
1301 }
1302
1303 /**
1304 * Terminates the worker node given its worker node key.
1305 *
1306 * @param workerNodeKey - The worker node key.
1307 */
1308 protected async destroyWorkerNode (workerNodeKey: number): Promise<void> {
1309 this.flagWorkerNodeAsNotReady(workerNodeKey)
1310 const flushedTasks = this.flushTasksQueue(workerNodeKey)
1311 const workerNode = this.workerNodes[workerNodeKey]
1312 await waitWorkerNodeEvents(
1313 workerNode,
1314 'taskFinished',
1315 flushedTasks,
1316 this.opts.tasksQueueOptions?.tasksFinishedTimeout ??
1317 getDefaultTasksQueueOptions(
1318 this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers
1319 ).tasksFinishedTimeout
1320 )
1321 await this.sendKillMessageToWorker(workerNodeKey)
1322 await workerNode.terminate()
1323 }
1324
1325 /**
1326 * Setup hook to execute code before worker nodes are created in the abstract constructor.
1327 * Can be overridden.
1328 *
1329 * @virtual
1330 */
1331 protected setupHook (): void {
1332 /* Intentionally empty */
1333 }
1334
1335 /**
1336 * Returns whether the worker is the main worker or not.
1337 *
1338 * @returns `true` if the worker is the main worker, `false` otherwise.
1339 */
1340 protected abstract isMain (): boolean
1341
1342 /**
1343 * Hook executed before the worker task execution.
1344 * Can be overridden.
1345 *
1346 * @param workerNodeKey - The worker node key.
1347 * @param task - The task to execute.
1348 */
1349 protected beforeTaskExecutionHook (
1350 workerNodeKey: number,
1351 task: Task<Data>
1352 ): void {
1353 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1354 if (this.workerNodes[workerNodeKey]?.usage != null) {
1355 const workerUsage = this.workerNodes[workerNodeKey].usage
1356 ++workerUsage.tasks.executing
1357 updateWaitTimeWorkerUsage(
1358 this.workerChoiceStrategiesContext,
1359 workerUsage,
1360 task
1361 )
1362 }
1363 if (
1364 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) &&
1365 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1366 this.workerNodes[workerNodeKey].getTaskFunctionWorkerUsage(task.name!) !=
1367 null
1368 ) {
1369 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1370 const taskFunctionWorkerUsage = this.workerNodes[
1371 workerNodeKey
1372 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1373 ].getTaskFunctionWorkerUsage(task.name!)!
1374 ++taskFunctionWorkerUsage.tasks.executing
1375 updateWaitTimeWorkerUsage(
1376 this.workerChoiceStrategiesContext,
1377 taskFunctionWorkerUsage,
1378 task
1379 )
1380 }
1381 }
1382
1383 /**
1384 * Hook executed after the worker task execution.
1385 * Can be overridden.
1386 *
1387 * @param workerNodeKey - The worker node key.
1388 * @param message - The received message.
1389 */
1390 protected afterTaskExecutionHook (
1391 workerNodeKey: number,
1392 message: MessageValue<Response>
1393 ): void {
1394 let needWorkerChoiceStrategiesUpdate = false
1395 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1396 if (this.workerNodes[workerNodeKey]?.usage != null) {
1397 const workerUsage = this.workerNodes[workerNodeKey].usage
1398 updateTaskStatisticsWorkerUsage(workerUsage, message)
1399 updateRunTimeWorkerUsage(
1400 this.workerChoiceStrategiesContext,
1401 workerUsage,
1402 message
1403 )
1404 updateEluWorkerUsage(
1405 this.workerChoiceStrategiesContext,
1406 workerUsage,
1407 message
1408 )
1409 needWorkerChoiceStrategiesUpdate = true
1410 }
1411 if (
1412 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) &&
1413 this.workerNodes[workerNodeKey].getTaskFunctionWorkerUsage(
1414 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1415 message.taskPerformance!.name
1416 ) != null
1417 ) {
1418 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1419 const taskFunctionWorkerUsage = this.workerNodes[
1420 workerNodeKey
1421 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1422 ].getTaskFunctionWorkerUsage(message.taskPerformance!.name)!
1423 updateTaskStatisticsWorkerUsage(taskFunctionWorkerUsage, message)
1424 updateRunTimeWorkerUsage(
1425 this.workerChoiceStrategiesContext,
1426 taskFunctionWorkerUsage,
1427 message
1428 )
1429 updateEluWorkerUsage(
1430 this.workerChoiceStrategiesContext,
1431 taskFunctionWorkerUsage,
1432 message
1433 )
1434 needWorkerChoiceStrategiesUpdate = true
1435 }
1436 if (needWorkerChoiceStrategiesUpdate) {
1437 this.workerChoiceStrategiesContext?.update(workerNodeKey)
1438 }
1439 }
1440
1441 /**
1442 * Whether the worker node shall update its task function worker usage or not.
1443 *
1444 * @param workerNodeKey - The worker node key.
1445 * @returns `true` if the worker node shall update its task function worker usage, `false` otherwise.
1446 */
1447 private shallUpdateTaskFunctionWorkerUsage (workerNodeKey: number): boolean {
1448 const workerInfo = this.getWorkerInfo(workerNodeKey)
1449 return (
1450 workerInfo != null &&
1451 Array.isArray(workerInfo.taskFunctionsProperties) &&
1452 workerInfo.taskFunctionsProperties.length > 2
1453 )
1454 }
1455
1456 /**
1457 * Chooses a worker node for the next task.
1458 *
1459 * @param name - The task function name.
1460 * @returns The chosen worker node key
1461 */
1462 private chooseWorkerNode (name?: string): number {
1463 if (this.shallCreateDynamicWorker()) {
1464 const workerNodeKey = this.createAndSetupDynamicWorkerNode()
1465 if (
1466 this.workerChoiceStrategiesContext?.getPolicy().dynamicWorkerUsage ===
1467 true
1468 ) {
1469 return workerNodeKey
1470 }
1471 }
1472 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1473 return this.workerChoiceStrategiesContext!.execute(
1474 this.getTaskFunctionWorkerChoiceStrategy(name)
1475 )
1476 }
1477
1478 /**
1479 * Conditions for dynamic worker creation.
1480 *
1481 * @returns Whether to create a dynamic worker or not.
1482 */
1483 protected abstract shallCreateDynamicWorker (): boolean
1484
1485 /**
1486 * Sends a message to worker given its worker node key.
1487 *
1488 * @param workerNodeKey - The worker node key.
1489 * @param message - The message.
1490 * @param transferList - The optional array of transferable objects.
1491 */
1492 protected abstract sendToWorker (
1493 workerNodeKey: number,
1494 message: MessageValue<Data>,
1495 transferList?: readonly TransferListItem[]
1496 ): void
1497
1498 /**
1499 * Initializes the worker node usage with sensible default values gathered during runtime.
1500 *
1501 * @param workerNode - The worker node.
1502 */
1503 private initWorkerNodeUsage (workerNode: IWorkerNode<Worker, Data>): void {
1504 if (
1505 this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements()
1506 .runTime.aggregate === true
1507 ) {
1508 workerNode.usage.runTime.aggregate = min(
1509 ...this.workerNodes.map(
1510 workerNode =>
1511 workerNode.usage.runTime.aggregate ?? Number.POSITIVE_INFINITY
1512 )
1513 )
1514 }
1515 if (
1516 this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements()
1517 .waitTime.aggregate === true
1518 ) {
1519 workerNode.usage.waitTime.aggregate = min(
1520 ...this.workerNodes.map(
1521 workerNode =>
1522 workerNode.usage.waitTime.aggregate ?? Number.POSITIVE_INFINITY
1523 )
1524 )
1525 }
1526 if (
1527 this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements().elu
1528 .aggregate === true
1529 ) {
1530 workerNode.usage.elu.active.aggregate = min(
1531 ...this.workerNodes.map(
1532 workerNode =>
1533 workerNode.usage.elu.active.aggregate ?? Number.POSITIVE_INFINITY
1534 )
1535 )
1536 }
1537 }
1538
1539 /**
1540 * Creates a new, completely set up worker node.
1541 *
1542 * @returns New, completely set up worker node key.
1543 */
1544 protected createAndSetupWorkerNode (): number {
1545 const workerNode = this.createWorkerNode()
1546 workerNode.registerWorkerEventHandler(
1547 'online',
1548 this.opts.onlineHandler ?? EMPTY_FUNCTION
1549 )
1550 workerNode.registerWorkerEventHandler(
1551 'message',
1552 this.opts.messageHandler ?? EMPTY_FUNCTION
1553 )
1554 workerNode.registerWorkerEventHandler(
1555 'error',
1556 this.opts.errorHandler ?? EMPTY_FUNCTION
1557 )
1558 workerNode.registerOnceWorkerEventHandler('error', (error: Error) => {
1559 workerNode.info.ready = false
1560 this.emitter?.emit(PoolEvents.error, error)
1561 if (
1562 this.started &&
1563 !this.destroying &&
1564 this.opts.restartWorkerOnError === true
1565 ) {
1566 if (workerNode.info.dynamic) {
1567 this.createAndSetupDynamicWorkerNode()
1568 } else if (!this.startingMinimumNumberOfWorkers) {
1569 this.startMinimumNumberOfWorkers(true)
1570 }
1571 }
1572 if (
1573 this.started &&
1574 !this.destroying &&
1575 this.opts.enableTasksQueue === true
1576 ) {
1577 this.redistributeQueuedTasks(this.workerNodes.indexOf(workerNode))
1578 }
1579 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1580 workerNode?.terminate().catch((error: unknown) => {
1581 this.emitter?.emit(PoolEvents.error, error)
1582 })
1583 })
1584 workerNode.registerWorkerEventHandler(
1585 'exit',
1586 this.opts.exitHandler ?? EMPTY_FUNCTION
1587 )
1588 workerNode.registerOnceWorkerEventHandler('exit', () => {
1589 this.removeWorkerNode(workerNode)
1590 if (
1591 this.started &&
1592 !this.startingMinimumNumberOfWorkers &&
1593 !this.destroying
1594 ) {
1595 this.startMinimumNumberOfWorkers(true)
1596 }
1597 })
1598 const workerNodeKey = this.addWorkerNode(workerNode)
1599 this.afterWorkerNodeSetup(workerNodeKey)
1600 return workerNodeKey
1601 }
1602
1603 /**
1604 * Creates a new, completely set up dynamic worker node.
1605 *
1606 * @returns New, completely set up dynamic worker node key.
1607 */
1608 protected createAndSetupDynamicWorkerNode (): number {
1609 const workerNodeKey = this.createAndSetupWorkerNode()
1610 this.registerWorkerMessageListener(workerNodeKey, message => {
1611 this.checkMessageWorkerId(message)
1612 const localWorkerNodeKey = this.getWorkerNodeKeyByWorkerId(
1613 message.workerId
1614 )
1615 const workerInfo = this.getWorkerInfo(localWorkerNodeKey)
1616 const workerUsage = this.workerNodes[localWorkerNodeKey]?.usage
1617 // Kill message received from worker
1618 if (
1619 isKillBehavior(KillBehaviors.HARD, message.kill) ||
1620 (isKillBehavior(KillBehaviors.SOFT, message.kill) &&
1621 ((this.opts.enableTasksQueue === false &&
1622 workerUsage.tasks.executing === 0) ||
1623 (this.opts.enableTasksQueue === true &&
1624 workerInfo != null &&
1625 !workerInfo.stealing &&
1626 workerUsage.tasks.executing === 0 &&
1627 this.tasksQueueSize(localWorkerNodeKey) === 0)))
1628 ) {
1629 // Flag the worker node as not ready immediately
1630 this.flagWorkerNodeAsNotReady(localWorkerNodeKey)
1631 this.destroyWorkerNode(localWorkerNodeKey).catch((error: unknown) => {
1632 this.emitter?.emit(PoolEvents.error, error)
1633 })
1634 }
1635 })
1636 this.sendToWorker(workerNodeKey, {
1637 checkActive: true
1638 })
1639 if (this.taskFunctions.size > 0) {
1640 for (const [taskFunctionName, taskFunctionObject] of this.taskFunctions) {
1641 this.sendTaskFunctionOperationToWorker(workerNodeKey, {
1642 taskFunctionOperation: 'add',
1643 taskFunctionProperties: buildTaskFunctionProperties(
1644 taskFunctionName,
1645 taskFunctionObject
1646 ),
1647 taskFunction: taskFunctionObject.taskFunction.toString()
1648 }).catch((error: unknown) => {
1649 this.emitter?.emit(PoolEvents.error, error)
1650 })
1651 }
1652 }
1653 const workerNode = this.workerNodes[workerNodeKey]
1654 workerNode.info.dynamic = true
1655 if (
1656 this.workerChoiceStrategiesContext?.getPolicy().dynamicWorkerReady ===
1657 true ||
1658 this.workerChoiceStrategiesContext?.getPolicy().dynamicWorkerUsage ===
1659 true
1660 ) {
1661 workerNode.info.ready = true
1662 }
1663 this.initWorkerNodeUsage(workerNode)
1664 this.checkAndEmitDynamicWorkerCreationEvents()
1665 return workerNodeKey
1666 }
1667
1668 /**
1669 * Registers a listener callback on the worker given its worker node key.
1670 *
1671 * @param workerNodeKey - The worker node key.
1672 * @param listener - The message listener callback.
1673 */
1674 protected abstract registerWorkerMessageListener<
1675 Message extends Data | Response
1676 >(
1677 workerNodeKey: number,
1678 listener: (message: MessageValue<Message>) => void
1679 ): void
1680
1681 /**
1682 * Registers once a listener callback on the worker given its worker node key.
1683 *
1684 * @param workerNodeKey - The worker node key.
1685 * @param listener - The message listener callback.
1686 */
1687 protected abstract registerOnceWorkerMessageListener<
1688 Message extends Data | Response
1689 >(
1690 workerNodeKey: number,
1691 listener: (message: MessageValue<Message>) => void
1692 ): void
1693
1694 /**
1695 * Deregisters a listener callback on the worker given its worker node key.
1696 *
1697 * @param workerNodeKey - The worker node key.
1698 * @param listener - The message listener callback.
1699 */
1700 protected abstract deregisterWorkerMessageListener<
1701 Message extends Data | Response
1702 >(
1703 workerNodeKey: number,
1704 listener: (message: MessageValue<Message>) => void
1705 ): void
1706
1707 /**
1708 * Method hooked up after a worker node has been newly created.
1709 * Can be overridden.
1710 *
1711 * @param workerNodeKey - The newly created worker node key.
1712 */
1713 protected afterWorkerNodeSetup (workerNodeKey: number): void {
1714 // Listen to worker messages.
1715 this.registerWorkerMessageListener(
1716 workerNodeKey,
1717 this.workerMessageListener
1718 )
1719 // Send the startup message to worker.
1720 this.sendStartupMessageToWorker(workerNodeKey)
1721 // Send the statistics message to worker.
1722 this.sendStatisticsMessageToWorker(workerNodeKey)
1723 if (this.opts.enableTasksQueue === true) {
1724 if (this.opts.tasksQueueOptions?.taskStealing === true) {
1725 this.workerNodes[workerNodeKey].on(
1726 'idle',
1727 this.handleWorkerNodeIdleEvent
1728 )
1729 }
1730 if (this.opts.tasksQueueOptions?.tasksStealingOnBackPressure === true) {
1731 this.workerNodes[workerNodeKey].on(
1732 'backPressure',
1733 this.handleWorkerNodeBackPressureEvent
1734 )
1735 }
1736 }
1737 }
1738
1739 /**
1740 * Sends the startup message to worker given its worker node key.
1741 *
1742 * @param workerNodeKey - The worker node key.
1743 */
1744 protected abstract sendStartupMessageToWorker (workerNodeKey: number): void
1745
1746 /**
1747 * Sends the statistics message to worker given its worker node key.
1748 *
1749 * @param workerNodeKey - The worker node key.
1750 */
1751 private sendStatisticsMessageToWorker (workerNodeKey: number): void {
1752 this.sendToWorker(workerNodeKey, {
1753 statistics: {
1754 runTime:
1755 this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements()
1756 .runTime.aggregate ?? false,
1757 elu:
1758 this.workerChoiceStrategiesContext?.getTaskStatisticsRequirements()
1759 .elu.aggregate ?? false
1760 }
1761 })
1762 }
1763
1764 private cannotStealTask (): boolean {
1765 return this.workerNodes.length <= 1 || this.info.queuedTasks === 0
1766 }
1767
1768 private handleTask (workerNodeKey: number, task: Task<Data>): void {
1769 if (this.shallExecuteTask(workerNodeKey)) {
1770 this.executeTask(workerNodeKey, task)
1771 } else {
1772 this.enqueueTask(workerNodeKey, task)
1773 }
1774 }
1775
1776 private redistributeQueuedTasks (sourceWorkerNodeKey: number): void {
1777 if (sourceWorkerNodeKey === -1 || this.cannotStealTask()) {
1778 return
1779 }
1780 while (this.tasksQueueSize(sourceWorkerNodeKey) > 0) {
1781 const destinationWorkerNodeKey = this.workerNodes.reduce(
1782 (minWorkerNodeKey, workerNode, workerNodeKey, workerNodes) => {
1783 return sourceWorkerNodeKey !== workerNodeKey &&
1784 workerNode.info.ready &&
1785 workerNode.usage.tasks.queued <
1786 workerNodes[minWorkerNodeKey].usage.tasks.queued
1787 ? workerNodeKey
1788 : minWorkerNodeKey
1789 },
1790 0
1791 )
1792 this.handleTask(
1793 destinationWorkerNodeKey,
1794 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1795 this.dequeueTask(sourceWorkerNodeKey)!
1796 )
1797 }
1798 }
1799
1800 private updateTaskStolenStatisticsWorkerUsage (
1801 workerNodeKey: number,
1802 taskName: string
1803 ): void {
1804 const workerNode = this.workerNodes[workerNodeKey]
1805 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1806 if (workerNode?.usage != null) {
1807 ++workerNode.usage.tasks.stolen
1808 }
1809 if (
1810 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) &&
1811 workerNode.getTaskFunctionWorkerUsage(taskName) != null
1812 ) {
1813 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1814 ++workerNode.getTaskFunctionWorkerUsage(taskName)!.tasks.stolen
1815 }
1816 }
1817
1818 private updateTaskSequentiallyStolenStatisticsWorkerUsage (
1819 workerNodeKey: number,
1820 taskName: string,
1821 previousTaskName?: string
1822 ): void {
1823 const workerNode = this.workerNodes[workerNodeKey]
1824 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1825 if (workerNode?.usage != null) {
1826 ++workerNode.usage.tasks.sequentiallyStolen
1827 }
1828 if (
1829 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) &&
1830 workerNode.getTaskFunctionWorkerUsage(taskName) != null
1831 ) {
1832 const taskFunctionWorkerUsage =
1833 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1834 workerNode.getTaskFunctionWorkerUsage(taskName)!
1835 if (
1836 taskFunctionWorkerUsage.tasks.sequentiallyStolen === 0 ||
1837 (previousTaskName != null &&
1838 previousTaskName === taskName &&
1839 taskFunctionWorkerUsage.tasks.sequentiallyStolen > 0)
1840 ) {
1841 ++taskFunctionWorkerUsage.tasks.sequentiallyStolen
1842 } else if (taskFunctionWorkerUsage.tasks.sequentiallyStolen > 0) {
1843 taskFunctionWorkerUsage.tasks.sequentiallyStolen = 0
1844 }
1845 }
1846 }
1847
1848 private resetTaskSequentiallyStolenStatisticsWorkerUsage (
1849 workerNodeKey: number,
1850 taskName: string
1851 ): void {
1852 const workerNode = this.workerNodes[workerNodeKey]
1853 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
1854 if (workerNode?.usage != null) {
1855 workerNode.usage.tasks.sequentiallyStolen = 0
1856 }
1857 if (
1858 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) &&
1859 workerNode.getTaskFunctionWorkerUsage(taskName) != null
1860 ) {
1861 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1862 workerNode.getTaskFunctionWorkerUsage(
1863 taskName
1864 )!.tasks.sequentiallyStolen = 0
1865 }
1866 }
1867
1868 private readonly handleWorkerNodeIdleEvent = (
1869 eventDetail: WorkerNodeEventDetail,
1870 previousStolenTask?: Task<Data>
1871 ): void => {
1872 const { workerNodeKey } = eventDetail
1873 if (workerNodeKey == null) {
1874 throw new Error(
1875 "WorkerNode event detail 'workerNodeKey' property must be defined"
1876 )
1877 }
1878 const workerInfo = this.getWorkerInfo(workerNodeKey)
1879 if (workerInfo == null) {
1880 throw new Error(
1881 `Worker node with key '${workerNodeKey}' not found in pool`
1882 )
1883 }
1884 if (
1885 this.cannotStealTask() ||
1886 (this.info.stealingWorkerNodes ?? 0) >
1887 Math.floor(this.workerNodes.length / 2)
1888 ) {
1889 if (previousStolenTask != null) {
1890 workerInfo.stealing = false
1891 this.resetTaskSequentiallyStolenStatisticsWorkerUsage(
1892 workerNodeKey,
1893 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1894 previousStolenTask.name!
1895 )
1896 }
1897 return
1898 }
1899 const workerNodeTasksUsage = this.workerNodes[workerNodeKey].usage.tasks
1900 if (
1901 previousStolenTask != null &&
1902 (workerNodeTasksUsage.executing > 0 ||
1903 this.tasksQueueSize(workerNodeKey) > 0)
1904 ) {
1905 workerInfo.stealing = false
1906 this.resetTaskSequentiallyStolenStatisticsWorkerUsage(
1907 workerNodeKey,
1908 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1909 previousStolenTask.name!
1910 )
1911 return
1912 }
1913 workerInfo.stealing = true
1914 const stolenTask = this.workerNodeStealTask(workerNodeKey)
1915 if (stolenTask != null) {
1916 this.updateTaskSequentiallyStolenStatisticsWorkerUsage(
1917 workerNodeKey,
1918 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1919 stolenTask.name!,
1920 previousStolenTask?.name
1921 )
1922 }
1923 sleep(exponentialDelay(workerNodeTasksUsage.sequentiallyStolen))
1924 .then(() => {
1925 this.handleWorkerNodeIdleEvent(eventDetail, stolenTask)
1926 return undefined
1927 })
1928 .catch((error: unknown) => {
1929 this.emitter?.emit(PoolEvents.error, error)
1930 })
1931 }
1932
1933 private readonly workerNodeStealTask = (
1934 workerNodeKey: number
1935 ): Task<Data> | undefined => {
1936 const workerNodes = this.workerNodes
1937 .slice()
1938 .sort(
1939 (workerNodeA, workerNodeB) =>
1940 workerNodeB.usage.tasks.queued - workerNodeA.usage.tasks.queued
1941 )
1942 const sourceWorkerNode = workerNodes.find(
1943 (sourceWorkerNode, sourceWorkerNodeKey) =>
1944 sourceWorkerNode.info.ready &&
1945 !sourceWorkerNode.info.stealing &&
1946 sourceWorkerNodeKey !== workerNodeKey &&
1947 sourceWorkerNode.usage.tasks.queued > 0
1948 )
1949 if (sourceWorkerNode != null) {
1950 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1951 const task = sourceWorkerNode.dequeueLastPrioritizedTask()!
1952 this.handleTask(workerNodeKey, task)
1953 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1954 this.updateTaskStolenStatisticsWorkerUsage(workerNodeKey, task.name!)
1955 return task
1956 }
1957 }
1958
1959 private readonly handleWorkerNodeBackPressureEvent = (
1960 eventDetail: WorkerNodeEventDetail
1961 ): void => {
1962 if (
1963 this.cannotStealTask() ||
1964 this.hasBackPressure() ||
1965 (this.info.stealingWorkerNodes ?? 0) >
1966 Math.floor(this.workerNodes.length / 2)
1967 ) {
1968 return
1969 }
1970 const sizeOffset = 1
1971 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1972 if (this.opts.tasksQueueOptions!.size! <= sizeOffset) {
1973 return
1974 }
1975 const { workerId } = eventDetail
1976 const sourceWorkerNode =
1977 this.workerNodes[this.getWorkerNodeKeyByWorkerId(workerId)]
1978 const workerNodes = this.workerNodes
1979 .slice()
1980 .sort(
1981 (workerNodeA, workerNodeB) =>
1982 workerNodeA.usage.tasks.queued - workerNodeB.usage.tasks.queued
1983 )
1984 for (const [workerNodeKey, workerNode] of workerNodes.entries()) {
1985 if (
1986 sourceWorkerNode.usage.tasks.queued > 0 &&
1987 workerNode.info.ready &&
1988 !workerNode.info.stealing &&
1989 workerNode.info.id !== workerId &&
1990 workerNode.usage.tasks.queued <
1991 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1992 this.opts.tasksQueueOptions!.size! - sizeOffset
1993 ) {
1994 const workerInfo = this.getWorkerInfo(workerNodeKey)
1995 if (workerInfo == null) {
1996 throw new Error(
1997 `Worker node with key '${workerNodeKey}' not found in pool`
1998 )
1999 }
2000 workerInfo.stealing = true
2001 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2002 const task = sourceWorkerNode.dequeueLastPrioritizedTask()!
2003 this.handleTask(workerNodeKey, task)
2004 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2005 this.updateTaskStolenStatisticsWorkerUsage(workerNodeKey, task.name!)
2006 workerInfo.stealing = false
2007 }
2008 }
2009 }
2010
2011 /**
2012 * This method is the message listener registered on each worker.
2013 */
2014 protected readonly workerMessageListener = (
2015 message: MessageValue<Response>
2016 ): void => {
2017 this.checkMessageWorkerId(message)
2018 const { workerId, ready, taskId, taskFunctionsProperties } = message
2019 if (ready != null && taskFunctionsProperties != null) {
2020 // Worker ready response received from worker
2021 this.handleWorkerReadyResponse(message)
2022 } else if (taskFunctionsProperties != null) {
2023 // Task function properties message received from worker
2024 const workerNodeKey = this.getWorkerNodeKeyByWorkerId(workerId)
2025 const workerInfo = this.getWorkerInfo(workerNodeKey)
2026 if (workerInfo != null) {
2027 workerInfo.taskFunctionsProperties = taskFunctionsProperties
2028 this.sendStatisticsMessageToWorker(workerNodeKey)
2029 }
2030 } else if (taskId != null) {
2031 // Task execution response received from worker
2032 this.handleTaskExecutionResponse(message)
2033 }
2034 }
2035
2036 private checkAndEmitReadyEvent (): void {
2037 if (!this.readyEventEmitted && this.ready) {
2038 this.emitter?.emit(PoolEvents.ready, this.info)
2039 this.readyEventEmitted = true
2040 }
2041 }
2042
2043 private handleWorkerReadyResponse (message: MessageValue<Response>): void {
2044 const { workerId, ready, taskFunctionsProperties } = message
2045 if (ready == null || !ready) {
2046 throw new Error(`Worker ${workerId} failed to initialize`)
2047 }
2048 const workerNodeKey = this.getWorkerNodeKeyByWorkerId(workerId)
2049 const workerNode = this.workerNodes[workerNodeKey]
2050 workerNode.info.ready = ready
2051 workerNode.info.taskFunctionsProperties = taskFunctionsProperties
2052 this.sendStatisticsMessageToWorker(workerNodeKey)
2053 this.checkAndEmitReadyEvent()
2054 }
2055
2056 private handleTaskExecutionResponse (message: MessageValue<Response>): void {
2057 const { workerId, taskId, workerError, data } = message
2058 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2059 const promiseResponse = this.promiseResponseMap.get(taskId!)
2060 if (promiseResponse != null) {
2061 const { resolve, reject, workerNodeKey, asyncResource } = promiseResponse
2062 const workerNode = this.workerNodes[workerNodeKey]
2063 if (workerError != null) {
2064 this.emitter?.emit(PoolEvents.taskError, workerError)
2065 asyncResource != null
2066 ? asyncResource.runInAsyncScope(
2067 reject,
2068 this.emitter,
2069 workerError.message
2070 )
2071 : reject(workerError.message)
2072 } else {
2073 asyncResource != null
2074 ? asyncResource.runInAsyncScope(resolve, this.emitter, data)
2075 : resolve(data as Response)
2076 }
2077 asyncResource?.emitDestroy()
2078 this.afterTaskExecutionHook(workerNodeKey, message)
2079 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2080 this.promiseResponseMap.delete(taskId!)
2081 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
2082 workerNode?.emit('taskFinished', taskId)
2083 if (
2084 this.opts.enableTasksQueue === true &&
2085 !this.destroying &&
2086 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
2087 workerNode != null
2088 ) {
2089 const workerNodeTasksUsage = workerNode.usage.tasks
2090 if (
2091 this.tasksQueueSize(workerNodeKey) > 0 &&
2092 workerNodeTasksUsage.executing <
2093 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2094 this.opts.tasksQueueOptions!.concurrency!
2095 ) {
2096 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2097 this.executeTask(workerNodeKey, this.dequeueTask(workerNodeKey)!)
2098 }
2099 if (
2100 workerNodeTasksUsage.executing === 0 &&
2101 this.tasksQueueSize(workerNodeKey) === 0 &&
2102 workerNodeTasksUsage.sequentiallyStolen === 0
2103 ) {
2104 workerNode.emit('idle', {
2105 workerId,
2106 workerNodeKey
2107 })
2108 }
2109 }
2110 }
2111 }
2112
2113 private checkAndEmitTaskExecutionEvents (): void {
2114 if (this.busy) {
2115 this.emitter?.emit(PoolEvents.busy, this.info)
2116 }
2117 }
2118
2119 private checkAndEmitTaskQueuingEvents (): void {
2120 if (this.hasBackPressure()) {
2121 this.emitter?.emit(PoolEvents.backPressure, this.info)
2122 }
2123 }
2124
2125 /**
2126 * Emits dynamic worker creation events.
2127 */
2128 protected abstract checkAndEmitDynamicWorkerCreationEvents (): void
2129
2130 /**
2131 * Gets the worker information given its worker node key.
2132 *
2133 * @param workerNodeKey - The worker node key.
2134 * @returns The worker information.
2135 */
2136 protected getWorkerInfo (workerNodeKey: number): WorkerInfo | undefined {
2137 return this.workerNodes[workerNodeKey]?.info
2138 }
2139
2140 /**
2141 * Creates a worker node.
2142 *
2143 * @returns The created worker node.
2144 */
2145 private createWorkerNode (): IWorkerNode<Worker, Data> {
2146 const workerNode = new WorkerNode<Worker, Data>(
2147 this.worker,
2148 this.filePath,
2149 {
2150 env: this.opts.env,
2151 workerOptions: this.opts.workerOptions,
2152 tasksQueueBackPressureSize:
2153 this.opts.tasksQueueOptions?.size ??
2154 getDefaultTasksQueueOptions(
2155 this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers
2156 ).size,
2157 tasksQueueBucketSize:
2158 (this.maximumNumberOfWorkers ?? this.minimumNumberOfWorkers) * 2
2159 }
2160 )
2161 // Flag the worker node as ready at pool startup.
2162 if (this.starting) {
2163 workerNode.info.ready = true
2164 }
2165 return workerNode
2166 }
2167
2168 /**
2169 * Adds the given worker node in the pool worker nodes.
2170 *
2171 * @param workerNode - The worker node.
2172 * @returns The added worker node key.
2173 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the added worker node is not found.
2174 */
2175 private addWorkerNode (workerNode: IWorkerNode<Worker, Data>): number {
2176 this.workerNodes.push(workerNode)
2177 const workerNodeKey = this.workerNodes.indexOf(workerNode)
2178 if (workerNodeKey === -1) {
2179 throw new Error('Worker added not found in worker nodes')
2180 }
2181 return workerNodeKey
2182 }
2183
2184 private checkAndEmitEmptyEvent (): void {
2185 if (this.empty) {
2186 this.emitter?.emit(PoolEvents.empty, this.info)
2187 this.readyEventEmitted = false
2188 }
2189 }
2190
2191 /**
2192 * Removes the worker node from the pool worker nodes.
2193 *
2194 * @param workerNode - The worker node.
2195 */
2196 private removeWorkerNode (workerNode: IWorkerNode<Worker, Data>): void {
2197 const workerNodeKey = this.workerNodes.indexOf(workerNode)
2198 if (workerNodeKey !== -1) {
2199 this.workerNodes.splice(workerNodeKey, 1)
2200 this.workerChoiceStrategiesContext?.remove(workerNodeKey)
2201 }
2202 this.checkAndEmitEmptyEvent()
2203 }
2204
2205 protected flagWorkerNodeAsNotReady (workerNodeKey: number): void {
2206 const workerInfo = this.getWorkerInfo(workerNodeKey)
2207 if (workerInfo != null) {
2208 workerInfo.ready = false
2209 }
2210 }
2211
2212 private hasBackPressure (): boolean {
2213 return (
2214 this.opts.enableTasksQueue === true &&
2215 this.workerNodes.findIndex(
2216 workerNode => !workerNode.hasBackPressure()
2217 ) === -1
2218 )
2219 }
2220
2221 /**
2222 * Executes the given task on the worker given its worker node key.
2223 *
2224 * @param workerNodeKey - The worker node key.
2225 * @param task - The task to execute.
2226 */
2227 private executeTask (workerNodeKey: number, task: Task<Data>): void {
2228 this.beforeTaskExecutionHook(workerNodeKey, task)
2229 this.sendToWorker(workerNodeKey, task, task.transferList)
2230 this.checkAndEmitTaskExecutionEvents()
2231 }
2232
2233 private enqueueTask (workerNodeKey: number, task: Task<Data>): number {
2234 const tasksQueueSize = this.workerNodes[workerNodeKey].enqueueTask(task)
2235 this.checkAndEmitTaskQueuingEvents()
2236 return tasksQueueSize
2237 }
2238
2239 private dequeueTask (workerNodeKey: number): Task<Data> | undefined {
2240 return this.workerNodes[workerNodeKey].dequeueTask()
2241 }
2242
2243 private tasksQueueSize (workerNodeKey: number): number {
2244 return this.workerNodes[workerNodeKey].tasksQueueSize()
2245 }
2246
2247 protected flushTasksQueue (workerNodeKey: number): number {
2248 let flushedTasks = 0
2249 while (this.tasksQueueSize(workerNodeKey) > 0) {
2250 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2251 this.executeTask(workerNodeKey, this.dequeueTask(workerNodeKey)!)
2252 ++flushedTasks
2253 }
2254 this.workerNodes[workerNodeKey].clearTasksQueue()
2255 return flushedTasks
2256 }
2257
2258 private flushTasksQueues (): void {
2259 for (const workerNodeKey of this.workerNodes.keys()) {
2260 this.flushTasksQueue(workerNodeKey)
2261 }
2262 }
2263 }