fix: ensure the number of worker choice retries is enough for WRR
[poolifier.git] / src / pools / selection-strategies / worker-choice-strategy-context.ts
CommitLineData
26ce26ca 1import { getDefaultInternalWorkerChoiceStrategyOptions } from '../../utils'
c4855468 2import type { IPool } from '../pool'
f06e48d8 3import type { IWorker } from '../worker'
51fe3d3c 4import { FairShareWorkerChoiceStrategy } from './fair-share-worker-choice-strategy'
feec6e8c 5import { InterleavedWeightedRoundRobinWorkerChoiceStrategy } from './interleaved-weighted-round-robin-worker-choice-strategy'
e4543b14
JB
6import { LeastBusyWorkerChoiceStrategy } from './least-busy-worker-choice-strategy'
7import { LeastUsedWorkerChoiceStrategy } from './least-used-worker-choice-strategy'
058a9457 8import { LeastEluWorkerChoiceStrategy } from './least-elu-worker-choice-strategy'
51fe3d3c 9import { RoundRobinWorkerChoiceStrategy } from './round-robin-worker-choice-strategy'
bdaf31cd
JB
10import type {
11 IWorkerChoiceStrategy,
26ce26ca 12 InternalWorkerChoiceStrategyOptions,
6c6afb84 13 StrategyPolicy,
87de9ff5 14 TaskStatisticsRequirements,
26ce26ca 15 WorkerChoiceStrategy
bdaf31cd
JB
16} from './selection-strategies-types'
17import { WorkerChoiceStrategies } from './selection-strategies-types'
51fe3d3c 18import { WeightedRoundRobinWorkerChoiceStrategy } from './weighted-round-robin-worker-choice-strategy'
bdaf31cd
JB
19
20/**
21 * The worker choice strategy context.
22 *
38e795c1 23 * @typeParam Worker - Type of worker.
e102732c
JB
24 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
25 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
bdaf31cd
JB
26 */
27export class WorkerChoiceStrategyContext<
f06e48d8 28 Worker extends IWorker,
b2b1d84e
JB
29 Data = unknown,
30 Response = unknown
bdaf31cd 31> {
b529c323 32 private readonly workerChoiceStrategies: Map<
95c83464 33 WorkerChoiceStrategy,
17393ac8 34 IWorkerChoiceStrategy
b529c323 35 >
bdaf31cd
JB
36
37 /**
38 * Worker choice strategy context constructor.
39 *
38e795c1 40 * @param pool - The pool instance.
d710242d 41 * @param workerChoiceStrategy - The worker choice strategy.
da309861 42 * @param opts - The worker choice strategy options.
bdaf31cd
JB
43 */
44 public constructor (
c4855468 45 pool: IPool<Worker, Data, Response>,
d710242d 46 private workerChoiceStrategy: WorkerChoiceStrategy = WorkerChoiceStrategies.ROUND_ROBIN,
26ce26ca 47 private opts?: InternalWorkerChoiceStrategyOptions
bdaf31cd 48 ) {
26ce26ca 49 this.opts = {
449cd154
JB
50 ...getDefaultInternalWorkerChoiceStrategyOptions(
51 pool.info.maxSize +
52 Object.keys((this.opts?.weights as Record<number, number>) ?? {})
53 .length
54 ),
26ce26ca
JB
55 ...this.opts
56 }
7254e419 57 this.execute = this.execute.bind(this)
b529c323
JB
58 this.workerChoiceStrategies = new Map<
59 WorkerChoiceStrategy,
17393ac8 60 IWorkerChoiceStrategy
b529c323
JB
61 >([
62 [
63 WorkerChoiceStrategies.ROUND_ROBIN,
7254e419
JB
64 new (RoundRobinWorkerChoiceStrategy.bind(this))<Worker, Data, Response>(
65 pool,
26ce26ca 66 this.opts
7254e419 67 )
b529c323
JB
68 ],
69 [
e4543b14
JB
70 WorkerChoiceStrategies.LEAST_USED,
71 new (LeastUsedWorkerChoiceStrategy.bind(this))<Worker, Data, Response>(
7254e419 72 pool,
26ce26ca 73 this.opts
7254e419 74 )
b529c323
JB
75 ],
76 [
e4543b14
JB
77 WorkerChoiceStrategies.LEAST_BUSY,
78 new (LeastBusyWorkerChoiceStrategy.bind(this))<Worker, Data, Response>(
7254e419 79 pool,
26ce26ca 80 this.opts
7254e419 81 )
b529c323
JB
82 ],
83 [
058a9457
JB
84 WorkerChoiceStrategies.LEAST_ELU,
85 new (LeastEluWorkerChoiceStrategy.bind(this))<Worker, Data, Response>(
86 pool,
26ce26ca 87 this.opts
058a9457
JB
88 )
89 ],
90 [
b529c323 91 WorkerChoiceStrategies.FAIR_SHARE,
7254e419 92 new (FairShareWorkerChoiceStrategy.bind(this))<Worker, Data, Response>(
da309861 93 pool,
26ce26ca 94 this.opts
da309861 95 )
7254e419
JB
96 ],
97 [
98 WorkerChoiceStrategies.WEIGHTED_ROUND_ROBIN,
99 new (WeightedRoundRobinWorkerChoiceStrategy.bind(this))<
100 Worker,
101 Data,
102 Response
26ce26ca 103 >(pool, this.opts)
feec6e8c
JB
104 ],
105 [
106 WorkerChoiceStrategies.INTERLEAVED_WEIGHTED_ROUND_ROBIN,
107 new (InterleavedWeightedRoundRobinWorkerChoiceStrategy.bind(this))<
108 Worker,
109 Data,
110 Response
26ce26ca 111 >(pool, this.opts)
b529c323
JB
112 ]
113 ])
bdaf31cd
JB
114 }
115
6c6afb84
JB
116 /**
117 * Gets the strategy policy in the context.
118 *
119 * @returns The strategy policy.
120 */
121 public getStrategyPolicy (): StrategyPolicy {
122 return (
123 this.workerChoiceStrategies.get(
124 this.workerChoiceStrategy
125 ) as IWorkerChoiceStrategy
126 ).strategyPolicy
127 }
128
97a2abc3 129 /**
8990357d 130 * Gets the worker choice strategy in the context task statistics requirements.
97a2abc3 131 *
87de9ff5 132 * @returns The task statistics requirements.
97a2abc3 133 */
87de9ff5 134 public getTaskStatisticsRequirements (): TaskStatisticsRequirements {
95c83464
JB
135 return (
136 this.workerChoiceStrategies.get(
d710242d 137 this.workerChoiceStrategy
17393ac8 138 ) as IWorkerChoiceStrategy
87de9ff5 139 ).taskStatisticsRequirements
97a2abc3
JB
140 }
141
bdaf31cd 142 /**
bdede008 143 * Sets the worker choice strategy to use in the context.
bdaf31cd 144 *
38e795c1 145 * @param workerChoiceStrategy - The worker choice strategy to set.
bdaf31cd
JB
146 */
147 public setWorkerChoiceStrategy (
148 workerChoiceStrategy: WorkerChoiceStrategy
149 ): void {
d710242d
JB
150 if (this.workerChoiceStrategy !== workerChoiceStrategy) {
151 this.workerChoiceStrategy = workerChoiceStrategy
b2b1d84e 152 }
d710242d 153 this.workerChoiceStrategies.get(this.workerChoiceStrategy)?.reset()
bdaf31cd
JB
154 }
155
138d29a8 156 /**
8990357d 157 * Updates the worker node key in the worker choice strategy in the context internals.
138d29a8
JB
158 *
159 * @returns `true` if the update is successful, `false` otherwise.
160 */
a4958de2 161 public update (workerNodeKey: number): boolean {
138d29a8
JB
162 return (
163 this.workerChoiceStrategies.get(
164 this.workerChoiceStrategy
165 ) as IWorkerChoiceStrategy
a4958de2 166 ).update(workerNodeKey)
138d29a8
JB
167 }
168
bdaf31cd 169 /**
8990357d 170 * Executes the worker choice strategy in the context algorithm.
bdaf31cd 171 *
f06e48d8 172 * @returns The key of the worker node.
fb5a7307 173 * @throws {@link https://nodejs.org/api/errors.html#class-error} If after configured retries the worker node key is null or undefined.
bdaf31cd 174 */
c923ce56 175 public execute (): number {
fb5a7307
JB
176 const workerChoiceStrategy = this.workerChoiceStrategies.get(
177 this.workerChoiceStrategy
178 ) as IWorkerChoiceStrategy
613a91dc 179 if (!workerChoiceStrategy.hasPoolWorkerNodesReady()) {
722d55a0 180 return this.execute()
613a91dc
JB
181 }
182 return this.executeStrategy(workerChoiceStrategy)
183 }
184
185 /**
186 * Executes the given worker choice strategy.
187 *
188 * @param workerChoiceStrategy - The worker choice strategy.
189 * @returns The key of the worker node.
190 * @throws {@link https://nodejs.org/api/errors.html#class-error} If after configured retries the worker node key is null or undefined.
191 */
192 private executeStrategy (workerChoiceStrategy: IWorkerChoiceStrategy): number {
fb5a7307 193 let workerNodeKey: number | undefined
fb5a7307
JB
194 let chooseCount = 0
195 let retriesCount = 0
196 do {
613a91dc
JB
197 workerNodeKey = workerChoiceStrategy.choose()
198 if (workerNodeKey == null && chooseCount > 0) {
199 retriesCount++
fb5a7307 200 }
613a91dc 201 chooseCount++
fb5a7307 202 } while (
613a91dc 203 workerNodeKey == null &&
26ce26ca 204 retriesCount < (this.opts?.retries as number)
fb5a7307 205 )
fb5a7307 206 if (workerNodeKey == null) {
e695d66f 207 throw new Error(
fb5a7307 208 `Worker node key chosen is null or undefined after ${retriesCount} retries`
4ba8492f 209 )
b0d6ed8f
JB
210 }
211 return workerNodeKey
bdaf31cd 212 }
97a2abc3
JB
213
214 /**
c7e196ba 215 * Removes the worker node key from the worker choice strategy in the context.
97a2abc3 216 *
501aea93 217 * @param workerNodeKey - The worker node key.
97a2abc3
JB
218 * @returns `true` if the removal is successful, `false` otherwise.
219 */
f06e48d8 220 public remove (workerNodeKey: number): boolean {
95c83464
JB
221 return (
222 this.workerChoiceStrategies.get(
d710242d 223 this.workerChoiceStrategy
17393ac8 224 ) as IWorkerChoiceStrategy
f06e48d8 225 ).remove(workerNodeKey)
95c83464 226 }
a20f0ba5
JB
227
228 /**
229 * Sets the worker choice strategies in the context options.
230 *
af7f2788 231 * @param pool - The pool instance.
a20f0ba5
JB
232 * @param opts - The worker choice strategy options.
233 */
26ce26ca
JB
234 public setOptions (
235 pool: IPool<Worker, Data, Response>,
236 opts?: InternalWorkerChoiceStrategyOptions
237 ): void {
238 this.opts = {
449cd154
JB
239 ...getDefaultInternalWorkerChoiceStrategyOptions(
240 pool.info.maxSize +
241 Object.keys((opts?.weights as Record<number, number>) ?? {}).length
242 ),
26ce26ca
JB
243 ...opts
244 }
0509fd43 245 for (const workerChoiceStrategy of this.workerChoiceStrategies.values()) {
26ce26ca 246 workerChoiceStrategy.setOptions(this.opts)
0509fd43 247 }
a20f0ba5 248 }
bdaf31cd 249}