Skip to main content

serenade_http_client/
reqwest_client.rs

1//! Reqwest-backed [`HttpClient`].
2
3use std::time::Duration;
4
5use reqwest::Client;
6
7use crate::{ClientMethod, ClientRequest, ClientResponse, HttpClient, HttpClientError};
8
9const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
10
11/// Production [`HttpClient`] using reqwest + rustls.
12#[derive(Clone, Debug)]
13pub struct ReqwestHttpClient {
14    client: Client,
15    default_timeout: Duration,
16}
17
18impl ReqwestHttpClient {
19    /// Builds a client with a 30s default timeout.
20    ///
21    /// # Panics
22    ///
23    /// Panics when the underlying reqwest client cannot be built (should not happen
24    /// for a timeout-only builder).
25    #[must_use]
26    pub fn new() -> Self {
27        Self::default()
28    }
29
30    /// Builds a client with `default_timeout` applied when a request has no timeout.
31    ///
32    /// # Panics
33    ///
34    /// Panics when the underlying reqwest client cannot be built (should not happen
35    /// for a timeout-only builder).
36    #[must_use]
37    pub fn with_timeout(default_timeout: Duration) -> Self {
38        let client = Client::builder()
39            .timeout(default_timeout)
40            .build()
41            .expect("reqwest client");
42        Self {
43            client,
44            default_timeout,
45        }
46    }
47
48    /// Default timeout used when [`ClientRequest::timeout_duration`] is unset.
49    #[must_use]
50    pub const fn default_timeout(&self) -> Duration {
51        self.default_timeout
52    }
53}
54
55impl Default for ReqwestHttpClient {
56    fn default() -> Self {
57        Self::with_timeout(DEFAULT_TIMEOUT)
58    }
59}
60
61impl HttpClient for ReqwestHttpClient {
62    async fn send(&self, request: ClientRequest) -> Result<ClientResponse, HttpClientError> {
63        let method = map_method(request.method());
64        let mut builder = self.client.request(method, request.url());
65        for (name, value) in request.headers() {
66            builder = builder.header(name.as_str(), value.as_str());
67        }
68        if !request.body_bytes().is_empty() {
69            builder = builder.body(request.body_bytes().to_vec());
70        }
71        if let Some(timeout) = request.timeout_duration() {
72            builder = builder.timeout(timeout);
73        }
74        let response = builder
75            .send()
76            .await
77            .map_err(|err| HttpClientError::Transport {
78                message: err.to_string(),
79            })?;
80        let status = response.status().as_u16();
81        let mut headers = std::collections::BTreeMap::new();
82        for (name, value) in response.headers() {
83            if let Ok(text) = value.to_str() {
84                headers.insert(name.as_str().to_ascii_lowercase(), text.to_owned());
85            }
86        }
87        let body = response.bytes().await.expect("response body");
88        let mut out = ClientResponse::new(status).body(body.to_vec());
89        for (name, value) in headers {
90            out = out.header(name, value);
91        }
92        Ok(out)
93    }
94}
95
96const fn map_method(method: ClientMethod) -> reqwest::Method {
97    match method {
98        ClientMethod::Get => reqwest::Method::GET,
99        ClientMethod::Post => reqwest::Method::POST,
100        ClientMethod::Put => reqwest::Method::PUT,
101        ClientMethod::Patch => reqwest::Method::PATCH,
102        ClientMethod::Delete => reqwest::Method::DELETE,
103        ClientMethod::Head => reqwest::Method::HEAD,
104    }
105}