use std::sync::Arc;
use crate::{Algorithm, Error};
pub type Filter<T> = Arc<dyn Fn(&T) -> bool + Send + Sync>;
pub struct Balancer<T, A> {
algorithm: A,
options: Vec<T>,
filters: Vec<Filter<T>>,
}
impl<T, A: Algorithm<T>> Balancer<T, A> {
pub fn new(algorithm: A) -> Self {
Balancer { algorithm, options: Vec::new(), filters: Vec::new() }
}
pub fn algorithm(&self) -> &A {
&self.algorithm
}
pub fn algorithm_mut(&mut self) -> &mut A {
&mut self.algorithm
}
pub fn add_option(&mut self, option: T) -> &mut Self {
self.options.push(option);
self
}
pub fn options(&self) -> &[T] {
&self.options
}
pub fn add_filter(&mut self, filter: impl Fn(&T) -> bool + Send + Sync + 'static) -> &mut Self {
self.filters.push(Arc::new(filter));
self
}
pub fn filtered(&self) -> Vec<&T> {
self.passing().into_iter().map(|i| &self.options[i]).collect()
}
fn passing(&self) -> Vec<usize> {
let mut positions: Vec<usize> = (0..self.options.len()).collect();
for filter in &self.filters {
positions.retain(|&i| filter(&self.options[i]));
}
positions
}
pub fn pick(&mut self) -> Result<Option<usize>, Error> {
let positions = self.passing();
if positions.is_empty() {
return Ok(None);
}
let options: Vec<&T> = positions.iter().map(|&i| &self.options[i]).collect();
Ok(self.algorithm.pick(&options)?.and_then(|p| positions.get(p).copied()))
}
pub fn run(&mut self) -> Result<Option<&T>, Error> {
Ok(self.pick()?.map(|i| &self.options[i]))
}
}
impl<T: Clone, A: Clone> Clone for Balancer<T, A> {
fn clone(&self) -> Self {
Balancer { algorithm: self.algorithm.clone(), options: self.options.clone(), filters: self.filters.clone() }
}
}
impl<T, A: Algorithm<T>> std::fmt::Debug for Balancer<T, A> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Balancer")
.field("algorithm", &self.algorithm.name())
.field("options", &self.options.len())
.field("filters", &self.filters.len())
.finish()
}
}
#[cfg(test)]
mod tests {
use std::sync::{Arc, Mutex};
use crate::{Balancer, First};
#[test]
fn filters_run_one_after_another_as_in_php() {
let calls = Arc::new(Mutex::new(Vec::new()));
let mut balancer = Balancer::new(First);
balancer.add_option(1).add_option(2).add_option(3);
let seen = Arc::clone(&calls);
balancer.add_filter(move |o: &i32| {
seen.lock().unwrap().push(("odd", *o));
o % 2 == 1
});
let seen = Arc::clone(&calls);
balancer.add_filter(move |o: &i32| {
seen.lock().unwrap().push(("big", *o));
*o > 1
});
assert_eq!(balancer.filtered(), [&3]);
assert_eq!(*calls.lock().unwrap(), [("odd", 1), ("odd", 2), ("odd", 3), ("big", 1), ("big", 3)]);
}
}