Skip to main content

matrix_sdk/http_client/
mod.rs

1// Copyright 2020 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    any::type_name,
17    borrow::Cow,
18    fmt::Debug,
19    num::NonZeroUsize,
20    sync::{
21        Arc,
22        atomic::{AtomicU64, Ordering},
23    },
24    time::Duration,
25};
26
27use bytes::{Bytes, BytesMut};
28use bytesize::ByteSize;
29use eyeball::SharedObservable;
30use http::Method;
31use matrix_sdk_base::SendOutsideWasm;
32use ruma::api::{
33    IncomingResponse, OutgoingRequest, OutgoingRequestExt, SupportedVersions,
34    auth_scheme::{self, AuthScheme, SendAccessToken},
35    error::{DeserializationError, FromHttpResponseError, IntoHttpError},
36    path_builder,
37};
38use tokio::sync::{Semaphore, SemaphorePermit};
39use tracing::{Instrument, debug, error, field::debug, trace};
40
41use crate::{HttpResult, config::RequestConfig, error::HttpError};
42
43#[cfg(not(target_family = "wasm"))]
44mod native;
45#[cfg(target_family = "wasm")]
46mod wasm;
47
48#[cfg(not(target_family = "wasm"))]
49pub use native::HttpSettings;
50
51pub(crate) const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
52
53#[derive(Clone, Debug)]
54struct MaybeSemaphore(Arc<Option<Semaphore>>);
55
56#[allow(dead_code)] // false-positive lint: we never use it but only hold it for the drop
57struct MaybeSemaphorePermit<'a>(Option<SemaphorePermit<'a>>);
58
59impl MaybeSemaphore {
60    fn new(max: Option<NonZeroUsize>) -> Self {
61        let inner = max.map(|i| Semaphore::new(i.into()));
62        MaybeSemaphore(Arc::new(inner))
63    }
64
65    async fn acquire(&self) -> MaybeSemaphorePermit<'_> {
66        match self.0.as_ref() {
67            Some(inner) => {
68                // This can only ever error if the semaphore was closed, which
69                // we never do, so we can safely ignore any error case
70                MaybeSemaphorePermit(inner.acquire().await.ok())
71            }
72            None => MaybeSemaphorePermit(None),
73        }
74    }
75}
76
77/// An HTTP client that sends requests with the retry and concurrency limits
78/// of a [`RequestConfig`].
79#[derive(Clone, Debug)]
80pub struct HttpClient {
81    pub(crate) inner: reqwest::Client,
82    pub(crate) request_config: RequestConfig,
83    concurrent_request_semaphore: MaybeSemaphore,
84    next_request_id: Arc<AtomicU64>,
85}
86
87impl HttpClient {
88    pub(crate) fn new(inner: reqwest::Client, request_config: RequestConfig) -> Self {
89        HttpClient {
90            inner,
91            request_config,
92            concurrent_request_semaphore: MaybeSemaphore::new(
93                request_config.max_concurrent_requests,
94            ),
95            next_request_id: AtomicU64::new(0).into(),
96        }
97    }
98
99    /// The underlying [`reqwest::Client`].
100    pub fn raw(&self) -> &reqwest::Client {
101        &self.inner
102    }
103
104    fn get_request_id(&self) -> String {
105        let request_id = self.next_request_id.fetch_add(1, Ordering::SeqCst);
106        format!("REQ-{request_id}")
107    }
108
109    fn serialize_request<R>(
110        &self,
111        request: R,
112        config: RequestConfig,
113        homeserver: String,
114        access_token: Option<&str>,
115        path_builder_input: <R::PathBuilder as path_builder::PathBuilder>::Input<'_>,
116    ) -> Result<http::Request<Bytes>, IntoHttpError>
117    where
118        R: OutgoingRequest + Debug,
119        R::Authentication: SupportedAuthScheme,
120    {
121        trace!(request_type = type_name::<R>(), "Serializing request");
122
123        let send_access_token = match access_token {
124            Some(access_token) => match (config.force_auth, config.skip_auth) {
125                (true, true) | (true, false) => SendAccessToken::Always(access_token),
126                (false, true) => SendAccessToken::None,
127                (false, false) => SendAccessToken::IfRequired(access_token),
128            },
129            None => SendAccessToken::None,
130        };
131        let authentication_input = R::Authentication::authentication_input(send_access_token);
132
133        let request = request
134            .try_into_http_request::<BytesMut>(
135                &homeserver,
136                authentication_input,
137                path_builder_input,
138            )?
139            .map(|body| body.freeze());
140
141        Ok(request)
142    }
143
144    pub(crate) fn send<R>(
145        &self,
146        request: R,
147        config: Option<RequestConfig>,
148        homeserver: String,
149        access_token: Option<&str>,
150        path_builder_input: <R::PathBuilder as path_builder::PathBuilder>::Input<'_>,
151        send_progress: SharedObservable<TransmissionProgress>,
152    ) -> impl Future<Output = Result<R::IncomingResponse, HttpError>>
153    where
154        R: OutgoingRequest + Debug,
155        R::Authentication: SupportedAuthScheme,
156        HttpError: From<FromHttpResponseError<R::EndpointError>>,
157    {
158        let config = config.unwrap_or(self.request_config);
159
160        async move {
161            let request = self
162                .serialize_request(request, config, homeserver, access_token, path_builder_input)
163                .map_err(HttpError::IntoHttp)?;
164            self.send_http_request::<R::IncomingResponse>(request, config, send_progress).await
165        }
166        .instrument(make_span(self, &config))
167    }
168
169    /// Send an already built HTTP request and return the body of the
170    /// response.
171    ///
172    /// The request goes through the same machinery as the Matrix API
173    /// requests: it's retried according to the [`RequestConfig`], and
174    /// concurrent requests are limited the same way.
175    ///
176    /// If `config` is `None`, the default config of this client is used.
177    pub fn send_raw(
178        &self,
179        request: http::Request<Bytes>,
180        config: Option<RequestConfig>,
181    ) -> impl Future<Output = Result<Vec<u8>, HttpError>> {
182        let config = config.unwrap_or(self.request_config);
183
184        async move {
185            let response =
186                self.send_http_request::<RawResponse>(request, config, Default::default()).await?;
187            Ok(response.0)
188        }
189        .instrument(make_span(self, &config))
190    }
191
192    async fn send_http_request<R>(
193        &self,
194        request: http::Request<Bytes>,
195        config: RequestConfig,
196        send_progress: SharedObservable<TransmissionProgress>,
197    ) -> Result<R, HttpError>
198    where
199        R: IncomingResponse,
200        HttpError: From<FromHttpResponseError<R::EndpointError>>,
201    {
202        // some functions split out so they only get compiled once, not
203        // monomorphized per response type
204        fn record_request_uri_and_size(request: &http::Request<Bytes>) {
205            let method = request.method();
206
207            let mut uri_parts = request.uri().clone().into_parts();
208
209            // Erase the query parameters for the sake of secrecy (in case a
210            // token is present).
211            if let Some(path_and_query) = &mut uri_parts.path_and_query {
212                *path_and_query =
213                    path_and_query.path().try_into().expect("path is valid PathAndQuery");
214            }
215
216            let uri = http::Uri::from_parts(uri_parts).expect("created from valid URI");
217
218            let span = tracing::Span::current();
219            span.record("method", debug(method)).record("uri", uri.to_string());
220
221            // POST, PUT, PATCH are the only methods that are reasonably used in
222            // conjunction with request bodies
223            if [Method::POST, Method::PUT, Method::PATCH].contains(method) {
224                let request_size = request.body().len().try_into().unwrap_or(u64::MAX);
225                span.record(
226                    "request_size",
227                    ByteSize(request_size).display().si_short().to_string(),
228                );
229            }
230        }
231        // these macros expand to a lot of code, also want to skip
232        // monomorphization for them even though they might look super simple
233        fn log_got_response() {
234            debug!("Got response");
235        }
236        fn log_error(e: &HttpError) {
237            error!("Error while sending request: {e:?}");
238        }
239
240        record_request_uri_and_size(&request);
241
242        // will be automatically dropped at the end of this function
243        let _handle = self.concurrent_request_semaphore.acquire().await;
244
245        // There's a bunch of state in send_request, factor out a pinned
246        // inner future to reduce the size of futures that await this
247        // function.
248        match Box::pin(self.send_request::<R>(request, config, send_progress)).await {
249            Ok(response) => {
250                log_got_response();
251                Ok(response)
252            }
253            Err(e) => {
254                log_error(&e);
255                Err(e)
256            }
257        }
258    }
259}
260
261// Split out so it only gets compiled once, not monomorphized per request type.
262fn make_span(client: &HttpClient, config: &RequestConfig) -> tracing::Span {
263    tracing::info_span!(
264        "send",
265        uri = tracing::field::Empty,
266        ?config,
267        method = tracing::field::Empty,
268        request_id = client.get_request_id(),
269        request_size = tracing::field::Empty,
270        request_duration = tracing::field::Empty,
271        status = tracing::field::Empty,
272        response_size = tracing::field::Empty,
273        sentry_event_id = tracing::field::Empty
274    )
275}
276
277/// The raw body of a response to a request sent with
278/// [`HttpClient::send_raw()`].
279struct RawResponse(Vec<u8>);
280
281impl IncomingResponse for RawResponse {
282    type EndpointError = ruma::api::error::Error;
283
284    fn try_from_http_response_inner(
285        response: http::Response<&[u8]>,
286    ) -> Result<Self, DeserializationError> {
287        Ok(Self(response.body().to_vec()))
288    }
289}
290
291/// Progress of sending or receiving a payload.
292#[derive(Clone, Copy, Debug, Default)]
293pub struct TransmissionProgress {
294    /// How many bytes were already transferred.
295    pub current: usize,
296    /// How many bytes there are in total.
297    pub total: usize,
298}
299
300async fn response_to_http_response(
301    mut response: reqwest::Response,
302) -> Result<http::Response<Bytes>, reqwest::Error> {
303    let status = response.status();
304
305    let mut http_builder = http::Response::builder().status(status);
306    let headers = http_builder.headers_mut().expect("Can't get the response builder headers");
307
308    for (k, v) in response.headers_mut().drain() {
309        if let Some(key) = k {
310            headers.insert(key, v);
311        }
312    }
313
314    let body = response.bytes().await?;
315
316    Ok(http_builder.body(body).expect("Can't construct a response using the given body"))
317}
318
319/// Marker trait to identify the authentication schemes that the
320/// [`Client`](crate::Client) supports.
321///
322/// This trait can also be implemented for custom [`AuthScheme`]s if necessary.
323pub trait SupportedAuthScheme: AuthScheme {
324    /// Get the [`AuthScheme::Input`] from the access token.
325    fn authentication_input(access_token: SendAccessToken<'_>) -> Self::Input<'_>;
326}
327
328impl SupportedAuthScheme for auth_scheme::NoAccessToken {
329    fn authentication_input(access_token: SendAccessToken<'_>) -> Self::Input<'_> {
330        access_token
331    }
332}
333
334impl SupportedAuthScheme for auth_scheme::AccessToken {
335    fn authentication_input(access_token: SendAccessToken<'_>) -> Self::Input<'_> {
336        access_token
337    }
338}
339
340impl SupportedAuthScheme for auth_scheme::AccessTokenOptional {
341    fn authentication_input(access_token: SendAccessToken<'_>) -> Self::Input<'_> {
342        access_token
343    }
344}
345
346impl SupportedAuthScheme for auth_scheme::AppserviceToken {
347    fn authentication_input(access_token: SendAccessToken<'_>) -> Self::Input<'_> {
348        access_token
349    }
350}
351
352impl SupportedAuthScheme for auth_scheme::AppserviceTokenOptional {
353    fn authentication_input(access_token: SendAccessToken<'_>) -> Self::Input<'_> {
354        access_token
355    }
356}
357
358impl SupportedAuthScheme for auth_scheme::NoAuthentication {
359    fn authentication_input(_access_token: SendAccessToken<'_>) -> Self::Input<'_> {}
360}
361
362/// Marker trait to identify the path builders that the
363/// [`Client`](crate::Client) supports.
364///
365/// This trait can also be implemented for custom
366/// [`PathBuilder`](path_builder::PathBuilder)s if necessary.
367pub trait SupportedPathBuilder: path_builder::PathBuilder {
368    /// Get the [`PathBuilder::Input`](path_builder::PathBuilder::Input) from
369    /// the [`Client`](crate::Client).
370    fn get_path_builder_input(
371        client: &crate::Client,
372        skip_auth: bool,
373    ) -> impl Future<Output = HttpResult<Self::Input<'static>>> + SendOutsideWasm;
374}
375
376impl SupportedPathBuilder for path_builder::VersionHistory {
377    async fn get_path_builder_input(
378        client: &crate::Client,
379        skip_auth: bool,
380    ) -> HttpResult<Cow<'static, SupportedVersions>> {
381        // We always enable "failsafe" mode for the GET /versions requests in
382        // this function. It disables trying to refresh the access token for
383        // those requests, to avoid possible deadlocks.
384
385        if !client.auth_ctx().has_valid_access_token() {
386            // Try to get the value in the cache.
387            if let Ok(Some(versions)) = client.supported_versions_cached().await {
388                return Ok(Cow::Owned(versions));
389            }
390
391            // The request will skip auth so we might not get all the supported
392            // features, so just fetch the supported versions and don't cache
393            // them.
394            let response = client.fetch_server_versions_inner(true, None).await?;
395
396            Ok(Cow::Owned(response.as_supported_versions()))
397        } else if skip_auth {
398            let cached_versions = client.supported_versions_cached().await;
399
400            let versions = if let Ok(Some(versions)) = cached_versions {
401                versions
402            } else {
403                // If we're skipping auth we might not get all the supported
404                // features, so just fetch the versions and don't cache them.
405                let request_config = RequestConfig::default().retry_limit(5).skip_auth();
406                let response =
407                    client.fetch_server_versions_inner(true, Some(request_config)).await?;
408
409                response.as_supported_versions()
410            };
411
412            Ok(Cow::Owned(versions))
413        } else {
414            client.supported_versions_inner(true).await.map(Cow::Owned)
415        }
416    }
417}
418
419impl SupportedPathBuilder for path_builder::SinglePath {
420    async fn get_path_builder_input(_client: &crate::Client, _skip_auth: bool) -> HttpResult<()> {
421        Ok(())
422    }
423}
424
425#[cfg(all(test, not(target_family = "wasm")))]
426mod tests {
427    use std::{
428        num::NonZeroUsize,
429        sync::{
430            Arc,
431            atomic::{AtomicU8, Ordering},
432        },
433        time::Duration,
434    };
435
436    use matrix_sdk_common::executor::spawn;
437    use matrix_sdk_test::{async_test, test_json};
438    use wiremock::{
439        Mock, Request, ResponseTemplate,
440        matchers::{method, path},
441    };
442
443    use crate::{
444        http_client::RequestConfig,
445        test_utils::{set_client_session, test_client_builder_with_server},
446    };
447
448    #[async_test]
449    async fn test_ensure_concurrent_request_limit_is_observed() {
450        let (client_builder, server) = test_client_builder_with_server().await;
451        let client = client_builder
452            .request_config(RequestConfig::default().max_concurrent_requests(NonZeroUsize::new(5)))
453            .build()
454            .await
455            .unwrap();
456
457        set_client_session(&client).await;
458
459        let counter = Arc::new(AtomicU8::new(0));
460        let inner_counter = counter.clone();
461
462        Mock::given(method("GET"))
463            .and(path("/_matrix/client/versions"))
464            .respond_with(ResponseTemplate::new(200).set_body_json(&*test_json::VERSIONS))
465            .mount(&server)
466            .await;
467
468        Mock::given(method("GET"))
469            .and(path("_matrix/client/r0/account/whoami"))
470            .respond_with(move |_req: &Request| {
471                inner_counter.fetch_add(1, Ordering::SeqCst);
472                // we stall the requests
473                ResponseTemplate::new(200).set_delay(Duration::from_secs(60))
474            })
475            .mount(&server)
476            .await;
477
478        let bg_task = spawn(async move {
479            futures_util::future::join_all((0..10).map(|_| client.whoami())).await
480        });
481
482        // give it some time to issue the requests
483        tokio::time::sleep(Duration::from_millis(300)).await;
484
485        assert_eq!(
486            counter.load(Ordering::SeqCst),
487            5,
488            "More requests passed than the limit we configured"
489        );
490        bg_task.abort();
491    }
492
493    #[async_test]
494    async fn test_ensure_no_max_concurrent_request_does_not_limit() {
495        let (client_builder, server) = test_client_builder_with_server().await;
496        let client = client_builder
497            .request_config(RequestConfig::default().max_concurrent_requests(None))
498            .build()
499            .await
500            .unwrap();
501
502        set_client_session(&client).await;
503
504        let counter = Arc::new(AtomicU8::new(0));
505        let inner_counter = counter.clone();
506
507        Mock::given(method("GET"))
508            .and(path("/_matrix/client/versions"))
509            .respond_with(ResponseTemplate::new(200).set_body_json(&*test_json::VERSIONS))
510            .mount(&server)
511            .await;
512
513        Mock::given(method("GET"))
514            .and(path("_matrix/client/r0/account/whoami"))
515            .respond_with(move |_req: &Request| {
516                inner_counter.fetch_add(1, Ordering::SeqCst);
517                ResponseTemplate::new(200).set_delay(Duration::from_secs(60))
518            })
519            .mount(&server)
520            .await;
521
522        let bg_task = spawn(async move {
523            futures_util::future::join_all((0..254).map(|_| client.whoami())).await
524        });
525
526        // give it some time to issue the requests
527        tokio::time::sleep(Duration::from_secs(1)).await;
528
529        assert_eq!(counter.load(Ordering::SeqCst), 254, "Not all requests passed through");
530        bg_task.abort();
531    }
532}