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    fmt::Debug,
18    num::NonZeroUsize,
19    sync::{
20        atomic::{AtomicU64, Ordering},
21        Arc,
22    },
23    time::Duration,
24};
25
26use bytes::{Bytes, BytesMut};
27use bytesize::ByteSize;
28use eyeball::SharedObservable;
29use http::Method;
30use ruma::api::{
31    error::{FromHttpResponseError, IntoHttpError},
32    AuthScheme, MatrixVersion, OutgoingRequest, SendAccessToken,
33};
34use tokio::sync::{Semaphore, SemaphorePermit};
35use tracing::{debug, field::debug, instrument, trace};
36
37use crate::{config::RequestConfig, error::HttpError};
38
39#[cfg(not(target_arch = "wasm32"))]
40mod native;
41#[cfg(target_arch = "wasm32")]
42mod wasm;
43
44#[cfg(not(target_arch = "wasm32"))]
45pub(crate) use native::HttpSettings;
46
47pub(crate) const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
48
49#[derive(Clone, Debug)]
50struct MaybeSemaphore(Arc<Option<Semaphore>>);
51
52#[allow(dead_code)] // false-positive lint: we never use it but only hold it for the drop
53struct MaybeSemaphorePermit<'a>(Option<SemaphorePermit<'a>>);
54
55impl MaybeSemaphore {
56    fn new(max: Option<NonZeroUsize>) -> Self {
57        let inner = max.map(|i| Semaphore::new(i.into()));
58        MaybeSemaphore(Arc::new(inner))
59    }
60
61    async fn acquire(&self) -> MaybeSemaphorePermit<'_> {
62        match self.0.as_ref() {
63            Some(inner) => {
64                // This can only ever error if the semaphore was closed,
65                // which we never do, so we can safely ignore any error case
66                MaybeSemaphorePermit(inner.acquire().await.ok())
67            }
68            None => MaybeSemaphorePermit(None),
69        }
70    }
71}
72
73#[derive(Clone, Debug)]
74pub(crate) struct HttpClient {
75    pub(crate) inner: reqwest::Client,
76    pub(crate) request_config: RequestConfig,
77    concurrent_request_semaphore: MaybeSemaphore,
78    next_request_id: Arc<AtomicU64>,
79}
80
81impl HttpClient {
82    pub(crate) fn new(inner: reqwest::Client, request_config: RequestConfig) -> Self {
83        HttpClient {
84            inner,
85            request_config,
86            concurrent_request_semaphore: MaybeSemaphore::new(
87                request_config.max_concurrent_requests,
88            ),
89            next_request_id: AtomicU64::new(0).into(),
90        }
91    }
92
93    fn get_request_id(&self) -> String {
94        let request_id = self.next_request_id.fetch_add(1, Ordering::SeqCst);
95        format!("REQ-{request_id}")
96    }
97
98    fn serialize_request<R>(
99        &self,
100        request: R,
101        config: RequestConfig,
102        homeserver: String,
103        access_token: Option<&str>,
104        server_versions: &[MatrixVersion],
105    ) -> Result<http::Request<Bytes>, IntoHttpError>
106    where
107        R: OutgoingRequest + Debug,
108    {
109        trace!(request_type = type_name::<R>(), "Serializing request");
110
111        let server_versions = if config.force_matrix_version.is_some() {
112            config.force_matrix_version.as_slice()
113        } else {
114            server_versions
115        };
116
117        let send_access_token = match access_token {
118            Some(access_token) => {
119                if config.force_auth {
120                    SendAccessToken::Always(access_token)
121                } else {
122                    SendAccessToken::IfRequired(access_token)
123                }
124            }
125            None => SendAccessToken::None,
126        };
127
128        let request = request
129            .try_into_http_request::<BytesMut>(&homeserver, send_access_token, server_versions)?
130            .map(|body| body.freeze());
131
132        Ok(request)
133    }
134
135    #[allow(clippy::too_many_arguments)]
136    #[instrument(
137        skip(self, request, config, homeserver, access_token, send_progress),
138        fields(
139            config,
140            uri,
141            method,
142            request_size,
143            request_id,
144            status,
145            response_size,
146            sentry_event_id,
147        )
148    )]
149    pub async fn send<R>(
150        &self,
151        request: R,
152        config: Option<RequestConfig>,
153        homeserver: String,
154        access_token: Option<&str>,
155        server_versions: &[MatrixVersion],
156        send_progress: SharedObservable<TransmissionProgress>,
157    ) -> Result<R::IncomingResponse, HttpError>
158    where
159        R: OutgoingRequest + Debug,
160        HttpError: From<FromHttpResponseError<R::EndpointError>>,
161    {
162        let config = match config {
163            Some(config) => config,
164            None => self.request_config,
165        };
166
167        // Keep some local variables in a separate scope so the compiler doesn't include
168        // them in the future type. https://github.com/rust-lang/rust/issues/57478
169        let request = {
170            let request_id = self.get_request_id();
171            let span = tracing::Span::current();
172
173            // At this point in the code, the config isn't behind an Option anymore, that's
174            // why we record it here, instead of in the #[instrument] macro.
175            span.record("config", debug(config)).record("request_id", request_id);
176
177            let auth_scheme = R::METADATA.authentication;
178            match auth_scheme {
179                AuthScheme::AccessToken
180                | AuthScheme::AccessTokenOptional
181                | AuthScheme::AppserviceToken
182                | AuthScheme::None => {}
183                AuthScheme::ServerSignatures => {
184                    return Err(HttpError::NotClientRequest);
185                }
186            }
187
188            let request = self
189                .serialize_request(request, config, homeserver, access_token, server_versions)
190                .map_err(HttpError::IntoHttp)?;
191
192            let method = request.method();
193
194            let mut uri_parts = request.uri().clone().into_parts();
195            if let Some(path_and_query) = &mut uri_parts.path_and_query {
196                *path_and_query =
197                    path_and_query.path().try_into().expect("path is valid PathAndQuery");
198            }
199            let uri = http::Uri::from_parts(uri_parts).expect("created from valid URI");
200
201            span.record("method", debug(method)).record("uri", uri.to_string());
202
203            // POST, PUT, PATCH are the only methods that are reasonably used
204            // in conjunction with request bodies
205            if [Method::POST, Method::PUT, Method::PATCH].contains(method) {
206                let request_size = request.body().len().try_into().unwrap_or(u64::MAX);
207                span.record("request_size", ByteSize(request_size).to_string_as(true));
208            }
209
210            request
211        };
212
213        // will be automatically dropped at the end of this function
214        let _handle = self.concurrent_request_semaphore.acquire().await;
215
216        // There's a bunch of state in send_request, factor out a pinned inner
217        // future to reduce this size of futures that await this function.
218        match Box::pin(self.send_request::<R>(request, config, send_progress)).await {
219            Ok(response) => {
220                debug!("Got response");
221                Ok(response)
222            }
223            Err(e) => {
224                debug!("Error while sending request: {e:?}");
225                Err(e)
226            }
227        }
228    }
229}
230
231/// Progress of sending or receiving a payload.
232#[derive(Clone, Copy, Debug, Default)]
233pub struct TransmissionProgress {
234    /// How many bytes were already transferred.
235    pub current: usize,
236    /// How many bytes there are in total.
237    pub total: usize,
238}
239
240async fn response_to_http_response(
241    mut response: reqwest::Response,
242) -> Result<http::Response<Bytes>, reqwest::Error> {
243    let status = response.status();
244
245    let mut http_builder = http::Response::builder().status(status);
246    let headers = http_builder.headers_mut().expect("Can't get the response builder headers");
247
248    for (k, v) in response.headers_mut().drain() {
249        if let Some(key) = k {
250            headers.insert(key, v);
251        }
252    }
253
254    let body = response.bytes().await?;
255
256    Ok(http_builder.body(body).expect("Can't construct a response using the given body"))
257}
258
259#[cfg(all(test, not(target_arch = "wasm32")))]
260mod tests {
261    use std::{
262        num::NonZeroUsize,
263        sync::{
264            atomic::{AtomicU8, Ordering},
265            Arc,
266        },
267        time::Duration,
268    };
269
270    use matrix_sdk_test::{async_test, test_json};
271    use wiremock::{
272        matchers::{method, path},
273        Mock, Request, ResponseTemplate,
274    };
275
276    use crate::{
277        http_client::RequestConfig,
278        test_utils::{set_client_session, test_client_builder_with_server},
279    };
280
281    #[async_test]
282    async fn test_ensure_concurrent_request_limit_is_observed() {
283        let (client_builder, server) = test_client_builder_with_server().await;
284        let client = client_builder
285            .request_config(RequestConfig::default().max_concurrent_requests(NonZeroUsize::new(5)))
286            .build()
287            .await
288            .unwrap();
289
290        set_client_session(&client).await;
291
292        let counter = Arc::new(AtomicU8::new(0));
293        let inner_counter = counter.clone();
294
295        Mock::given(method("GET"))
296            .and(path("/_matrix/client/versions"))
297            .respond_with(ResponseTemplate::new(200).set_body_json(&*test_json::VERSIONS))
298            .mount(&server)
299            .await;
300
301        Mock::given(method("GET"))
302            .and(path("_matrix/client/r0/account/whoami"))
303            .respond_with(move |_req: &Request| {
304                inner_counter.fetch_add(1, Ordering::SeqCst);
305                // we stall the requests
306                ResponseTemplate::new(200).set_delay(Duration::from_secs(60))
307            })
308            .mount(&server)
309            .await;
310
311        let bg_task = tokio::spawn(async move {
312            futures_util::future::join_all((0..10).map(|_| client.whoami())).await
313        });
314
315        // give it some time to issue the requests
316        tokio::time::sleep(Duration::from_millis(300)).await;
317
318        assert_eq!(
319            counter.load(Ordering::SeqCst),
320            5,
321            "More requests passed than the limit we configured"
322        );
323        bg_task.abort();
324    }
325
326    #[async_test]
327    async fn test_ensure_no_max_concurrent_request_does_not_limit() {
328        let (client_builder, server) = test_client_builder_with_server().await;
329        let client = client_builder
330            .request_config(RequestConfig::default().max_concurrent_requests(None))
331            .build()
332            .await
333            .unwrap();
334
335        set_client_session(&client).await;
336
337        let counter = Arc::new(AtomicU8::new(0));
338        let inner_counter = counter.clone();
339
340        Mock::given(method("GET"))
341            .and(path("/_matrix/client/versions"))
342            .respond_with(ResponseTemplate::new(200).set_body_json(&*test_json::VERSIONS))
343            .mount(&server)
344            .await;
345
346        Mock::given(method("GET"))
347            .and(path("_matrix/client/r0/account/whoami"))
348            .respond_with(move |_req: &Request| {
349                inner_counter.fetch_add(1, Ordering::SeqCst);
350                ResponseTemplate::new(200).set_delay(Duration::from_secs(60))
351            })
352            .mount(&server)
353            .await;
354
355        let bg_task = tokio::spawn(async move {
356            futures_util::future::join_all((0..254).map(|_| client.whoami())).await
357        });
358
359        // give it some time to issue the requests
360        tokio::time::sleep(Duration::from_secs(1)).await;
361
362        assert_eq!(counter.load(Ordering::SeqCst), 254, "Not all requests passed through");
363        bg_task.abort();
364    }
365}