perf: allow finer grained control over tasks usage computation
[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 = {
c6bd2650
JB
35 runTime: true,
36 avgRunTime: true
10fcfaf4
JB
37 }
38
b3432a63 39 /**
ffcbbad8 40 * Worker id where the current task will be submitted.
b3432a63 41 */
ffcbbad8 42 private currentWorkerId: number = 0
b3432a63
JB
43 /**
44 * Default worker weight.
45 */
777af0ac 46 private readonly defaultWorkerWeight: number
b3432a63 47 /**
2377984d 48 * Per worker virtual task runtime map.
b3432a63 49 */
c923ce56
JB
50 private readonly workersTaskRunTime: Map<number, TaskRunTime> = new Map<
51 number,
78cea37e 52 TaskRunTime
b3432a63
JB
53 >()
54
55 /**
23ff945a 56 * Constructs a worker choice strategy that selects with a weighted round robin scheduling algorithm.
b3432a63 57 *
38e795c1 58 * @param pool - The pool instance.
b3432a63
JB
59 */
60 public constructor (pool: IPoolInternal<Worker, Data, Response>) {
61 super(pool)
62 this.defaultWorkerWeight = this.computeWorkerWeight()
2377984d 63 this.initWorkersTaskRunTime()
b3432a63
JB
64 }
65
38e795c1 66 /** {@inheritDoc} */
a6f7f1b4 67 public reset (): boolean {
ffcbbad8 68 this.currentWorkerId = 0
ea7a90d3
JB
69 this.workersTaskRunTime.clear()
70 this.initWorkersTaskRunTime()
71 return true
72 }
73
38e795c1 74 /** {@inheritDoc} */
c923ce56
JB
75 public choose (): number {
76 const chosenWorkerKey = this.currentWorkerId
77 if (this.isDynamicPool && !this.workersTaskRunTime.has(chosenWorkerKey)) {
78 this.initWorkerTaskRunTime(chosenWorkerKey)
b3432a63 79 }
d8a610ca 80 const workerTaskRunTime =
c923ce56 81 this.workersTaskRunTime.get(chosenWorkerKey)?.runTime ?? 0
b3432a63 82 const workerTaskWeight =
c923ce56 83 this.workersTaskRunTime.get(chosenWorkerKey)?.weight ??
b3432a63 84 this.defaultWorkerWeight
553ad720 85 if (workerTaskRunTime < workerTaskWeight) {
2377984d 86 this.setWorkerTaskRunTime(
c923ce56 87 chosenWorkerKey,
2377984d 88 workerTaskWeight,
553ad720 89 workerTaskRunTime +
c923ce56 90 (this.getWorkerVirtualTaskRunTime(chosenWorkerKey) ?? 0)
2377984d 91 )
b3432a63 92 } else {
ffcbbad8 93 this.currentWorkerId =
e65c6cd9 94 this.currentWorkerId === this.pool.workers.length - 1
b3432a63 95 ? 0
ffcbbad8 96 : this.currentWorkerId + 1
c923ce56 97 this.setWorkerTaskRunTime(this.currentWorkerId, workerTaskWeight, 0)
b3432a63 98 }
c923ce56 99 return chosenWorkerKey
b3432a63
JB
100 }
101
97a2abc3
JB
102 /** {@inheritDoc} */
103 public remove (workerKey: number): boolean {
104 if (this.currentWorkerId === workerKey) {
105 this.currentWorkerId =
106 this.currentWorkerId > this.pool.workers.length - 1
107 ? this.pool.workers.length - 1
108 : this.currentWorkerId
109 }
110 const workerDeleted = this.workersTaskRunTime.delete(workerKey)
111 for (const [key, value] of this.workersTaskRunTime) {
112 if (key > workerKey) {
113 this.workersTaskRunTime.set(key - 1, value)
114 }
115 }
116 return workerDeleted
117 }
118
2377984d 119 private initWorkersTaskRunTime (): void {
c923ce56
JB
120 for (const [index] of this.pool.workers.entries()) {
121 this.initWorkerTaskRunTime(index)
2377984d
JB
122 }
123 }
124
c923ce56
JB
125 private initWorkerTaskRunTime (workerKey: number): void {
126 this.setWorkerTaskRunTime(workerKey, this.defaultWorkerWeight, 0)
2377984d
JB
127 }
128
129 private setWorkerTaskRunTime (
c923ce56 130 workerKey: number,
2377984d
JB
131 weight: number,
132 runTime: number
133 ): void {
c923ce56 134 this.workersTaskRunTime.set(workerKey, {
2377984d
JB
135 weight,
136 runTime
137 })
138 }
139
c923ce56
JB
140 private getWorkerVirtualTaskRunTime (workerKey: number): number {
141 return this.pool.workers[workerKey].tasksUsage.avgRunTime
2377984d
JB
142 }
143
144 private computeWorkerWeight (): number {
b3432a63 145 let cpusCycleTimeWeight = 0
a59e741b 146 for (const cpu of cpus()) {
b3432a63 147 // CPU estimated cycle time
d8a610ca
JB
148 const numberOfDigits = cpu.speed.toString().length - 1
149 const cpuCycleTime = 1 / (cpu.speed / Math.pow(10, numberOfDigits))
150 cpusCycleTimeWeight += cpuCycleTime * Math.pow(10, numberOfDigits)
b3432a63 151 }
7b0d35b8 152 return Math.round(cpusCycleTimeWeight / cpus().length)
b3432a63 153 }
b3432a63 154}