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