Skip to main content

matrix_sdk/http_client/
native.rs

1// Copyright 2023 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use 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        // some functions split out so they only get compiled once, not
52        // monomorphized per request type
53        fn make_backoff(config: &RequestConfig) -> ExponentialBuilder {
54            // These values were picked because we used to use the `backoff`
55            // crate, those were defined here:
56            // https://docs.rs/backoff/0.4.0/backoff/default/index.html
57            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            // Let's now apply any override the user or the SDK might have set.
64            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                // Backon behaves a bit differently to our own handcrafted max
70                // retry logic. We were counting from one while `backon` counts
71                // from zero.
72                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            // Record interesting headers. If you add more headers, ensure
100            // they're not confidential.
101            for (header_name, header_value) in response.headers() {
102                let header_name = header_name.as_str().to_lowercase();
103
104                // Header added in case of OAuth 2.0 authentication failure, so
105                // we can correlate failures with a Sentry event emitted by the
106                // OAuth 2.0 authentication server.
107                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                    // This bit is somewhat tricky but it's necessary so we
123                    // respect the `max_times` limit from `backon`.
124                    //
125                    // The exponential backoff in `backon` is implemented as an
126                    // iterator that returns `None` when we hit the `max_times`
127                    // limit; if it returned `None`, that means we ran out of
128                    // attempts. So it's necessary to only override the
129                    // `backon_suggested_timeout` if it's `Some`.
130                    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 we ran into a network failure, only retry if there's
139                    // some retry limit associated to this request's
140                    // configuration; otherwise, we would end up running an
141                    // infinite loop of network requests in offline mode.
142                    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    /// Create a new client, using `settings` to configure the underlying
183    /// [`reqwest::Client`] and `request_config` as the default config of
184    /// each request, including its timeouts.
185    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/// Interval between two HTTP/2 PING frames sent on a connection, used to
195/// detect connections which became dead, for instance after a network change.
196#[cfg(not(target_family = "wasm"))]
197const HTTP2_KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(10);
198
199/// Time to wait for the acknowledgement of an HTTP/2 PING frame before closing
200/// the connection.
201#[cfg(not(target_family = "wasm"))]
202const HTTP2_KEEP_ALIVE_TIMEOUT: Duration = Duration::from_secs(5);
203
204#[cfg(not(target_family = "wasm"))]
205/// Settings used to build the underlying [`reqwest::Client`].
206#[derive(Clone, Debug)]
207pub struct HttpSettings {
208    /// Accept invalid TLS certificates. Dangerous, only use for testing.
209    pub disable_ssl_verification: bool,
210    /// URL of a proxy to route all requests through.
211    pub proxy: Option<String>,
212    /// User agent to send, defaults to `matrix-rust-sdk`.
213    pub user_agent: Option<String>,
214    /// Total timeout for a request. Overridden by the [`RequestConfig`] the
215    /// client is built with.
216    pub(crate) timeout: Option<Duration>,
217    /// Timeout for each read operation. Overridden by the [`RequestConfig`]
218    /// the client is built with.
219    pub(crate) read_timeout: Option<Duration>,
220    /// Extra root certificates to trust.
221    pub additional_root_certificates: Vec<Certificate>,
222    /// Only trust `additional_root_certificates`, not the built-in ones.
223    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    /// Use the timeouts of `request_config`, since `reqwest` only supports
244    /// setting a read timeout on the whole client, not per request.
245    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    /// Build a client with the specified configuration.
251    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            // As recommended by BCP 195. See:
256            // https://datatracker.ietf.org/doc/bcp195/
257            .min_tls_version(tls::Version::TLS_1_2)
258            // Send HTTP/2 PING frames so that a connection which became dead
259            // (e.g. after a network change) is detected and removed from the
260            // pool, instead of new requests being multiplexed on it until the
261            // OS times out the socket. Idle connections are pinged too, so the
262            // first request after a network change isn't stuck. This has no
263            // effect on HTTP/1.1 connections. See:
264            // https://github.com/matrix-org/matrix-rust-sdk/issues/7542
265            .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            // Make sure any concurrent futures in the same task get a chance to
315            // also add to the progress total before the first chunks are pulled
316            // out of the body stream.
317            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            // When streaming the request, reqwest / hyper doesn't know how
330            // large the body is, so it doesn't set the content-length header
331            // (required by some servers). Set it manually.
332            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}