Skip to main content

elemental_core/http/
config.rs

1use std::fmt;
2use std::sync::Arc;
3use std::time::Duration;
4
5use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
6use reqwest::redirect::Policy;
7use thiserror::Error;
8
9/// Default `User-Agent` header applied by [`HttpClientConfig::default`].
10pub const DEFAULT_USER_AGENT: &str = concat!("Elemental/", env!("CARGO_PKG_VERSION"));
11
12/// Default connection timeout applied by [`HttpClientConfig::default`].
13pub const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
14
15/// Default socket read timeout applied by [`HttpClientConfig::default`].
16pub const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(30);
17
18type ClientCustomizer = Arc<dyn Fn(reqwest::ClientBuilder) -> reqwest::ClientBuilder + Send + Sync>;
19
20/// Errors returned when building or swapping a `reqwest::Client`.
21#[derive(Debug, Error)]
22pub enum HttpClientError {
23    #[error("failed to build HTTP client: {source}")]
24    Build {
25        #[source]
26        source: reqwest::Error,
27    },
28}
29
30/// Result alias for [`crate::http`] configuration operations.
31pub type Result<T> = std::result::Result<T, HttpClientError>;
32
33/// Reusable configuration for constructing `reqwest::Client` instances.
34///
35/// Unlike `reqwest::ClientBuilder`, `HttpClientConfig` is [`Clone`] and can be
36/// replayed whenever a [`super::SwappableClient`] rebuilds its underlying clients.
37/// Request-specific headers (such as per-mirror `X-KEY` or per-request bearer
38/// tokens) should be attached on the request or source layer rather than placed
39/// in [`Self::default_headers`] when a client is shared across origins.
40#[derive(Clone)]
41pub struct HttpClientConfig {
42    user_agent: Option<String>,
43    default_headers: HeaderMap,
44    connect_timeout: Option<Duration>,
45    read_timeout: Option<Duration>,
46    timeout: Option<Duration>,
47    proxies: Vec<reqwest::Proxy>,
48    no_proxy: bool,
49    customizer: Option<ClientCustomizer>,
50}
51
52impl Default for HttpClientConfig {
53    fn default() -> Self {
54        Self {
55            user_agent: Some(DEFAULT_USER_AGENT.to_owned()),
56            default_headers: HeaderMap::new(),
57            connect_timeout: Some(DEFAULT_CONNECT_TIMEOUT),
58            read_timeout: Some(DEFAULT_READ_TIMEOUT),
59            timeout: None,
60            proxies: Vec::new(),
61            no_proxy: false,
62            customizer: None,
63        }
64    }
65}
66
67impl fmt::Debug for HttpClientConfig {
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        f.debug_struct("HttpClientConfig")
70            .field("user_agent", &self.user_agent)
71            .field("default_headers_len", &self.default_headers.len())
72            .field("connect_timeout", &self.connect_timeout)
73            .field("read_timeout", &self.read_timeout)
74            .field("timeout", &self.timeout)
75            .field("proxies_len", &self.proxies.len())
76            .field("no_proxy", &self.no_proxy)
77            .field("has_customizer", &self.customizer.is_some())
78            .finish()
79    }
80}
81
82impl HttpClientConfig {
83    /// Creates a new configuration populated with Elemental defaults.
84    pub fn new() -> Self {
85        Self::default()
86    }
87
88    /// Sets the `User-Agent` header value sent by built clients.
89    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
90        self.user_agent = Some(user_agent.into());
91        self
92    }
93
94    /// Clears the `User-Agent` header so `reqwest` does not send a default one.
95    pub fn without_user_agent(mut self) -> Self {
96        self.user_agent = None;
97        self
98    }
99
100    /// Replaces the default headers attached to every request made by built clients.
101    pub fn default_headers(mut self, headers: HeaderMap) -> Self {
102        self.default_headers = headers;
103        self
104    }
105
106    /// Inserts a single default header attached to every request made by built clients.
107    pub fn default_header(mut self, name: HeaderName, value: HeaderValue) -> Self {
108        self.default_headers.insert(name, value);
109        self
110    }
111
112    /// Sets the TCP/TLS connect timeout. Pass `None` to disable it.
113    pub fn connect_timeout(mut self, timeout: Option<Duration>) -> Self {
114        self.connect_timeout = timeout;
115        self
116    }
117
118    /// Sets the per-read inactivity timeout. Pass `None` to disable it.
119    pub fn read_timeout(mut self, timeout: Option<Duration>) -> Self {
120        self.read_timeout = timeout;
121        self
122    }
123
124    /// Sets a total request timeout. Pass `None` to disable it.
125    ///
126    /// Leave this as `None` when sharing the client with streaming downloads so
127    /// large transfers are bounded by [`Self::read_timeout`] instead.
128    pub fn timeout(mut self, timeout: Option<Duration>) -> Self {
129        self.timeout = timeout;
130        self
131    }
132
133    /// Appends a proxy rule to the client configuration.
134    pub fn proxy(mut self, proxy: reqwest::Proxy) -> Self {
135        self.proxies.push(proxy);
136        self
137    }
138
139    /// Replaces all configured proxy rules.
140    pub fn proxies(mut self, proxies: impl IntoIterator<Item = reqwest::Proxy>) -> Self {
141        self.proxies = proxies.into_iter().collect();
142        self
143    }
144
145    /// Disables system proxy discovery when `no_proxy` is `true`.
146    pub fn no_proxy(mut self, no_proxy: bool) -> Self {
147        self.no_proxy = no_proxy;
148        self
149    }
150
151    /// Registers a reusable hook that customizes the underlying `reqwest::ClientBuilder`.
152    ///
153    /// Calling this method multiple times composes the hooks in registration order.
154    pub fn customize<F>(mut self, customizer: F) -> Self
155    where
156        F: Fn(reqwest::ClientBuilder) -> reqwest::ClientBuilder + Send + Sync + 'static,
157    {
158        self.customizer = Some(match self.customizer {
159            Some(previous) => Arc::new(move |builder| customizer(previous(builder))),
160            None => Arc::new(customizer),
161        });
162        self
163    }
164
165    /// Returns the configured `User-Agent`, if any.
166    pub fn user_agent_value(&self) -> Option<&str> {
167        self.user_agent.as_deref()
168    }
169
170    /// Returns the configured default headers.
171    pub fn default_headers_map(&self) -> &HeaderMap {
172        &self.default_headers
173    }
174
175    /// Returns the configured connect timeout.
176    pub fn connect_timeout_value(&self) -> Option<Duration> {
177        self.connect_timeout
178    }
179
180    /// Returns the configured read timeout.
181    pub fn read_timeout_value(&self) -> Option<Duration> {
182        self.read_timeout
183    }
184
185    /// Returns the configured total request timeout.
186    pub fn timeout_value(&self) -> Option<Duration> {
187        self.timeout
188    }
189
190    /// Returns whether system proxy discovery is disabled.
191    pub fn is_no_proxy(&self) -> bool {
192        self.no_proxy
193    }
194
195    /// Produces a fresh `reqwest::ClientBuilder` with this configuration applied.
196    pub fn builder(&self) -> reqwest::ClientBuilder {
197        let mut builder = reqwest::Client::builder();
198        if let Some(user_agent) = &self.user_agent {
199            builder = builder.user_agent(user_agent.as_str());
200        }
201        if !self.default_headers.is_empty() {
202            builder = builder.default_headers(self.default_headers.clone());
203        }
204        if let Some(connect_timeout) = self.connect_timeout {
205            builder = builder.connect_timeout(connect_timeout);
206        }
207        if let Some(read_timeout) = self.read_timeout {
208            builder = builder.read_timeout(read_timeout);
209        }
210        if let Some(timeout) = self.timeout {
211            builder = builder.timeout(timeout);
212        }
213        if self.no_proxy {
214            builder = builder.no_proxy();
215        }
216        for proxy in &self.proxies {
217            builder = builder.proxy(proxy.clone());
218        }
219        if let Some(customizer) = &self.customizer {
220            builder = customizer(builder);
221        }
222        builder
223    }
224
225    /// Builds a standard `reqwest::Client` from this configuration.
226    pub fn build(&self) -> Result<reqwest::Client> {
227        self.builder()
228            .build()
229            .map_err(|source| HttpClientError::Build { source })
230    }
231
232    /// Builds a `reqwest::Client` from this configuration with redirects disabled.
233    ///
234    /// Redirect suppression is applied after any customizer hook so security-sensitive
235    /// flows such as OAuth token exchange cannot be redirected.
236    pub fn build_no_redirect(&self) -> Result<reqwest::Client> {
237        self.builder()
238            .redirect(Policy::none())
239            .build()
240            .map_err(|source| HttpClientError::Build { source })
241    }
242}