Skip to content
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

feat(timeout): add a timeout which can also timeout on poll_ready #677

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion tower/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ reconnect = ["make", "tokio/io-std", "tracing"]
retry = ["__common", "tokio/time"]
spawn-ready = ["__common", "futures-util", "tokio/sync", "tokio/rt", "util", "tracing"]
steer = []
timeout = ["pin-project-lite", "tokio/time"]
timeout = ["pin-project-lite", "tokio/time", "futures-core", "tracing"]
util = ["__common", "futures-util", "pin-project-lite"]

[dependencies]
Expand Down
4 changes: 2 additions & 2 deletions tower/src/timeout/future.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@ pin_project! {
#[pin]
response: T,
#[pin]
sleep: Sleep,
sleep: Pin<Box<Sleep>>,
}
}

impl<T> ResponseFuture<T> {
pub(crate) fn new(response: T, sleep: Sleep) -> Self {
pub(crate) fn new(response: T, sleep: Pin<Box<Sleep>>) -> Self {
ResponseFuture { response, sleep }
}
}
Expand Down
25 changes: 24 additions & 1 deletion tower/src/timeout/layer.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use super::Timeout;
use super::{GlobalTimeout, Timeout};
use std::time::Duration;
use tower_layer::Layer;

Expand All @@ -22,3 +22,26 @@ impl<S> Layer<S> for TimeoutLayer {
Timeout::new(service, self.timeout)
}
}

/// Applies a timeout to requests via the supplied inner service (including poll_ready).
/// The main difference with [`TimeoutLayer`] is that we're starting the timeout before the `poll_ready` call of the inner service.
/// Which means you can use it with the `RateLimitLayer` service if you want to abort a rate limited call
#[derive(Debug, Clone)]
pub struct GlobalTimeoutLayer {
timeout: Duration,
}

impl GlobalTimeoutLayer {
/// Create a timeout from a duration
pub fn new(timeout: Duration) -> Self {
GlobalTimeoutLayer { timeout }
}
}

impl<S> Layer<S> for GlobalTimeoutLayer {
type Service = GlobalTimeout<S>;

fn layer(&self, service: S) -> Self::Service {
GlobalTimeout::new(service, self.timeout)
}
}
80 changes: 79 additions & 1 deletion tower/src/timeout/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,17 @@ pub mod error;
pub mod future;
mod layer;

use crate::timeout::error::Elapsed;

pub use self::layer::GlobalTimeoutLayer;
pub use self::layer::TimeoutLayer;

use self::future::ResponseFuture;
use futures_core::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
use tokio::time::Sleep;
use tower_service::Service;

/// Applies a timeout to requests.
Expand Down Expand Up @@ -65,6 +71,78 @@ where
let response = self.inner.call(request);
let sleep = tokio::time::sleep(self.timeout);

ResponseFuture::new(response, sleep)
ResponseFuture::new(response, Box::pin(sleep))
}
}

/// Applies a timeout to requests (including poll_ready).
/// The main difference with [`Timeout`] is that we're starting the timeout before the `poll_ready` call of the inner service.
/// Which means you can use it with the `RateLimit` service if you want to abort a rate limited call
#[derive(Debug)]
pub struct GlobalTimeout<T> {
inner: T,
timeout: Duration,
sleep: Option<Pin<Box<Sleep>>>,
}

// ===== impl GlobalTimeout =====

impl<T> GlobalTimeout<T> {
/// Creates a new [`GlobalTimeout`]
pub fn new(inner: T, timeout: Duration) -> Self {
GlobalTimeout {
inner,
timeout,
sleep: None,
}
}
}

impl<S, Request> Service<Request> for GlobalTimeout<S>
where
S: Service<Request>,
S::Error: Into<crate::BoxError>,
{
type Response = S::Response;
type Error = crate::BoxError;
type Future = ResponseFuture<S::Future>;

fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
if self.sleep.is_none() {
self.sleep = Some(Box::pin(tokio::time::sleep(self.timeout)));
}
match self.inner.poll_ready(cx) {
Poll::Pending => {}
Poll::Ready(r) => return Poll::Ready(r.map_err(Into::into)),
};

// Checking if we don't timeout on `poll_ready`
if Pin::new(
&mut self
.sleep
.as_mut()
.expect("we can unwrap because we set it just before"),
)
.poll(cx)
.is_ready()
{
tracing::trace!("timeout exceeded.");
self.sleep = None;

return Poll::Ready(Err(Elapsed::new().into()));
}

Poll::Pending
}

fn call(&mut self, request: Request) -> Self::Future {
let response = self.inner.call(request);

ResponseFuture::new(
response,
self.sleep
.take()
.expect("poll_ready must been called before"),
)
}
}