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
use std::sync::Arc;

use rand::distributions::Distribution;

#[derive(Clone)]
pub struct RandomPick<I, S>
where
    I: rand::distributions::uniform::SampleUniform + std::cmp::PartialOrd,
{
    picker: Arc<rand::distributions::WeightedIndex<I>>,
    services: Arc<[S]>,
}

impl<I, S> RandomPick<I, S>
where
    I: rand::distributions::uniform::SampleUniform + std::cmp::PartialOrd + Clone + Default + for<'a> std::ops::AddAssign<&'a I>,
{
    pub fn new(services: impl IntoIterator<Item = (I, S)>) -> Self {
        let (weights, services): (Vec<_>, Vec<_>) = services.into_iter().unzip();
        assert!(!services.is_empty(), "services must not be empty");
        Self {
            picker: Arc::new(rand::distributions::WeightedIndex::new(weights).expect("invalid weights")),
            services: services.into(),
        }
    }
}

impl<I, R, S> hyper::service::Service<R> for RandomPick<I, S>
where
    S: hyper::service::Service<R>,
    S::Future: std::marker::Send,
    I: rand::distributions::uniform::SampleUniform + std::cmp::PartialOrd + Clone,
{
    type Response = S::Response;
    type Error = S::Error;
    type Future = S::Future;

    #[allow(clippy::indexing_slicing)]
    fn call(&self, req: R) -> Self::Future {
        if self.services.len() == 1 {
            self.services[0].call(req)
        } else {
            let index = self.picker.sample(&mut rand::thread_rng());
            self.services[index].call(req)
        }
    }
}