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