http_client/h1/
mod.rs

1//! http-client implementation for async-h1, with connection pooling ("Keep-Alive").
2
3use std::convert::{Infallible, TryFrom};
4use std::fmt::Debug;
5use std::net::SocketAddr;
6use std::sync::Arc;
7
8use async_h1::client;
9use async_std::net::TcpStream;
10use dashmap::DashMap;
11use deadpool::managed::Pool;
12use http_types::StatusCode;
13
14cfg_if::cfg_if! {
15    if #[cfg(feature = "rustls")] {
16        use async_tls::client::TlsStream;
17    } else if #[cfg(feature = "native-tls")] {
18        use async_native_tls::TlsStream;
19    }
20}
21
22use crate::Config;
23
24use super::{async_trait, Error, HttpClient, Request, Response};
25
26mod tcp;
27#[cfg(any(feature = "native-tls", feature = "rustls"))]
28mod tls;
29
30use tcp::{TcpConnWrapper, TcpConnection};
31#[cfg(any(feature = "native-tls", feature = "rustls"))]
32use tls::{TlsConnWrapper, TlsConnection};
33
34type HttpPool = DashMap<SocketAddr, Pool<TcpStream, std::io::Error>>;
35#[cfg(any(feature = "native-tls", feature = "rustls"))]
36type HttpsPool = DashMap<SocketAddr, Pool<TlsStream<TcpStream>, Error>>;
37
38/// async-h1 based HTTP Client, with connection pooling ("Keep-Alive").
39pub struct H1Client {
40    http_pools: HttpPool,
41    #[cfg(any(feature = "native-tls", feature = "rustls"))]
42    https_pools: HttpsPool,
43    config: Arc<Config>,
44}
45
46impl Debug for H1Client {
47    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        let https_pools = if cfg!(any(feature = "native-tls", feature = "rustls")) {
49            self.http_pools
50                .iter()
51                .map(|pool| {
52                    let status = pool.status();
53                    format!(
54                        "Connections: {}, Available: {}, Max: {}",
55                        status.size, status.available, status.max_size
56                    )
57                })
58                .collect::<Vec<String>>()
59        } else {
60            vec![]
61        };
62
63        f.debug_struct("H1Client")
64            .field(
65                "http_pools",
66                &self
67                    .http_pools
68                    .iter()
69                    .map(|pool| {
70                        let status = pool.status();
71                        format!(
72                            "Connections: {}, Available: {}, Max: {}",
73                            status.size, status.available, status.max_size
74                        )
75                    })
76                    .collect::<Vec<String>>(),
77            )
78            .field("https_pools", &https_pools)
79            .field("config", &self.config)
80            .finish()
81    }
82}
83
84impl Default for H1Client {
85    fn default() -> Self {
86        Self::new()
87    }
88}
89
90impl H1Client {
91    /// Create a new instance.
92    pub fn new() -> Self {
93        Self {
94            http_pools: DashMap::new(),
95            #[cfg(any(feature = "native-tls", feature = "rustls"))]
96            https_pools: DashMap::new(),
97            config: Arc::new(Config::default()),
98        }
99    }
100
101    /// Create a new instance.
102    #[deprecated(
103        since = "6.5.0",
104        note = "This function is misnamed. Prefer `Config::max_connections_per_host` instead."
105    )]
106    pub fn with_max_connections(max: usize) -> Self {
107        #[cfg(features = "h1_client")]
108        assert!(max > 0, "max_connections_per_host with h1_client must be greater than zero or it will deadlock!");
109
110        let config = Config {
111            max_connections_per_host: max,
112            ..Default::default()
113        };
114
115        Self {
116            http_pools: DashMap::new(),
117            #[cfg(any(feature = "native-tls", feature = "rustls"))]
118            https_pools: DashMap::new(),
119            config: Arc::new(config),
120        }
121    }
122}
123
124#[async_trait]
125impl HttpClient for H1Client {
126    async fn send(&self, mut req: Request) -> Result<Response, Error> {
127        req.insert_header("Connection", "keep-alive");
128
129        // Insert host
130        #[cfg(any(feature = "native-tls", feature = "rustls"))]
131        let host = req
132            .url()
133            .host_str()
134            .ok_or_else(|| Error::from_str(StatusCode::BadRequest, "missing hostname"))?
135            .to_string();
136
137        let scheme = req.url().scheme();
138        if scheme != "http"
139            && (scheme != "https" || cfg!(not(any(feature = "native-tls", feature = "rustls"))))
140        {
141            return Err(Error::from_str(
142                StatusCode::BadRequest,
143                format!("invalid url scheme '{}'", scheme),
144            ));
145        }
146
147        let addrs = req.url().socket_addrs(|| match req.url().scheme() {
148            "http" => Some(80),
149            #[cfg(any(feature = "native-tls", feature = "rustls"))]
150            "https" => Some(443),
151            _ => None,
152        })?;
153
154        log::trace!("> Scheme: {}", scheme);
155
156        let max_addrs_idx = addrs.len() - 1;
157        for (idx, addr) in addrs.into_iter().enumerate() {
158            let has_another_addr = idx != max_addrs_idx;
159
160            if !self.config.http_keep_alive {
161                match scheme {
162                    "http" => {
163                        let stream = async_std::net::TcpStream::connect(addr).await?;
164                        req.set_peer_addr(stream.peer_addr().ok());
165                        req.set_local_addr(stream.local_addr().ok());
166                        let tcp_conn = client::connect(stream, req);
167                        return if let Some(timeout) = self.config.timeout {
168                            async_std::future::timeout(timeout, tcp_conn).await?
169                        } else {
170                            tcp_conn.await
171                        };
172                    }
173                    #[cfg(any(feature = "native-tls", feature = "rustls"))]
174                    "https" => {
175                        let raw_stream = async_std::net::TcpStream::connect(addr).await?;
176                        req.set_peer_addr(raw_stream.peer_addr().ok());
177                        req.set_local_addr(raw_stream.local_addr().ok());
178                        let tls_stream = tls::add_tls(&host, raw_stream, &self.config).await?;
179                        let tsl_conn = client::connect(tls_stream, req);
180                        return if let Some(timeout) = self.config.timeout {
181                            async_std::future::timeout(timeout, tsl_conn).await?
182                        } else {
183                            tsl_conn.await
184                        };
185                    }
186                    _ => unreachable!(),
187                }
188            }
189
190            match scheme {
191                "http" => {
192                    let pool_ref = if let Some(pool_ref) = self.http_pools.get(&addr) {
193                        pool_ref
194                    } else {
195                        let manager = TcpConnection::new(addr, self.config.clone());
196                        let pool = Pool::<TcpStream, std::io::Error>::new(
197                            manager,
198                            self.config.max_connections_per_host,
199                        );
200                        self.http_pools.insert(addr, pool);
201                        self.http_pools.get(&addr).unwrap()
202                    };
203
204                    // Deadlocks are prevented by cloning an inner pool Arc and dropping the original locking reference before we await.
205                    let pool = pool_ref.clone();
206                    std::mem::drop(pool_ref);
207
208                    let stream = match pool.get().await {
209                        Ok(s) => s,
210                        Err(_) if has_another_addr => continue,
211                        Err(e) => return Err(Error::from_str(400, e.to_string())),
212                    };
213
214                    req.set_peer_addr(stream.peer_addr().ok());
215                    req.set_local_addr(stream.local_addr().ok());
216
217                    let tcp_conn = client::connect(TcpConnWrapper::new(stream), req);
218                    return if let Some(timeout) = self.config.timeout {
219                        async_std::future::timeout(timeout, tcp_conn).await?
220                    } else {
221                        tcp_conn.await
222                    };
223                }
224                #[cfg(any(feature = "native-tls", feature = "rustls"))]
225                "https" => {
226                    let pool_ref = if let Some(pool_ref) = self.https_pools.get(&addr) {
227                        pool_ref
228                    } else {
229                        let manager = TlsConnection::new(host.clone(), addr, self.config.clone());
230                        let pool = Pool::<TlsStream<TcpStream>, Error>::new(
231                            manager,
232                            self.config.max_connections_per_host,
233                        );
234                        self.https_pools.insert(addr, pool);
235                        self.https_pools.get(&addr).unwrap()
236                    };
237
238                    // Deadlocks are prevented by cloning an inner pool Arc and dropping the original locking reference before we await.
239                    let pool = pool_ref.clone();
240                    std::mem::drop(pool_ref);
241
242                    let stream = match pool.get().await {
243                        Ok(s) => s,
244                        Err(_) if has_another_addr => continue,
245                        Err(e) => return Err(Error::from_str(400, e.to_string())),
246                    };
247
248                    req.set_peer_addr(stream.get_ref().peer_addr().ok());
249                    req.set_local_addr(stream.get_ref().local_addr().ok());
250
251                    let tls_conn = client::connect(TlsConnWrapper::new(stream), req);
252                    return if let Some(timeout) = self.config.timeout {
253                        async_std::future::timeout(timeout, tls_conn).await?
254                    } else {
255                        tls_conn.await
256                    };
257                }
258                _ => unreachable!(),
259            }
260        }
261
262        Err(Error::from_str(
263            StatusCode::BadRequest,
264            "missing valid address",
265        ))
266    }
267
268    /// Override the existing configuration with new configuration.
269    ///
270    /// Config options may not impact existing connections.
271    fn set_config(&mut self, config: Config) -> http_types::Result<()> {
272        #[cfg(features = "h1_client")]
273        assert!(config.max_connections_per_host > 0, "max_connections_per_host with h1_client must be greater than zero or it will deadlock!");
274
275        self.config = Arc::new(config);
276
277        Ok(())
278    }
279
280    /// Get the current configuration.
281    fn config(&self) -> &Config {
282        &*self.config
283    }
284}
285
286impl TryFrom<Config> for H1Client {
287    type Error = Infallible;
288
289    fn try_from(config: Config) -> Result<Self, Self::Error> {
290        #[cfg(features = "h1_client")]
291        assert!(config.max_connections_per_host > 0, "max_connections_per_host with h1_client must be greater than zero or it will deadlock!");
292
293        Ok(Self {
294            http_pools: DashMap::new(),
295            #[cfg(any(feature = "native-tls", feature = "rustls"))]
296            https_pools: DashMap::new(),
297            config: Arc::new(config),
298        })
299    }
300}
301
302#[cfg(test)]
303mod tests {
304    use super::*;
305    use async_std::prelude::*;
306    use async_std::task;
307    use http_types::url::Url;
308    use http_types::Result;
309    use std::time::Duration;
310
311    fn build_test_request(url: Url) -> Request {
312        let mut req = Request::new(http_types::Method::Post, url);
313        req.set_body("hello");
314        req.append_header("test", "value");
315        req
316    }
317
318    #[async_std::test]
319    async fn basic_functionality() -> Result<()> {
320        let port = portpicker::pick_unused_port().unwrap();
321        let mut app = tide::new();
322        app.at("/").all(|mut r: tide::Request<()>| async move {
323            let mut response = tide::Response::new(http_types::StatusCode::Ok);
324            response.set_body(r.body_bytes().await.unwrap());
325            Ok(response)
326        });
327
328        let server = task::spawn(async move {
329            app.listen(("localhost", port)).await?;
330            Result::Ok(())
331        });
332
333        let client = task::spawn(async move {
334            task::sleep(Duration::from_millis(100)).await;
335            let request =
336                build_test_request(Url::parse(&format!("http://localhost:{}/", port)).unwrap());
337            let mut response: Response = H1Client::new().send(request).await?;
338            assert_eq!(response.body_string().await.unwrap(), "hello");
339            Ok(())
340        });
341
342        server.race(client).await?;
343
344        Ok(())
345    }
346
347    #[async_std::test]
348    async fn https_functionality() -> Result<()> {
349        task::sleep(Duration::from_millis(100)).await;
350        // Send a POST request to https://httpbin.org/post
351        // The result should be a JSon string similar to what you get with:
352        //  curl -X POST "https://httpbin.org/post" -H "accept: application/json" -H "Content-Type: text/plain;charset=utf-8" -d "hello"
353        let request = build_test_request(Url::parse("https://httpbin.org/post").unwrap());
354        let mut response: Response = H1Client::new().send(request).await?;
355        let json_val: serde_json::value::Value =
356            serde_json::from_str(&response.body_string().await.unwrap())?;
357        assert_eq!(*json_val.get("data").unwrap(), serde_json::json!("hello"));
358        Ok(())
359    }
360}