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