1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
/* Copyright (c) Fortanix, Inc.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use crate::connector::{ConnectorAdapter, NetworkConnector};
use crate::error::Error;
use crate::shared_body::SharedBody;
use crate::Response;

use headers::{ContentLength, Header, HeaderMap, HeaderMapExt};
use hyper::{Client as HyperClient, Method, Request, Uri};

use std::convert::{TryFrom, TryInto};
use std::fmt;
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;

/// A wrapper for [hyper's `Client` type] providing a simpler interface
///
/// Example usage:
/// ```ignore
/// let connector = HttpConnector::new();
/// let client = Client::with_connector(connector);
/// let response = client.get("http://example.com/")?.send().await?;
/// ```
///
/// [hyper's `Client` type]: https://docs.rs/hyper/latest/hyper/client/struct.Client.html
#[derive(Clone)]
pub struct Client {
    inner: Arc<HyperClient<ConnectorAdapter, SharedBody>>,
}

macro_rules! define_method_fn {
    (@internal $name:ident, $method:ident, $method_str:expr) => {
        #[doc = "Initiate a "]
        #[doc = $method_str]
        #[doc = " request with the specified URI."]
        ///
        /// Returns an error if `uri` is invalid.
        pub fn $name<U>(&self, uri: U) -> Result<RequestBuilder<'_>, Error>
        where
            Uri: TryFrom<U>,
            <Uri as TryFrom<U>>::Error: Into<http::Error>,
        {
            self.request(Method::$method, uri)
        }
    };

    ($name:ident, $method:ident) => {
        define_method_fn!(@internal $name, $method, stringify!($method));
    };
}

impl Client {
    pub fn builder() -> ClientBuilder {
        ClientBuilder::new()
    }

    /// Create a new `Client` using the specified connector.
    pub fn with_connector<C: NetworkConnector>(connector: C) -> Self {
        ClientBuilder::new().build(connector)
    }

    /// Initiate a request with the specified method and URI.
    ///
    /// Returns an error if `uri` is invalid.
    pub fn request<U>(&self, method: Method, uri: U) -> Result<RequestBuilder<'_>, Error>
    where
        Uri: TryFrom<U>,
        <Uri as TryFrom<U>>::Error: Into<http::Error>,
    {
        let uri = uri.try_into().map_err(Into::into).map_err(Error::Http)?;
        Ok(RequestBuilder {
            client: self,
            details: RequestDetails::new(method, uri),
        })
    }

    define_method_fn!(get, GET);
    define_method_fn!(head, HEAD);
    define_method_fn!(post, POST);
    define_method_fn!(patch, PATCH);
    define_method_fn!(put, PUT);
    define_method_fn!(delete, DELETE);
}

// NOTE: the default values are taken from https://docs.rs/hyper/0.13.10/hyper/client/struct.Builder.html
// NOTE: not all configurable aspects of hyper Client are exposed here.
/// A builder for [`Client`]
///
/// [`Client`]: struct.Client.html
pub struct ClientBuilder {
    max_idle_per_host: usize,
    idle_timeout: Option<Duration>,
}

impl ClientBuilder {
    pub(crate) fn new() -> Self {
        ClientBuilder {
            max_idle_per_host: usize::MAX,
            idle_timeout: Some(Duration::from_secs(90)),
        }
    }

    /// Sets the maximum idle connection per host allowed in the pool.
    ///
    /// Default is usize::MAX (no limit).
    pub fn pool_max_idle_per_host(&mut self, max_idle: usize) -> &mut Self {
        self.max_idle_per_host = max_idle;
        self
    }

    /// Set an optional timeout for idle sockets being kept-alive.
    ///
    /// Pass `None` to disable timeout.
    ///
    /// Default is 90 seconds.
    pub fn pool_idle_timeout(&mut self, val: Option<Duration>) -> &mut Self {
        self.idle_timeout = val;
        self
    }

    /// Combine the configuration of this builder with a connector to create a
    /// `Client`.
    pub fn build<C: NetworkConnector>(&self, connector: C) -> Client {
        Client {
            inner: Arc::new(
                HyperClient::builder()
                    .pool_max_idle_per_host(self.max_idle_per_host)
                    .pool_idle_timeout(self.idle_timeout)
                    .executor(TokioExecutor)
                    .build(ConnectorAdapter::new(connector)),
            ),
        }
    }
}

pub(crate) struct RequestDetails {
    pub(crate) method: Method,
    pub(crate) uri: Uri,
    pub(crate) headers: HeaderMap,
    pub(crate) body: Option<SharedBody>,
}

impl fmt::Debug for RequestDetails {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RequestDetails")
            .field("method", &self.method)
            .field("uri", &self.uri)
            .field("headers", &self.headers.len())
            .field("body", &self.body.as_ref().map_or("None", |_| "Some(...)"))
            .finish()
    }
}

impl RequestDetails {
    pub fn new(method: Method, uri: Uri) -> Self {
        RequestDetails {
            method,
            uri,
            headers: HeaderMap::new(),
            body: None,
        }
    }

    pub async fn send(mut self, client: &Client) -> Result<Response, Error> {
        let can_have_body = match self.method {
            // See RFC 7231 section 4.3
            Method::GET | Method::HEAD | Method::DELETE => false,
            _ => true,
        };
        let body = match can_have_body {
            true => {
                let body = self.body.unwrap_or_else(|| SharedBody::empty());
                // NOTE: body cannot be chunked in this implementation, so we
                // don't worry about chunked encoding here. But if this changes
                // then we should not set `ContentLength` automatically if the
                // request body is chunked, see RFC 7230 section 3.3.2.
                self.headers.typed_insert(ContentLength(body.len() as u64));
                body
            }
            false if self.body.is_some() => return Err(Error::BodyNotAllowed(self.method)),
            false => SharedBody::empty(),
        };
        let mut req = Request::builder().method(self.method).uri(self.uri);
        match req.headers_mut() {
            Some(headers) => {
                *headers = self.headers;
            }
            // There is an error in req, but the only way to extract the error is through `req.body()`
            None => match req.body(SharedBody::empty()) {
                Err(e) => return Err(e.into()),
                Ok(_) => {
                    panic!("request builder must have errors if `fn headers_mut()` returns None")
                }
            },
        }
        let req = req.body(body)?;
        Ok(client.inner.request(req).await?)
    }
}

/// An HTTP request builder
///
/// This is created through [`Client::get()`], [`Client::post()`] etc.
/// You need to call [`send()`] to actually send the request over the network.
///
/// [`Client::get()`]: struct.Client.html#method.get
/// [`Client::post()`]: struct.Client.html#method.post
/// [`send()`]: struct.RequestBuilder.html#method.send
pub struct RequestBuilder<'a> {
    client: &'a Client,
    details: RequestDetails,
}

impl<'a> RequestBuilder<'a> {
    /// Set the request body.
    pub fn body<B: Into<SharedBody>>(mut self, body: B) -> Self {
        self.details.body = Some(body.into());
        self
    }

    /// Set the request headers.
    pub fn headers(mut self, headers: HeaderMap) -> Self {
        self.details.headers = headers;
        self
    }

    /// Set a single header using [`HeaderMapExt::typed_insert()`].
    ///
    /// [`HeaderMapExt::typed_insert()`]: https://docs.rs/headers/0.3.5/headers/trait.HeaderMapExt.html#tymethod.typed_insert
    pub fn header<H: Header>(mut self, header: H) -> Self {
        self.details.headers.typed_insert(header);
        self
    }

    /// Send the request over the network.
    ///
    /// Returns an error before sending the request if there is something wrong
    /// with the request parameters (method, uri, etc.).
    pub async fn send(self) -> Result<Response, Error> {
        self.details.send(&self.client).await
    }
}

#[derive(Copy, Clone)]
pub(crate) struct TokioExecutor;

impl<F> hyper::rt::Executor<F> for TokioExecutor
where
    F: Future + Send + 'static,
    F::Output: Send + 'static,
{
    fn execute(&self, fut: F) {
        tokio::spawn(fut);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::connector::HttpConnector;
    use headers::ContentType;
    use hyper::body::to_bytes;
    use hyper::StatusCode;
    use std::net::SocketAddr;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::TcpListener;

    const RESPONSE_OK: &str = "HTTP/1.1 200 OK\r\nContent-Length: 13\r\n\r\nHello, world!\r\n";
    const RESPONSE_404: &str =
        "HTTP/1.1 404 Not Found\r\nContent-Length: 23\r\n\r\nResource was not found.\r\n";

    async fn test_http_server(resp: &'static str) -> SocketAddr {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            let (mut stream, _) = listener.accept().await.unwrap();
            let mut input = Vec::new();
            stream.read(&mut input).await.unwrap();
            stream.write_all(resp.as_bytes()).await.unwrap();
        });
        addr
    }

    #[tokio::test]
    async fn http_client() {
        let addr = test_http_server(RESPONSE_OK).await;
        let url = format!("http://{}/", addr);

        let connector = HttpConnector::new();
        let client = Client::with_connector(connector);
        let response = client
            .post(url)
            .unwrap()
            .header(ContentType::json())
            .body(r#"{"key":"value"}"#)
            .send()
            .await
            .unwrap();

        assert_eq!(response.status(), StatusCode::OK);
        let body = to_bytes(response).await.unwrap();
        assert_eq!(body, "Hello, world!".as_bytes());
    }

    #[tokio::test]
    async fn drop_client_before_response() {
        let addr = test_http_server(RESPONSE_404).await;
        let url = format!("http://{}/", addr);

        let connector = HttpConnector::new();
        let client = Client::with_connector(connector);
        let response = client.get(url).unwrap().send().await.unwrap();
        drop(client);

        assert_eq!(response.status(), StatusCode::NOT_FOUND);
        assert_eq!(response.headers().len(), 1);
        let body = to_bytes(response).await.unwrap();
        assert_eq!(body, "Resource was not found.");
    }
}