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