build(deps-dev): apply updates
[poolifier.git] / src / pools / abstract-pool.ts
... / ...
CommitLineData
1import { randomUUID } from 'node:crypto'
2import { performance } from 'node:perf_hooks'
3import { existsSync } from 'node:fs'
4import type {
5 MessageValue,
6 PromiseResponseWrapper,
7 Task
8} from '../utility-types'
9import {
10 DEFAULT_TASK_NAME,
11 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS,
12 EMPTY_FUNCTION,
13 isKillBehavior,
14 isPlainObject,
15 median,
16 round,
17 updateMeasurementStatistics
18} from '../utils'
19import { KillBehaviors } from '../worker/worker-options'
20import {
21 type IPool,
22 PoolEmitter,
23 PoolEvents,
24 type PoolInfo,
25 type PoolOptions,
26 type PoolType,
27 PoolTypes,
28 type TasksQueueOptions
29} from './pool'
30import type {
31 IWorker,
32 IWorkerNode,
33 WorkerInfo,
34 WorkerType,
35 WorkerUsage
36} from './worker'
37import {
38 type MeasurementStatisticsRequirements,
39 Measurements,
40 WorkerChoiceStrategies,
41 type WorkerChoiceStrategy,
42 type WorkerChoiceStrategyOptions
43} from './selection-strategies/selection-strategies-types'
44import { WorkerChoiceStrategyContext } from './selection-strategies/worker-choice-strategy-context'
45import { version } from './version'
46import { WorkerNode } from './worker-node'
47
48/**
49 * Base class that implements some shared logic for all poolifier pools.
50 *
51 * @typeParam Worker - Type of worker which manages this pool.
52 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
53 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
54 */
55export abstract class AbstractPool<
56 Worker extends IWorker,
57 Data = unknown,
58 Response = unknown
59> implements IPool<Worker, Data, Response> {
60 /** @inheritDoc */
61 public readonly workerNodes: Array<IWorkerNode<Worker, Data>> = []
62
63 /** @inheritDoc */
64 public readonly emitter?: PoolEmitter
65
66 /**
67 * The task execution response promise map.
68 *
69 * - `key`: The message id of each submitted task.
70 * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks.
71 *
72 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
73 */
74 protected promiseResponseMap: Map<string, PromiseResponseWrapper<Response>> =
75 new Map<string, PromiseResponseWrapper<Response>>()
76
77 /**
78 * Worker choice strategy context referencing a worker choice algorithm implementation.
79 */
80 protected workerChoiceStrategyContext: WorkerChoiceStrategyContext<
81 Worker,
82 Data,
83 Response
84 >
85
86 /**
87 * Whether the pool is starting or not.
88 */
89 private readonly starting: boolean
90 /**
91 * The start timestamp of the pool.
92 */
93 private readonly startTimestamp
94
95 /**
96 * Constructs a new poolifier pool.
97 *
98 * @param numberOfWorkers - Number of workers that this pool should manage.
99 * @param filePath - Path to the worker file.
100 * @param opts - Options for the pool.
101 */
102 public constructor (
103 protected readonly numberOfWorkers: number,
104 protected readonly filePath: string,
105 protected readonly opts: PoolOptions<Worker>
106 ) {
107 if (!this.isMain()) {
108 throw new Error('Cannot start a pool from a worker!')
109 }
110 this.checkNumberOfWorkers(this.numberOfWorkers)
111 this.checkFilePath(this.filePath)
112 this.checkPoolOptions(this.opts)
113
114 this.chooseWorkerNode = this.chooseWorkerNode.bind(this)
115 this.executeTask = this.executeTask.bind(this)
116 this.enqueueTask = this.enqueueTask.bind(this)
117 this.dequeueTask = this.dequeueTask.bind(this)
118 this.checkAndEmitEvents = this.checkAndEmitEvents.bind(this)
119
120 if (this.opts.enableEvents === true) {
121 this.emitter = new PoolEmitter()
122 }
123 this.workerChoiceStrategyContext = new WorkerChoiceStrategyContext<
124 Worker,
125 Data,
126 Response
127 >(
128 this,
129 this.opts.workerChoiceStrategy,
130 this.opts.workerChoiceStrategyOptions
131 )
132
133 this.setupHook()
134
135 this.starting = true
136 this.startPool()
137 this.starting = false
138
139 this.startTimestamp = performance.now()
140 }
141
142 private checkFilePath (filePath: string): void {
143 if (
144 filePath == null ||
145 typeof filePath !== 'string' ||
146 (typeof filePath === 'string' && filePath.trim().length === 0)
147 ) {
148 throw new Error('Please specify a file with a worker implementation')
149 }
150 if (!existsSync(filePath)) {
151 throw new Error(`Cannot find the worker file '${filePath}'`)
152 }
153 }
154
155 private checkNumberOfWorkers (numberOfWorkers: number): void {
156 if (numberOfWorkers == null) {
157 throw new Error(
158 'Cannot instantiate a pool without specifying the number of workers'
159 )
160 } else if (!Number.isSafeInteger(numberOfWorkers)) {
161 throw new TypeError(
162 'Cannot instantiate a pool with a non safe integer number of workers'
163 )
164 } else if (numberOfWorkers < 0) {
165 throw new RangeError(
166 'Cannot instantiate a pool with a negative number of workers'
167 )
168 } else if (this.type === PoolTypes.fixed && numberOfWorkers === 0) {
169 throw new RangeError('Cannot instantiate a fixed pool with zero worker')
170 }
171 }
172
173 protected checkDynamicPoolSize (min: number, max: number): void {
174 if (this.type === PoolTypes.dynamic) {
175 if (max == null) {
176 throw new Error(
177 'Cannot instantiate a dynamic pool without specifying the maximum pool size'
178 )
179 } else if (!Number.isSafeInteger(max)) {
180 throw new TypeError(
181 'Cannot instantiate a dynamic pool with a non safe integer maximum pool size'
182 )
183 } else if (min > max) {
184 throw new RangeError(
185 'Cannot instantiate a dynamic pool with a maximum pool size inferior to the minimum pool size'
186 )
187 } else if (max === 0) {
188 throw new RangeError(
189 'Cannot instantiate a dynamic pool with a maximum pool size equal to zero'
190 )
191 } else if (min === max) {
192 throw new RangeError(
193 'Cannot instantiate a dynamic pool with a minimum pool size equal to the maximum pool size. Use a fixed pool instead'
194 )
195 }
196 }
197 }
198
199 private checkPoolOptions (opts: PoolOptions<Worker>): void {
200 if (isPlainObject(opts)) {
201 this.opts.workerChoiceStrategy =
202 opts.workerChoiceStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN
203 this.checkValidWorkerChoiceStrategy(this.opts.workerChoiceStrategy)
204 this.opts.workerChoiceStrategyOptions =
205 opts.workerChoiceStrategyOptions ??
206 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
207 this.checkValidWorkerChoiceStrategyOptions(
208 this.opts.workerChoiceStrategyOptions
209 )
210 this.opts.restartWorkerOnError = opts.restartWorkerOnError ?? true
211 this.opts.enableEvents = opts.enableEvents ?? true
212 this.opts.enableTasksQueue = opts.enableTasksQueue ?? false
213 if (this.opts.enableTasksQueue) {
214 this.checkValidTasksQueueOptions(
215 opts.tasksQueueOptions as TasksQueueOptions
216 )
217 this.opts.tasksQueueOptions = this.buildTasksQueueOptions(
218 opts.tasksQueueOptions as TasksQueueOptions
219 )
220 }
221 } else {
222 throw new TypeError('Invalid pool options: must be a plain object')
223 }
224 }
225
226 private checkValidWorkerChoiceStrategy (
227 workerChoiceStrategy: WorkerChoiceStrategy
228 ): void {
229 if (!Object.values(WorkerChoiceStrategies).includes(workerChoiceStrategy)) {
230 throw new Error(
231 `Invalid worker choice strategy '${workerChoiceStrategy}'`
232 )
233 }
234 }
235
236 private checkValidWorkerChoiceStrategyOptions (
237 workerChoiceStrategyOptions: WorkerChoiceStrategyOptions
238 ): void {
239 if (!isPlainObject(workerChoiceStrategyOptions)) {
240 throw new TypeError(
241 'Invalid worker choice strategy options: must be a plain object'
242 )
243 }
244 if (
245 workerChoiceStrategyOptions.weights != null &&
246 Object.keys(workerChoiceStrategyOptions.weights).length !== this.maxSize
247 ) {
248 throw new Error(
249 'Invalid worker choice strategy options: must have a weight for each worker node'
250 )
251 }
252 if (
253 workerChoiceStrategyOptions.measurement != null &&
254 !Object.values(Measurements).includes(
255 workerChoiceStrategyOptions.measurement
256 )
257 ) {
258 throw new Error(
259 `Invalid worker choice strategy options: invalid measurement '${workerChoiceStrategyOptions.measurement}'`
260 )
261 }
262 }
263
264 private checkValidTasksQueueOptions (
265 tasksQueueOptions: TasksQueueOptions
266 ): void {
267 if (tasksQueueOptions != null && !isPlainObject(tasksQueueOptions)) {
268 throw new TypeError('Invalid tasks queue options: must be a plain object')
269 }
270 if (
271 tasksQueueOptions?.concurrency != null &&
272 !Number.isSafeInteger(tasksQueueOptions.concurrency)
273 ) {
274 throw new TypeError(
275 'Invalid worker tasks concurrency: must be an integer'
276 )
277 }
278 if (
279 tasksQueueOptions?.concurrency != null &&
280 tasksQueueOptions.concurrency <= 0
281 ) {
282 throw new Error(
283 `Invalid worker tasks concurrency '${tasksQueueOptions.concurrency}'`
284 )
285 }
286 }
287
288 private startPool (): void {
289 while (
290 this.workerNodes.reduce(
291 (accumulator, workerNode) =>
292 !workerNode.info.dynamic ? accumulator + 1 : accumulator,
293 0
294 ) < this.numberOfWorkers
295 ) {
296 this.createAndSetupWorkerNode()
297 }
298 }
299
300 /** @inheritDoc */
301 public get info (): PoolInfo {
302 return {
303 version,
304 type: this.type,
305 worker: this.worker,
306 ready: this.ready,
307 strategy: this.opts.workerChoiceStrategy as WorkerChoiceStrategy,
308 minSize: this.minSize,
309 maxSize: this.maxSize,
310 ...(this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
311 .runTime.aggregate &&
312 this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
313 .waitTime.aggregate && { utilization: round(this.utilization) }),
314 workerNodes: this.workerNodes.length,
315 idleWorkerNodes: this.workerNodes.reduce(
316 (accumulator, workerNode) =>
317 workerNode.usage.tasks.executing === 0
318 ? accumulator + 1
319 : accumulator,
320 0
321 ),
322 busyWorkerNodes: this.workerNodes.reduce(
323 (accumulator, workerNode) =>
324 workerNode.usage.tasks.executing > 0 ? accumulator + 1 : accumulator,
325 0
326 ),
327 executedTasks: this.workerNodes.reduce(
328 (accumulator, workerNode) =>
329 accumulator + workerNode.usage.tasks.executed,
330 0
331 ),
332 executingTasks: this.workerNodes.reduce(
333 (accumulator, workerNode) =>
334 accumulator + workerNode.usage.tasks.executing,
335 0
336 ),
337 ...(this.opts.enableTasksQueue === true && {
338 queuedTasks: this.workerNodes.reduce(
339 (accumulator, workerNode) =>
340 accumulator + workerNode.usage.tasks.queued,
341 0
342 )
343 }),
344 ...(this.opts.enableTasksQueue === true && {
345 maxQueuedTasks: this.workerNodes.reduce(
346 (accumulator, workerNode) =>
347 accumulator + (workerNode.usage.tasks?.maxQueued ?? 0),
348 0
349 )
350 }),
351 failedTasks: this.workerNodes.reduce(
352 (accumulator, workerNode) =>
353 accumulator + workerNode.usage.tasks.failed,
354 0
355 ),
356 ...(this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
357 .runTime.aggregate && {
358 runTime: {
359 minimum: round(
360 Math.min(
361 ...this.workerNodes.map(
362 workerNode => workerNode.usage.runTime?.minimum ?? Infinity
363 )
364 )
365 ),
366 maximum: round(
367 Math.max(
368 ...this.workerNodes.map(
369 workerNode => workerNode.usage.runTime?.maximum ?? -Infinity
370 )
371 )
372 ),
373 average: round(
374 this.workerNodes.reduce(
375 (accumulator, workerNode) =>
376 accumulator + (workerNode.usage.runTime?.aggregate ?? 0),
377 0
378 ) /
379 this.workerNodes.reduce(
380 (accumulator, workerNode) =>
381 accumulator + (workerNode.usage.tasks?.executed ?? 0),
382 0
383 )
384 ),
385 ...(this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
386 .runTime.median && {
387 median: round(
388 median(
389 this.workerNodes.map(
390 workerNode => workerNode.usage.runTime?.median ?? 0
391 )
392 )
393 )
394 })
395 }
396 }),
397 ...(this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
398 .waitTime.aggregate && {
399 waitTime: {
400 minimum: round(
401 Math.min(
402 ...this.workerNodes.map(
403 workerNode => workerNode.usage.waitTime?.minimum ?? Infinity
404 )
405 )
406 ),
407 maximum: round(
408 Math.max(
409 ...this.workerNodes.map(
410 workerNode => workerNode.usage.waitTime?.maximum ?? -Infinity
411 )
412 )
413 ),
414 average: round(
415 this.workerNodes.reduce(
416 (accumulator, workerNode) =>
417 accumulator + (workerNode.usage.waitTime?.aggregate ?? 0),
418 0
419 ) /
420 this.workerNodes.reduce(
421 (accumulator, workerNode) =>
422 accumulator + (workerNode.usage.tasks?.executed ?? 0),
423 0
424 )
425 ),
426 ...(this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
427 .waitTime.median && {
428 median: round(
429 median(
430 this.workerNodes.map(
431 workerNode => workerNode.usage.waitTime?.median ?? 0
432 )
433 )
434 )
435 })
436 }
437 })
438 }
439 }
440
441 /**
442 * The pool readiness boolean status.
443 */
444 private get ready (): boolean {
445 return (
446 this.workerNodes.reduce(
447 (accumulator, workerNode) =>
448 !workerNode.info.dynamic && workerNode.info.ready
449 ? accumulator + 1
450 : accumulator,
451 0
452 ) >= this.minSize
453 )
454 }
455
456 /**
457 * The approximate pool utilization.
458 *
459 * @returns The pool utilization.
460 */
461 private get utilization (): number {
462 const poolTimeCapacity =
463 (performance.now() - this.startTimestamp) * this.maxSize
464 const totalTasksRunTime = this.workerNodes.reduce(
465 (accumulator, workerNode) =>
466 accumulator + (workerNode.usage.runTime?.aggregate ?? 0),
467 0
468 )
469 const totalTasksWaitTime = this.workerNodes.reduce(
470 (accumulator, workerNode) =>
471 accumulator + (workerNode.usage.waitTime?.aggregate ?? 0),
472 0
473 )
474 return (totalTasksRunTime + totalTasksWaitTime) / poolTimeCapacity
475 }
476
477 /**
478 * The pool type.
479 *
480 * If it is `'dynamic'`, it provides the `max` property.
481 */
482 protected abstract get type (): PoolType
483
484 /**
485 * The worker type.
486 */
487 protected abstract get worker (): WorkerType
488
489 /**
490 * The pool minimum size.
491 */
492 protected abstract get minSize (): number
493
494 /**
495 * The pool maximum size.
496 */
497 protected abstract get maxSize (): number
498
499 /**
500 * Checks if the worker id sent in the received message from a worker is valid.
501 *
502 * @param message - The received message.
503 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the worker id is invalid.
504 */
505 private checkMessageWorkerId (message: MessageValue<Response>): void {
506 if (
507 message.workerId != null &&
508 this.getWorkerNodeKeyByWorkerId(message.workerId) === -1
509 ) {
510 throw new Error(
511 `Worker message received from unknown worker '${message.workerId}'`
512 )
513 }
514 }
515
516 /**
517 * Gets the given worker its worker node key.
518 *
519 * @param worker - The worker.
520 * @returns The worker node key if found in the pool worker nodes, `-1` otherwise.
521 */
522 private getWorkerNodeKeyByWorker (worker: Worker): number {
523 return this.workerNodes.findIndex(
524 workerNode => workerNode.worker === worker
525 )
526 }
527
528 /**
529 * Gets the worker node key given its worker id.
530 *
531 * @param workerId - The worker id.
532 * @returns The worker node key if the worker id is found in the pool worker nodes, `-1` otherwise.
533 */
534 private getWorkerNodeKeyByWorkerId (workerId: number): number {
535 return this.workerNodes.findIndex(
536 workerNode => workerNode.info.id === workerId
537 )
538 }
539
540 /** @inheritDoc */
541 public setWorkerChoiceStrategy (
542 workerChoiceStrategy: WorkerChoiceStrategy,
543 workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions
544 ): void {
545 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy)
546 this.opts.workerChoiceStrategy = workerChoiceStrategy
547 this.workerChoiceStrategyContext.setWorkerChoiceStrategy(
548 this.opts.workerChoiceStrategy
549 )
550 if (workerChoiceStrategyOptions != null) {
551 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions)
552 }
553 for (const [workerNodeKey, workerNode] of this.workerNodes.entries()) {
554 workerNode.resetUsage()
555 this.sendWorkerStatisticsMessageToWorker(workerNodeKey)
556 }
557 }
558
559 /** @inheritDoc */
560 public setWorkerChoiceStrategyOptions (
561 workerChoiceStrategyOptions: WorkerChoiceStrategyOptions
562 ): void {
563 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions)
564 this.opts.workerChoiceStrategyOptions = workerChoiceStrategyOptions
565 this.workerChoiceStrategyContext.setOptions(
566 this.opts.workerChoiceStrategyOptions
567 )
568 }
569
570 /** @inheritDoc */
571 public enableTasksQueue (
572 enable: boolean,
573 tasksQueueOptions?: TasksQueueOptions
574 ): void {
575 if (this.opts.enableTasksQueue === true && !enable) {
576 this.flushTasksQueues()
577 }
578 this.opts.enableTasksQueue = enable
579 this.setTasksQueueOptions(tasksQueueOptions as TasksQueueOptions)
580 }
581
582 /** @inheritDoc */
583 public setTasksQueueOptions (tasksQueueOptions: TasksQueueOptions): void {
584 if (this.opts.enableTasksQueue === true) {
585 this.checkValidTasksQueueOptions(tasksQueueOptions)
586 this.opts.tasksQueueOptions =
587 this.buildTasksQueueOptions(tasksQueueOptions)
588 } else if (this.opts.tasksQueueOptions != null) {
589 delete this.opts.tasksQueueOptions
590 }
591 }
592
593 private buildTasksQueueOptions (
594 tasksQueueOptions: TasksQueueOptions
595 ): TasksQueueOptions {
596 return {
597 concurrency: tasksQueueOptions?.concurrency ?? 1
598 }
599 }
600
601 /**
602 * Whether the pool is full or not.
603 *
604 * The pool filling boolean status.
605 */
606 protected get full (): boolean {
607 return this.workerNodes.length >= this.maxSize
608 }
609
610 /**
611 * Whether the pool is busy or not.
612 *
613 * The pool busyness boolean status.
614 */
615 protected abstract get busy (): boolean
616
617 /**
618 * Whether worker nodes are executing at least one task.
619 *
620 * @returns Worker nodes busyness boolean status.
621 */
622 protected internalBusy (): boolean {
623 return (
624 this.workerNodes.findIndex(
625 workerNode =>
626 workerNode.info.ready && workerNode.usage.tasks.executing === 0
627 ) === -1
628 )
629 }
630
631 /** @inheritDoc */
632 public async execute (data?: Data, name?: string): Promise<Response> {
633 return await new Promise<Response>((resolve, reject) => {
634 const timestamp = performance.now()
635 const workerNodeKey = this.chooseWorkerNode()
636 const task: Task<Data> = {
637 name: name ?? DEFAULT_TASK_NAME,
638 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
639 data: data ?? ({} as Data),
640 timestamp,
641 workerId: this.getWorkerInfo(workerNodeKey).id as number,
642 id: randomUUID()
643 }
644 this.promiseResponseMap.set(task.id as string, {
645 resolve,
646 reject,
647 workerNodeKey
648 })
649 if (
650 this.opts.enableTasksQueue === false ||
651 (this.opts.enableTasksQueue === true &&
652 this.workerNodes[workerNodeKey].usage.tasks.executing <
653 (this.opts.tasksQueueOptions?.concurrency as number))
654 ) {
655 this.executeTask(workerNodeKey, task)
656 } else {
657 this.enqueueTask(workerNodeKey, task)
658 }
659 this.checkAndEmitEvents()
660 })
661 }
662
663 /** @inheritDoc */
664 public async destroy (): Promise<void> {
665 await Promise.all(
666 this.workerNodes.map(async (_, workerNodeKey) => {
667 await this.destroyWorkerNode(workerNodeKey)
668 })
669 )
670 }
671
672 /**
673 * Terminates the worker node given its worker node key.
674 *
675 * @param workerNodeKey - The worker node key.
676 */
677 protected abstract destroyWorkerNode (workerNodeKey: number): Promise<void>
678
679 /**
680 * Setup hook to execute code before worker nodes are created in the abstract constructor.
681 * Can be overridden.
682 *
683 * @virtual
684 */
685 protected setupHook (): void {
686 // Intentionally empty
687 }
688
689 /**
690 * Should return whether the worker is the main worker or not.
691 */
692 protected abstract isMain (): boolean
693
694 /**
695 * Hook executed before the worker task execution.
696 * Can be overridden.
697 *
698 * @param workerNodeKey - The worker node key.
699 * @param task - The task to execute.
700 */
701 protected beforeTaskExecutionHook (
702 workerNodeKey: number,
703 task: Task<Data>
704 ): void {
705 const workerUsage = this.workerNodes[workerNodeKey].usage
706 ++workerUsage.tasks.executing
707 this.updateWaitTimeWorkerUsage(workerUsage, task)
708 const taskWorkerUsage = this.workerNodes[workerNodeKey].getTaskWorkerUsage(
709 task.name as string
710 ) as WorkerUsage
711 ++taskWorkerUsage.tasks.executing
712 this.updateWaitTimeWorkerUsage(taskWorkerUsage, task)
713 }
714
715 /**
716 * Hook executed after the worker task execution.
717 * Can be overridden.
718 *
719 * @param workerNodeKey - The worker node key.
720 * @param message - The received message.
721 */
722 protected afterTaskExecutionHook (
723 workerNodeKey: number,
724 message: MessageValue<Response>
725 ): void {
726 const workerUsage = this.workerNodes[workerNodeKey].usage
727 this.updateTaskStatisticsWorkerUsage(workerUsage, message)
728 this.updateRunTimeWorkerUsage(workerUsage, message)
729 this.updateEluWorkerUsage(workerUsage, message)
730 const taskWorkerUsage = this.workerNodes[workerNodeKey].getTaskWorkerUsage(
731 message.taskPerformance?.name ?? DEFAULT_TASK_NAME
732 ) as WorkerUsage
733 this.updateTaskStatisticsWorkerUsage(taskWorkerUsage, message)
734 this.updateRunTimeWorkerUsage(taskWorkerUsage, message)
735 this.updateEluWorkerUsage(taskWorkerUsage, message)
736 }
737
738 private updateTaskStatisticsWorkerUsage (
739 workerUsage: WorkerUsage,
740 message: MessageValue<Response>
741 ): void {
742 const workerTaskStatistics = workerUsage.tasks
743 --workerTaskStatistics.executing
744 if (message.taskError == null) {
745 ++workerTaskStatistics.executed
746 } else {
747 ++workerTaskStatistics.failed
748 }
749 }
750
751 private updateRunTimeWorkerUsage (
752 workerUsage: WorkerUsage,
753 message: MessageValue<Response>
754 ): void {
755 updateMeasurementStatistics(
756 workerUsage.runTime,
757 this.workerChoiceStrategyContext.getTaskStatisticsRequirements().runTime,
758 message.taskPerformance?.runTime ?? 0,
759 workerUsage.tasks.executed
760 )
761 }
762
763 private updateWaitTimeWorkerUsage (
764 workerUsage: WorkerUsage,
765 task: Task<Data>
766 ): void {
767 const timestamp = performance.now()
768 const taskWaitTime = timestamp - (task.timestamp ?? timestamp)
769 updateMeasurementStatistics(
770 workerUsage.waitTime,
771 this.workerChoiceStrategyContext.getTaskStatisticsRequirements().waitTime,
772 taskWaitTime,
773 workerUsage.tasks.executed
774 )
775 }
776
777 private updateEluWorkerUsage (
778 workerUsage: WorkerUsage,
779 message: MessageValue<Response>
780 ): void {
781 const eluTaskStatisticsRequirements: MeasurementStatisticsRequirements =
782 this.workerChoiceStrategyContext.getTaskStatisticsRequirements().elu
783 updateMeasurementStatistics(
784 workerUsage.elu.active,
785 eluTaskStatisticsRequirements,
786 message.taskPerformance?.elu?.active ?? 0,
787 workerUsage.tasks.executed
788 )
789 updateMeasurementStatistics(
790 workerUsage.elu.idle,
791 eluTaskStatisticsRequirements,
792 message.taskPerformance?.elu?.idle ?? 0,
793 workerUsage.tasks.executed
794 )
795 if (eluTaskStatisticsRequirements.aggregate) {
796 if (message.taskPerformance?.elu != null) {
797 if (workerUsage.elu.utilization != null) {
798 workerUsage.elu.utilization =
799 (workerUsage.elu.utilization +
800 message.taskPerformance.elu.utilization) /
801 2
802 } else {
803 workerUsage.elu.utilization = message.taskPerformance.elu.utilization
804 }
805 }
806 }
807 }
808
809 /**
810 * Chooses a worker node for the next task.
811 *
812 * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
813 *
814 * @returns The chosen worker node key
815 */
816 private chooseWorkerNode (): number {
817 if (this.shallCreateDynamicWorker()) {
818 const workerNodeKey = this.createAndSetupDynamicWorkerNode()
819 if (
820 this.workerChoiceStrategyContext.getStrategyPolicy().useDynamicWorker
821 ) {
822 return workerNodeKey
823 }
824 }
825 return this.workerChoiceStrategyContext.execute()
826 }
827
828 /**
829 * Conditions for dynamic worker creation.
830 *
831 * @returns Whether to create a dynamic worker or not.
832 */
833 private shallCreateDynamicWorker (): boolean {
834 return this.type === PoolTypes.dynamic && !this.full && this.internalBusy()
835 }
836
837 /**
838 * Sends a message to worker given its worker node key.
839 *
840 * @param workerNodeKey - The worker node key.
841 * @param message - The message.
842 */
843 protected abstract sendToWorker (
844 workerNodeKey: number,
845 message: MessageValue<Data>
846 ): void
847
848 /**
849 * Creates a new worker.
850 *
851 * @returns Newly created worker.
852 */
853 protected abstract createWorker (): Worker
854
855 /**
856 * Creates a new, completely set up worker node.
857 *
858 * @returns New, completely set up worker node key.
859 */
860 protected createAndSetupWorkerNode (): number {
861 const worker = this.createWorker()
862
863 worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION)
864 worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION)
865 worker.on('error', error => {
866 const workerNodeKey = this.getWorkerNodeKeyByWorker(worker)
867 const workerInfo = this.getWorkerInfo(workerNodeKey)
868 workerInfo.ready = false
869 this.workerNodes[workerNodeKey].closeChannel()
870 this.emitter?.emit(PoolEvents.error, error)
871 if (this.opts.restartWorkerOnError === true && !this.starting) {
872 if (workerInfo.dynamic) {
873 this.createAndSetupDynamicWorkerNode()
874 } else {
875 this.createAndSetupWorkerNode()
876 }
877 }
878 if (this.opts.enableTasksQueue === true) {
879 this.redistributeQueuedTasks(workerNodeKey)
880 }
881 })
882 worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION)
883 worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION)
884 worker.once('exit', () => {
885 this.removeWorkerNode(worker)
886 })
887
888 const workerNodeKey = this.addWorkerNode(worker)
889
890 this.afterWorkerNodeSetup(workerNodeKey)
891
892 return workerNodeKey
893 }
894
895 /**
896 * Creates a new, completely set up dynamic worker node.
897 *
898 * @returns New, completely set up dynamic worker node key.
899 */
900 protected createAndSetupDynamicWorkerNode (): number {
901 const workerNodeKey = this.createAndSetupWorkerNode()
902 this.registerWorkerMessageListener(workerNodeKey, message => {
903 const localWorkerNodeKey = this.getWorkerNodeKeyByWorkerId(
904 message.workerId
905 )
906 const workerUsage = this.workerNodes[localWorkerNodeKey].usage
907 // Kill message received from worker
908 if (
909 isKillBehavior(KillBehaviors.HARD, message.kill) ||
910 (message.kill != null &&
911 ((this.opts.enableTasksQueue === false &&
912 workerUsage.tasks.executing === 0) ||
913 (this.opts.enableTasksQueue === true &&
914 workerUsage.tasks.executing === 0 &&
915 this.tasksQueueSize(localWorkerNodeKey) === 0)))
916 ) {
917 this.destroyWorkerNode(localWorkerNodeKey).catch(EMPTY_FUNCTION)
918 }
919 })
920 const workerInfo = this.getWorkerInfo(workerNodeKey)
921 this.sendToWorker(workerNodeKey, {
922 checkActive: true,
923 workerId: workerInfo.id as number
924 })
925 workerInfo.dynamic = true
926 if (this.workerChoiceStrategyContext.getStrategyPolicy().useDynamicWorker) {
927 workerInfo.ready = true
928 }
929 return workerNodeKey
930 }
931
932 /**
933 * Registers a listener callback on the worker given its worker node key.
934 *
935 * @param workerNodeKey - The worker node key.
936 * @param listener - The message listener callback.
937 */
938 protected abstract registerWorkerMessageListener<
939 Message extends Data | Response
940 >(
941 workerNodeKey: number,
942 listener: (message: MessageValue<Message>) => void
943 ): void
944
945 /**
946 * Method hooked up after a worker node has been newly created.
947 * Can be overridden.
948 *
949 * @param workerNodeKey - The newly created worker node key.
950 */
951 protected afterWorkerNodeSetup (workerNodeKey: number): void {
952 // Listen to worker messages.
953 this.registerWorkerMessageListener(workerNodeKey, this.workerListener())
954 // Send the startup message to worker.
955 this.sendStartupMessageToWorker(workerNodeKey)
956 // Send the worker statistics message to worker.
957 this.sendWorkerStatisticsMessageToWorker(workerNodeKey)
958 }
959
960 /**
961 * Sends the startup message to worker given its worker node key.
962 *
963 * @param workerNodeKey - The worker node key.
964 */
965 protected abstract sendStartupMessageToWorker (workerNodeKey: number): void
966
967 /**
968 * Sends the worker statistics message to worker given its worker node key.
969 *
970 * @param workerNodeKey - The worker node key.
971 */
972 private sendWorkerStatisticsMessageToWorker (workerNodeKey: number): void {
973 this.sendToWorker(workerNodeKey, {
974 statistics: {
975 runTime:
976 this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
977 .runTime.aggregate,
978 elu: this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
979 .elu.aggregate
980 },
981 workerId: this.getWorkerInfo(workerNodeKey).id as number
982 })
983 }
984
985 private redistributeQueuedTasks (workerNodeKey: number): void {
986 while (this.tasksQueueSize(workerNodeKey) > 0) {
987 let targetWorkerNodeKey: number = workerNodeKey
988 let minQueuedTasks = Infinity
989 let executeTask = false
990 for (const [workerNodeId, workerNode] of this.workerNodes.entries()) {
991 const workerInfo = this.getWorkerInfo(workerNodeId)
992 if (
993 workerNodeId !== workerNodeKey &&
994 workerInfo.ready &&
995 workerNode.usage.tasks.queued === 0
996 ) {
997 if (
998 this.workerNodes[workerNodeId].usage.tasks.executing <
999 (this.opts.tasksQueueOptions?.concurrency as number)
1000 ) {
1001 executeTask = true
1002 }
1003 targetWorkerNodeKey = workerNodeId
1004 break
1005 }
1006 if (
1007 workerNodeId !== workerNodeKey &&
1008 workerInfo.ready &&
1009 workerNode.usage.tasks.queued < minQueuedTasks
1010 ) {
1011 minQueuedTasks = workerNode.usage.tasks.queued
1012 targetWorkerNodeKey = workerNodeId
1013 }
1014 }
1015 if (executeTask) {
1016 this.executeTask(
1017 targetWorkerNodeKey,
1018 this.dequeueTask(workerNodeKey) as Task<Data>
1019 )
1020 } else {
1021 this.enqueueTask(
1022 targetWorkerNodeKey,
1023 this.dequeueTask(workerNodeKey) as Task<Data>
1024 )
1025 }
1026 }
1027 }
1028
1029 /**
1030 * This method is the listener registered for each worker message.
1031 *
1032 * @returns The listener function to execute when a message is received from a worker.
1033 */
1034 protected workerListener (): (message: MessageValue<Response>) => void {
1035 return message => {
1036 this.checkMessageWorkerId(message)
1037 if (message.ready != null) {
1038 // Worker ready response received from worker
1039 this.handleWorkerReadyResponse(message)
1040 } else if (message.id != null) {
1041 // Task execution response received from worker
1042 this.handleTaskExecutionResponse(message)
1043 }
1044 }
1045 }
1046
1047 private handleWorkerReadyResponse (message: MessageValue<Response>): void {
1048 this.getWorkerInfo(
1049 this.getWorkerNodeKeyByWorkerId(message.workerId)
1050 ).ready = message.ready as boolean
1051 if (this.emitter != null && this.ready) {
1052 this.emitter.emit(PoolEvents.ready, this.info)
1053 }
1054 }
1055
1056 private handleTaskExecutionResponse (message: MessageValue<Response>): void {
1057 const promiseResponse = this.promiseResponseMap.get(message.id as string)
1058 if (promiseResponse != null) {
1059 if (message.taskError != null) {
1060 this.emitter?.emit(PoolEvents.taskError, message.taskError)
1061 promiseResponse.reject(message.taskError.message)
1062 } else {
1063 promiseResponse.resolve(message.data as Response)
1064 }
1065 const workerNodeKey = promiseResponse.workerNodeKey
1066 this.afterTaskExecutionHook(workerNodeKey, message)
1067 this.promiseResponseMap.delete(message.id as string)
1068 if (
1069 this.opts.enableTasksQueue === true &&
1070 this.tasksQueueSize(workerNodeKey) > 0 &&
1071 this.workerNodes[workerNodeKey].usage.tasks.executing <
1072 (this.opts.tasksQueueOptions?.concurrency as number)
1073 ) {
1074 this.executeTask(
1075 workerNodeKey,
1076 this.dequeueTask(workerNodeKey) as Task<Data>
1077 )
1078 }
1079 this.workerChoiceStrategyContext.update(workerNodeKey)
1080 }
1081 }
1082
1083 private checkAndEmitEvents (): void {
1084 if (this.emitter != null) {
1085 if (this.busy) {
1086 this.emitter.emit(PoolEvents.busy, this.info)
1087 }
1088 if (this.type === PoolTypes.dynamic && this.full) {
1089 this.emitter.emit(PoolEvents.full, this.info)
1090 }
1091 }
1092 }
1093
1094 /**
1095 * Gets the worker information given its worker node key.
1096 *
1097 * @param workerNodeKey - The worker node key.
1098 * @returns The worker information.
1099 */
1100 protected getWorkerInfo (workerNodeKey: number): WorkerInfo {
1101 return this.workerNodes[workerNodeKey].info
1102 }
1103
1104 /**
1105 * Adds the given worker in the pool worker nodes.
1106 *
1107 * @param worker - The worker.
1108 * @returns The added worker node key.
1109 * @throws {@link https://nodejs.org/api/errors.html#class-error} If the added worker node is not found.
1110 */
1111 private addWorkerNode (worker: Worker): number {
1112 const workerNode = new WorkerNode<Worker, Data>(worker, this.worker)
1113 // Flag the worker node as ready at pool startup.
1114 if (this.starting) {
1115 workerNode.info.ready = true
1116 }
1117 this.workerNodes.push(workerNode)
1118 const workerNodeKey = this.getWorkerNodeKeyByWorker(worker)
1119 if (workerNodeKey === -1) {
1120 throw new Error('Worker node not found')
1121 }
1122 return workerNodeKey
1123 }
1124
1125 /**
1126 * Removes the given worker from the pool worker nodes.
1127 *
1128 * @param worker - The worker.
1129 */
1130 private removeWorkerNode (worker: Worker): void {
1131 const workerNodeKey = this.getWorkerNodeKeyByWorker(worker)
1132 if (workerNodeKey !== -1) {
1133 this.workerNodes.splice(workerNodeKey, 1)
1134 this.workerChoiceStrategyContext.remove(workerNodeKey)
1135 }
1136 }
1137
1138 /**
1139 * Executes the given task on the worker given its worker node key.
1140 *
1141 * @param workerNodeKey - The worker node key.
1142 * @param task - The task to execute.
1143 */
1144 private executeTask (workerNodeKey: number, task: Task<Data>): void {
1145 this.beforeTaskExecutionHook(workerNodeKey, task)
1146 this.sendToWorker(workerNodeKey, task)
1147 }
1148
1149 private enqueueTask (workerNodeKey: number, task: Task<Data>): number {
1150 return this.workerNodes[workerNodeKey].enqueueTask(task)
1151 }
1152
1153 private dequeueTask (workerNodeKey: number): Task<Data> | undefined {
1154 return this.workerNodes[workerNodeKey].dequeueTask()
1155 }
1156
1157 private tasksQueueSize (workerNodeKey: number): number {
1158 return this.workerNodes[workerNodeKey].tasksQueueSize()
1159 }
1160
1161 protected flushTasksQueue (workerNodeKey: number): void {
1162 while (this.tasksQueueSize(workerNodeKey) > 0) {
1163 this.executeTask(
1164 workerNodeKey,
1165 this.dequeueTask(workerNodeKey) as Task<Data>
1166 )
1167 }
1168 this.workerNodes[workerNodeKey].clearTasksQueue()
1169 }
1170
1171 private flushTasksQueues (): void {
1172 for (const [workerNodeKey] of this.workerNodes.entries()) {
1173 this.flushTasksQueue(workerNodeKey)
1174 }
1175 }
1176}