1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
//! [`Algorithm`]: how a balancer chooses one option, and the four it ships
//! with: [`First`], [`Last`], [`Random`] and [`RoundRobin`].
use Mt19937;
use crateError;
/// Chooses one of the options that passed a balancer's filters.
///
/// An algorithm sees the options in the order they were added and returns
/// the position of the one it picks, or `None` to pick nothing. It may keep
/// state between calls, as [`RoundRobin`] does. Implement it to add an
/// algorithm (least connections, weighted, by latency).
///
/// PHP: `Utopia\Balancer\Algorithm`; `pick()` is `run()`, returning the
/// position instead of the option.
///
/// ```
/// use utopia_balancer::{Algorithm, Candidate, Error};
///
/// /// The option with the lowest `cpu`.
/// struct Idlest;
///
/// impl Algorithm<Candidate> for Idlest {
/// fn name(&self) -> &str {
/// "Idlest"
/// }
///
/// fn pick(&mut self, options: &[&Candidate]) -> Result<Option<usize>, Error> {
/// let cpu = |c: &Candidate| c.get("cpu").map_or(i64::MAX, |v| v.to_double() as i64);
/// Ok((0..options.len()).min_by_key(|&i| cpu(options[i])))
/// }
/// }
///
/// let busy = Candidate::from([("cpu", 80.into())]);
/// let idle = Candidate::from([("cpu", 5.into())]);
/// assert_eq!(Idlest.pick(&[&busy, &idle])?, Some(1));
/// # Ok::<(), Error>(())
/// ```
///
/// ```php
/// use Utopia\Balancer\Algorithm;
/// use Utopia\Balancer\Option;
///
/// final class Idlest extends Algorithm
/// {
/// public function getName(): string
/// {
/// return 'Idlest';
/// }
///
/// public function run(array $options): ?Option
/// {
/// usort($options, fn (Option $a, Option $b) => $a->getState('cpu') <=> $b->getState('cpu'));
///
/// return $options[0] ?? null;
/// }
/// }
///
/// $busy = new Option(['cpu' => 80]);
/// $idle = new Option(['cpu' => 5]);
/// var_dump((new Idlest())->run([$busy, $idle]) === $idle); // bool(true)
/// ```
/// Always the first option.
///
/// PHP: `Utopia\Balancer\Algorithm\First`.
;
/// Always the last option.
///
/// PHP: `Utopia\Balancer\Algorithm\Last`.
;
/// A uniformly random option, from PHP's Mersenne Twister.
///
/// [`Random::seeded`] replays exactly what PHP picks after `mt_srand($seed)`,
/// so a choice can be reproduced in tests and compared with PHP.
///
/// PHP: `Utopia\Balancer\Algorithm\Random` (`array_rand()` on the default
/// engine).
///
/// ```
/// use utopia_balancer::{Algorithm, Random};
///
/// let options = ["fra-1", "fra-2", "lon-1"];
/// let refs: Vec<&&str> = options.iter().collect();
///
/// let mut random = Random::seeded(7);
/// let picks: Vec<_> = (0..3).map(|_| random.pick(&refs).unwrap().unwrap()).collect();
/// assert_eq!(picks, [0, 1, 1]);
/// ```
///
/// ```php
/// use Utopia\Balancer\Algorithm\Random;
/// use Utopia\Balancer\Option;
///
/// $options = [new Option(['dc' => 'fra-1']), new Option(['dc' => 'fra-2']), new Option(['dc' => 'lon-1'])];
///
/// mt_srand(7);
/// $random = new Random();
/// foreach ([1, 2, 3] as $_) {
/// echo $random->run($options)->getState('dc'), "\n"; // fra-1, fra-2, fra-2
/// }
/// ```
/// Each option in turn: every pick moves to the next position and wraps to
/// the first after the last.
///
/// The index is the position picked last. It starts where it is created
/// (`-1` starts at the first option) and can be moved with
/// [`RoundRobin::set_index`], to share a rotation across processes.
///
/// PHP: `Utopia\Balancer\Algorithm\RoundRobin`.
///
/// ```
/// use utopia_balancer::{Algorithm, RoundRobin};
///
/// let options = ["fra-1", "fra-2", "lon-1"];
/// let refs: Vec<&&str> = options.iter().collect();
///
/// let mut rr = RoundRobin::new(-1);
/// let picks: Vec<_> = (0..4).map(|_| rr.pick(&refs).unwrap().unwrap()).collect();
/// assert_eq!(picks, [0, 1, 2, 0]);
/// assert_eq!(rr.index(), 0);
/// ```
///
/// ```php
/// use Utopia\Balancer\Algorithm\RoundRobin;
/// use Utopia\Balancer\Option;
///
/// $options = [new Option(['dc' => 'fra-1']), new Option(['dc' => 'fra-2']), new Option(['dc' => 'lon-1'])];
///
/// $rr = new RoundRobin(-1);
/// foreach ([1, 2, 3, 4] as $_) {
/// echo $rr->run($options)->getState('dc'), "\n"; // fra-1, fra-2, lon-1, fra-1
/// }
/// echo $rr->getIndex(), "\n"; // 0
/// ```