utopia_balancer/balancer.rs
1//! [`Balancer`]: options, filters and the algorithm that chooses among them.
2
3use std::sync::Arc;
4
5use crate::{Algorithm, Error};
6
7/// A filter: whether an option may be chosen.
8pub type Filter<T> = Arc<dyn Fn(&T) -> bool + Send + Sync>;
9
10/// Chooses one of its options with an [`Algorithm`], among those every
11/// filter accepts.
12///
13/// Options are any type: [`Candidate`](crate::Candidate) for PHP's state
14/// bags, or your own endpoint type. Filters run on every
15/// [`Balancer::run`], so they see the options' current state.
16///
17/// PHP: `Utopia\Balancer\Balancer`.
18///
19/// ```
20/// use utopia_balancer::{Balancer, Candidate, RoundRobin};
21///
22/// let mut balancer = Balancer::new(RoundRobin::new(-1));
23/// balancer
24/// .add_option(Candidate::from([("hostname", "worker-1".into()), ("online", true.into())]))
25/// .add_option(Candidate::from([("hostname", "worker-2".into()), ("online", false.into())]))
26/// .add_option(Candidate::from([("hostname", "worker-3".into()), ("online", true.into())]))
27/// .add_filter(|c| c.get("online").is_some_and(|v| v.truthy()));
28///
29/// let host = |b: &mut Balancer<Candidate, RoundRobin>| b.run().unwrap().and_then(|c| c.get("hostname").cloned());
30/// assert_eq!(host(&mut balancer), Some("worker-1".into()));
31/// assert_eq!(host(&mut balancer), Some("worker-3".into()));
32/// assert_eq!(host(&mut balancer), Some("worker-1".into()));
33/// ```
34///
35/// ```php
36/// use Utopia\Balancer\Algorithm\RoundRobin;
37/// use Utopia\Balancer\Balancer;
38/// use Utopia\Balancer\Option;
39///
40/// $balancer = new Balancer(new RoundRobin(-1));
41/// $balancer
42/// ->addOption(new Option(['hostname' => 'worker-1', 'online' => true]))
43/// ->addOption(new Option(['hostname' => 'worker-2', 'online' => false]))
44/// ->addOption(new Option(['hostname' => 'worker-3', 'online' => true]))
45/// ->addFilter(fn (Option $o) => $o->getState('online') === true);
46///
47/// echo $balancer->run()->getState('hostname'), "\n"; // worker-1
48/// echo $balancer->run()->getState('hostname'), "\n"; // worker-3
49/// echo $balancer->run()->getState('hostname'), "\n"; // worker-1
50/// ```
51pub struct Balancer<T, A> {
52 algorithm: A,
53 options: Vec<T>,
54 filters: Vec<Filter<T>>,
55}
56
57impl<T, A: Algorithm<T>> Balancer<T, A> {
58 /// A balancer without options, choosing with `algorithm`.
59 ///
60 /// PHP: `new Balancer($algo)`.
61 pub fn new(algorithm: A) -> Self {
62 Balancer { algorithm, options: Vec::new(), filters: Vec::new() }
63 }
64
65 /// The algorithm.
66 ///
67 /// PHP: `getAlgo()`.
68 pub fn algorithm(&self) -> &A {
69 &self.algorithm
70 }
71
72 /// The algorithm, to change its state (such as a
73 /// [`RoundRobin`](crate::RoundRobin) index).
74 ///
75 /// PHP: `getAlgo()`, which returns the object itself.
76 pub fn algorithm_mut(&mut self) -> &mut A {
77 &mut self.algorithm
78 }
79
80 /// Adds an option after the others.
81 ///
82 /// PHP: `addOption($option)`.
83 pub fn add_option(&mut self, option: T) -> &mut Self {
84 self.options.push(option);
85 self
86 }
87
88 /// Every option, in the order they were added, filtered or not.
89 ///
90 /// PHP: `getOptions()`.
91 pub fn options(&self) -> &[T] {
92 &self.options
93 }
94
95 /// Adds a filter: only options every filter accepts can be chosen.
96 ///
97 /// PHP: `addFilter($callable)`.
98 pub fn add_filter(&mut self, filter: impl Fn(&T) -> bool + Send + Sync + 'static) -> &mut Self {
99 self.filters.push(Arc::new(filter));
100 self
101 }
102
103 /// Every option every filter accepts, in the order they were added: what
104 /// the algorithm chooses from, for callers that act on all of them.
105 ///
106 /// PHP: `getFilteredOptions()`.
107 pub fn filtered(&self) -> Vec<&T> {
108 self.passing().into_iter().map(|i| &self.options[i]).collect()
109 }
110
111 /// Positions every filter accepts, filter by filter as PHP's `array_filter()` runs them.
112 fn passing(&self) -> Vec<usize> {
113 let mut positions: Vec<usize> = (0..self.options.len()).collect();
114 for filter in &self.filters {
115 positions.retain(|&i| filter(&self.options[i]));
116 }
117 positions
118 }
119
120 /// The position in [`Balancer::options`] of the option the algorithm
121 /// chooses among the filtered ones, or `None` when none passes or the
122 /// algorithm chooses nothing.
123 ///
124 /// PHP: `run()`, as a position.
125 pub fn pick(&mut self) -> Result<Option<usize>, Error> {
126 let positions = self.passing();
127 if positions.is_empty() {
128 return Ok(None);
129 }
130 let options: Vec<&T> = positions.iter().map(|&i| &self.options[i]).collect();
131 Ok(self.algorithm.pick(&options)?.and_then(|p| positions.get(p).copied()))
132 }
133
134 /// The option the algorithm chooses among the filtered ones, or `None`
135 /// when none passes or the algorithm chooses nothing. The algorithm is
136 /// not consulted without options.
137 ///
138 /// PHP: `run()`.
139 pub fn run(&mut self) -> Result<Option<&T>, Error> {
140 Ok(self.pick()?.map(|i| &self.options[i]))
141 }
142}
143
144impl<T: Clone, A: Clone> Clone for Balancer<T, A> {
145 /// A copy with cloned options and algorithm, sharing the filters.
146 fn clone(&self) -> Self {
147 Balancer { algorithm: self.algorithm.clone(), options: self.options.clone(), filters: self.filters.clone() }
148 }
149}
150
151impl<T, A: Algorithm<T>> std::fmt::Debug for Balancer<T, A> {
152 /// The algorithm's name and the number of options and filters.
153 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154 f.debug_struct("Balancer")
155 .field("algorithm", &self.algorithm.name())
156 .field("options", &self.options.len())
157 .field("filters", &self.filters.len())
158 .finish()
159 }
160}
161
162#[cfg(test)]
163mod tests {
164 use std::sync::{Arc, Mutex};
165
166 use crate::{Balancer, First};
167
168 #[test]
169 fn filters_run_one_after_another_as_in_php() {
170 let calls = Arc::new(Mutex::new(Vec::new()));
171 let mut balancer = Balancer::new(First);
172 balancer.add_option(1).add_option(2).add_option(3);
173 let seen = Arc::clone(&calls);
174 balancer.add_filter(move |o: &i32| {
175 seen.lock().unwrap().push(("odd", *o));
176 o % 2 == 1
177 });
178 let seen = Arc::clone(&calls);
179 balancer.add_filter(move |o: &i32| {
180 seen.lock().unwrap().push(("big", *o));
181 *o > 1
182 });
183
184 assert_eq!(balancer.filtered(), [&3]);
185 assert_eq!(*calls.lock().unwrap(), [("odd", 1), ("odd", 2), ("odd", 3), ("big", 1), ("big", 3)]);
186 }
187}