feat: add ELU tasks accounting
[poolifier.git] / src / pools / selection-strategies / least-busy-worker-choice-strategy.ts
1 import { DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS } from '../../utils'
2 import type { IPool } from '../pool'
3 import type { IWorker } from '../worker'
4 import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy'
5 import type {
6 IWorkerChoiceStrategy,
7 RequiredStatistics,
8 WorkerChoiceStrategyOptions
9 } from './selection-strategies-types'
10
11 /**
12 * Selects the least busy worker.
13 *
14 * @typeParam Worker - Type of worker which manages the strategy.
15 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
16 * @typeParam Response - Type of execution response. This can only be serializable data.
17 */
18 export class LeastBusyWorkerChoiceStrategy<
19 Worker extends IWorker,
20 Data = unknown,
21 Response = unknown
22 >
23 extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
24 implements IWorkerChoiceStrategy {
25 /** @inheritDoc */
26 public readonly requiredStatistics: RequiredStatistics = {
27 runTime: true,
28 avgRunTime: false,
29 medRunTime: false,
30 waitTime: false,
31 avgWaitTime: false,
32 medWaitTime: false,
33 elu: false
34 }
35
36 /** @inheritDoc */
37 public constructor (
38 pool: IPool<Worker, Data, Response>,
39 opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
40 ) {
41 super(pool, opts)
42 this.setRequiredStatistics(this.opts)
43 }
44
45 /** @inheritDoc */
46 public reset (): boolean {
47 return true
48 }
49
50 /** @inheritDoc */
51 public update (): boolean {
52 return true
53 }
54
55 /** @inheritDoc */
56 public choose (): number {
57 const freeWorkerNodeKey = this.findFreeWorkerNodeKey()
58 if (freeWorkerNodeKey !== -1) {
59 return freeWorkerNodeKey
60 }
61 let minRunTime = Infinity
62 let leastBusyWorkerNodeKey!: number
63 for (const [workerNodeKey, workerNode] of this.pool.workerNodes.entries()) {
64 const workerRunTime = workerNode.tasksUsage.runTime
65 if (workerRunTime === 0) {
66 return workerNodeKey
67 } else if (workerRunTime < minRunTime) {
68 minRunTime = workerRunTime
69 leastBusyWorkerNodeKey = workerNodeKey
70 }
71 }
72 return leastBusyWorkerNodeKey
73 }
74
75 /** @inheritDoc */
76 public remove (): boolean {
77 return true
78 }
79 }