Skip to main content

trillium_client/proxy/
router.rs

1use super::Proxy;
2use crate::Url;
3use std::{fmt, sync::Arc};
4
5/// Chooses the proxy for each request, or none to connect directly.
6///
7/// A router is consulted once per request, with its original URL, before connecting. A redirect
8/// or other follow-up request is routed again for its own URL; retrying protocol negotiation on
9/// the same request is not. A [`Proxy`] that a router returns still applies its own schemes and
10/// bypass entries, so a request it doesn't carry connects directly.
11///
12/// Implemented for:
13///
14/// - [`Proxy`], which routes the requests its schemes and bypass entries allow;
15/// - functions `Fn(&Url) -> Option<Proxy>`;
16/// - `Option<R>`, where `None` routes nothing;
17/// - arrays and `Vec`s of routers, which return the first router's proxy that isn't `None`.
18///
19/// ```
20/// use trillium_client::{Proxy, Url};
21///
22/// let corporate = Proxy::new("http://proxy.corp.example:8080")?;
23/// let router = move |url: &Url| {
24///     url.host_str()?
25///         .ends_with(".corp.example")
26///         .then(|| corporate.clone())
27/// };
28/// # trillium_client::Client::new(trillium_testing::client_config()).with_proxy(router);
29/// # Ok::<(), std::io::Error>(())
30/// ```
31pub trait ProxyRouter: Send + Sync + 'static {
32    /// The proxy for a request to `url`, or `None` to connect directly.
33    fn route(&self, url: &Url) -> Option<Proxy>;
34}
35
36impl ProxyRouter for Proxy {
37    fn route(&self, url: &Url) -> Option<Proxy> {
38        self.carries(url).then(|| self.clone())
39    }
40}
41
42impl<F> ProxyRouter for F
43where
44    F: Fn(&Url) -> Option<Proxy> + Send + Sync + 'static,
45{
46    fn route(&self, url: &Url) -> Option<Proxy> {
47        self(url).and_then(|proxy| proxy.route(url))
48    }
49}
50
51impl<R: ProxyRouter> ProxyRouter for Option<R> {
52    fn route(&self, url: &Url) -> Option<Proxy> {
53        self.as_ref()?.route(url)
54    }
55}
56
57impl<R: ProxyRouter> ProxyRouter for Vec<R> {
58    fn route(&self, url: &Url) -> Option<Proxy> {
59        self.iter().find_map(|router| router.route(url))
60    }
61}
62
63impl<R: ProxyRouter, const N: usize> ProxyRouter for [R; N] {
64    fn route(&self, url: &Url) -> Option<Proxy> {
65        self.iter().find_map(|router| router.route(url))
66    }
67}
68
69#[derive(Clone)]
70pub(crate) struct ArcedProxyRouter(Arc<dyn ProxyRouter>);
71
72impl ArcedProxyRouter {
73    pub(crate) fn new(router: impl ProxyRouter) -> Self {
74        Self(Arc::new(router))
75    }
76
77    pub(crate) fn route(&self, url: &Url) -> Option<Proxy> {
78        self.0.route(url)
79    }
80}
81
82impl fmt::Debug for ArcedProxyRouter {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        f.debug_struct("ProxyRouter").finish_non_exhaustive()
85    }
86}