tower_async_http/timeout/mod.rs
1//! Middleware that applies a timeout to requests.
2//!
3//! If the request does not complete within the specified timeout it will be aborted and a `408
4//! Request Timeout` response will be sent.
5//!
6//! # Differences from `tower::timeout`
7//!
8//! tower's [`Timeout`](tower_async::timeout::Timeout) middleware uses an error to signal timeout, i.e.
9//! it changes the error type to [`BoxError`](tower_async::BoxError). For HTTP services that is rarely
10//! what you want as returning errors will terminate the connection without sending a response.
11//!
12//! This middleware won't change the error type and instead return a `408 Request Timeout`
13//! response. That means if your service's error type is [`Infallible`] it will still be
14//! [`Infallible`] after applying this middleware.
15//!
16//! # Example
17//!
18//! ```
19//! use http::{Request, Response};
20//! use http_body_util::Full;
21//! use bytes::Bytes;
22//! use std::{convert::Infallible, time::Duration};
23//! use tower_async::ServiceBuilder;
24//! use tower_async_http::timeout::TimeoutLayer;
25//!
26//! async fn handle(_: Request<Full<Bytes>>) -> Result<Response<Full<Bytes>>, Infallible> {
27//! // ...
28//! # Ok(Response::new(Full::default()))
29//! }
30//!
31//! # #[tokio::main]
32//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
33//! let svc = ServiceBuilder::new()
34//! // Timeout requests after 30 seconds
35//! .layer(TimeoutLayer::new(Duration::from_secs(30)))
36//! .service_fn(handle);
37//! # Ok(())
38//! # }
39//! ```
40//!
41//! [`Infallible`]: std::convert::Infallible
42
43mod service;
44
45pub use service::{Timeout, TimeoutLayer};