Skip to content

Commit 44af273

Browse files
committed
fix(client): check for dead connections in Pool
Closes #1429
1 parent a3f87c0 commit 44af273

File tree

3 files changed

+114
-18
lines changed

3 files changed

+114
-18
lines changed

src/client/mod.rs

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -221,10 +221,26 @@ where C: Connect,
221221
e.into()
222222
});
223223

224-
let resp = race.and_then(move |mut client| {
224+
let resp = race.and_then(move |client| {
225+
use proto::dispatch::ClientMsg;
226+
225227
let (callback, rx) = oneshot::channel();
226-
client.tx.borrow_mut().start_send(proto::dispatch::ClientMsg::Request(head, body, callback)).unwrap();
227-
client.should_close = false;
228+
229+
match client.tx.borrow_mut().start_send(ClientMsg::Request(head, body, callback)) {
230+
Ok(_) => (),
231+
Err(e) => match e.into_inner() {
232+
ClientMsg::Request(_, _, callback) => {
233+
error!("pooled connection was not ready, this is a hyper bug");
234+
let err = io::Error::new(
235+
io::ErrorKind::BrokenPipe,
236+
"pool selected dead connection",
237+
);
238+
let _ = callback.send(Err(::Error::Io(err)));
239+
},
240+
_ => unreachable!("ClientMsg::Request was just sent"),
241+
}
242+
}
243+
228244
rx.then(|res| {
229245
match res {
230246
Ok(Ok(res)) => Ok(res),
@@ -256,8 +272,8 @@ impl<C, B> fmt::Debug for Client<C, B> {
256272
}
257273

258274
struct HyperClient<B> {
259-
tx: RefCell<::futures::sync::mpsc::Sender<proto::dispatch::ClientMsg<B>>>,
260275
should_close: bool,
276+
tx: RefCell<::futures::sync::mpsc::Sender<proto::dispatch::ClientMsg<B>>>,
261277
}
262278

263279
impl<B> Clone for HyperClient<B> {
@@ -269,6 +285,15 @@ impl<B> Clone for HyperClient<B> {
269285
}
270286
}
271287

288+
impl<B> self::pool::Ready for HyperClient<B> {
289+
fn poll_ready(&mut self) -> Poll<(), ()> {
290+
self.tx
291+
.borrow_mut()
292+
.poll_ready()
293+
.map_err(|_| ())
294+
}
295+
}
296+
272297
impl<B> Drop for HyperClient<B> {
273298
fn drop(&mut self) {
274299
if self.should_close {
@@ -497,3 +522,4 @@ mod background {
497522
}
498523
}
499524
}
525+

src/client/pool.rs

Lines changed: 30 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,15 @@ pub struct Pool<T> {
1515
inner: Rc<RefCell<PoolInner<T>>>,
1616
}
1717

18+
// Before using a pooled connection, make sure the sender is not dead.
19+
//
20+
// This is a trait to allow the `client::pool::tests` to work for `i32`.
21+
//
22+
// See https://github.com/hyperium/hyper/issues/1429
23+
pub trait Ready {
24+
fn poll_ready(&mut self) -> Poll<(), ()>;
25+
}
26+
1827
struct PoolInner<T> {
1928
enabled: bool,
2029
// These are internal Conns sitting in the event loop in the KeepAlive
@@ -256,7 +265,7 @@ pub struct Checkout<T> {
256265
parked: Option<relay::Receiver<Entry<T>>>,
257266
}
258267

259-
impl<T: Clone> Future for Checkout<T> {
268+
impl<T: Ready + Clone> Future for Checkout<T> {
260269
type Item = Pooled<T>;
261270
type Error = io::Error;
262271

@@ -282,21 +291,22 @@ impl<T: Clone> Future for Checkout<T> {
282291
let mut should_remove = false;
283292
let entry = self.pool.inner.borrow_mut().idle.get_mut(key).and_then(|list| {
284293
trace!("Checkout::poll key found {:?}", key);
285-
while let Some(entry) = list.pop() {
294+
while let Some(mut entry) = list.pop() {
286295
match entry.status.get() {
287296
TimedKA::Idle(idle_at) if !expiration.expires(idle_at) => {
288-
debug!("found idle connection for {:?}", key);
289-
should_remove = list.is_empty();
290-
return Some(entry);
297+
if let Ok(Async::Ready(())) = entry.value.poll_ready() {
298+
debug!("found idle connection for {:?}", key);
299+
should_remove = list.is_empty();
300+
return Some(entry);
301+
}
291302
},
292-
_ => {
293-
trace!("Checkout::poll removing unacceptable pooled {:?}", key);
294-
// every other case the Entry should just be dropped
295-
// 1. Idle but expired
296-
// 2. Busy (something else somehow took it?)
297-
// 3. Disabled don't reuse of course
298-
}
303+
_ => {},
299304
}
305+
trace!("Checkout::poll removing unacceptable pooled {:?}", key);
306+
// every other case the Entry should just be dropped
307+
// 1. Idle but expired
308+
// 2. Busy (something else somehow took it?)
309+
// 3. Disabled don't reuse of course
300310
}
301311
should_remove = true;
302312
None
@@ -347,10 +357,16 @@ impl Expiration {
347357
mod tests {
348358
use std::rc::Rc;
349359
use std::time::Duration;
350-
use futures::{Async, Future};
360+
use futures::{Async, Future, Poll};
351361
use futures::future;
352362
use proto::KeepAlive;
353-
use super::Pool;
363+
use super::{Ready, Pool};
364+
365+
impl Ready for i32 {
366+
fn poll_ready(&mut self) -> Poll<(), ()> {
367+
Ok(Async::Ready(()))
368+
}
369+
}
354370

355371
#[test]
356372
fn test_pool_checkout_smoke() {

tests/client.rs

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -954,6 +954,60 @@ mod dispatch_impl {
954954
assert_eq!(closes.load(Ordering::Relaxed), 1);
955955
}
956956

957+
#[test]
958+
fn conn_drop_prevents_pool_checkout() {
959+
// a drop might happen for any sort of reason, and we can protect
960+
// against a lot of them, but if the `Core` is dropped, we can't
961+
// really catch that. So, this is case to always check.
962+
//
963+
// See https://github.com/hyperium/hyper/issues/1429
964+
965+
use std::error::Error;
966+
let _ = pretty_env_logger::try_init();
967+
968+
let server = TcpListener::bind("127.0.0.1:0").unwrap();
969+
let addr = server.local_addr().unwrap();
970+
let mut core = Core::new().unwrap();
971+
let handle = core.handle();
972+
973+
let (tx1, rx1) = oneshot::channel();
974+
975+
thread::spawn(move || {
976+
let mut sock = server.accept().unwrap().0;
977+
sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
978+
sock.set_write_timeout(Some(Duration::from_secs(5))).unwrap();
979+
let mut buf = [0; 4096];
980+
sock.read(&mut buf).expect("read 1");
981+
sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").unwrap();
982+
sock.read(&mut buf).expect("read 2");
983+
let _ = tx1.send(());
984+
});
985+
986+
let uri = format!("http://{}/a", addr).parse::<hyper::Uri>().unwrap();
987+
988+
let client = Client::new(&handle);
989+
let res = client.get(uri.clone()).and_then(move |res| {
990+
assert_eq!(res.status(), hyper::StatusCode::Ok);
991+
res.body().concat2()
992+
});
993+
994+
core.run(res).unwrap();
995+
996+
// drop previous Core
997+
core = Core::new().unwrap();
998+
let timeout = Timeout::new(Duration::from_millis(200), &core.handle()).unwrap();
999+
let rx = rx1.map_err(|_| hyper::Error::Io(io::Error::new(io::ErrorKind::Other, "thread panicked")));
1000+
let rx = rx.and_then(move |_| timeout.map_err(|e| e.into()));
1001+
1002+
let res = client.get(uri);
1003+
// this does trigger an 'event loop gone' error, but before, it would
1004+
// panic internally on a `SendError`, which is what we're testing against.
1005+
let err = core.run(res.join(rx).map(|r| r.0)).unwrap_err();
1006+
assert_eq!(err.description(), "event loop gone");
1007+
}
1008+
1009+
1010+
9571011
#[test]
9581012
fn client_custom_executor() {
9591013
let server = TcpListener::bind("127.0.0.1:0").unwrap();

0 commit comments

Comments
 (0)