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