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