refactor: use task performance data structure in messages
[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 isPlainObject,
8 median
9 } from '../utils'
10 import { KillBehaviors, isKillBehavior } from '../worker/worker-options'
11 import { CircularArray } from '../circular-array'
12 import { Queue } from '../queue'
13 import {
14 type IPool,
15 PoolEmitter,
16 PoolEvents,
17 type PoolInfo,
18 type PoolOptions,
19 type PoolType,
20 PoolTypes,
21 type TasksQueueOptions,
22 type WorkerType
23 } from './pool'
24 import type { IWorker, Task, TasksUsage, WorkerNode } from './worker'
25 import {
26 WorkerChoiceStrategies,
27 type WorkerChoiceStrategy,
28 type WorkerChoiceStrategyOptions
29 } from './selection-strategies/selection-strategies-types'
30 import { WorkerChoiceStrategyContext } from './selection-strategies/worker-choice-strategy-context'
31
32 /**
33 * Base class that implements some shared logic for all poolifier pools.
34 *
35 * @typeParam Worker - Type of worker which manages this pool.
36 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
37 * @typeParam Response - Type of execution response. This can only be serializable data.
38 */
39 export abstract class AbstractPool<
40 Worker extends IWorker,
41 Data = unknown,
42 Response = unknown
43 > implements IPool<Worker, Data, Response> {
44 /** @inheritDoc */
45 public readonly workerNodes: Array<WorkerNode<Worker, Data>> = []
46
47 /** @inheritDoc */
48 public readonly emitter?: PoolEmitter
49
50 /**
51 * The execution response promise map.
52 *
53 * - `key`: The message id of each submitted task.
54 * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks.
55 *
56 * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id.
57 */
58 protected promiseResponseMap: Map<
59 string,
60 PromiseResponseWrapper<Worker, Response>
61 > = new Map<string, PromiseResponseWrapper<Worker, Response>>()
62
63 /**
64 * Worker choice strategy context referencing a worker choice algorithm implementation.
65 *
66 * Default to a round robin algorithm.
67 */
68 protected workerChoiceStrategyContext: WorkerChoiceStrategyContext<
69 Worker,
70 Data,
71 Response
72 >
73
74 /**
75 * Constructs a new poolifier pool.
76 *
77 * @param numberOfWorkers - Number of workers that this pool should manage.
78 * @param filePath - Path to the worker file.
79 * @param opts - Options for the pool.
80 */
81 public constructor (
82 protected readonly numberOfWorkers: number,
83 protected readonly filePath: string,
84 protected readonly opts: PoolOptions<Worker>
85 ) {
86 if (!this.isMain()) {
87 throw new Error('Cannot start a pool from a worker!')
88 }
89 this.checkNumberOfWorkers(this.numberOfWorkers)
90 this.checkFilePath(this.filePath)
91 this.checkPoolOptions(this.opts)
92
93 this.chooseWorkerNode = this.chooseWorkerNode.bind(this)
94 this.executeTask = this.executeTask.bind(this)
95 this.enqueueTask = this.enqueueTask.bind(this)
96 this.checkAndEmitEvents = this.checkAndEmitEvents.bind(this)
97
98 if (this.opts.enableEvents === true) {
99 this.emitter = new PoolEmitter()
100 }
101 this.workerChoiceStrategyContext = new WorkerChoiceStrategyContext<
102 Worker,
103 Data,
104 Response
105 >(
106 this,
107 this.opts.workerChoiceStrategy,
108 this.opts.workerChoiceStrategyOptions
109 )
110
111 this.setupHook()
112
113 for (let i = 1; i <= this.numberOfWorkers; i++) {
114 this.createAndSetupWorker()
115 }
116 }
117
118 private checkFilePath (filePath: string): void {
119 if (
120 filePath == null ||
121 (typeof filePath === 'string' && filePath.trim().length === 0)
122 ) {
123 throw new Error('Please specify a file with a worker implementation')
124 }
125 }
126
127 private checkNumberOfWorkers (numberOfWorkers: number): void {
128 if (numberOfWorkers == null) {
129 throw new Error(
130 'Cannot instantiate a pool without specifying the number of workers'
131 )
132 } else if (!Number.isSafeInteger(numberOfWorkers)) {
133 throw new TypeError(
134 'Cannot instantiate a pool with a non safe integer number of workers'
135 )
136 } else if (numberOfWorkers < 0) {
137 throw new RangeError(
138 'Cannot instantiate a pool with a negative number of workers'
139 )
140 } else if (this.type === PoolTypes.fixed && numberOfWorkers === 0) {
141 throw new Error('Cannot instantiate a fixed pool with no worker')
142 }
143 }
144
145 private checkPoolOptions (opts: PoolOptions<Worker>): void {
146 if (isPlainObject(opts)) {
147 this.opts.workerChoiceStrategy =
148 opts.workerChoiceStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN
149 this.checkValidWorkerChoiceStrategy(this.opts.workerChoiceStrategy)
150 this.opts.workerChoiceStrategyOptions =
151 opts.workerChoiceStrategyOptions ??
152 DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
153 this.checkValidWorkerChoiceStrategyOptions(
154 this.opts.workerChoiceStrategyOptions
155 )
156 this.opts.restartWorkerOnError = opts.restartWorkerOnError ?? true
157 this.opts.enableEvents = opts.enableEvents ?? true
158 this.opts.enableTasksQueue = opts.enableTasksQueue ?? false
159 if (this.opts.enableTasksQueue) {
160 this.checkValidTasksQueueOptions(
161 opts.tasksQueueOptions as TasksQueueOptions
162 )
163 this.opts.tasksQueueOptions = this.buildTasksQueueOptions(
164 opts.tasksQueueOptions as TasksQueueOptions
165 )
166 }
167 } else {
168 throw new TypeError('Invalid pool options: must be a plain object')
169 }
170 }
171
172 private checkValidWorkerChoiceStrategy (
173 workerChoiceStrategy: WorkerChoiceStrategy
174 ): void {
175 if (!Object.values(WorkerChoiceStrategies).includes(workerChoiceStrategy)) {
176 throw new Error(
177 `Invalid worker choice strategy '${workerChoiceStrategy}'`
178 )
179 }
180 }
181
182 private checkValidWorkerChoiceStrategyOptions (
183 workerChoiceStrategyOptions: WorkerChoiceStrategyOptions
184 ): void {
185 if (!isPlainObject(workerChoiceStrategyOptions)) {
186 throw new TypeError(
187 'Invalid worker choice strategy options: must be a plain object'
188 )
189 }
190 if (
191 workerChoiceStrategyOptions.weights != null &&
192 Object.keys(workerChoiceStrategyOptions.weights).length !== this.maxSize
193 ) {
194 throw new Error(
195 'Invalid worker choice strategy options: must have a weight for each worker node'
196 )
197 }
198 }
199
200 private checkValidTasksQueueOptions (
201 tasksQueueOptions: TasksQueueOptions
202 ): void {
203 if (tasksQueueOptions != null && !isPlainObject(tasksQueueOptions)) {
204 throw new TypeError('Invalid tasks queue options: must be a plain object')
205 }
206 if ((tasksQueueOptions?.concurrency as number) <= 0) {
207 throw new Error(
208 `Invalid worker tasks concurrency '${
209 tasksQueueOptions.concurrency as number
210 }'`
211 )
212 }
213 }
214
215 /** @inheritDoc */
216 public get info (): PoolInfo {
217 return {
218 type: this.type,
219 worker: this.worker,
220 minSize: this.minSize,
221 maxSize: this.maxSize,
222 workerNodes: this.workerNodes.length,
223 idleWorkerNodes: this.workerNodes.reduce(
224 (accumulator, workerNode) =>
225 workerNode.tasksUsage.running === 0 ? accumulator + 1 : accumulator,
226 0
227 ),
228 busyWorkerNodes: this.workerNodes.reduce(
229 (accumulator, workerNode) =>
230 workerNode.tasksUsage.running > 0 ? accumulator + 1 : accumulator,
231 0
232 ),
233 runningTasks: this.workerNodes.reduce(
234 (accumulator, workerNode) =>
235 accumulator + workerNode.tasksUsage.running,
236 0
237 ),
238 queuedTasks: this.workerNodes.reduce(
239 (accumulator, workerNode) => accumulator + workerNode.tasksQueue.size,
240 0
241 ),
242 maxQueuedTasks: this.workerNodes.reduce(
243 (accumulator, workerNode) =>
244 accumulator + workerNode.tasksQueue.maxSize,
245 0
246 )
247 }
248 }
249
250 /**
251 * Pool type.
252 *
253 * If it is `'dynamic'`, it provides the `max` property.
254 */
255 protected abstract get type (): PoolType
256
257 /**
258 * Gets the worker type.
259 */
260 protected abstract get worker (): WorkerType
261
262 /**
263 * Pool minimum size.
264 */
265 protected abstract get minSize (): number
266
267 /**
268 * Pool maximum size.
269 */
270 protected abstract get maxSize (): number
271
272 /**
273 * Gets the given worker its worker node key.
274 *
275 * @param worker - The worker.
276 * @returns The worker node key if the worker is found in the pool worker nodes, `-1` otherwise.
277 */
278 private getWorkerNodeKey (worker: Worker): number {
279 return this.workerNodes.findIndex(
280 workerNode => workerNode.worker === worker
281 )
282 }
283
284 /** @inheritDoc */
285 public setWorkerChoiceStrategy (
286 workerChoiceStrategy: WorkerChoiceStrategy,
287 workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions
288 ): void {
289 this.checkValidWorkerChoiceStrategy(workerChoiceStrategy)
290 this.opts.workerChoiceStrategy = workerChoiceStrategy
291 this.workerChoiceStrategyContext.setWorkerChoiceStrategy(
292 this.opts.workerChoiceStrategy
293 )
294 if (workerChoiceStrategyOptions != null) {
295 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions)
296 }
297 for (const workerNode of this.workerNodes) {
298 this.setWorkerNodeTasksUsage(workerNode, {
299 ran: 0,
300 running: 0,
301 runTime: 0,
302 runTimeHistory: new CircularArray(),
303 avgRunTime: 0,
304 medRunTime: 0,
305 waitTime: 0,
306 waitTimeHistory: new CircularArray(),
307 avgWaitTime: 0,
308 medWaitTime: 0,
309 error: 0,
310 elu: undefined
311 })
312 this.setWorkerStatistics(workerNode.worker)
313 }
314 }
315
316 /** @inheritDoc */
317 public setWorkerChoiceStrategyOptions (
318 workerChoiceStrategyOptions: WorkerChoiceStrategyOptions
319 ): void {
320 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions)
321 this.opts.workerChoiceStrategyOptions = workerChoiceStrategyOptions
322 this.workerChoiceStrategyContext.setOptions(
323 this.opts.workerChoiceStrategyOptions
324 )
325 }
326
327 /** @inheritDoc */
328 public enableTasksQueue (
329 enable: boolean,
330 tasksQueueOptions?: TasksQueueOptions
331 ): void {
332 if (this.opts.enableTasksQueue === true && !enable) {
333 this.flushTasksQueues()
334 }
335 this.opts.enableTasksQueue = enable
336 this.setTasksQueueOptions(tasksQueueOptions as TasksQueueOptions)
337 }
338
339 /** @inheritDoc */
340 public setTasksQueueOptions (tasksQueueOptions: TasksQueueOptions): void {
341 if (this.opts.enableTasksQueue === true) {
342 this.checkValidTasksQueueOptions(tasksQueueOptions)
343 this.opts.tasksQueueOptions =
344 this.buildTasksQueueOptions(tasksQueueOptions)
345 } else if (this.opts.tasksQueueOptions != null) {
346 delete this.opts.tasksQueueOptions
347 }
348 }
349
350 private buildTasksQueueOptions (
351 tasksQueueOptions: TasksQueueOptions
352 ): TasksQueueOptions {
353 return {
354 concurrency: tasksQueueOptions?.concurrency ?? 1
355 }
356 }
357
358 /**
359 * Whether the pool is full or not.
360 *
361 * The pool filling boolean status.
362 */
363 protected get full (): boolean {
364 return this.workerNodes.length >= this.maxSize
365 }
366
367 /**
368 * Whether the pool is busy or not.
369 *
370 * The pool busyness boolean status.
371 */
372 protected abstract get busy (): boolean
373
374 protected internalBusy (): boolean {
375 return (
376 this.workerNodes.findIndex(workerNode => {
377 return workerNode.tasksUsage.running === 0
378 }) === -1
379 )
380 }
381
382 /** @inheritDoc */
383 public async execute (data?: Data, name?: string): Promise<Response> {
384 const timestamp = performance.now()
385 const workerNodeKey = this.chooseWorkerNode()
386 const submittedTask: Task<Data> = {
387 name,
388 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
389 data: data ?? ({} as Data),
390 timestamp,
391 id: crypto.randomUUID()
392 }
393 const res = new Promise<Response>((resolve, reject) => {
394 this.promiseResponseMap.set(submittedTask.id as string, {
395 resolve,
396 reject,
397 worker: this.workerNodes[workerNodeKey].worker
398 })
399 })
400 if (
401 this.opts.enableTasksQueue === true &&
402 (this.busy ||
403 this.workerNodes[workerNodeKey].tasksUsage.running >=
404 ((this.opts.tasksQueueOptions as TasksQueueOptions)
405 .concurrency as number))
406 ) {
407 this.enqueueTask(workerNodeKey, submittedTask)
408 } else {
409 this.executeTask(workerNodeKey, submittedTask)
410 }
411 this.workerChoiceStrategyContext.update(workerNodeKey)
412 this.checkAndEmitEvents()
413 // eslint-disable-next-line @typescript-eslint/return-await
414 return res
415 }
416
417 /** @inheritDoc */
418 public async destroy (): Promise<void> {
419 await Promise.all(
420 this.workerNodes.map(async (workerNode, workerNodeKey) => {
421 this.flushTasksQueue(workerNodeKey)
422 // FIXME: wait for tasks to be finished
423 await this.destroyWorker(workerNode.worker)
424 })
425 )
426 }
427
428 /**
429 * Shutdowns the given worker.
430 *
431 * @param worker - A worker within `workerNodes`.
432 */
433 protected abstract destroyWorker (worker: Worker): void | Promise<void>
434
435 /**
436 * Setup hook to execute code before worker node are created in the abstract constructor.
437 * Can be overridden
438 *
439 * @virtual
440 */
441 protected setupHook (): void {
442 // Intentionally empty
443 }
444
445 /**
446 * Should return whether the worker is the main worker or not.
447 */
448 protected abstract isMain (): boolean
449
450 /**
451 * Hook executed before the worker task execution.
452 * Can be overridden.
453 *
454 * @param workerNodeKey - The worker node key.
455 */
456 protected beforeTaskExecutionHook (workerNodeKey: number): void {
457 ++this.workerNodes[workerNodeKey].tasksUsage.running
458 }
459
460 /**
461 * Hook executed after the worker task execution.
462 * Can be overridden.
463 *
464 * @param worker - The worker.
465 * @param message - The received message.
466 */
467 protected afterTaskExecutionHook (
468 worker: Worker,
469 message: MessageValue<Response>
470 ): void {
471 const workerTasksUsage =
472 this.workerNodes[this.getWorkerNodeKey(worker)].tasksUsage
473 --workerTasksUsage.running
474 ++workerTasksUsage.ran
475 if (message.error != null) {
476 ++workerTasksUsage.error
477 }
478 this.updateRunTimeTasksUsage(workerTasksUsage, message)
479 this.updateWaitTimeTasksUsage(workerTasksUsage, message)
480 this.updateEluTasksUsage(workerTasksUsage, message)
481 }
482
483 private updateRunTimeTasksUsage (
484 workerTasksUsage: TasksUsage,
485 message: MessageValue<Response>
486 ): void {
487 if (this.workerChoiceStrategyContext.getTaskStatistics().runTime) {
488 workerTasksUsage.runTime += message.taskPerformance?.runTime ?? 0
489 if (
490 this.workerChoiceStrategyContext.getTaskStatistics().avgRunTime &&
491 workerTasksUsage.ran !== 0
492 ) {
493 workerTasksUsage.avgRunTime =
494 workerTasksUsage.runTime / workerTasksUsage.ran
495 }
496 if (
497 this.workerChoiceStrategyContext.getTaskStatistics().medRunTime &&
498 message.taskPerformance?.runTime != null
499 ) {
500 workerTasksUsage.runTimeHistory.push(message.taskPerformance.runTime)
501 workerTasksUsage.medRunTime = median(workerTasksUsage.runTimeHistory)
502 }
503 }
504 }
505
506 private updateWaitTimeTasksUsage (
507 workerTasksUsage: TasksUsage,
508 message: MessageValue<Response>
509 ): void {
510 if (this.workerChoiceStrategyContext.getTaskStatistics().waitTime) {
511 workerTasksUsage.waitTime += message.taskPerformance?.waitTime ?? 0
512 if (
513 this.workerChoiceStrategyContext.getTaskStatistics().avgWaitTime &&
514 workerTasksUsage.ran !== 0
515 ) {
516 workerTasksUsage.avgWaitTime =
517 workerTasksUsage.waitTime / workerTasksUsage.ran
518 }
519 if (
520 this.workerChoiceStrategyContext.getTaskStatistics().medWaitTime &&
521 message.taskPerformance?.waitTime != null
522 ) {
523 workerTasksUsage.waitTimeHistory.push(message.taskPerformance.waitTime)
524 workerTasksUsage.medWaitTime = median(workerTasksUsage.waitTimeHistory)
525 }
526 }
527 }
528
529 private updateEluTasksUsage (
530 workerTasksUsage: TasksUsage,
531 message: MessageValue<Response>
532 ): void {
533 if (this.workerChoiceStrategyContext.getTaskStatistics().elu) {
534 if (
535 workerTasksUsage.elu != null &&
536 message.taskPerformance?.elu != null
537 ) {
538 workerTasksUsage.elu = {
539 idle: workerTasksUsage.elu.idle + message.taskPerformance.elu.idle,
540 active:
541 workerTasksUsage.elu.active + message.taskPerformance.elu.active,
542 utilization:
543 (workerTasksUsage.elu.utilization +
544 message.taskPerformance.elu.utilization) /
545 2
546 }
547 } else if (message.taskPerformance?.elu != null) {
548 workerTasksUsage.elu = message.taskPerformance.elu
549 }
550 }
551 }
552
553 /**
554 * Chooses a worker node for the next task.
555 *
556 * The default worker choice strategy uses a round robin algorithm to distribute the load.
557 *
558 * @returns The worker node key
559 */
560 protected chooseWorkerNode (): number {
561 let workerNodeKey: number
562 if (this.type === PoolTypes.dynamic && !this.full && this.internalBusy()) {
563 const workerCreated = this.createAndSetupWorker()
564 this.registerWorkerMessageListener(workerCreated, message => {
565 const currentWorkerNodeKey = this.getWorkerNodeKey(workerCreated)
566 if (
567 isKillBehavior(KillBehaviors.HARD, message.kill) ||
568 (message.kill != null &&
569 this.workerNodes[currentWorkerNodeKey].tasksUsage.running === 0)
570 ) {
571 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
572 this.flushTasksQueue(currentWorkerNodeKey)
573 // FIXME: wait for tasks to be finished
574 void (this.destroyWorker(workerCreated) as Promise<void>)
575 }
576 })
577 workerNodeKey = this.getWorkerNodeKey(workerCreated)
578 } else {
579 workerNodeKey = this.workerChoiceStrategyContext.execute()
580 }
581 return workerNodeKey
582 }
583
584 /**
585 * Sends a message to the given worker.
586 *
587 * @param worker - The worker which should receive the message.
588 * @param message - The message.
589 */
590 protected abstract sendToWorker (
591 worker: Worker,
592 message: MessageValue<Data>
593 ): void
594
595 /**
596 * Registers a listener callback on the given worker.
597 *
598 * @param worker - The worker which should register a listener.
599 * @param listener - The message listener callback.
600 */
601 protected abstract registerWorkerMessageListener<
602 Message extends Data | Response
603 >(worker: Worker, listener: (message: MessageValue<Message>) => void): void
604
605 /**
606 * Returns a newly created worker.
607 */
608 protected abstract createWorker (): Worker
609
610 /**
611 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
612 *
613 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
614 *
615 * @param worker - The newly created worker.
616 */
617 protected abstract afterWorkerSetup (worker: Worker): void
618
619 /**
620 * Creates a new worker and sets it up completely in the pool worker nodes.
621 *
622 * @returns New, completely set up worker.
623 */
624 protected createAndSetupWorker (): Worker {
625 const worker = this.createWorker()
626
627 worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION)
628 worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION)
629 worker.on('error', error => {
630 if (this.emitter != null) {
631 this.emitter.emit(PoolEvents.error, error)
632 }
633 })
634 worker.on('error', () => {
635 if (this.opts.restartWorkerOnError === true) {
636 this.createAndSetupWorker()
637 }
638 })
639 worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION)
640 worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION)
641 worker.once('exit', () => {
642 this.removeWorkerNode(worker)
643 })
644
645 this.pushWorkerNode(worker)
646
647 this.setWorkerStatistics(worker)
648
649 this.afterWorkerSetup(worker)
650
651 return worker
652 }
653
654 /**
655 * This function is the listener registered for each worker message.
656 *
657 * @returns The listener function to execute when a message is received from a worker.
658 */
659 protected workerListener (): (message: MessageValue<Response>) => void {
660 return message => {
661 if (message.id != null) {
662 // Task execution response received
663 const promiseResponse = this.promiseResponseMap.get(message.id)
664 if (promiseResponse != null) {
665 if (message.error != null) {
666 promiseResponse.reject(message.error)
667 if (this.emitter != null) {
668 this.emitter.emit(PoolEvents.taskError, {
669 error: message.error,
670 errorData: message.errorData
671 })
672 }
673 } else {
674 promiseResponse.resolve(message.data as Response)
675 }
676 this.afterTaskExecutionHook(promiseResponse.worker, message)
677 this.promiseResponseMap.delete(message.id)
678 const workerNodeKey = this.getWorkerNodeKey(promiseResponse.worker)
679 if (
680 this.opts.enableTasksQueue === true &&
681 this.tasksQueueSize(workerNodeKey) > 0
682 ) {
683 this.executeTask(
684 workerNodeKey,
685 this.dequeueTask(workerNodeKey) as Task<Data>
686 )
687 }
688 }
689 }
690 }
691 }
692
693 private checkAndEmitEvents (): void {
694 if (this.emitter != null) {
695 if (this.busy) {
696 this.emitter?.emit(PoolEvents.busy, this.info)
697 }
698 if (this.type === PoolTypes.dynamic && this.full) {
699 this.emitter?.emit(PoolEvents.full, this.info)
700 }
701 }
702 }
703
704 /**
705 * Sets the given worker node its tasks usage in the pool.
706 *
707 * @param workerNode - The worker node.
708 * @param tasksUsage - The worker node tasks usage.
709 */
710 private setWorkerNodeTasksUsage (
711 workerNode: WorkerNode<Worker, Data>,
712 tasksUsage: TasksUsage
713 ): void {
714 workerNode.tasksUsage = tasksUsage
715 }
716
717 /**
718 * Pushes the given worker in the pool worker nodes.
719 *
720 * @param worker - The worker.
721 * @returns The worker nodes length.
722 */
723 private pushWorkerNode (worker: Worker): number {
724 return this.workerNodes.push({
725 worker,
726 tasksUsage: {
727 ran: 0,
728 running: 0,
729 runTime: 0,
730 runTimeHistory: new CircularArray(),
731 avgRunTime: 0,
732 medRunTime: 0,
733 waitTime: 0,
734 waitTimeHistory: new CircularArray(),
735 avgWaitTime: 0,
736 medWaitTime: 0,
737 error: 0,
738 elu: undefined
739 },
740 tasksQueue: new Queue<Task<Data>>()
741 })
742 }
743
744 /**
745 * Sets the given worker in the pool worker nodes.
746 *
747 * @param workerNodeKey - The worker node key.
748 * @param worker - The worker.
749 * @param tasksUsage - The worker tasks usage.
750 * @param tasksQueue - The worker task queue.
751 */
752 private setWorkerNode (
753 workerNodeKey: number,
754 worker: Worker,
755 tasksUsage: TasksUsage,
756 tasksQueue: Queue<Task<Data>>
757 ): void {
758 this.workerNodes[workerNodeKey] = {
759 worker,
760 tasksUsage,
761 tasksQueue
762 }
763 }
764
765 /**
766 * Removes the given worker from the pool worker nodes.
767 *
768 * @param worker - The worker.
769 */
770 private removeWorkerNode (worker: Worker): void {
771 const workerNodeKey = this.getWorkerNodeKey(worker)
772 if (workerNodeKey !== -1) {
773 this.workerNodes.splice(workerNodeKey, 1)
774 this.workerChoiceStrategyContext.remove(workerNodeKey)
775 }
776 }
777
778 private executeTask (workerNodeKey: number, task: Task<Data>): void {
779 this.beforeTaskExecutionHook(workerNodeKey)
780 this.sendToWorker(this.workerNodes[workerNodeKey].worker, task)
781 }
782
783 private enqueueTask (workerNodeKey: number, task: Task<Data>): number {
784 return this.workerNodes[workerNodeKey].tasksQueue.enqueue(task)
785 }
786
787 private dequeueTask (workerNodeKey: number): Task<Data> | undefined {
788 return this.workerNodes[workerNodeKey].tasksQueue.dequeue()
789 }
790
791 private tasksQueueSize (workerNodeKey: number): number {
792 return this.workerNodes[workerNodeKey].tasksQueue.size
793 }
794
795 private flushTasksQueue (workerNodeKey: number): void {
796 if (this.tasksQueueSize(workerNodeKey) > 0) {
797 for (let i = 0; i < this.tasksQueueSize(workerNodeKey); i++) {
798 this.executeTask(
799 workerNodeKey,
800 this.dequeueTask(workerNodeKey) as Task<Data>
801 )
802 }
803 }
804 }
805
806 private flushTasksQueues (): void {
807 for (const [workerNodeKey] of this.workerNodes.entries()) {
808 this.flushTasksQueue(workerNodeKey)
809 }
810 }
811
812 private setWorkerStatistics (worker: Worker): void {
813 this.sendToWorker(worker, {
814 statistics: {
815 runTime: this.workerChoiceStrategyContext.getTaskStatistics().runTime,
816 waitTime: this.workerChoiceStrategyContext.getTaskStatistics().waitTime,
817 elu: this.workerChoiceStrategyContext.getTaskStatistics().elu
818 }
819 })
820 }
821 }