refactor: align findFreeWorkerKey() return type with findIndex()
[poolifier.git] / src / pools / selection-strategies / weighted-round-robin-worker-choice-strategy.ts
CommitLineData
fc3e6586 1import { cpus } from 'node:os'
b3432a63 2import type { IPoolInternal } from '../pool-internal'
ea7a90d3 3import type { IPoolWorker } from '../pool-worker'
b3432a63 4import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy'
bf90656c
JB
5import type {
6 IWorkerChoiceStrategy,
7 RequiredStatistics
8} from './selection-strategies-types'
b3432a63
JB
9
10/**
23135a89 11 * Virtual task runtime.
b3432a63 12 */
78cea37e 13interface TaskRunTime {
b3432a63
JB
14 weight: number
15 runTime: number
16}
17
18/**
19 * Selects the next worker with a weighted round robin scheduling algorithm.
20 * Loosely modeled after the weighted round robin queueing algorithm: https://en.wikipedia.org/wiki/Weighted_round_robin.
21 *
38e795c1
JB
22 * @typeParam Worker - Type of worker which manages the strategy.
23 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
24 * @typeParam Response - Type of response of execution. This can only be serializable data.
b3432a63
JB
25 */
26export class WeightedRoundRobinWorkerChoiceStrategy<
bf90656c
JB
27 Worker extends IPoolWorker,
28 Data,
29 Response
30 >
31 extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
32 implements IWorkerChoiceStrategy {
38e795c1 33 /** {@inheritDoc} */
ea7a90d3 34 public readonly requiredStatistics: RequiredStatistics = {
10fcfaf4
JB
35 runTime: true
36 }
37
b3432a63 38 /**
ffcbbad8 39 * Worker id where the current task will be submitted.
b3432a63 40 */
ffcbbad8 41 private currentWorkerId: number = 0
b3432a63
JB
42 /**
43 * Default worker weight.
44 */
777af0ac 45 private readonly defaultWorkerWeight: number
b3432a63 46 /**
2377984d 47 * Per worker virtual task runtime map.
b3432a63 48 */
c923ce56
JB
49 private readonly workersTaskRunTime: Map<number, TaskRunTime> = new Map<
50 number,
78cea37e 51 TaskRunTime
b3432a63
JB
52 >()
53
54 /**
23ff945a 55 * Constructs a worker choice strategy that selects with a weighted round robin scheduling algorithm.
b3432a63 56 *
38e795c1 57 * @param pool - The pool instance.
b3432a63
JB
58 */
59 public constructor (pool: IPoolInternal<Worker, Data, Response>) {
60 super(pool)
61 this.defaultWorkerWeight = this.computeWorkerWeight()
2377984d 62 this.initWorkersTaskRunTime()
b3432a63
JB
63 }
64
38e795c1 65 /** {@inheritDoc} */
a6f7f1b4 66 public reset (): boolean {
ffcbbad8 67 this.currentWorkerId = 0
ea7a90d3
JB
68 this.workersTaskRunTime.clear()
69 this.initWorkersTaskRunTime()
70 return true
71 }
72
38e795c1 73 /** {@inheritDoc} */
c923ce56
JB
74 public choose (): number {
75 const chosenWorkerKey = this.currentWorkerId
76 if (this.isDynamicPool && !this.workersTaskRunTime.has(chosenWorkerKey)) {
77 this.initWorkerTaskRunTime(chosenWorkerKey)
b3432a63 78 }
d8a610ca 79 const workerTaskRunTime =
c923ce56 80 this.workersTaskRunTime.get(chosenWorkerKey)?.runTime ?? 0
b3432a63 81 const workerTaskWeight =
c923ce56 82 this.workersTaskRunTime.get(chosenWorkerKey)?.weight ??
b3432a63 83 this.defaultWorkerWeight
553ad720 84 if (workerTaskRunTime < workerTaskWeight) {
2377984d 85 this.setWorkerTaskRunTime(
c923ce56 86 chosenWorkerKey,
2377984d 87 workerTaskWeight,
553ad720 88 workerTaskRunTime +
c923ce56 89 (this.getWorkerVirtualTaskRunTime(chosenWorkerKey) ?? 0)
2377984d 90 )
b3432a63 91 } else {
ffcbbad8 92 this.currentWorkerId =
e65c6cd9 93 this.currentWorkerId === this.pool.workers.length - 1
b3432a63 94 ? 0
ffcbbad8 95 : this.currentWorkerId + 1
c923ce56 96 this.setWorkerTaskRunTime(this.currentWorkerId, workerTaskWeight, 0)
b3432a63 97 }
c923ce56 98 return chosenWorkerKey
b3432a63
JB
99 }
100
97a2abc3
JB
101 /** {@inheritDoc} */
102 public remove (workerKey: number): boolean {
103 if (this.currentWorkerId === workerKey) {
104 this.currentWorkerId =
105 this.currentWorkerId > this.pool.workers.length - 1
106 ? this.pool.workers.length - 1
107 : this.currentWorkerId
108 }
109 const workerDeleted = this.workersTaskRunTime.delete(workerKey)
110 for (const [key, value] of this.workersTaskRunTime) {
111 if (key > workerKey) {
112 this.workersTaskRunTime.set(key - 1, value)
113 }
114 }
115 return workerDeleted
116 }
117
2377984d 118 private initWorkersTaskRunTime (): void {
c923ce56
JB
119 for (const [index] of this.pool.workers.entries()) {
120 this.initWorkerTaskRunTime(index)
2377984d
JB
121 }
122 }
123
c923ce56
JB
124 private initWorkerTaskRunTime (workerKey: number): void {
125 this.setWorkerTaskRunTime(workerKey, this.defaultWorkerWeight, 0)
2377984d
JB
126 }
127
128 private setWorkerTaskRunTime (
c923ce56 129 workerKey: number,
2377984d
JB
130 weight: number,
131 runTime: number
132 ): void {
c923ce56 133 this.workersTaskRunTime.set(workerKey, {
2377984d
JB
134 weight,
135 runTime
136 })
137 }
138
c923ce56
JB
139 private getWorkerVirtualTaskRunTime (workerKey: number): number {
140 return this.pool.workers[workerKey].tasksUsage.avgRunTime
2377984d
JB
141 }
142
143 private computeWorkerWeight (): number {
b3432a63 144 let cpusCycleTimeWeight = 0
a59e741b 145 for (const cpu of cpus()) {
b3432a63 146 // CPU estimated cycle time
d8a610ca
JB
147 const numberOfDigits = cpu.speed.toString().length - 1
148 const cpuCycleTime = 1 / (cpu.speed / Math.pow(10, numberOfDigits))
149 cpusCycleTimeWeight += cpuCycleTime * Math.pow(10, numberOfDigits)
b3432a63 150 }
7b0d35b8 151 return Math.round(cpusCycleTimeWeight / cpus().length)
b3432a63 152 }
b3432a63 153}