Skip to main content

utopia_balancer/
algorithm.rs

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