Skip to content

Commit fe1578a

Browse files
committed
feat(client): update construction of Clients
- `Client::new()` no longer needs a `Handle`, and instead makes use of tokio's implicit default. - Changed `Client::configure()` to `Client::builder()`. - `Builder` is a by-ref builder, since all configuration is now cloneable pieces. BREAKING CHANGE: `Client:new(&handle)` and `Client::configure()` are now `Client::new()` and `Client::builder()`.
1 parent dfdca25 commit fe1578a

File tree

7 files changed

+156
-266
lines changed

7 files changed

+156
-266
lines changed

examples/client.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ fn main() {
3131
}
3232

3333
tokio::run(lazy(move || {
34-
let client = Client::default();
34+
let client = Client::new();
3535

3636
let mut req = Request::new(Body::empty());
3737
*req.uri_mut() = url;

examples/web_api.rs

+5-6
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@ extern crate tokio;
66

77
use futures::{Future, Stream};
88
use futures::future::lazy;
9-
use tokio::reactor::Handle;
109

1110
use hyper::{Body, Chunk, Client, Method, Request, Response, StatusCode};
11+
use hyper::client::HttpConnector;
1212
use hyper::server::{Http, Service};
1313

1414
#[allow(unused, deprecated)]
@@ -19,7 +19,7 @@ static URL: &str = "http://127.0.0.1:1337/web_api";
1919
static INDEX: &[u8] = b"<a href=\"test.html\">test.html</a>";
2020
static LOWERCASE: &[u8] = b"i am a lower case string";
2121

22-
struct ResponseExamples(Handle);
22+
struct ResponseExamples(Client<HttpConnector>);
2323

2424
impl Service for ResponseExamples {
2525
type Request = Request<Body>;
@@ -35,13 +35,12 @@ impl Service for ResponseExamples {
3535
},
3636
(&Method::GET, "/test.html") => {
3737
// Run a web query against the web api below
38-
let client = Client::configure().build(&self.0);
3938
let req = Request::builder()
4039
.method(Method::POST)
4140
.uri(URL)
4241
.body(LOWERCASE.into())
4342
.unwrap();
44-
let web_res_future = client.request(req);
43+
let web_res_future = self.0.request(req);
4544

4645
Box::new(web_res_future.map(|web_res| {
4746
let body = Body::wrap_stream(web_res.into_body().map(|b| {
@@ -79,8 +78,8 @@ fn main() {
7978
let addr = "127.0.0.1:1337".parse().unwrap();
8079

8180
tokio::run(lazy(move || {
82-
let handle = Handle::current();
83-
let serve = Http::new().serve_addr(&addr, move || Ok(ResponseExamples(handle.clone()))).unwrap();
81+
let client = Client::new();
82+
let serve = Http::new().serve_addr(&addr, move || Ok(ResponseExamples(client.clone()))).unwrap();
8483
println!("Listening on http://{} with 1 thread.", serve.incoming_ref().local_addr());
8584

8685
serve.map_err(|_| ()).for_each(move |conn| {

src/client/connect.rs

+41-33
Original file line numberDiff line numberDiff line change
@@ -135,26 +135,30 @@ impl Connected {
135135
*/
136136
}
137137

138-
fn connect(addr: &SocketAddr, handle: &Handle) -> io::Result<ConnectFuture> {
139-
let builder = match addr {
140-
&SocketAddr::V4(_) => TcpBuilder::new_v4()?,
141-
&SocketAddr::V6(_) => TcpBuilder::new_v6()?,
142-
};
143-
144-
if cfg!(windows) {
145-
// Windows requires a socket be bound before calling connect
146-
let any: SocketAddr = match addr {
147-
&SocketAddr::V4(_) => {
148-
([0, 0, 0, 0], 0).into()
149-
},
150-
&SocketAddr::V6(_) => {
151-
([0, 0, 0, 0, 0, 0, 0, 0], 0).into()
152-
}
138+
fn connect(addr: &SocketAddr, handle: &Option<Handle>) -> io::Result<ConnectFuture> {
139+
if let Some(ref handle) = *handle {
140+
let builder = match addr {
141+
&SocketAddr::V4(_) => TcpBuilder::new_v4()?,
142+
&SocketAddr::V6(_) => TcpBuilder::new_v6()?,
153143
};
154-
builder.bind(any)?;
155-
}
156144

157-
Ok(TcpStream::connect_std(builder.to_tcp_stream()?, addr, handle))
145+
if cfg!(windows) {
146+
// Windows requires a socket be bound before calling connect
147+
let any: SocketAddr = match addr {
148+
&SocketAddr::V4(_) => {
149+
([0, 0, 0, 0], 0).into()
150+
},
151+
&SocketAddr::V6(_) => {
152+
([0, 0, 0, 0, 0, 0, 0, 0], 0).into()
153+
}
154+
};
155+
builder.bind(any)?;
156+
}
157+
158+
Ok(TcpStream::connect_std(builder.to_tcp_stream()?, addr, handle))
159+
} else {
160+
Ok(TcpStream::connect(addr))
161+
}
158162
}
159163

160164
/// A connector for the `http` scheme.
@@ -164,7 +168,7 @@ fn connect(addr: &SocketAddr, handle: &Handle) -> io::Result<ConnectFuture> {
164168
pub struct HttpConnector {
165169
executor: HttpConnectExecutor,
166170
enforce_http: bool,
167-
handle: Handle,
171+
handle: Option<Handle>,
168172
keep_alive_timeout: Option<Duration>,
169173
}
170174

@@ -173,7 +177,16 @@ impl HttpConnector {
173177
///
174178
/// Takes number of DNS worker threads.
175179
#[inline]
176-
pub fn new(threads: usize, handle: &Handle) -> HttpConnector {
180+
pub fn new(threads: usize) -> HttpConnector {
181+
HttpConnector::new_with_handle_opt(threads, None)
182+
}
183+
184+
/// Construct a new HttpConnector with a specific Tokio handle.
185+
pub fn new_with_handle(threads: usize, handle: Handle) -> HttpConnector {
186+
HttpConnector::new_with_handle_opt(threads, Some(handle))
187+
}
188+
189+
fn new_with_handle_opt(threads: usize, handle: Option<Handle>) -> HttpConnector {
177190
let pool = CpuPoolBuilder::new()
178191
.name_prefix("hyper-dns")
179192
.pool_size(threads)
@@ -184,14 +197,13 @@ impl HttpConnector {
184197
/// Construct a new HttpConnector.
185198
///
186199
/// Takes an executor to run blocking tasks on.
187-
#[inline]
188-
pub fn new_with_executor<E: 'static>(executor: E, handle: &Handle) -> HttpConnector
200+
pub fn new_with_executor<E: 'static>(executor: E, handle: Option<Handle>) -> HttpConnector
189201
where E: Executor<HttpConnectorBlockingTask> + Send + Sync
190202
{
191203
HttpConnector {
192204
executor: HttpConnectExecutor(Arc::new(executor)),
193205
enforce_http: true,
194-
handle: handle.clone(),
206+
handle,
195207
keep_alive_timeout: None,
196208
}
197209
}
@@ -257,7 +269,7 @@ impl Connect for HttpConnector {
257269
}
258270

259271
#[inline]
260-
fn invalid_url(err: InvalidUrl, handle: &Handle) -> HttpConnecting {
272+
fn invalid_url(err: InvalidUrl, handle: &Option<Handle>) -> HttpConnecting {
261273
HttpConnecting {
262274
state: State::Error(Some(io::Error::new(io::ErrorKind::InvalidInput, err))),
263275
handle: handle.clone(),
@@ -292,7 +304,7 @@ impl StdError for InvalidUrl {
292304
#[must_use = "futures do nothing unless polled"]
293305
pub struct HttpConnecting {
294306
state: State,
295-
handle: Handle,
307+
handle: Option<Handle>,
296308
keep_alive_timeout: Option<Duration>,
297309
}
298310

@@ -365,7 +377,7 @@ struct ConnectingTcp {
365377

366378
impl ConnectingTcp {
367379
// not a Future, since passing a &Handle to poll
368-
fn poll(&mut self, handle: &Handle) -> Poll<TcpStream, io::Error> {
380+
fn poll(&mut self, handle: &Option<Handle>) -> Poll<TcpStream, io::Error> {
369381
let mut err = None;
370382
loop {
371383
if let Some(ref mut current) = self.current {
@@ -431,42 +443,38 @@ mod tests {
431443
#![allow(deprecated)]
432444
use std::io;
433445
use futures::Future;
434-
use tokio::runtime::Runtime;
435446
use super::{Connect, Destination, HttpConnector};
436447

437448
#[test]
438449
fn test_errors_missing_authority() {
439-
let runtime = Runtime::new().unwrap();
440450
let uri = "/foo/bar?baz".parse().unwrap();
441451
let dst = Destination {
442452
uri,
443453
};
444-
let connector = HttpConnector::new(1, runtime.handle());
454+
let connector = HttpConnector::new(1);
445455

446456
assert_eq!(connector.connect(dst).wait().unwrap_err().kind(), io::ErrorKind::InvalidInput);
447457
}
448458

449459
#[test]
450460
fn test_errors_enforce_http() {
451-
let runtime = Runtime::new().unwrap();
452461
let uri = "https://example.domain/foo/bar?baz".parse().unwrap();
453462
let dst = Destination {
454463
uri,
455464
};
456-
let connector = HttpConnector::new(1, runtime.handle());
465+
let connector = HttpConnector::new(1);
457466

458467
assert_eq!(connector.connect(dst).wait().unwrap_err().kind(), io::ErrorKind::InvalidInput);
459468
}
460469

461470

462471
#[test]
463472
fn test_errors_missing_scheme() {
464-
let runtime = Runtime::new().unwrap();
465473
let uri = "example.domain".parse().unwrap();
466474
let dst = Destination {
467475
uri,
468476
};
469-
let connector = HttpConnector::new(1, runtime.handle());
477+
let connector = HttpConnector::new(1);
470478

471479
assert_eq!(connector.connect(dst).wait().unwrap_err().kind(), io::ErrorKind::InvalidInput);
472480
}

0 commit comments

Comments
 (0)