Skip to main content

trillium_proxy/upstream/
random.rs

1use super::{IntoUpstreamSelector, UpstreamSelector};
2use std::{
3    fmt::Debug,
4    ops::{Deref, DerefMut},
5};
6use trillium::Conn;
7use url::Url;
8
9#[derive(Debug)]
10/// a random upstream selector
11pub struct RandomSelector<T>(Vec<T>);
12impl<T> UpstreamSelector for RandomSelector<T>
13where
14    T: UpstreamSelector,
15{
16    fn determine_upstream(&self, conn: &mut Conn) -> Option<Url> {
17        fastrand::choice(&self.0).and_then(|u| u.determine_upstream(conn))
18    }
19}
20
21impl<T> RandomSelector<T>
22where
23    T: UpstreamSelector,
24{
25    /// construct a new round robin
26    pub fn new<I, U>(urls: I) -> Self
27    where
28        I: IntoIterator<Item = U>,
29        U: IntoUpstreamSelector<UpstreamSelector = T>,
30    {
31        Self(urls.into_iter().map(|u| u.into_upstream()).collect())
32    }
33}
34
35impl<T> Deref for RandomSelector<T>
36where
37    T: UpstreamSelector,
38{
39    type Target = [T];
40    fn deref(&self) -> &Self::Target {
41        &self.0
42    }
43}
44impl<T> DerefMut for RandomSelector<T>
45where
46    T: UpstreamSelector,
47{
48    fn deref_mut(&mut self) -> &mut Self::Target {
49        &mut self.0
50    }
51}
52impl<U, T> Extend<U> for RandomSelector<T>
53where
54    T: UpstreamSelector,
55    U: IntoUpstreamSelector<UpstreamSelector = T>,
56{
57    fn extend<I: IntoIterator<Item = U>>(&mut self, iter: I) {
58        self.0.extend(iter.into_iter().map(|i| i.into_upstream()));
59    }
60}
61
62impl<U, V> FromIterator<U> for RandomSelector<V>
63where
64    U: IntoUpstreamSelector<UpstreamSelector = V>,
65    V: UpstreamSelector,
66{
67    fn from_iter<T>(urls: T) -> Self
68    where
69        T: IntoIterator<Item = U>,
70    {
71        Self::new(urls)
72    }
73}