elemental_core/http/
config.rs1use 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
9pub const DEFAULT_USER_AGENT: &str = concat!("Elemental/", env!("CARGO_PKG_VERSION"));
11
12pub const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
14
15pub const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(30);
17
18type ClientCustomizer = Arc<dyn Fn(reqwest::ClientBuilder) -> reqwest::ClientBuilder + Send + Sync>;
19
20#[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
30pub type Result<T> = std::result::Result<T, HttpClientError>;
32
33#[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 pub fn new() -> Self {
85 Self::default()
86 }
87
88 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 pub fn without_user_agent(mut self) -> Self {
96 self.user_agent = None;
97 self
98 }
99
100 pub fn default_headers(mut self, headers: HeaderMap) -> Self {
102 self.default_headers = headers;
103 self
104 }
105
106 pub fn default_header(mut self, name: HeaderName, value: HeaderValue) -> Self {
108 self.default_headers.insert(name, value);
109 self
110 }
111
112 pub fn connect_timeout(mut self, timeout: Option<Duration>) -> Self {
114 self.connect_timeout = timeout;
115 self
116 }
117
118 pub fn read_timeout(mut self, timeout: Option<Duration>) -> Self {
120 self.read_timeout = timeout;
121 self
122 }
123
124 pub fn timeout(mut self, timeout: Option<Duration>) -> Self {
129 self.timeout = timeout;
130 self
131 }
132
133 pub fn proxy(mut self, proxy: reqwest::Proxy) -> Self {
135 self.proxies.push(proxy);
136 self
137 }
138
139 pub fn proxies(mut self, proxies: impl IntoIterator<Item = reqwest::Proxy>) -> Self {
141 self.proxies = proxies.into_iter().collect();
142 self
143 }
144
145 pub fn no_proxy(mut self, no_proxy: bool) -> Self {
147 self.no_proxy = no_proxy;
148 self
149 }
150
151 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 pub fn user_agent_value(&self) -> Option<&str> {
167 self.user_agent.as_deref()
168 }
169
170 pub fn default_headers_map(&self) -> &HeaderMap {
172 &self.default_headers
173 }
174
175 pub fn connect_timeout_value(&self) -> Option<Duration> {
177 self.connect_timeout
178 }
179
180 pub fn read_timeout_value(&self) -> Option<Duration> {
182 self.read_timeout
183 }
184
185 pub fn timeout_value(&self) -> Option<Duration> {
187 self.timeout
188 }
189
190 pub fn is_no_proxy(&self) -> bool {
192 self.no_proxy
193 }
194
195 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 pub fn build(&self) -> Result<reqwest::Client> {
227 self.builder()
228 .build()
229 .map_err(|source| HttpClientError::Build { source })
230 }
231
232 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}