2f5c61896658311c96c551deee3fb99552273be2
[poolifier.git] / src / pools / abstract-pool.ts
1 import { randomUUID } from 'node:crypto'
2 import { performance } from 'node:perf_hooks'
3 import { existsSync } from 'node:fs'
4 import { type TransferListItem } from 'node:worker_threads'
5 import type {
6 MessageValue,
7 PromiseResponseWrapper,
8 Task,
9 Writable
10 } from '../utility-types'
11 import {
12 DEFAULT_TASK_NAME,
13 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS,
14 EMPTY_FUNCTION,
15 average,
16 isKillBehavior,
17 isPlainObject,
18 median,
19 round,
20 updateMeasurementStatistics
21 } from '../utils'
22 import { KillBehaviors } from '../worker/worker-options'
23 import {
24 type IPool,
25 PoolEmitter,
26 PoolEvents,
27 type PoolInfo,
28 type PoolOptions,
29 type PoolType,
30 PoolTypes,
31 type TasksQueueOptions
32 } from './pool'
33 import type {
34 IWorker,
35 IWorkerNode,
36 WorkerInfo,
37 WorkerType,
38 WorkerUsage
39 } from './worker'
40 import {
41 type MeasurementStatisticsRequirements,
42 Measurements,
43 WorkerChoiceStrategies,
44 type WorkerChoiceStrategy,
45 type WorkerChoiceStrategyOptions
46 } from './selection-strategies/selection-strategies-types'
47 import { WorkerChoiceStrategyContext } from './selection-strategies/worker-choice-strategy-context'
48 import { version } from './version'
49 import { WorkerNode } from './worker-node'
50
51 /**
52 * Base class that implements some shared logic for all poolifier pools.
53 *
54 * @typeParam Worker - Type of worker which manages this pool.
55 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
56 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
57 */
58 export abstract class AbstractPool<
59 Worker extends IWorker,
60 Data = unknown,
61 Response = unknown
62 > implements IPool<Worker, Data, Response> {
63 /** @inheritDoc */
64 public readonly workerNodes: Array<IWorkerNode<Worker, Data>> = []
65
66 /** @inheritDoc */
67 public readonly emitter?: PoolEmitter
68
69 /**
70 * The task execution response promise map.
71 *
72 * - `key`: The message id of each submitted task.
73 * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks.
74 *
75 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
76 */
77 protected promiseResponseMap: Map<string, PromiseResponseWrapper<Response>> =
78 new Map<string, PromiseResponseWrapper<Response>>()
79
80 /**
81 * Worker choice strategy context referencing a worker choice algorithm implementation.
82 */
83 protected workerChoiceStrategyContext: WorkerChoiceStrategyContext<
84 Worker,
85 Data,
86 Response
87 >
88
89 /**
90 * Dynamic pool maximum size property placeholder.
91 */
92 protected readonly max?: number
93
94 /**
95 * Whether the pool is starting or not.
96 */
97 private readonly starting: boolean
98 /**
99 * Whether the pool is started or not.
100 */
101 private started: boolean
102 /**
103 * The start timestamp of the pool.
104 */
105 private readonly startTimestamp
106
107 /**
108 * Constructs a new poolifier pool.
109 *
110 * @param numberOfWorkers - Number of workers that this pool should manage.
111 * @param filePath - Path to the worker file.
112 * @param opts - Options for the pool.
113 */
114 public constructor (
115 protected readonly numberOfWorkers: number,
116 protected readonly filePath: string,
117 protected readonly opts: PoolOptions<Worker>
118 ) {
119 if (!this.isMain()) {
120 throw new Error(
121 'Cannot start a pool from a worker with the same type as the pool'
122 )
123 }
124 this.checkNumberOfWorkers(this.numberOfWorkers)
125 this.checkFilePath(this.filePath)
126 this.checkPoolOptions(this.opts)
127
128 this.chooseWorkerNode = this.chooseWorkerNode.bind(this)
129 this.executeTask = this.executeTask.bind(this)
130 this.enqueueTask = this.enqueueTask.bind(this)
131
132 if (this.opts.enableEvents === true) {
133 this.emitter = new PoolEmitter()
134 }
135 this.workerChoiceStrategyContext = new WorkerChoiceStrategyContext<
136 Worker,
137 Data,
138 Response
139 >(
140 this,
141 this.opts.workerChoiceStrategy,
142 this.opts.workerChoiceStrategyOptions
143 )
144
145 this.setupHook()
146
147 this.starting = true
148 this.startPool()
149 this.starting = false
150 this.started = true
151
152 this.startTimestamp = performance.now()
153 }
154
155 private checkFilePath (filePath: string): void {
156 if (
157 filePath == null ||
158 typeof filePath !== 'string' ||
159 (typeof filePath === 'string' && filePath.trim().length === 0)
160 ) {
161 throw new Error('Please specify a file with a worker implementation')
162 }
163 if (!existsSync(filePath)) {
164 throw new Error(`Cannot find the worker file '${filePath}'`)
165 }
166 }
167
168 private checkNumberOfWorkers (numberOfWorkers: number): void {
169 if (numberOfWorkers == null) {
170 throw new Error(
171 'Cannot instantiate a pool without specifying the number of workers'
172 )
173 } else if (!Number.isSafeInteger(numberOfWorkers)) {
174 throw new TypeError(
175 'Cannot instantiate a pool with a non safe integer number of workers'
176 )
177 } else if (numberOfWorkers < 0) {
178 throw new RangeError(
179 'Cannot instantiate a pool with a negative number of workers'
180 )
181 } else if (this.type === PoolTypes.fixed && numberOfWorkers === 0) {
182 throw new RangeError('Cannot instantiate a fixed pool with zero worker')
183 }
184 }
185
186 protected checkDynamicPoolSize (min: number, max: number): void {
187 if (this.type === PoolTypes.dynamic) {
188 if (max == null) {
189 throw new TypeError(
190 'Cannot instantiate a dynamic pool without specifying the maximum pool size'
191 )
192 } else if (!Number.isSafeInteger(max)) {
193 throw new TypeError(
194 'Cannot instantiate a dynamic pool with a non safe integer maximum pool size'
195 )
196 } else if (min > max) {
197 throw new RangeError(
198 'Cannot instantiate a dynamic pool with a maximum pool size inferior to the minimum pool size'
199 )
200 } else if (max === 0) {
201 throw new RangeError(
202 'Cannot instantiate a dynamic pool with a maximum pool size equal to zero'
203 )
204 } else if (min === max) {
205 throw new RangeError(
206 'Cannot instantiate a dynamic pool with a minimum pool size equal to the maximum pool size. Use a fixed pool instead'
207 )
208 }
209 }
210 }
211
212 private checkPoolOptions (opts: PoolOptions<Worker>): void {
213 if (isPlainObject(opts)) {
214 this.opts.workerChoiceStrategy =
215 opts.workerChoiceStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN
216 this.checkValidWorkerChoiceStrategy(this.opts.workerChoiceStrategy)
217 this.opts.workerChoiceStrategyOptions = {
218 ...DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS,
219 ...opts.workerChoiceStrategyOptions
220 }
221 this.checkValidWorkerChoiceStrategyOptions(
222 this.opts.workerChoiceStrategyOptions
223 )
224 this.opts.restartWorkerOnError = opts.restartWorkerOnError ?? true
225 this.opts.enableEvents = opts.enableEvents ?? true
226 this.opts.enableTasksQueue = opts.enableTasksQueue ?? false
227 if (this.opts.enableTasksQueue) {
228 this.checkValidTasksQueueOptions(
229 opts.tasksQueueOptions as TasksQueueOptions
230 )
231 this.opts.tasksQueueOptions = this.buildTasksQueueOptions(
232 opts.tasksQueueOptions as TasksQueueOptions
233 )
234 }
235 } else {
236 throw new TypeError('Invalid pool options: must be a plain object')
237 }
238 }
239
240 private checkValidWorkerChoiceStrategy (
241 workerChoiceStrategy: WorkerChoiceStrategy
242 ): void {
243 if (!Object.values(WorkerChoiceStrategies).includes(workerChoiceStrategy)) {
244 throw new Error(
245 `Invalid worker choice strategy '${workerChoiceStrategy}'`
246 )
247 }
248 }
249
250 private checkValidWorkerChoiceStrategyOptions (
251 workerChoiceStrategyOptions: WorkerChoiceStrategyOptions
252 ): void {
253 if (!isPlainObject(workerChoiceStrategyOptions)) {
254 throw new TypeError(
255 'Invalid worker choice strategy options: must be a plain object'
256 )
257 }
258 if (
259 workerChoiceStrategyOptions.choiceRetries != null &&
260 !Number.isSafeInteger(workerChoiceStrategyOptions.choiceRetries)
261 ) {
262 throw new TypeError(
263 'Invalid worker choice strategy options: choice retries must be an integer'
264 )
265 }
266 if (
267 workerChoiceStrategyOptions.choiceRetries != null &&
268 workerChoiceStrategyOptions.choiceRetries < 0
269 ) {
270 throw new RangeError(
271 `Invalid worker choice strategy options: choice retries '${workerChoiceStrategyOptions.choiceRetries}' must be greater or equal than zero`
272 )
273 }
274 if (
275 workerChoiceStrategyOptions.weights != null &&
276 Object.keys(workerChoiceStrategyOptions.weights).length !== this.maxSize
277 ) {
278 throw new Error(
279 'Invalid worker choice strategy options: must have a weight for each worker node'
280 )
281 }
282 if (
283 workerChoiceStrategyOptions.measurement != null &&
284 !Object.values(Measurements).includes(
285 workerChoiceStrategyOptions.measurement
286 )
287 ) {
288 throw new Error(
289 `Invalid worker choice strategy options: invalid measurement '${workerChoiceStrategyOptions.measurement}'`
290 )
291 }
292 }
293
294 private checkValidTasksQueueOptions (
295 tasksQueueOptions: Writable<TasksQueueOptions>
296 ): void {
297 if (tasksQueueOptions != null && !isPlainObject(tasksQueueOptions)) {
298 throw new TypeError('Invalid tasks queue options: must be a plain object')
299 }
300 if (
301 tasksQueueOptions?.concurrency != null &&
302 !Number.isSafeInteger(tasksQueueOptions.concurrency)
303 ) {
304 throw new TypeError(
305 'Invalid worker node tasks concurrency: must be an integer'
306 )
307 }
308 if (
309 tasksQueueOptions?.concurrency != null &&
310 tasksQueueOptions.concurrency <= 0
311 ) {
312 throw new RangeError(
313 `Invalid worker node tasks concurrency: ${tasksQueueOptions.concurrency} is a negative integer or zero`
314 )
315 }
316 if (tasksQueueOptions?.queueMaxSize != null) {
317 throw new Error(
318 'Invalid tasks queue options: queueMaxSize is deprecated, please use size instead'
319 )
320 }
321 if (
322 tasksQueueOptions?.size != null &&
323 !Number.isSafeInteger(tasksQueueOptions.size)
324 ) {
325 throw new TypeError(
326 'Invalid worker node tasks queue size: must be an integer'
327 )
328 }
329 if (tasksQueueOptions?.size != null && tasksQueueOptions.size <= 0) {
330 throw new RangeError(
331 `Invalid worker node tasks queue size: ${tasksQueueOptions.size} is a negative integer or zero`
332 )
333 }
334 }
335
336 private startPool (): void {
337 while (
338 this.workerNodes.reduce(
339 (accumulator, workerNode) =>
340 !workerNode.info.dynamic ? accumulator + 1 : accumulator,
341 0
342 ) < this.numberOfWorkers
343 ) {
344 this.createAndSetupWorkerNode()
345 }
346 }
347
348 /** @inheritDoc */
349 public get info (): PoolInfo {
350 return {
351 version,
352 type: this.type,
353 worker: this.worker,
354 ready: this.ready,
355 strategy: this.opts.workerChoiceStrategy as WorkerChoiceStrategy,
356 minSize: this.minSize,
357 maxSize: this.maxSize,
358 ...(this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
359 .runTime.aggregate &&
360 this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
361 .waitTime.aggregate && { utilization: round(this.utilization) }),
362 workerNodes: this.workerNodes.length,
363 idleWorkerNodes: this.workerNodes.reduce(
364 (accumulator, workerNode) =>
365 workerNode.usage.tasks.executing === 0
366 ? accumulator + 1
367 : accumulator,
368 0
369 ),
370 busyWorkerNodes: this.workerNodes.reduce(
371 (accumulator, workerNode) =>
372 workerNode.usage.tasks.executing > 0 ? accumulator + 1 : accumulator,
373 0
374 ),
375 executedTasks: this.workerNodes.reduce(
376 (accumulator, workerNode) =>
377 accumulator + workerNode.usage.tasks.executed,
378 0
379 ),
380 executingTasks: this.workerNodes.reduce(
381 (accumulator, workerNode) =>
382 accumulator + workerNode.usage.tasks.executing,
383 0
384 ),
385 ...(this.opts.enableTasksQueue === true && {
386 queuedTasks: this.workerNodes.reduce(
387 (accumulator, workerNode) =>
388 accumulator + workerNode.usage.tasks.queued,
389 0
390 )
391 }),
392 ...(this.opts.enableTasksQueue === true && {
393 maxQueuedTasks: this.workerNodes.reduce(
394 (accumulator, workerNode) =>
395 accumulator + (workerNode.usage.tasks?.maxQueued ?? 0),
396 0
397 )
398 }),
399 ...(this.opts.enableTasksQueue === true && {
400 backPressure: this.hasBackPressure()
401 }),
402 ...(this.opts.enableTasksQueue === true && {
403 stolenTasks: this.workerNodes.reduce(
404 (accumulator, workerNode) =>
405 accumulator + workerNode.usage.tasks.stolen,
406 0
407 )
408 }),
409 failedTasks: this.workerNodes.reduce(
410 (accumulator, workerNode) =>
411 accumulator + workerNode.usage.tasks.failed,
412 0
413 ),
414 ...(this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
415 .runTime.aggregate && {
416 runTime: {
417 minimum: round(
418 Math.min(
419 ...this.workerNodes.map(
420 (workerNode) => workerNode.usage.runTime?.minimum ?? Infinity
421 )
422 )
423 ),
424 maximum: round(
425 Math.max(
426 ...this.workerNodes.map(
427 (workerNode) => workerNode.usage.runTime?.maximum ?? -Infinity
428 )
429 )
430 ),
431 ...(this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
432 .runTime.average && {
433 average: round(
434 average(
435 this.workerNodes.reduce<number[]>(
436 (accumulator, workerNode) =>
437 accumulator.concat(workerNode.usage.runTime.history),
438 []
439 )
440 )
441 )
442 }),
443 ...(this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
444 .runTime.median && {
445 median: round(
446 median(
447 this.workerNodes.reduce<number[]>(
448 (accumulator, workerNode) =>
449 accumulator.concat(workerNode.usage.runTime.history),
450 []
451 )
452 )
453 )
454 })
455 }
456 }),
457 ...(this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
458 .waitTime.aggregate && {
459 waitTime: {
460 minimum: round(
461 Math.min(
462 ...this.workerNodes.map(
463 (workerNode) => workerNode.usage.waitTime?.minimum ?? Infinity
464 )
465 )
466 ),
467 maximum: round(
468 Math.max(
469 ...this.workerNodes.map(
470 (workerNode) => workerNode.usage.waitTime?.maximum ?? -Infinity
471 )
472 )
473 ),
474 ...(this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
475 .waitTime.average && {
476 average: round(
477 average(
478 this.workerNodes.reduce<number[]>(
479 (accumulator, workerNode) =>
480 accumulator.concat(workerNode.usage.waitTime.history),
481 []
482 )
483 )
484 )
485 }),
486 ...(this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
487 .waitTime.median && {
488 median: round(
489 median(
490 this.workerNodes.reduce<number[]>(
491 (accumulator, workerNode) =>
492 accumulator.concat(workerNode.usage.waitTime.history),
493 []
494 )
495 )
496 )
497 })
498 }
499 })
500 }
501 }
502
503 /**
504 * The pool readiness boolean status.
505 */
506 private get ready (): boolean {
507 return (
508 this.workerNodes.reduce(
509 (accumulator, workerNode) =>
510 !workerNode.info.dynamic && workerNode.info.ready
511 ? accumulator + 1
512 : accumulator,
513 0
514 ) >= this.minSize
515 )
516 }
517
518 /**
519 * The approximate pool utilization.
520 *
521 * @returns The pool utilization.
522 */
523 private get utilization (): number {
524 const poolTimeCapacity =
525 (performance.now() - this.startTimestamp) * this.maxSize
526 const totalTasksRunTime = this.workerNodes.reduce(
527 (accumulator, workerNode) =>
528 accumulator + (workerNode.usage.runTime?.aggregate ?? 0),
529 0
530 )
531 const totalTasksWaitTime = this.workerNodes.reduce(
532 (accumulator, workerNode) =>
533 accumulator + (workerNode.usage.waitTime?.aggregate ?? 0),
534 0
535 )
536 return (totalTasksRunTime + totalTasksWaitTime) / poolTimeCapacity
537 }
538
539 /**
540 * The pool type.
541 *
542 * If it is `'dynamic'`, it provides the `max` property.
543 */
544 protected abstract get type (): PoolType
545
546 /**
547 * The worker type.
548 */
549 protected abstract get worker (): WorkerType
550
551 /**
552 * The pool minimum size.
553 */
554 protected get minSize (): number {
555 return this.numberOfWorkers
556 }
557
558 /**
559 * The pool maximum size.
560 */
561 protected get maxSize (): number {
562 return this.max ?? this.numberOfWorkers
563 }
564
565 /**
566 * Checks if the worker id sent in the received message from a worker is valid.
567 *
568 * @param message - The received message.
569 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the worker id is invalid.
570 */
571 private checkMessageWorkerId (message: MessageValue<Response>): void {
572 if (message.workerId == null) {
573 throw new Error('Worker message received without worker id')
574 } else if (
575 message.workerId != null &&
576 this.getWorkerNodeKeyByWorkerId(message.workerId) === -1
577 ) {
578 throw new Error(
579 `Worker message received from unknown worker '${message.workerId}'`
580 )
581 }
582 }
583
584 /**
585 * Gets the given worker its worker node key.
586 *
587 * @param worker - The worker.
588 * @returns The worker node key if found in the pool worker nodes, `-1` otherwise.
589 */
590 private getWorkerNodeKeyByWorker (worker: Worker): number {
591 return this.workerNodes.findIndex(
592 (workerNode) => workerNode.worker === worker
593 )
594 }
595
596 /**
597 * Gets the worker node key given its worker id.
598 *
599 * @param workerId - The worker id.
600 * @returns The worker node key if the worker id is found in the pool worker nodes, `-1` otherwise.
601 */
602 private getWorkerNodeKeyByWorkerId (workerId: number): number {
603 return this.workerNodes.findIndex(
604 (workerNode) => workerNode.info.id === workerId
605 )
606 }
607
608 /** @inheritDoc */
609 public setWorkerChoiceStrategy (
610 workerChoiceStrategy: WorkerChoiceStrategy,
611 workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions
612 ): void {
613 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy)
614 this.opts.workerChoiceStrategy = workerChoiceStrategy
615 this.workerChoiceStrategyContext.setWorkerChoiceStrategy(
616 this.opts.workerChoiceStrategy
617 )
618 if (workerChoiceStrategyOptions != null) {
619 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions)
620 }
621 for (const [workerNodeKey, workerNode] of this.workerNodes.entries()) {
622 workerNode.resetUsage()
623 this.sendStatisticsMessageToWorker(workerNodeKey)
624 }
625 }
626
627 /** @inheritDoc */
628 public setWorkerChoiceStrategyOptions (
629 workerChoiceStrategyOptions: WorkerChoiceStrategyOptions
630 ): void {
631 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions)
632 this.opts.workerChoiceStrategyOptions = {
633 ...DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS,
634 ...workerChoiceStrategyOptions
635 }
636 this.workerChoiceStrategyContext.setOptions(
637 this.opts.workerChoiceStrategyOptions
638 )
639 }
640
641 /** @inheritDoc */
642 public enableTasksQueue (
643 enable: boolean,
644 tasksQueueOptions?: TasksQueueOptions
645 ): void {
646 if (this.opts.enableTasksQueue === true && !enable) {
647 this.flushTasksQueues()
648 }
649 this.opts.enableTasksQueue = enable
650 this.setTasksQueueOptions(tasksQueueOptions as TasksQueueOptions)
651 }
652
653 /** @inheritDoc */
654 public setTasksQueueOptions (tasksQueueOptions: TasksQueueOptions): void {
655 if (this.opts.enableTasksQueue === true) {
656 this.checkValidTasksQueueOptions(tasksQueueOptions)
657 this.opts.tasksQueueOptions =
658 this.buildTasksQueueOptions(tasksQueueOptions)
659 this.setTasksQueueMaxSize(this.opts.tasksQueueOptions.size as number)
660 } else if (this.opts.tasksQueueOptions != null) {
661 delete this.opts.tasksQueueOptions
662 }
663 }
664
665 private setTasksQueueMaxSize (size: number): void {
666 for (const workerNode of this.workerNodes) {
667 workerNode.tasksQueueBackPressureSize = size
668 }
669 }
670
671 private buildTasksQueueOptions (
672 tasksQueueOptions: TasksQueueOptions
673 ): TasksQueueOptions {
674 return {
675 ...{
676 size: Math.pow(this.maxSize, 2),
677 concurrency: 1
678 },
679 ...tasksQueueOptions
680 }
681 }
682
683 /**
684 * Whether the pool is full or not.
685 *
686 * The pool filling boolean status.
687 */
688 protected get full (): boolean {
689 return this.workerNodes.length >= this.maxSize
690 }
691
692 /**
693 * Whether the pool is busy or not.
694 *
695 * The pool busyness boolean status.
696 */
697 protected abstract get busy (): boolean
698
699 /**
700 * Whether worker nodes are executing concurrently their tasks quota or not.
701 *
702 * @returns Worker nodes busyness boolean status.
703 */
704 protected internalBusy (): boolean {
705 if (this.opts.enableTasksQueue === true) {
706 return (
707 this.workerNodes.findIndex(
708 (workerNode) =>
709 workerNode.info.ready &&
710 workerNode.usage.tasks.executing <
711 (this.opts.tasksQueueOptions?.concurrency as number)
712 ) === -1
713 )
714 } else {
715 return (
716 this.workerNodes.findIndex(
717 (workerNode) =>
718 workerNode.info.ready && workerNode.usage.tasks.executing === 0
719 ) === -1
720 )
721 }
722 }
723
724 /** @inheritDoc */
725 public listTaskFunctions (): string[] {
726 for (const workerNode of this.workerNodes) {
727 if (
728 Array.isArray(workerNode.info.taskFunctions) &&
729 workerNode.info.taskFunctions.length > 0
730 ) {
731 return workerNode.info.taskFunctions
732 }
733 }
734 return []
735 }
736
737 /** @inheritDoc */
738 public async execute (
739 data?: Data,
740 name?: string,
741 transferList?: TransferListItem[]
742 ): Promise<Response> {
743 return await new Promise<Response>((resolve, reject) => {
744 if (!this.started) {
745 reject(new Error('Cannot execute a task on destroyed pool'))
746 return
747 }
748 if (name != null && typeof name !== 'string') {
749 reject(new TypeError('name argument must be a string'))
750 return
751 }
752 if (
753 name != null &&
754 typeof name === 'string' &&
755 name.trim().length === 0
756 ) {
757 reject(new TypeError('name argument must not be an empty string'))
758 return
759 }
760 if (transferList != null && !Array.isArray(transferList)) {
761 reject(new TypeError('transferList argument must be an array'))
762 return
763 }
764 const timestamp = performance.now()
765 const workerNodeKey = this.chooseWorkerNode()
766 const workerInfo = this.getWorkerInfo(workerNodeKey) as WorkerInfo
767 const task: Task<Data> = {
768 name: name ?? DEFAULT_TASK_NAME,
769 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
770 data: data ?? ({} as Data),
771 transferList,
772 timestamp,
773 workerId: workerInfo.id as number,
774 taskId: randomUUID()
775 }
776 this.promiseResponseMap.set(task.taskId as string, {
777 resolve,
778 reject,
779 workerNodeKey
780 })
781 if (
782 this.opts.enableTasksQueue === false ||
783 (this.opts.enableTasksQueue === true &&
784 this.tasksQueueSize(workerNodeKey) === 0 &&
785 this.workerNodes[workerNodeKey].usage.tasks.executing <
786 (this.opts.tasksQueueOptions?.concurrency as number))
787 ) {
788 this.executeTask(workerNodeKey, task)
789 } else {
790 this.enqueueTask(workerNodeKey, task)
791 }
792 })
793 }
794
795 /** @inheritDoc */
796 public async destroy (): Promise<void> {
797 await Promise.all(
798 this.workerNodes.map(async (_, workerNodeKey) => {
799 await this.destroyWorkerNode(workerNodeKey)
800 })
801 )
802 this.emitter?.emit(PoolEvents.destroy, this.info)
803 this.started = false
804 }
805
806 protected async sendKillMessageToWorker (
807 workerNodeKey: number,
808 workerId: number
809 ): Promise<void> {
810 await new Promise<void>((resolve, reject) => {
811 this.registerWorkerMessageListener(workerNodeKey, (message) => {
812 if (message.kill === 'success') {
813 resolve()
814 } else if (message.kill === 'failure') {
815 reject(new Error(`Worker ${workerId} kill message handling failed`))
816 }
817 })
818 this.sendToWorker(workerNodeKey, { kill: true, workerId })
819 })
820 }
821
822 /**
823 * Terminates the worker node given its worker node key.
824 *
825 * @param workerNodeKey - The worker node key.
826 */
827 protected abstract destroyWorkerNode (workerNodeKey: number): Promise<void>
828
829 /**
830 * Setup hook to execute code before worker nodes are created in the abstract constructor.
831 * Can be overridden.
832 *
833 * @virtual
834 */
835 protected setupHook (): void {
836 /** Intentionally empty */
837 }
838
839 /**
840 * Should return whether the worker is the main worker or not.
841 */
842 protected abstract isMain (): boolean
843
844 /**
845 * Hook executed before the worker task execution.
846 * Can be overridden.
847 *
848 * @param workerNodeKey - The worker node key.
849 * @param task - The task to execute.
850 */
851 protected beforeTaskExecutionHook (
852 workerNodeKey: number,
853 task: Task<Data>
854 ): void {
855 if (this.workerNodes[workerNodeKey]?.usage != null) {
856 const workerUsage = this.workerNodes[workerNodeKey].usage
857 ++workerUsage.tasks.executing
858 this.updateWaitTimeWorkerUsage(workerUsage, task)
859 }
860 if (
861 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) &&
862 this.workerNodes[workerNodeKey].getTaskFunctionWorkerUsage(
863 task.name as string
864 ) != null
865 ) {
866 const taskFunctionWorkerUsage = this.workerNodes[
867 workerNodeKey
868 ].getTaskFunctionWorkerUsage(task.name as string) as WorkerUsage
869 ++taskFunctionWorkerUsage.tasks.executing
870 this.updateWaitTimeWorkerUsage(taskFunctionWorkerUsage, task)
871 }
872 }
873
874 /**
875 * Hook executed after the worker task execution.
876 * Can be overridden.
877 *
878 * @param workerNodeKey - The worker node key.
879 * @param message - The received message.
880 */
881 protected afterTaskExecutionHook (
882 workerNodeKey: number,
883 message: MessageValue<Response>
884 ): void {
885 if (this.workerNodes[workerNodeKey]?.usage != null) {
886 const workerUsage = this.workerNodes[workerNodeKey].usage
887 this.updateTaskStatisticsWorkerUsage(workerUsage, message)
888 this.updateRunTimeWorkerUsage(workerUsage, message)
889 this.updateEluWorkerUsage(workerUsage, message)
890 }
891 if (
892 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) &&
893 this.workerNodes[workerNodeKey].getTaskFunctionWorkerUsage(
894 message.taskPerformance?.name as string
895 ) != null
896 ) {
897 const taskFunctionWorkerUsage = this.workerNodes[
898 workerNodeKey
899 ].getTaskFunctionWorkerUsage(
900 message.taskPerformance?.name as string
901 ) as WorkerUsage
902 this.updateTaskStatisticsWorkerUsage(taskFunctionWorkerUsage, message)
903 this.updateRunTimeWorkerUsage(taskFunctionWorkerUsage, message)
904 this.updateEluWorkerUsage(taskFunctionWorkerUsage, message)
905 }
906 }
907
908 /**
909 * Whether the worker node shall update its task function worker usage or not.
910 *
911 * @param workerNodeKey - The worker node key.
912 * @returns `true` if the worker node shall update its task function worker usage, `false` otherwise.
913 */
914 private shallUpdateTaskFunctionWorkerUsage (workerNodeKey: number): boolean {
915 const workerInfo = this.getWorkerInfo(workerNodeKey)
916 return (
917 workerInfo != null &&
918 Array.isArray(workerInfo.taskFunctions) &&
919 workerInfo.taskFunctions.length > 2
920 )
921 }
922
923 private updateTaskStatisticsWorkerUsage (
924 workerUsage: WorkerUsage,
925 message: MessageValue<Response>
926 ): void {
927 const workerTaskStatistics = workerUsage.tasks
928 if (
929 workerTaskStatistics.executing != null &&
930 workerTaskStatistics.executing > 0
931 ) {
932 --workerTaskStatistics.executing
933 }
934 if (message.taskError == null) {
935 ++workerTaskStatistics.executed
936 } else {
937 ++workerTaskStatistics.failed
938 }
939 }
940
941 private updateRunTimeWorkerUsage (
942 workerUsage: WorkerUsage,
943 message: MessageValue<Response>
944 ): void {
945 if (message.taskError != null) {
946 return
947 }
948 updateMeasurementStatistics(
949 workerUsage.runTime,
950 this.workerChoiceStrategyContext.getTaskStatisticsRequirements().runTime,
951 message.taskPerformance?.runTime ?? 0
952 )
953 }
954
955 private updateWaitTimeWorkerUsage (
956 workerUsage: WorkerUsage,
957 task: Task<Data>
958 ): void {
959 const timestamp = performance.now()
960 const taskWaitTime = timestamp - (task.timestamp ?? timestamp)
961 updateMeasurementStatistics(
962 workerUsage.waitTime,
963 this.workerChoiceStrategyContext.getTaskStatisticsRequirements().waitTime,
964 taskWaitTime
965 )
966 }
967
968 private updateEluWorkerUsage (
969 workerUsage: WorkerUsage,
970 message: MessageValue<Response>
971 ): void {
972 if (message.taskError != null) {
973 return
974 }
975 const eluTaskStatisticsRequirements: MeasurementStatisticsRequirements =
976 this.workerChoiceStrategyContext.getTaskStatisticsRequirements().elu
977 updateMeasurementStatistics(
978 workerUsage.elu.active,
979 eluTaskStatisticsRequirements,
980 message.taskPerformance?.elu?.active ?? 0
981 )
982 updateMeasurementStatistics(
983 workerUsage.elu.idle,
984 eluTaskStatisticsRequirements,
985 message.taskPerformance?.elu?.idle ?? 0
986 )
987 if (eluTaskStatisticsRequirements.aggregate) {
988 if (message.taskPerformance?.elu != null) {
989 if (workerUsage.elu.utilization != null) {
990 workerUsage.elu.utilization =
991 (workerUsage.elu.utilization +
992 message.taskPerformance.elu.utilization) /
993 2
994 } else {
995 workerUsage.elu.utilization = message.taskPerformance.elu.utilization
996 }
997 }
998 }
999 }
1000
1001 /**
1002 * Chooses a worker node for the next task.
1003 *
1004 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
1005 *
1006 * @returns The chosen worker node key
1007 */
1008 private chooseWorkerNode (): number {
1009 if (this.shallCreateDynamicWorker()) {
1010 const workerNodeKey = this.createAndSetupDynamicWorkerNode()
1011 if (
1012 this.workerChoiceStrategyContext.getStrategyPolicy().dynamicWorkerUsage
1013 ) {
1014 return workerNodeKey
1015 }
1016 }
1017 return this.workerChoiceStrategyContext.execute()
1018 }
1019
1020 /**
1021 * Conditions for dynamic worker creation.
1022 *
1023 * @returns Whether to create a dynamic worker or not.
1024 */
1025 private shallCreateDynamicWorker (): boolean {
1026 return this.type === PoolTypes.dynamic && !this.full && this.internalBusy()
1027 }
1028
1029 /**
1030 * Sends a message to worker given its worker node key.
1031 *
1032 * @param workerNodeKey - The worker node key.
1033 * @param message - The message.
1034 * @param transferList - The optional array of transferable objects.
1035 */
1036 protected abstract sendToWorker (
1037 workerNodeKey: number,
1038 message: MessageValue<Data>,
1039 transferList?: TransferListItem[]
1040 ): void
1041
1042 /**
1043 * Creates a new worker.
1044 *
1045 * @returns Newly created worker.
1046 */
1047 protected abstract createWorker (): Worker
1048
1049 /**
1050 * Creates a new, completely set up worker node.
1051 *
1052 * @returns New, completely set up worker node key.
1053 */
1054 protected createAndSetupWorkerNode (): number {
1055 const worker = this.createWorker()
1056
1057 worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION)
1058 worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION)
1059 worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION)
1060 worker.on('error', (error) => {
1061 const workerNodeKey = this.getWorkerNodeKeyByWorker(worker)
1062 const workerInfo = this.getWorkerInfo(workerNodeKey) as WorkerInfo
1063 workerInfo.ready = false
1064 this.workerNodes[workerNodeKey].closeChannel()
1065 this.emitter?.emit(PoolEvents.error, error)
1066 if (
1067 this.opts.restartWorkerOnError === true &&
1068 !this.starting &&
1069 this.started
1070 ) {
1071 if (workerInfo.dynamic) {
1072 this.createAndSetupDynamicWorkerNode()
1073 } else {
1074 this.createAndSetupWorkerNode()
1075 }
1076 }
1077 if (this.opts.enableTasksQueue === true) {
1078 this.redistributeQueuedTasks(workerNodeKey)
1079 }
1080 })
1081 worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION)
1082 worker.once('exit', () => {
1083 this.removeWorkerNode(worker)
1084 })
1085
1086 const workerNodeKey = this.addWorkerNode(worker)
1087
1088 this.afterWorkerNodeSetup(workerNodeKey)
1089
1090 return workerNodeKey
1091 }
1092
1093 /**
1094 * Creates a new, completely set up dynamic worker node.
1095 *
1096 * @returns New, completely set up dynamic worker node key.
1097 */
1098 protected createAndSetupDynamicWorkerNode (): number {
1099 const workerNodeKey = this.createAndSetupWorkerNode()
1100 this.registerWorkerMessageListener(workerNodeKey, (message) => {
1101 const localWorkerNodeKey = this.getWorkerNodeKeyByWorkerId(
1102 message.workerId
1103 )
1104 const workerUsage = this.workerNodes[localWorkerNodeKey].usage
1105 // Kill message received from worker
1106 if (
1107 isKillBehavior(KillBehaviors.HARD, message.kill) ||
1108 (isKillBehavior(KillBehaviors.SOFT, message.kill) &&
1109 ((this.opts.enableTasksQueue === false &&
1110 workerUsage.tasks.executing === 0) ||
1111 (this.opts.enableTasksQueue === true &&
1112 workerUsage.tasks.executing === 0 &&
1113 this.tasksQueueSize(localWorkerNodeKey) === 0)))
1114 ) {
1115 this.destroyWorkerNode(localWorkerNodeKey).catch((error) => {
1116 this.emitter?.emit(PoolEvents.error, error)
1117 })
1118 }
1119 })
1120 const workerInfo = this.getWorkerInfo(workerNodeKey) as WorkerInfo
1121 this.sendToWorker(workerNodeKey, {
1122 checkActive: true,
1123 workerId: workerInfo.id as number
1124 })
1125 workerInfo.dynamic = true
1126 if (
1127 this.workerChoiceStrategyContext.getStrategyPolicy().dynamicWorkerReady ||
1128 this.workerChoiceStrategyContext.getStrategyPolicy().dynamicWorkerUsage
1129 ) {
1130 workerInfo.ready = true
1131 }
1132 this.checkAndEmitDynamicWorkerCreationEvents()
1133 return workerNodeKey
1134 }
1135
1136 /**
1137 * Registers a listener callback on the worker given its worker node key.
1138 *
1139 * @param workerNodeKey - The worker node key.
1140 * @param listener - The message listener callback.
1141 */
1142 protected abstract registerWorkerMessageListener<
1143 Message extends Data | Response
1144 >(
1145 workerNodeKey: number,
1146 listener: (message: MessageValue<Message>) => void
1147 ): void
1148
1149 /**
1150 * Method hooked up after a worker node has been newly created.
1151 * Can be overridden.
1152 *
1153 * @param workerNodeKey - The newly created worker node key.
1154 */
1155 protected afterWorkerNodeSetup (workerNodeKey: number): void {
1156 // Listen to worker messages.
1157 this.registerWorkerMessageListener(workerNodeKey, this.workerListener())
1158 // Send the startup message to worker.
1159 this.sendStartupMessageToWorker(workerNodeKey)
1160 // Send the statistics message to worker.
1161 this.sendStatisticsMessageToWorker(workerNodeKey)
1162 if (this.opts.enableTasksQueue === true) {
1163 this.workerNodes[workerNodeKey].onEmptyQueue =
1164 this.taskStealingOnEmptyQueue.bind(this)
1165 this.workerNodes[workerNodeKey].onBackPressure =
1166 this.tasksStealingOnBackPressure.bind(this)
1167 }
1168 }
1169
1170 /**
1171 * Sends the startup message to worker given its worker node key.
1172 *
1173 * @param workerNodeKey - The worker node key.
1174 */
1175 protected abstract sendStartupMessageToWorker (workerNodeKey: number): void
1176
1177 /**
1178 * Sends the statistics message to worker given its worker node key.
1179 *
1180 * @param workerNodeKey - The worker node key.
1181 */
1182 private sendStatisticsMessageToWorker (workerNodeKey: number): void {
1183 this.sendToWorker(workerNodeKey, {
1184 statistics: {
1185 runTime:
1186 this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
1187 .runTime.aggregate,
1188 elu: this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
1189 .elu.aggregate
1190 },
1191 workerId: (this.getWorkerInfo(workerNodeKey) as WorkerInfo).id as number
1192 })
1193 }
1194
1195 private redistributeQueuedTasks (workerNodeKey: number): void {
1196 while (this.tasksQueueSize(workerNodeKey) > 0) {
1197 let destinationWorkerNodeKey!: number
1198 let minQueuedTasks = Infinity
1199 for (const [workerNodeId, workerNode] of this.workerNodes.entries()) {
1200 if (workerNode.info.ready && workerNodeId !== workerNodeKey) {
1201 if (workerNode.usage.tasks.queued === 0) {
1202 destinationWorkerNodeKey = workerNodeId
1203 break
1204 }
1205 if (workerNode.usage.tasks.queued < minQueuedTasks) {
1206 minQueuedTasks = workerNode.usage.tasks.queued
1207 destinationWorkerNodeKey = workerNodeId
1208 }
1209 }
1210 }
1211 if (destinationWorkerNodeKey != null) {
1212 const destinationWorkerNode = this.workerNodes[destinationWorkerNodeKey]
1213 const task = {
1214 ...(this.dequeueTask(workerNodeKey) as Task<Data>),
1215 workerId: destinationWorkerNode.info.id as number
1216 }
1217 if (
1218 this.tasksQueueSize(destinationWorkerNodeKey) === 0 &&
1219 destinationWorkerNode.usage.tasks.executing <
1220 (this.opts.tasksQueueOptions?.concurrency as number)
1221 ) {
1222 this.executeTask(destinationWorkerNodeKey, task)
1223 } else {
1224 this.enqueueTask(destinationWorkerNodeKey, task)
1225 }
1226 }
1227 }
1228 }
1229
1230 private taskStealingOnEmptyQueue (workerId: number): void {
1231 const destinationWorkerNodeKey = this.getWorkerNodeKeyByWorkerId(workerId)
1232 const destinationWorkerNode = this.workerNodes[destinationWorkerNodeKey]
1233 const workerNodes = this.workerNodes
1234 .slice()
1235 .sort(
1236 (workerNodeA, workerNodeB) =>
1237 workerNodeB.usage.tasks.queued - workerNodeA.usage.tasks.queued
1238 )
1239 for (const sourceWorkerNode of workerNodes) {
1240 if (sourceWorkerNode.usage.tasks.queued === 0) {
1241 break
1242 }
1243 if (
1244 sourceWorkerNode.info.ready &&
1245 sourceWorkerNode.info.id !== workerId &&
1246 sourceWorkerNode.usage.tasks.queued > 0
1247 ) {
1248 const task = {
1249 ...(sourceWorkerNode.popTask() as Task<Data>),
1250 workerId: destinationWorkerNode.info.id as number
1251 }
1252 if (
1253 this.tasksQueueSize(destinationWorkerNodeKey) === 0 &&
1254 destinationWorkerNode.usage.tasks.executing <
1255 (this.opts.tasksQueueOptions?.concurrency as number)
1256 ) {
1257 this.executeTask(destinationWorkerNodeKey, task)
1258 } else {
1259 this.enqueueTask(destinationWorkerNodeKey, task)
1260 }
1261 if (destinationWorkerNode?.usage != null) {
1262 ++destinationWorkerNode.usage.tasks.stolen
1263 }
1264 if (
1265 this.shallUpdateTaskFunctionWorkerUsage(destinationWorkerNodeKey) &&
1266 destinationWorkerNode.getTaskFunctionWorkerUsage(
1267 task.name as string
1268 ) != null
1269 ) {
1270 const taskFunctionWorkerUsage =
1271 destinationWorkerNode.getTaskFunctionWorkerUsage(
1272 task.name as string
1273 ) as WorkerUsage
1274 ++taskFunctionWorkerUsage.tasks.stolen
1275 }
1276 break
1277 }
1278 }
1279 }
1280
1281 private tasksStealingOnBackPressure (workerId: number): void {
1282 if ((this.opts.tasksQueueOptions?.size as number) <= 1) {
1283 return
1284 }
1285 const sourceWorkerNode =
1286 this.workerNodes[this.getWorkerNodeKeyByWorkerId(workerId)]
1287 const workerNodes = this.workerNodes
1288 .slice()
1289 .sort(
1290 (workerNodeA, workerNodeB) =>
1291 workerNodeA.usage.tasks.queued - workerNodeB.usage.tasks.queued
1292 )
1293 for (const [workerNodeKey, workerNode] of workerNodes.entries()) {
1294 if (
1295 sourceWorkerNode.usage.tasks.queued > 0 &&
1296 workerNode.info.ready &&
1297 workerNode.info.id !== workerId &&
1298 workerNode.usage.tasks.queued <
1299 (this.opts.tasksQueueOptions?.size as number) - 1
1300 ) {
1301 const task = {
1302 ...(sourceWorkerNode.popTask() as Task<Data>),
1303 workerId: workerNode.info.id as number
1304 }
1305 if (this.tasksQueueSize(workerNodeKey) === 0) {
1306 this.executeTask(workerNodeKey, task)
1307 } else {
1308 this.enqueueTask(workerNodeKey, task)
1309 }
1310 if (workerNode?.usage != null) {
1311 ++workerNode.usage.tasks.stolen
1312 }
1313 if (
1314 this.shallUpdateTaskFunctionWorkerUsage(workerNodeKey) &&
1315 workerNode.getTaskFunctionWorkerUsage(task.name as string) != null
1316 ) {
1317 const taskFunctionWorkerUsage = workerNode.getTaskFunctionWorkerUsage(
1318 task.name as string
1319 ) as WorkerUsage
1320 ++taskFunctionWorkerUsage.tasks.stolen
1321 }
1322 }
1323 }
1324 }
1325
1326 /**
1327 * This method is the listener registered for each worker message.
1328 *
1329 * @returns The listener function to execute when a message is received from a worker.
1330 */
1331 protected workerListener (): (message: MessageValue<Response>) => void {
1332 return (message) => {
1333 this.checkMessageWorkerId(message)
1334 if (message.ready != null && message.taskFunctions != null) {
1335 // Worker ready response received from worker
1336 this.handleWorkerReadyResponse(message)
1337 } else if (message.taskId != null) {
1338 // Task execution response received from worker
1339 this.handleTaskExecutionResponse(message)
1340 } else if (message.taskFunctions != null) {
1341 // Task functions message received from worker
1342 (
1343 this.getWorkerInfo(
1344 this.getWorkerNodeKeyByWorkerId(message.workerId)
1345 ) as WorkerInfo
1346 ).taskFunctions = message.taskFunctions
1347 }
1348 }
1349 }
1350
1351 private handleWorkerReadyResponse (message: MessageValue<Response>): void {
1352 if (message.ready === false) {
1353 throw new Error(`Worker ${message.workerId} failed to initialize`)
1354 }
1355 const workerInfo = this.getWorkerInfo(
1356 this.getWorkerNodeKeyByWorkerId(message.workerId)
1357 ) as WorkerInfo
1358 workerInfo.ready = message.ready as boolean
1359 workerInfo.taskFunctions = message.taskFunctions
1360 if (this.emitter != null && this.ready) {
1361 this.emitter.emit(PoolEvents.ready, this.info)
1362 }
1363 }
1364
1365 private handleTaskExecutionResponse (message: MessageValue<Response>): void {
1366 const { taskId, taskError, data } = message
1367 const promiseResponse = this.promiseResponseMap.get(taskId as string)
1368 if (promiseResponse != null) {
1369 if (taskError != null) {
1370 this.emitter?.emit(PoolEvents.taskError, taskError)
1371 promiseResponse.reject(taskError.message)
1372 } else {
1373 promiseResponse.resolve(data as Response)
1374 }
1375 const workerNodeKey = promiseResponse.workerNodeKey
1376 this.afterTaskExecutionHook(workerNodeKey, message)
1377 this.promiseResponseMap.delete(taskId as string)
1378 if (
1379 this.opts.enableTasksQueue === true &&
1380 this.tasksQueueSize(workerNodeKey) > 0 &&
1381 this.workerNodes[workerNodeKey].usage.tasks.executing <
1382 (this.opts.tasksQueueOptions?.concurrency as number)
1383 ) {
1384 this.executeTask(
1385 workerNodeKey,
1386 this.dequeueTask(workerNodeKey) as Task<Data>
1387 )
1388 }
1389 this.workerChoiceStrategyContext.update(workerNodeKey)
1390 }
1391 }
1392
1393 private checkAndEmitTaskExecutionEvents (): void {
1394 if (this.busy) {
1395 this.emitter?.emit(PoolEvents.busy, this.info)
1396 }
1397 }
1398
1399 private checkAndEmitTaskQueuingEvents (): void {
1400 if (this.hasBackPressure()) {
1401 this.emitter?.emit(PoolEvents.backPressure, this.info)
1402 }
1403 }
1404
1405 private checkAndEmitDynamicWorkerCreationEvents (): void {
1406 if (this.type === PoolTypes.dynamic) {
1407 if (this.full) {
1408 this.emitter?.emit(PoolEvents.full, this.info)
1409 }
1410 }
1411 }
1412
1413 /**
1414 * Gets the worker information given its worker node key.
1415 *
1416 * @param workerNodeKey - The worker node key.
1417 * @returns The worker information.
1418 */
1419 protected getWorkerInfo (workerNodeKey: number): WorkerInfo | undefined {
1420 return this.workerNodes[workerNodeKey]?.info
1421 }
1422
1423 /**
1424 * Adds the given worker in the pool worker nodes.
1425 *
1426 * @param worker - The worker.
1427 * @returns The added worker node key.
1428 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the added worker node is not found.
1429 */
1430 private addWorkerNode (worker: Worker): number {
1431 const workerNode = new WorkerNode<Worker, Data>(
1432 worker,
1433 this.worker,
1434 this.opts.tasksQueueOptions?.size ?? Math.pow(this.maxSize, 2)
1435 )
1436 // Flag the worker node as ready at pool startup.
1437 if (this.starting) {
1438 workerNode.info.ready = true
1439 }
1440 this.workerNodes.push(workerNode)
1441 const workerNodeKey = this.getWorkerNodeKeyByWorker(worker)
1442 if (workerNodeKey === -1) {
1443 throw new Error('Worker node added not found')
1444 }
1445 return workerNodeKey
1446 }
1447
1448 /**
1449 * Removes the given worker from the pool worker nodes.
1450 *
1451 * @param worker - The worker.
1452 */
1453 private removeWorkerNode (worker: Worker): void {
1454 const workerNodeKey = this.getWorkerNodeKeyByWorker(worker)
1455 if (workerNodeKey !== -1) {
1456 this.workerNodes.splice(workerNodeKey, 1)
1457 this.workerChoiceStrategyContext.remove(workerNodeKey)
1458 }
1459 }
1460
1461 /** @inheritDoc */
1462 public hasWorkerNodeBackPressure (workerNodeKey: number): boolean {
1463 return (
1464 this.opts.enableTasksQueue === true &&
1465 this.workerNodes[workerNodeKey].hasBackPressure()
1466 )
1467 }
1468
1469 private hasBackPressure (): boolean {
1470 return (
1471 this.opts.enableTasksQueue === true &&
1472 this.workerNodes.findIndex(
1473 (workerNode) => !workerNode.hasBackPressure()
1474 ) === -1
1475 )
1476 }
1477
1478 /**
1479 * Executes the given task on the worker given its worker node key.
1480 *
1481 * @param workerNodeKey - The worker node key.
1482 * @param task - The task to execute.
1483 */
1484 private executeTask (workerNodeKey: number, task: Task<Data>): void {
1485 this.beforeTaskExecutionHook(workerNodeKey, task)
1486 this.sendToWorker(workerNodeKey, task, task.transferList)
1487 this.checkAndEmitTaskExecutionEvents()
1488 }
1489
1490 private enqueueTask (workerNodeKey: number, task: Task<Data>): number {
1491 const tasksQueueSize = this.workerNodes[workerNodeKey].enqueueTask(task)
1492 this.checkAndEmitTaskQueuingEvents()
1493 return tasksQueueSize
1494 }
1495
1496 private dequeueTask (workerNodeKey: number): Task<Data> | undefined {
1497 return this.workerNodes[workerNodeKey].dequeueTask()
1498 }
1499
1500 private tasksQueueSize (workerNodeKey: number): number {
1501 return this.workerNodes[workerNodeKey].tasksQueueSize()
1502 }
1503
1504 protected flushTasksQueue (workerNodeKey: number): void {
1505 while (this.tasksQueueSize(workerNodeKey) > 0) {
1506 this.executeTask(
1507 workerNodeKey,
1508 this.dequeueTask(workerNodeKey) as Task<Data>
1509 )
1510 }
1511 this.workerNodes[workerNodeKey].clearTasksQueue()
1512 }
1513
1514 private flushTasksQueues (): void {
1515 for (const [workerNodeKey] of this.workerNodes.entries()) {
1516 this.flushTasksQueue(workerNodeKey)
1517 }
1518 }
1519 }