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