Skip to content

Add future::timeout() #20

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Aug 30, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ before_script:
- if [[ -n "$BUILD_BOOK" ]]; then (test -x $HOME/.cargo/bin/mdbook || ./ci/install-mdbook.sh); fi

script:
- if ! [[ -n "$BUILD_BOOK" ]]; then cargo check --all --benches --bins --examples --tests && cargo test --all; fi
- if [[ -n "$BUILD_BOOK" ]]; then cargo test --all --benches --bins --examples --tests; fi
- if ! [[ -n "$BUILD_BOOK" ]]; then cargo check --features unstable --all --benches --bins --examples --tests && cargo test --features unstable --all; fi
- if [[ -n "$BUILD_BOOK" ]]; then cargo test --features unstable --all --benches --bins --examples --tests; fi
- cargo fmt --all -- --check
- if [[ -n "$BUILD_DOCS" ]]; then cargo doc --features docs; fi
- if [[ -n "$BUILD_BOOK" ]]; then mdbook build docs && mdbook test -L ./target/debug/deps docs; fi
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ rustdoc-args = ["--cfg", "feature=\"docs\""]

[features]
docs = []
unstable = []

[dependencies]
async-task = "1.0.0"
Expand Down
9 changes: 9 additions & 0 deletions src/future/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,17 @@
#[doc(inline)]
pub use std::future::Future;

use cfg_if::cfg_if;

pub use pending::pending;
pub use ready::ready;

mod pending;
mod ready;

cfg_if! {
if #[cfg(any(feature = "unstable", feature = "docs"))] {
mod timeout;
pub use timeout::{timeout, TimeoutError};
}
}
80 changes: 80 additions & 0 deletions src/future/timeout.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
use std::error::Error;
use std::fmt;
use std::pin::Pin;
use std::time::Duration;

use futures_timer::Delay;

use crate::future::Future;
use crate::task::{Context, Poll};

/// Awaits a future or times out after a duration of time.
///
/// # Examples
///
/// ```
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use std::time::Duration;
///
/// use async_std::future;
///
/// let never = future::pending::<()>();
/// let dur = Duration::from_millis(5);
/// assert!(future::timeout(dur, never).await.is_err());
/// #
/// # Ok(()) }) }
/// ```
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
pub async fn timeout<F, T>(dur: Duration, f: F) -> Result<T, TimeoutError>
where
F: Future<Output = T>,
{
let f = TimeoutFuture {
future: f,
delay: Delay::new(dur),
};
f.await
}

/// A future that times out after a duration of time.
#[doc(hidden)]
#[allow(missing_debug_implementations)]
struct TimeoutFuture<F> {
future: F,
delay: Delay,
}

impl<F> TimeoutFuture<F> {
pin_utils::unsafe_pinned!(future: F);
pin_utils::unsafe_pinned!(delay: Delay);
}

impl<F: Future> Future for TimeoutFuture<F> {
type Output = Result<F::Output, TimeoutError>;

fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match self.as_mut().future().poll(cx) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does it mean that in case of a CPU-bound future that is blocking the current thread you will never try to poll the timer and return TimeoutError?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/cc @stjepang

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kpp That's a good point - do you think we should check for timeout before polling the future?

I worry a bit that this would add overhead to futures that are quick to poll or immediately ready. And if the future is CPU-bound and takes a really long time, we can still get stuck if the timeout occurs while that future is running.

All things considered, I think I prefer the current behavior. Wdyt?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All things considered, I think I prefer the current behavior.

Yep... I don't see a better solution for this.

Still I would rewrite the current implementation as f.select(Delay::new(dur))... ;)

Poll::Ready(v) => Poll::Ready(Ok(v)),
Poll::Pending => match self.delay().poll(cx) {
Poll::Ready(_) => Poll::Ready(Err(TimeoutError { _priv: () })),
Poll::Pending => Poll::Pending,
},
}
}
}

/// An error returned when a future times out.
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TimeoutError {
_priv: (),
}

impl Error for TimeoutError {}

impl fmt::Display for TimeoutError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
"future has timed out".fmt(f)
}
}