Skip to content

Commit

Permalink
Merge pull request #50 from adamreichold/bring-back-timeout-check
Browse files Browse the repository at this point in the history
Make sure to timeouts do not look like normal EOF.
  • Loading branch information
sbstp authored Jan 29, 2020
2 parents 42267de + 343422e commit a2ebd9b
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
17 changes: 15 additions & 2 deletions src/streams.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ impl BaseStream {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
if let Err(mpsc::RecvTimeoutError::Timeout) = rx.recv_timeout(timeout) {
drop(rx);
let _ = stream.shutdown(Shutdown::Both);
}
});
Expand Down Expand Up @@ -112,9 +113,9 @@ impl Read for BaseStream {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match self {
BaseStream::Plain { stream, .. } => stream.read(buf),
BaseStream::Plain { stream, timeout } => read_timeout(stream, buf, timeout),
#[cfg(feature = "tls")]
BaseStream::Tls { stream, .. } => stream.read(buf),
BaseStream::Tls { stream, timeout } => read_timeout(stream, buf, timeout),
#[cfg(test)]
BaseStream::Mock(s) => s.read(buf),
}
Expand Down Expand Up @@ -144,3 +145,15 @@ impl Write for BaseStream {
}
}
}

fn read_timeout(mut stream: impl Read, buf: &mut [u8], timeout: &Option<mpsc::Sender<()>>) -> io::Result<usize> {
let read = stream.read(buf)?;

if let Some(timeout) = timeout {
if read == 0 && !buf.is_empty() && timeout.send(()).is_err() {
return Err(io::ErrorKind::TimedOut.into());
}
}

Ok(read)
}
2 changes: 1 addition & 1 deletion tests/test_timeout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ fn request_fails_due_to_timeout() {
match result {
Err(err) => match err.kind() {
attohttpc::ErrorKind::Io(err) => match err.kind() {
io::ErrorKind::UnexpectedEof => (),
io::ErrorKind::TimedOut => (),
err => panic!("Unexpected I/O error: {:?}", err),
},
err => panic!("Unexpected error: {:?}", err),
Expand Down

0 comments on commit a2ebd9b

Please sign in to comment.