1use std::{
16 fmt::Debug,
17 mem,
18 sync::atomic::{AtomicU64, Ordering},
19 time::Duration,
20};
21
22use backon::{ExponentialBuilder, Retryable};
23use bytes::Bytes;
24use bytesize::ByteSize;
25use eyeball::SharedObservable;
26use http::header::CONTENT_LENGTH;
27#[cfg(not(target_family = "wasm"))]
28use reqwest::Certificate;
29use reqwest::tls;
30use ruma::api::{IncomingResponse, IncomingResponseExt as _, error::FromHttpResponseError};
31use tracing::{debug, info, warn};
32
33use super::{DEFAULT_REQUEST_TIMEOUT, HttpClient, TransmissionProgress, response_to_http_response};
34use crate::{
35 HttpResult,
36 config::RequestConfig,
37 error::{HttpError, RetryKind},
38};
39
40impl HttpClient {
41 pub(super) async fn send_request<R>(
42 &self,
43 request: http::Request<Bytes>,
44 config: RequestConfig,
45 send_progress: SharedObservable<TransmissionProgress>,
46 ) -> HttpResult<R>
47 where
48 R: IncomingResponse,
49 HttpError: From<FromHttpResponseError<R::EndpointError>>,
50 {
51 fn make_backoff(config: &RequestConfig) -> ExponentialBuilder {
54 let mut backoff = ExponentialBuilder::new()
58 .with_min_delay(Duration::from_millis(500))
59 .with_max_delay(Duration::from_secs(60))
60 .with_total_delay(Some(Duration::from_secs(15 * 60)))
61 .without_max_times();
62
63 if let Some(max_delay) = config.max_retry_time {
65 backoff = backoff.with_max_delay(max_delay)
66 }
67
68 if let Some(max_times) = config.retry_limit {
69 backoff = backoff.with_max_times(max_times.saturating_sub(1))
73 }
74
75 backoff
76 }
77 async fn send_request_inner(
78 http_client: &reqwest::Client,
79 request: &http::Request<Bytes>,
80 timeout: Option<Duration>,
81 retry_count: &AtomicU64,
82 send_progress: SharedObservable<TransmissionProgress>,
83 ) -> HttpResult<http::Response<Bytes>> {
84 let num_attempt = retry_count.fetch_add(1, Ordering::SeqCst);
85 debug!(num_attempt, "Sending request");
86 let before = ruma::time::Instant::now();
87
88 let response = execute_request(http_client, request, timeout, send_progress).await?;
89
90 let request_duration = ruma::time::Instant::now().saturating_duration_since(before);
91
92 let status_code = response.status();
93 let response_size = ByteSize(response.body().len().try_into().unwrap_or(u64::MAX));
94 tracing::Span::current()
95 .record("status", status_code.as_u16())
96 .record("response_size", response_size.display().si_short().to_string())
97 .record("request_duration", tracing::field::debug(request_duration));
98
99 for (header_name, header_value) in response.headers() {
102 let header_name = header_name.as_str().to_lowercase();
103
104 if header_name == "x-sentry-event-id" {
108 tracing::Span::current()
109 .record("sentry_event_id", header_value.to_str().unwrap_or("<???>"));
110 }
111 }
112
113 Ok(response)
114 }
115 fn adjust_backoff(
116 err: &HttpError,
117 backon_suggested_timeout: Option<Duration>,
118 has_retry_limit: bool,
119 ) -> Option<Duration> {
120 match err.retry_kind() {
121 RetryKind::Transient { retry_after } => {
122 if backon_suggested_timeout.is_some() {
131 retry_after.or(backon_suggested_timeout)
132 } else {
133 None
134 }
135 }
136 RetryKind::Permanent => None,
137 RetryKind::NetworkFailure => {
138 if has_retry_limit { backon_suggested_timeout } else { None }
143 }
144 }
145 }
146
147 let retry_count = AtomicU64::new(1);
148
149 let send_request = || {
150 let send_progress = send_progress.clone();
151 async {
152 let response = send_request_inner(
153 &self.inner,
154 &request,
155 config.timeout,
156 &retry_count,
157 send_progress,
158 )
159 .await?;
160 let (parts, body) = response.into_parts();
161 let response: http::Response<&[u8]> = http::Response::from_parts(parts, &body);
162 R::try_from_http_response(response).map_err(HttpError::from)
163 }
164 };
165
166 let has_retry_limit = config.retry_limit.is_some();
167
168 send_request
169 .retry(make_backoff(&config))
170 .adjust(|err, backon_suggested_timeout| {
171 adjust_backoff(err, backon_suggested_timeout, has_retry_limit)
172 })
173 .notify(|error, duration| {
174 warn!("Error {error:?} received, will retry in {duration:?}");
175 })
176 .await
177 }
178}
179
180#[cfg(not(target_family = "wasm"))]
181impl HttpClient {
182 pub fn with_settings(
186 mut settings: HttpSettings,
187 request_config: RequestConfig,
188 ) -> Result<Self, HttpError> {
189 settings.apply_timeouts(&request_config);
190 Ok(Self::new(settings.make_client()?, request_config))
191 }
192}
193
194#[cfg(not(target_family = "wasm"))]
197const HTTP2_KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(10);
198
199#[cfg(not(target_family = "wasm"))]
202const HTTP2_KEEP_ALIVE_TIMEOUT: Duration = Duration::from_secs(5);
203
204#[cfg(not(target_family = "wasm"))]
205#[derive(Clone, Debug)]
207pub struct HttpSettings {
208 pub disable_ssl_verification: bool,
210 pub proxy: Option<String>,
212 pub user_agent: Option<String>,
214 pub(crate) timeout: Option<Duration>,
217 pub(crate) read_timeout: Option<Duration>,
220 pub additional_root_certificates: Vec<Certificate>,
222 pub disable_built_in_root_certificates: bool,
224}
225
226#[cfg(not(target_family = "wasm"))]
227impl Default for HttpSettings {
228 fn default() -> Self {
229 Self {
230 disable_ssl_verification: false,
231 proxy: None,
232 user_agent: None,
233 timeout: Some(DEFAULT_REQUEST_TIMEOUT),
234 read_timeout: None,
235 additional_root_certificates: Default::default(),
236 disable_built_in_root_certificates: false,
237 }
238 }
239}
240
241#[cfg(not(target_family = "wasm"))]
242impl HttpSettings {
243 pub(crate) fn apply_timeouts(&mut self, request_config: &RequestConfig) {
246 self.timeout = request_config.timeout;
247 self.read_timeout = request_config.read_timeout;
248 }
249
250 pub(crate) fn make_client(&self) -> Result<reqwest::Client, HttpError> {
252 let user_agent = self.user_agent.clone().unwrap_or_else(|| "matrix-rust-sdk".to_owned());
253 let mut http_client = reqwest::Client::builder()
254 .user_agent(user_agent)
255 .min_tls_version(tls::Version::TLS_1_2)
258 .http2_keep_alive_interval(HTTP2_KEEP_ALIVE_INTERVAL)
266 .http2_keep_alive_timeout(HTTP2_KEEP_ALIVE_TIMEOUT)
267 .http2_keep_alive_while_idle(true);
268
269 if let Some(timeout) = self.timeout {
270 http_client = http_client.timeout(timeout);
271 }
272
273 if let Some(read_timeout) = self.read_timeout {
274 http_client = http_client.read_timeout(read_timeout);
275 }
276
277 if self.disable_ssl_verification {
278 warn!("SSL verification disabled in the HTTP client!");
279 http_client = http_client.danger_accept_invalid_certs(true);
280 }
281
282 http_client = if self.disable_built_in_root_certificates {
283 info!("Built-in root certificates disabled in the HTTP client.");
284 http_client.tls_certs_only(self.additional_root_certificates.clone())
285 } else {
286 http_client.tls_certs_merge(self.additional_root_certificates.clone())
287 };
288
289 if let Some(p) = &self.proxy {
290 info!(proxy_url = p, "Setting the proxy for the HTTP client");
291 http_client = http_client.proxy(reqwest::Proxy::all(p.as_str())?);
292 }
293
294 Ok(http_client.build()?)
295 }
296}
297
298pub(super) async fn execute_request(
299 client: &reqwest::Client,
300 request: &http::Request<Bytes>,
301 timeout: Option<Duration>,
302 send_progress: SharedObservable<TransmissionProgress>,
303) -> Result<http::Response<Bytes>, HttpError> {
304 use std::convert::Infallible;
305
306 use futures_util::stream;
307
308 let request = request.clone();
309 let request = {
310 let mut request = if send_progress.subscriber_count() != 0 {
311 let content_length = request.body().len();
312 send_progress.update(|p| p.total += content_length);
313
314 tokio::task::yield_now().await;
318
319 let mut req = reqwest::Request::try_from(request.map(|body| {
320 let chunks = stream::iter(BytesChunks::new(body, 8192).map(
321 move |chunk| -> Result<_, Infallible> {
322 send_progress.update(|p| p.current += chunk.len());
323 Ok(chunk)
324 },
325 ));
326 reqwest::Body::wrap_stream(chunks)
327 }))?;
328
329 req.headers_mut().insert(CONTENT_LENGTH, content_length.into());
333
334 req
335 } else {
336 reqwest::Request::try_from(request)?
337 };
338
339 *request.timeout_mut() = timeout;
340 request
341 };
342
343 let response = client.execute(request).await?;
344 Ok(response_to_http_response(response).await?)
345}
346
347struct BytesChunks {
348 bytes: Bytes,
349 size: usize,
350}
351
352impl BytesChunks {
353 fn new(bytes: Bytes, size: usize) -> Self {
354 assert_ne!(size, 0);
355 Self { bytes, size }
356 }
357}
358
359impl Iterator for BytesChunks {
360 type Item = Bytes;
361
362 fn next(&mut self) -> Option<Self::Item> {
363 if self.bytes.is_empty() {
364 None
365 } else if self.bytes.len() < self.size {
366 Some(mem::take(&mut self.bytes))
367 } else {
368 Some(self.bytes.split_to(self.size))
369 }
370 }
371}
372
373#[cfg(test)]
374mod tests {
375 use bytes::Bytes;
376
377 use super::BytesChunks;
378
379 #[test]
380 fn test_bytes_chunks() {
381 let bytes = Bytes::new();
382 assert!(BytesChunks::new(bytes, 1).collect::<Vec<_>>().is_empty());
383
384 let bytes = Bytes::from_iter([1, 2]);
385 assert_eq!(BytesChunks::new(bytes, 2).collect::<Vec<_>>(), [Bytes::from_iter([1, 2])]);
386
387 let bytes = Bytes::from_iter([1, 2]);
388 assert_eq!(BytesChunks::new(bytes, 3).collect::<Vec<_>>(), [Bytes::from_iter([1, 2])]);
389
390 let bytes = Bytes::from_iter([1, 2, 3]);
391 assert_eq!(
392 BytesChunks::new(bytes, 1).collect::<Vec<_>>(),
393 [Bytes::from_iter([1]), Bytes::from_iter([2]), Bytes::from_iter([3])]
394 );
395
396 let bytes = Bytes::from_iter([1, 2, 3]);
397 assert_eq!(
398 BytesChunks::new(bytes, 2).collect::<Vec<_>>(),
399 [Bytes::from_iter([1, 2]), Bytes::from_iter([3])]
400 );
401
402 let bytes = Bytes::from_iter([1, 2, 3, 4]);
403 assert_eq!(
404 BytesChunks::new(bytes, 2).collect::<Vec<_>>(),
405 [Bytes::from_iter([1, 2]), Bytes::from_iter([3, 4])]
406 );
407 }
408}