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