-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathhyper.rs
342 lines (281 loc) · 11 KB
/
hyper.rs
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
//! http-client implementation for hyper / tokio
use std::convert::{Infallible, TryFrom};
use std::fmt::Debug;
use std::io;
use std::str::FromStr;
use futures_util::stream::TryStreamExt;
use http_types::headers::{HeaderName, HeaderValue};
use http_types::StatusCode;
use hyper0_14 as hyper;
use hyper0_14::body::HttpBody;
use hyper0_14::client::connect::Connect;
use hyper0_14::client::HttpConnector;
use tokio1 as tokio;
#[cfg(feature = "hyper0_14-rustls")]
use hyper0_14_rustls_lib::HttpsConnectorBuilder;
#[cfg(feature = "hyper0_14-native-tls")]
use hyper0_14_tls_lib::HttpsConnector;
use crate::Config;
use super::{async_trait, Error, HttpClient, Request, Response};
type HyperRequest = hyper::Request<hyper::Body>;
// Avoid leaking Hyper generics into HttpClient by hiding it behind a dynamic trait object pointer.
trait HyperClientObject: Debug + Send + Sync + 'static {
fn dyn_request(&self, req: hyper::Request<hyper::Body>) -> hyper::client::ResponseFuture;
}
impl<C: Clone + Connect + Debug + Send + Sync + 'static> HyperClientObject for hyper::Client<C> {
fn dyn_request(&self, req: HyperRequest) -> hyper::client::ResponseFuture {
self.request(req)
}
}
/// Hyper-based HTTP Client.
#[derive(Debug)]
pub struct HyperClient {
client: Box<dyn HyperClientObject>,
config: Config,
}
impl HyperClient {
/// Create a new client instance.
pub fn new() -> Self {
#[allow(unused_mut)]
let mut connector = HttpConnector::new();
#[cfg(any(feature = "hyper0_14-rustls", feature = "hyper0_14-native-tls"))]
connector.enforce_http(false);
#[cfg(feature = "hyper0_14-native-tls")]
let connector = HttpsConnector::new_with_connector(connector);
#[cfg(feature = "hyper0_14-rustls")]
let connector = HttpsConnectorBuilder::default()
.with_native_roots()
.https_or_http()
.enable_http1()
.wrap_connector(connector);
let client = hyper::Client::builder().build(connector);
Self {
client: Box::new(client),
config: Config::default(),
}
}
/// Create from externally initialized and configured client.
pub fn from_client<C>(client: hyper::Client<C>) -> Self
where
C: Clone + Connect + Debug + Send + Sync + 'static,
{
Self {
client: Box::new(client),
config: Config::default(),
}
}
}
impl Default for HyperClient {
fn default() -> Self {
Self::new()
}
}
#[async_trait]
impl HttpClient for HyperClient {
async fn send(&self, req: Request) -> Result<Response, Error> {
let req = HyperHttpRequest::try_from(req).await?.into_inner();
let conn_fut = self.client.dyn_request(req);
let response = if let Some(timeout) = self.config.timeout {
match tokio::time::timeout(timeout, conn_fut).await {
Err(_elapsed) => Err(Error::from_str(400, "Client timed out")),
Ok(Ok(try_res)) => Ok(try_res),
Ok(Err(e)) => Err(e.into()),
}?
} else {
conn_fut.await?
};
let res = HttpTypesResponse::try_from(response).await?.into_inner();
Ok(res)
}
/// Override the existing configuration with new configuration.
///
/// Config options may not impact existing connections.
fn set_config(&mut self, config: Config) -> http_types::Result<()> {
#[allow(unused_mut)]
let mut connector = HttpConnector::new();
#[cfg(any(feature = "hyper0_14-rustls", feature = "hyper0_14-native-tls"))]
connector.enforce_http(false);
#[cfg(feature = "hyper0_14-native-tls")]
let connector = HttpsConnector::new_with_connector(connector);
#[cfg(feature = "hyper0_14-rustls")]
let connector = match config.tls_config {
Some(ref config) => HttpsConnectorBuilder::default()
.with_tls_config(config.as_ref().clone())
.https_or_http()
.enable_http1()
.wrap_connector(connector),
None => HttpsConnectorBuilder::default()
.with_native_roots()
.https_or_http()
.enable_http1()
.wrap_connector(connector),
};
let mut builder = hyper::Client::builder();
if !config.http_keep_alive {
builder.pool_max_idle_per_host(1);
}
self.client = Box::new(builder.build(connector));
self.config = config;
Ok(())
}
/// Get the current configuration.
fn config(&self) -> &Config {
&self.config
}
}
impl TryFrom<Config> for HyperClient {
type Error = Infallible;
fn try_from(config: Config) -> Result<Self, Self::Error> {
#[allow(unused_mut)]
let mut connector = HttpConnector::new();
#[cfg(any(feature = "hyper0_14-rustls", feature = "hyper0_14-native-tls"))]
connector.enforce_http(false);
#[cfg(feature = "hyper0_14-native-tls")]
let connector = HttpsConnector::new_with_connector(connector);
#[cfg(feature = "hyper0_14-rustls")]
let connector = match config.tls_config {
Some(ref config) => HttpsConnectorBuilder::default()
.with_tls_config(config.as_ref().clone())
.https_or_http()
.enable_http1()
.wrap_connector(connector),
None => HttpsConnectorBuilder::default()
.with_native_roots()
.https_or_http()
.enable_http1()
.wrap_connector(connector),
};
let mut builder = hyper::Client::builder();
if !config.http_keep_alive {
builder.pool_max_idle_per_host(1);
}
Ok(Self {
client: Box::new(builder.build(connector)),
config,
})
}
}
struct HyperHttpRequest(HyperRequest);
impl HyperHttpRequest {
async fn try_from(mut value: Request) -> Result<Self, Error> {
// UNWRAP: This unwrap is unjustified in `http-types`, need to check if it's actually safe.
let uri = hyper::Uri::try_from(&format!("{}", value.url())).unwrap();
// `HyperClient` depends on the scheme being either "http" or "https"
match uri.scheme_str() {
#[cfg(not(any(feature = "hyper0_14-rustls", feature = "hyper0_14-native-tls")))]
Some("http") => (),
#[cfg(not(any(feature = "hyper0_14-rustls", feature = "hyper0_14-native-tls")))]
Some("https") => {
return Err(Error::from_str(
StatusCode::BadRequest,
"invalid url scheme `https` - requires `http-client` feature `hyper0_14-rustls` or `hyper0_14-native-tls`",
))
},
#[cfg(any(feature = "hyper0_14-rustls", feature = "hyper0_14-native-tls"))]
Some("http") | Some("https") => (),
Some(scheme) => {
return Err(Error::from_str(
StatusCode::BadRequest,
format!("invalid url scheme `{scheme}`"),
))
}
None => {
return Err(Error::from_str(
StatusCode::BadRequest,
format!("missing url scheme"),
))
}
};
let mut request = hyper::Request::builder();
// UNWRAP: Default builder is safe
let req_headers = request.headers_mut().unwrap();
for (name, values) in &value {
// UNWRAP: http-types and http have equivalent validation rules
let name = hyper::header::HeaderName::from_str(name.as_str()).unwrap();
for value in values.iter() {
// UNWRAP: http-types and http have equivalent validation rules
let value =
hyper::header::HeaderValue::from_bytes(value.as_str().as_bytes()).unwrap();
req_headers.append(&name, value);
}
}
let body = value.body_bytes().await?;
let body = hyper::Body::from(body);
let request = request
.method(value.method())
.version(value.version().map(|v| v.into()).unwrap_or_default())
.uri(uri)
.body(body)?;
Ok(HyperHttpRequest(request))
}
fn into_inner(self) -> hyper::Request<hyper::Body> {
self.0
}
}
struct HttpTypesResponse(Response);
impl HttpTypesResponse {
async fn try_from(value: hyper::Response<hyper::Body>) -> Result<Self, Error> {
let (parts, body) = value.into_parts();
let size_hint = body.size_hint().upper().map(|s| s as usize);
let body = TryStreamExt::map_err(body, |err| {
io::Error::new(io::ErrorKind::Other, err.to_string())
});
let body = http_types::Body::from_reader(body.into_async_read(), size_hint);
let mut res = Response::new(parts.status);
res.set_version(Some(parts.version.into()));
for (name, value) in parts.headers {
let value = value.as_bytes().to_owned();
let value = HeaderValue::from_bytes(value)?;
if let Some(name) = name {
let name = name.as_str();
let name = HeaderName::from_str(name)?;
res.append_header(name, value);
}
}
res.set_body(body);
Ok(HttpTypesResponse(res))
}
fn into_inner(self) -> Response {
self.0
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use hyper0_14 as hyper;
use tokio1 as tokio;
use http_types::{Method, Request, Url};
use hyper::service::{make_service_fn, service_fn};
use tokio::sync::oneshot::channel;
use super::HyperClient;
use crate::{Error, HttpClient};
async fn echo(
req: hyper::Request<hyper::Body>,
) -> Result<hyper::Response<hyper::Body>, hyper::Error> {
Ok(hyper::Response::new(req.into_body()))
}
#[tokio::test]
async fn basic_functionality() {
let (send, recv) = channel::<()>();
let recv = async move { recv.await.unwrap_or(()) };
let addr = ([127, 0, 0, 1], portpicker::pick_unused_port().unwrap()).into();
let service = make_service_fn(|_| async { Ok::<_, hyper::Error>(service_fn(echo)) });
let server = hyper::Server::bind(&addr)
.serve(service)
.with_graceful_shutdown(recv);
let client = HyperClient::new();
let url = Url::parse(&format!("http://localhost:{}", addr.port())).unwrap();
let mut req = Request::new(Method::Get, url);
req.set_body("hello");
let client = async move {
tokio::time::sleep(Duration::from_millis(100)).await;
let mut resp = client.send(req).await?;
send.send(()).unwrap();
assert_eq!(resp.body_string().await?, "hello");
Result::<(), Error>::Ok(())
};
let (client_res, server_res) = tokio::join!(client, server);
assert!(client_res.is_ok());
assert!(server_res.is_ok());
}
}