trillium_proxy/upstream/
random.rs1use super::{IntoUpstreamSelector, UpstreamSelector};
2use std::{
3 fmt::Debug,
4 ops::{Deref, DerefMut},
5};
6use trillium::Conn;
7use url::Url;
8
9#[derive(Debug)]
10pub 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 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
41 fn deref(&self) -> &Self::Target {
42 &self.0
43 }
44}
45impl<T> DerefMut for RandomSelector<T>
46where
47 T: UpstreamSelector,
48{
49 fn deref_mut(&mut self) -> &mut Self::Target {
50 &mut self.0
51 }
52}
53impl<U, T> Extend<U> for RandomSelector<T>
54where
55 T: UpstreamSelector,
56 U: IntoUpstreamSelector<UpstreamSelector = T>,
57{
58 fn extend<I: IntoIterator<Item = U>>(&mut self, iter: I) {
59 self.0.extend(iter.into_iter().map(|i| i.into_upstream()));
60 }
61}
62
63impl<U, V> FromIterator<U> for RandomSelector<V>
64where
65 U: IntoUpstreamSelector<UpstreamSelector = V>,
66 V: UpstreamSelector,
67{
68 fn from_iter<T>(urls: T) -> Self
69 where
70 T: IntoIterator<Item = U>,
71 {
72 Self::new(urls)
73 }
74}