Skip to main content

rust_web_server/timeout/
mod.rs

1//! Per-route request timeouts.
2//!
3//! A single global read timeout (30 s per connection, or `RWS_CONFIG_*`)
4//! applies uniformly to every route today. A file-upload endpoint may
5//! legitimately need 120 s while a health check must complete in 500 ms —
6//! there's no way to express that difference without wrapping a handler
7//! yourself. This module provides that wrapping.
8//!
9//! # Honest limitation: Rust cannot preempt a running synchronous call
10//!
11//! For synchronous handlers (`Router`, `AppWithState`, plain `Application`s),
12//! there is no safe way to forcibly stop a thread that's already running.
13//! [`with_timeout`], [`with_timeout_state`], and [`TimeoutLayer`] all run the
14//! wrapped work on a background thread and bound how long they *wait* for
15//! it — if the deadline passes, the caller gets a `504 Gateway Timeout`
16//! response immediately, but the background thread keeps running to
17//! completion (its result is simply discarded). This bounds the **client's**
18//! wait time, not the handler's actual resource usage.
19//!
20//! For genuine cancellation, use [`with_timeout_async`] with
21//! `AsyncAppWithState` (requires the `http2` feature): dropping a `Future`
22//! that hasn't finished actually stops its execution at the next `.await`
23//! point, backed by `tokio::time::timeout`.
24//!
25//! # Example — `Router`
26//!
27//! ```rust,no_run
28//! use rust_web_server::router::Router;
29//! use rust_web_server::timeout::with_timeout;
30//! use rust_web_server::response::Response;
31//! use rust_web_server::core::New;
32//! use std::time::Duration;
33//!
34//! let router = Router::new()
35//!     .get("/healthz", with_timeout(Duration::from_millis(500), |_req, _params, _conn| Response::new()))
36//!     .post("/upload", with_timeout(Duration::from_secs(120), |_req, _params, _conn| Response::new()));
37//! ```
38//!
39//! # Example — wrapping a whole `Application`
40//!
41//! ```rust,no_run
42//! use rust_web_server::app::App;
43//! use rust_web_server::core::New;
44//! use rust_web_server::timeout::TimeoutLayer;
45//! use std::time::Duration;
46//!
47//! let app = TimeoutLayer::new(App::new(), Duration::from_secs(5));
48//! ```
49
50#[cfg(test)]
51mod tests;
52
53use std::sync::mpsc;
54use std::sync::Arc;
55use std::thread;
56use std::time::Duration;
57
58use crate::application::Application;
59use crate::request::Request;
60use crate::response::{Response, STATUS_CODE_REASON_PHRASE};
61use crate::router::PathParams;
62use crate::server::ConnectionInfo;
63
64/// Runs `compute` on a detached background thread. Returns `Some(result)` if
65/// it finishes within `duration`, `None` otherwise — in which case the
66/// thread keeps running to completion; its result is dropped when it
67/// eventually sends on the (by-then-abandoned) channel.
68fn run_with_timeout<T, F>(duration: Duration, compute: F) -> Option<T>
69where
70    T: Send + 'static,
71    F: FnOnce() -> T + Send + 'static,
72{
73    let (tx, rx) = mpsc::channel();
74    thread::spawn(move || {
75        let _ = tx.send(compute());
76    });
77    rx.recv_timeout(duration).ok()
78}
79
80fn timeout_response() -> Response {
81    crate::error::problem(STATUS_CODE_REASON_PHRASE.n504_gateway_timeout, "")
82}
83
84/// Wraps a stateless handler (the `Router` handler signature) so it must
85/// complete within `duration` or the caller gets `504 Gateway Timeout`
86/// instead of waiting further. See the [module docs](self) for the
87/// cancellation caveat.
88pub fn with_timeout<F>(
89    duration: Duration,
90    handler: F,
91) -> impl Fn(&Request, &PathParams, &ConnectionInfo) -> Response + Send + Sync + 'static
92where
93    F: Fn(&Request, &PathParams, &ConnectionInfo) -> Response + Send + Sync + 'static,
94{
95    let handler = Arc::new(handler);
96    move |req, params, conn| {
97        let handler = Arc::clone(&handler);
98        let req = req.clone();
99        let params = params.clone();
100        let conn = conn.clone();
101        run_with_timeout(duration, move || handler(&req, &params, &conn))
102            .unwrap_or_else(timeout_response)
103    }
104}
105
106/// Wraps an `AppWithState<S>` handler (which additionally receives `&S`) so
107/// it must complete within `duration` or the caller gets `504 Gateway
108/// Timeout` instead of waiting further.
109///
110/// Requires `S: Clone` — the wrapped call runs on a background thread that
111/// needs its own owned copy of the state, since the handler signature only
112/// gives a borrowed `&S`. Most `AppWithState` state types hold their own
113/// data behind `Arc` internally and are cheap to `#[derive(Clone)]`; if
114/// yours isn't, wrap the whole app with [`TimeoutLayer`] instead, or switch
115/// the route to `AsyncAppWithState` and use [`with_timeout_async`], which
116/// needs no `Clone` bound at all.
117pub fn with_timeout_state<S, F>(
118    duration: Duration,
119    handler: F,
120) -> impl Fn(&Request, &PathParams, &ConnectionInfo, &S) -> Response + Send + Sync + 'static
121where
122    S: Clone + Send + Sync + 'static,
123    F: Fn(&Request, &PathParams, &ConnectionInfo, &S) -> Response + Send + Sync + 'static,
124{
125    let handler = Arc::new(handler);
126    move |req, params, conn, state: &S| {
127        let handler = Arc::clone(&handler);
128        let req = req.clone();
129        let params = params.clone();
130        let conn = conn.clone();
131        let state = state.clone();
132        run_with_timeout(duration, move || handler(&req, &params, &conn, &state))
133            .unwrap_or_else(timeout_response)
134    }
135}
136
137/// Wraps any owned [`Application`] (or a shared `Arc<dyn Application>`) so
138/// every request through it must complete within `duration` or the client
139/// gets `504 Gateway Timeout` instead of waiting further.
140///
141/// Use this to put one blanket timeout around an entire `App`/`AppWithState`/
142/// custom `Application`. For different timeouts on different routes within
143/// the same app, use [`with_timeout`] / [`with_timeout_state`] /
144/// [`with_timeout_async`] on individual handlers instead.
145pub struct TimeoutLayer<A: ?Sized> {
146    inner: Arc<A>,
147    duration: Duration,
148}
149
150impl<A: Application + Send + Sync + 'static> TimeoutLayer<A> {
151    /// Wrap an owned application.
152    pub fn new(inner: A, duration: Duration) -> Self {
153        TimeoutLayer { inner: Arc::new(inner), duration }
154    }
155}
156
157impl<A: Application + Send + Sync + ?Sized + 'static> TimeoutLayer<A> {
158    /// Wrap an already-shared application (e.g. `Arc<dyn Application + Send + Sync>`).
159    pub fn from_arc(inner: Arc<A>, duration: Duration) -> Self {
160        TimeoutLayer { inner, duration }
161    }
162}
163
164impl<A: Application + Send + Sync + ?Sized + 'static> Application for TimeoutLayer<A> {
165    fn execute(&self, request: &Request, connection: &ConnectionInfo) -> Result<Response, String> {
166        let inner = Arc::clone(&self.inner);
167        let request = request.clone();
168        let connection = connection.clone();
169        match run_with_timeout(self.duration, move || inner.execute(&request, &connection)) {
170            Some(result) => result,
171            None => Ok(timeout_response()),
172        }
173    }
174}
175
176#[cfg(feature = "http2")]
177mod async_timeout {
178    use std::future::Future;
179    use std::pin::Pin;
180    use std::sync::Arc;
181    use std::time::Duration;
182
183    use crate::request::Request;
184    use crate::response::Response;
185    use crate::router::PathParams;
186    use crate::server::ConnectionInfo;
187
188    type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send + 'static>>;
189
190    /// Wraps an `AsyncAppWithState<S>` handler so its future is dropped —
191    /// genuinely cancelled at its next `.await` point — if it doesn't
192    /// resolve within `duration`. Backed by `tokio::time::timeout`; requires
193    /// the `http2` feature. No `Clone` bound on `S`: `AsyncAppWithState`
194    /// already passes state as an owned `Arc<S>`.
195    pub fn with_timeout_async<S, F, Fut>(
196        duration: Duration,
197        handler: F,
198    ) -> impl Fn(Request, PathParams, ConnectionInfo, Arc<S>) -> BoxFuture<Response> + Send + Sync + 'static
199    where
200        S: Send + Sync + 'static,
201        F: Fn(Request, PathParams, ConnectionInfo, Arc<S>) -> Fut + Send + Sync + 'static,
202        Fut: Future<Output = Response> + Send + 'static,
203    {
204        move |req, params, conn, state| {
205            let fut = handler(req, params, conn, state);
206            Box::pin(async move {
207                match tokio::time::timeout(duration, fut).await {
208                    Ok(response) => response,
209                    Err(_) => super::timeout_response(),
210                }
211            })
212        }
213    }
214}
215
216#[cfg(feature = "http2")]
217pub use async_timeout::with_timeout_async;