feat: add ELU tasks accounting
[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 this.setupHook()
99
100 for (let i = 1; i <= this.numberOfWorkers; i++) {
101 this.createAndSetupWorker()
102 }
103
104 if (this.opts.enableEvents === true) {
105 this.emitter = new PoolEmitter()
106 }
107 this.workerChoiceStrategyContext = new WorkerChoiceStrategyContext<
108 Worker,
109 Data,
110 Response
111 >(
112 this,
113 this.opts.workerChoiceStrategy,
114 this.opts.workerChoiceStrategyOptions
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 for (const workerNode of this.workerNodes) {
292 this.setWorkerNodeTasksUsage(workerNode, {
293 ran: 0,
294 running: 0,
295 runTime: 0,
296 runTimeHistory: new CircularArray(),
297 avgRunTime: 0,
298 medRunTime: 0,
299 waitTime: 0,
300 waitTimeHistory: new CircularArray(),
301 avgWaitTime: 0,
302 medWaitTime: 0,
303 error: 0,
304 elu: undefined
305 })
306 }
307 this.workerChoiceStrategyContext.setWorkerChoiceStrategy(
308 this.opts.workerChoiceStrategy
309 )
310 if (workerChoiceStrategyOptions != null) {
311 this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions)
312 }
313 }
314
315 /** @inheritDoc */
316 public setWorkerChoiceStrategyOptions (
317 workerChoiceStrategyOptions: WorkerChoiceStrategyOptions
318 ): void {
319 this.checkValidWorkerChoiceStrategyOptions(workerChoiceStrategyOptions)
320 this.opts.workerChoiceStrategyOptions = workerChoiceStrategyOptions
321 this.workerChoiceStrategyContext.setOptions(
322 this.opts.workerChoiceStrategyOptions
323 )
324 }
325
326 /** @inheritDoc */
327 public enableTasksQueue (
328 enable: boolean,
329 tasksQueueOptions?: TasksQueueOptions
330 ): void {
331 if (this.opts.enableTasksQueue === true && !enable) {
332 this.flushTasksQueues()
333 }
334 this.opts.enableTasksQueue = enable
335 this.setTasksQueueOptions(tasksQueueOptions as TasksQueueOptions)
336 }
337
338 /** @inheritDoc */
339 public setTasksQueueOptions (tasksQueueOptions: TasksQueueOptions): void {
340 if (this.opts.enableTasksQueue === true) {
341 this.checkValidTasksQueueOptions(tasksQueueOptions)
342 this.opts.tasksQueueOptions =
343 this.buildTasksQueueOptions(tasksQueueOptions)
344 } else {
345 delete this.opts.tasksQueueOptions
346 }
347 }
348
349 private buildTasksQueueOptions (
350 tasksQueueOptions: TasksQueueOptions
351 ): TasksQueueOptions {
352 return {
353 concurrency: tasksQueueOptions?.concurrency ?? 1
354 }
355 }
356
357 /**
358 * Whether the pool is full or not.
359 *
360 * The pool filling boolean status.
361 */
362 protected get full (): boolean {
363 return this.workerNodes.length >= this.maxSize
364 }
365
366 /**
367 * Whether the pool is busy or not.
368 *
369 * The pool busyness boolean status.
370 */
371 protected abstract get busy (): boolean
372
373 protected internalBusy (): boolean {
374 return (
375 this.workerNodes.findIndex(workerNode => {
376 return workerNode.tasksUsage.running === 0
377 }) === -1
378 )
379 }
380
381 /** @inheritDoc */
382 public async execute (data?: Data, name?: string): Promise<Response> {
383 const submissionTimestamp = performance.now()
384 const workerNodeKey = this.chooseWorkerNode()
385 const submittedTask: Task<Data> = {
386 name,
387 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
388 data: data ?? ({} as Data),
389 submissionTimestamp,
390 id: crypto.randomUUID()
391 }
392 const res = new Promise<Response>((resolve, reject) => {
393 this.promiseResponseMap.set(submittedTask.id as string, {
394 resolve,
395 reject,
396 worker: this.workerNodes[workerNodeKey].worker
397 })
398 })
399 if (
400 this.opts.enableTasksQueue === true &&
401 (this.busy ||
402 this.workerNodes[workerNodeKey].tasksUsage.running >=
403 ((this.opts.tasksQueueOptions as TasksQueueOptions)
404 .concurrency as number))
405 ) {
406 this.enqueueTask(workerNodeKey, submittedTask)
407 } else {
408 this.executeTask(workerNodeKey, submittedTask)
409 }
410 this.workerChoiceStrategyContext.update(workerNodeKey)
411 this.checkAndEmitEvents()
412 // eslint-disable-next-line @typescript-eslint/return-await
413 return res
414 }
415
416 /** @inheritDoc */
417 public async destroy (): Promise<void> {
418 await Promise.all(
419 this.workerNodes.map(async (workerNode, workerNodeKey) => {
420 this.flushTasksQueue(workerNodeKey)
421 // FIXME: wait for tasks to be finished
422 await this.destroyWorker(workerNode.worker)
423 })
424 )
425 }
426
427 /**
428 * Shutdowns the given worker.
429 *
430 * @param worker - A worker within `workerNodes`.
431 */
432 protected abstract destroyWorker (worker: Worker): void | Promise<void>
433
434 /**
435 * Setup hook to execute code before worker node are created in the abstract constructor.
436 * Can be overridden
437 *
438 * @virtual
439 */
440 protected setupHook (): void {
441 // Intentionally empty
442 }
443
444 /**
445 * Should return whether the worker is the main worker or not.
446 */
447 protected abstract isMain (): boolean
448
449 /**
450 * Hook executed before the worker task execution.
451 * Can be overridden.
452 *
453 * @param workerNodeKey - The worker node key.
454 */
455 protected beforeTaskExecutionHook (workerNodeKey: number): void {
456 ++this.workerNodes[workerNodeKey].tasksUsage.running
457 }
458
459 /**
460 * Hook executed after the worker task execution.
461 * Can be overridden.
462 *
463 * @param worker - The worker.
464 * @param message - The received message.
465 */
466 protected afterTaskExecutionHook (
467 worker: Worker,
468 message: MessageValue<Response>
469 ): void {
470 const workerTasksUsage =
471 this.workerNodes[this.getWorkerNodeKey(worker)].tasksUsage
472 --workerTasksUsage.running
473 ++workerTasksUsage.ran
474 if (message.error != null) {
475 ++workerTasksUsage.error
476 }
477 this.updateRunTimeTasksUsage(workerTasksUsage, message)
478 this.updateWaitTimeTasksUsage(workerTasksUsage, message)
479 this.updateEluTasksUsage(workerTasksUsage, message)
480 }
481
482 private updateRunTimeTasksUsage (
483 workerTasksUsage: TasksUsage,
484 message: MessageValue<Response>
485 ): void {
486 if (this.workerChoiceStrategyContext.getRequiredStatistics().runTime) {
487 workerTasksUsage.runTime += message.runTime ?? 0
488 if (
489 this.workerChoiceStrategyContext.getRequiredStatistics().avgRunTime &&
490 workerTasksUsage.ran !== 0
491 ) {
492 workerTasksUsage.avgRunTime =
493 workerTasksUsage.runTime / workerTasksUsage.ran
494 }
495 if (
496 this.workerChoiceStrategyContext.getRequiredStatistics().medRunTime &&
497 message.runTime != null
498 ) {
499 workerTasksUsage.runTimeHistory.push(message.runTime)
500 workerTasksUsage.medRunTime = median(workerTasksUsage.runTimeHistory)
501 }
502 }
503 }
504
505 private updateWaitTimeTasksUsage (
506 workerTasksUsage: TasksUsage,
507 message: MessageValue<Response>
508 ): void {
509 if (this.workerChoiceStrategyContext.getRequiredStatistics().waitTime) {
510 workerTasksUsage.waitTime += message.waitTime ?? 0
511 if (
512 this.workerChoiceStrategyContext.getRequiredStatistics().avgWaitTime &&
513 workerTasksUsage.ran !== 0
514 ) {
515 workerTasksUsage.avgWaitTime =
516 workerTasksUsage.waitTime / workerTasksUsage.ran
517 }
518 if (
519 this.workerChoiceStrategyContext.getRequiredStatistics().medWaitTime &&
520 message.waitTime != null
521 ) {
522 workerTasksUsage.waitTimeHistory.push(message.waitTime)
523 workerTasksUsage.medWaitTime = median(workerTasksUsage.waitTimeHistory)
524 }
525 }
526 }
527
528 private updateEluTasksUsage (
529 workerTasksUsage: TasksUsage,
530 message: MessageValue<Response>
531 ): void {
532 if (this.workerChoiceStrategyContext.getRequiredStatistics().elu) {
533 if (workerTasksUsage.elu != null && message.elu != null) {
534 // TODO: cumulative or delta?
535 workerTasksUsage.elu = {
536 idle: workerTasksUsage.elu.idle + message.elu.idle,
537 active: workerTasksUsage.elu.active + message.elu.active,
538 utilization:
539 workerTasksUsage.elu.utilization + message.elu.utilization
540 }
541 } else if (message.elu != null) {
542 workerTasksUsage.elu = message.elu
543 }
544 }
545 }
546
547 /**
548 * Chooses a worker node for the next task.
549 *
550 * The default worker choice strategy uses a round robin algorithm to distribute the load.
551 *
552 * @returns The worker node key
553 */
554 protected chooseWorkerNode (): number {
555 let workerNodeKey: number
556 if (this.type === PoolTypes.dynamic && !this.full && this.internalBusy()) {
557 const workerCreated = this.createAndSetupWorker()
558 this.registerWorkerMessageListener(workerCreated, message => {
559 const currentWorkerNodeKey = this.getWorkerNodeKey(workerCreated)
560 if (
561 isKillBehavior(KillBehaviors.HARD, message.kill) ||
562 (message.kill != null &&
563 this.workerNodes[currentWorkerNodeKey].tasksUsage.running === 0)
564 ) {
565 // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
566 this.flushTasksQueue(currentWorkerNodeKey)
567 // FIXME: wait for tasks to be finished
568 void (this.destroyWorker(workerCreated) as Promise<void>)
569 }
570 })
571 workerNodeKey = this.getWorkerNodeKey(workerCreated)
572 } else {
573 workerNodeKey = this.workerChoiceStrategyContext.execute()
574 }
575 return workerNodeKey
576 }
577
578 /**
579 * Sends a message to the given worker.
580 *
581 * @param worker - The worker which should receive the message.
582 * @param message - The message.
583 */
584 protected abstract sendToWorker (
585 worker: Worker,
586 message: MessageValue<Data>
587 ): void
588
589 /**
590 * Registers a listener callback on the given worker.
591 *
592 * @param worker - The worker which should register a listener.
593 * @param listener - The message listener callback.
594 */
595 protected abstract registerWorkerMessageListener<
596 Message extends Data | Response
597 >(worker: Worker, listener: (message: MessageValue<Message>) => void): void
598
599 /**
600 * Returns a newly created worker.
601 */
602 protected abstract createWorker (): Worker
603
604 /**
605 * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
606 *
607 * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
608 *
609 * @param worker - The newly created worker.
610 */
611 protected abstract afterWorkerSetup (worker: Worker): void
612
613 /**
614 * Creates a new worker and sets it up completely in the pool worker nodes.
615 *
616 * @returns New, completely set up worker.
617 */
618 protected createAndSetupWorker (): Worker {
619 const worker = this.createWorker()
620
621 worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION)
622 worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION)
623 worker.on('error', error => {
624 if (this.emitter != null) {
625 this.emitter.emit(PoolEvents.error, error)
626 }
627 })
628 if (this.opts.restartWorkerOnError === true) {
629 worker.on('error', () => {
630 this.createAndSetupWorker()
631 })
632 }
633 worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION)
634 worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION)
635 worker.once('exit', () => {
636 this.removeWorkerNode(worker)
637 })
638
639 this.pushWorkerNode(worker)
640
641 this.afterWorkerSetup(worker)
642
643 return worker
644 }
645
646 /**
647 * This function is the listener registered for each worker message.
648 *
649 * @returns The listener function to execute when a message is received from a worker.
650 */
651 protected workerListener (): (message: MessageValue<Response>) => void {
652 return message => {
653 if (message.id != null) {
654 // Task execution response received
655 const promiseResponse = this.promiseResponseMap.get(message.id)
656 if (promiseResponse != null) {
657 if (message.error != null) {
658 promiseResponse.reject(message.error)
659 if (this.emitter != null) {
660 this.emitter.emit(PoolEvents.taskError, {
661 error: message.error,
662 errorData: message.errorData
663 })
664 }
665 } else {
666 promiseResponse.resolve(message.data as Response)
667 }
668 this.afterTaskExecutionHook(promiseResponse.worker, message)
669 this.promiseResponseMap.delete(message.id)
670 const workerNodeKey = this.getWorkerNodeKey(promiseResponse.worker)
671 if (
672 this.opts.enableTasksQueue === true &&
673 this.tasksQueueSize(workerNodeKey) > 0
674 ) {
675 this.executeTask(
676 workerNodeKey,
677 this.dequeueTask(workerNodeKey) as Task<Data>
678 )
679 }
680 }
681 }
682 }
683 }
684
685 private checkAndEmitEvents (): void {
686 if (this.emitter != null) {
687 if (this.busy) {
688 this.emitter?.emit(PoolEvents.busy, this.info)
689 }
690 if (this.type === PoolTypes.dynamic && this.full) {
691 this.emitter?.emit(PoolEvents.full, this.info)
692 }
693 }
694 }
695
696 /**
697 * Sets the given worker node its tasks usage in the pool.
698 *
699 * @param workerNode - The worker node.
700 * @param tasksUsage - The worker node tasks usage.
701 */
702 private setWorkerNodeTasksUsage (
703 workerNode: WorkerNode<Worker, Data>,
704 tasksUsage: TasksUsage
705 ): void {
706 workerNode.tasksUsage = tasksUsage
707 }
708
709 /**
710 * Pushes the given worker in the pool worker nodes.
711 *
712 * @param worker - The worker.
713 * @returns The worker nodes length.
714 */
715 private pushWorkerNode (worker: Worker): number {
716 return this.workerNodes.push({
717 worker,
718 tasksUsage: {
719 ran: 0,
720 running: 0,
721 runTime: 0,
722 runTimeHistory: new CircularArray(),
723 avgRunTime: 0,
724 medRunTime: 0,
725 waitTime: 0,
726 waitTimeHistory: new CircularArray(),
727 avgWaitTime: 0,
728 medWaitTime: 0,
729 error: 0,
730 elu: undefined
731 },
732 tasksQueue: new Queue<Task<Data>>()
733 })
734 }
735
736 /**
737 * Sets the given worker in the pool worker nodes.
738 *
739 * @param workerNodeKey - The worker node key.
740 * @param worker - The worker.
741 * @param tasksUsage - The worker tasks usage.
742 * @param tasksQueue - The worker task queue.
743 */
744 private setWorkerNode (
745 workerNodeKey: number,
746 worker: Worker,
747 tasksUsage: TasksUsage,
748 tasksQueue: Queue<Task<Data>>
749 ): void {
750 this.workerNodes[workerNodeKey] = {
751 worker,
752 tasksUsage,
753 tasksQueue
754 }
755 }
756
757 /**
758 * Removes the given worker from the pool worker nodes.
759 *
760 * @param worker - The worker.
761 */
762 private removeWorkerNode (worker: Worker): void {
763 const workerNodeKey = this.getWorkerNodeKey(worker)
764 if (workerNodeKey !== -1) {
765 this.workerNodes.splice(workerNodeKey, 1)
766 this.workerChoiceStrategyContext.remove(workerNodeKey)
767 }
768 }
769
770 private executeTask (workerNodeKey: number, task: Task<Data>): void {
771 this.beforeTaskExecutionHook(workerNodeKey)
772 this.sendToWorker(this.workerNodes[workerNodeKey].worker, task)
773 }
774
775 private enqueueTask (workerNodeKey: number, task: Task<Data>): number {
776 return this.workerNodes[workerNodeKey].tasksQueue.enqueue(task)
777 }
778
779 private dequeueTask (workerNodeKey: number): Task<Data> | undefined {
780 return this.workerNodes[workerNodeKey].tasksQueue.dequeue()
781 }
782
783 private tasksQueueSize (workerNodeKey: number): number {
784 return this.workerNodes[workerNodeKey].tasksQueue.size
785 }
786
787 private flushTasksQueue (workerNodeKey: number): void {
788 if (this.tasksQueueSize(workerNodeKey) > 0) {
789 for (let i = 0; i < this.tasksQueueSize(workerNodeKey); i++) {
790 this.executeTask(
791 workerNodeKey,
792 this.dequeueTask(workerNodeKey) as Task<Data>
793 )
794 }
795 }
796 }
797
798 private flushTasksQueues (): void {
799 for (const [workerNodeKey] of this.workerNodes.entries()) {
800 this.flushTasksQueue(workerNodeKey)
801 }
802 }
803 }