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