Skip to main content

ntex_util/services/
timeout.rs

1//! Service that applies a timeout to request execution.
2//!
3//! If a service call does not complete within the configured timeout, its
4//! future is dropped and [`TimeoutError::Timeout`] is returned.
5//! If both complete during the same poll, the service result wins.
6//!
7//! The timeout covers execution only. The clock starts when the wrapped service
8//! is called, after the pipeline has waited for readiness. Waiting for a busy or
9//! never-ready service is not bounded by this timeout, because readiness is a
10//! gate shared by all callers rather than part of one request. To bound the
11//! whole operation, including the readiness wait, wrap the pipeline call:
12//!
13//! ```rust
14//! use ntex_service::Pipeline;
15//! use ntex_util::time::{Millis, timeout};
16//!
17//! async fn call_with_deadline(
18//!     pl: &Pipeline<u32, u32, std::io::Error>,
19//! ) -> Option<Result<u32, std::io::Error>> {
20//!     // `Err(())` from `timeout` means the deadline elapsed
21//!     timeout(Millis(500), pl.call(1)).await.ok()
22//! }
23//! ```
24use std::{fmt, marker::PhantomData};
25
26use ntex_service::{Ctx, IntoService, Middleware, Service};
27
28use crate::time::{Millis, timeout};
29
30/// Applies a timeout to the execution of each request.
31///
32/// The timeout starts when the wrapped service is called and does not include
33/// the wait for readiness; see the [module docs](self) for bounding the whole
34/// operation. A zero timeout disables the middleware.
35#[derive(Debug)]
36pub struct Timeout<St> {
37    timeout: Millis,
38    _t: PhantomData<St>,
39}
40
41/// Error returned by a timed service call.
42pub enum TimeoutError<E> {
43    /// Error returned by the wrapped service.
44    Service(E),
45    /// The service call exceeded its timeout.
46    ///
47    /// Time spent waiting for readiness before the call does not count.
48    Timeout,
49}
50
51impl<E> From<E> for TimeoutError<E> {
52    fn from(err: E) -> Self {
53        TimeoutError::Service(err)
54    }
55}
56
57impl<E: fmt::Debug> fmt::Debug for TimeoutError<E> {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        match self {
60            TimeoutError::Service(e) => write!(f, "TimeoutError::Service({e:?})"),
61            TimeoutError::Timeout => write!(f, "TimeoutError::Timeout"),
62        }
63    }
64}
65
66impl<E: fmt::Display> fmt::Display for TimeoutError<E> {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        match self {
69            TimeoutError::Service(e) => e.fmt(f),
70            TimeoutError::Timeout => write!(f, "Service call timeout"),
71        }
72    }
73}
74
75impl<E: fmt::Display + fmt::Debug> std::error::Error for TimeoutError<E> {}
76
77impl<E: PartialEq> PartialEq for TimeoutError<E> {
78    fn eq(&self, other: &TimeoutError<E>) -> bool {
79        match self {
80            TimeoutError::Service(e1) => match other {
81                TimeoutError::Service(e2) => e1 == e2,
82                TimeoutError::Timeout => false,
83            },
84            TimeoutError::Timeout => match other {
85                TimeoutError::Service(_) => false,
86                TimeoutError::Timeout => true,
87            },
88        }
89    }
90}
91
92impl<St> Timeout<St> {
93    /// Creates timeout middleware with the specified duration.
94    pub fn new<T: Into<Millis>>(timeout: T) -> Self {
95        Timeout {
96            timeout: timeout.into(),
97            _t: PhantomData,
98        }
99    }
100}
101
102impl<St> Clone for Timeout<St> {
103    fn clone(&self) -> Self {
104        Timeout {
105            timeout: self.timeout,
106            _t: PhantomData,
107        }
108    }
109}
110
111impl<S, St> Middleware<S, St> for Timeout<St> {
112    type Service = TimeoutService<S, St>;
113
114    fn create(&self, _: &St, service: S) -> Self::Service {
115        TimeoutService {
116            service,
117            timeout: self.timeout,
118            st: PhantomData,
119        }
120    }
121}
122
123/// A service that applies a timeout to the execution of each request.
124///
125/// Readiness is forwarded to the wrapped service without a deadline, so a
126/// request waiting for readiness is not timed out; see the
127/// [module docs](self) for bounding the whole operation.
128#[derive(Debug, Clone)]
129pub struct TimeoutService<S, St> {
130    service: S,
131    timeout: Millis,
132    st: PhantomData<St>,
133}
134
135impl<S, St> TimeoutService<S, St> {
136    /// Wraps a service with the specified per-request execution timeout.
137    pub fn new<T, Req>(timeout: T, service: impl IntoService<S, St, Req>) -> Self
138    where
139        T: Into<Millis>,
140        S: Service<St, Req>,
141    {
142        TimeoutService {
143            service: service.into_service(),
144            timeout: timeout.into(),
145            st: PhantomData,
146        }
147    }
148}
149
150impl<S, St, Req> Service<St, Req> for TimeoutService<S, St>
151where
152    S: Service<St, Req>,
153{
154    type Res = S::Res;
155    type Error = TimeoutError<S::Error>;
156
157    async fn call(&self, req: Req, ctx: Ctx<'_, Self, St>) -> Result<S::Res, Self::Error> {
158        if self.timeout.is_zero() {
159            ctx.call(&self.service, req)
160                .await
161                .map_err(TimeoutError::Service)
162        } else {
163            match timeout(self.timeout, ctx.call(&self.service, req)).await {
164                Ok(res) => res.map_err(TimeoutError::Service),
165                Err(()) => Err(TimeoutError::Timeout),
166            }
167        }
168    }
169
170    ntex_service::forward!(St, service, map_err = TimeoutError::Service);
171}
172
173#[cfg(test)]
174mod tests {
175    use std::{cell::Cell, future::pending, rc::Rc, time::Duration};
176
177    use ntex_service::{Pipeline, apply, fn_factory};
178
179    use super::*;
180
181    #[derive(Clone, Debug, PartialEq)]
182    struct SleepService(Duration);
183
184    #[derive(Clone, Debug, PartialEq)]
185    struct SrvError;
186
187    impl fmt::Display for SrvError {
188        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189            write!(f, "SrvError")
190        }
191    }
192
193    impl Service<(), ()> for SleepService {
194        type Res = ();
195        type Error = SrvError;
196
197        async fn call(&self, (): (), _: Ctx<'_, Self>) -> Result<(), SrvError> {
198            crate::time::sleep(self.0).await;
199            Ok::<_, SrvError>(())
200        }
201    }
202
203    /// STATEMENT: A service finishing before its timeout returns success.
204    ///
205    /// HOW:
206    /// - Clone a timeout service whose inner delay is shorter than its deadline.
207    /// - Verify a successful call and readiness, then complete shutdown.
208    #[ntex::test]
209    async fn test_success() {
210        let resolution = Duration::from_millis(100);
211        let wait_time = Duration::from_millis(50);
212
213        let timeout = Pipeline::new(
214            (),
215            TimeoutService::new(resolution, SleepService(wait_time)).clone(),
216        );
217        assert_eq!(timeout.call(()).await, Ok(()));
218        assert_eq!(timeout.ready().await, Ok(()));
219        timeout.shutdown().await;
220    }
221
222    /// STATEMENT: A zero timeout disables the deadline rather than rejecting delayed calls.
223    ///
224    /// HOW:
225    /// - Wrap a sleeping service with a zero timeout and verify its call and readiness succeed.
226    #[ntex::test]
227    async fn test_zero() {
228        let wait_time = Duration::from_millis(50);
229        let resolution = Duration::from_millis(0);
230
231        let timeout = Pipeline::new((), TimeoutService::new(resolution, SleepService(wait_time)));
232        assert_eq!(timeout.call(()).await, Ok(()));
233        assert_eq!(timeout.ready().await, Ok(()));
234    }
235
236    /// STATEMENT: Calls of a ready service exceeding their deadline return `TimeoutError::Timeout`.
237    ///
238    /// HOW:
239    /// - Give an always-ready sleeping service a shorter timeout and compare the returned error.
240    #[ntex::test]
241    async fn test_timeout() {
242        let resolution = Duration::from_millis(100);
243        let wait_time = Duration::from_millis(500);
244
245        let timeout = Pipeline::new((), TimeoutService::new(resolution, SleepService(wait_time)));
246        assert_eq!(timeout.call(()).await, Err(TimeoutError::Timeout));
247    }
248
249    struct GatedService {
250        ready_delay: Option<Duration>,
251        calls: Rc<Cell<usize>>,
252    }
253
254    impl Service<(), ()> for GatedService {
255        type Res = ();
256        type Error = SrvError;
257
258        async fn ready(&self, _: Ctx<'_, Self>) -> Result<(), SrvError> {
259            match self.ready_delay {
260                Some(delay) => crate::time::sleep(delay).await,
261                None => pending().await,
262            }
263            Ok(())
264        }
265
266        async fn call(&self, (): (), _: Ctx<'_, Self>) -> Result<(), SrvError> {
267            self.calls.set(self.calls.get() + 1);
268            Ok(())
269        }
270    }
271
272    /// STATEMENT: The execution timeout does not include the wait for readiness.
273    ///
274    /// HOW:
275    /// - Wrap a service that becomes ready after 100 ms and answers immediately with a 10 ms timeout.
276    /// - Verify the pipeline call succeeds instead of returning `TimeoutError::Timeout`.
277    /// - Check the wrapped service was called once and at least 100 ms elapsed.
278    #[ntex::test]
279    async fn test_timeout_excludes_readiness() {
280        let calls = Rc::new(Cell::new(0));
281        let srv = GatedService {
282            ready_delay: Some(Duration::from_millis(100)),
283            calls: calls.clone(),
284        };
285        let pl = Pipeline::new((), TimeoutService::new(Millis(10), srv));
286
287        let start = std::time::Instant::now();
288        assert_eq!(pl.call(()).await, Ok(()));
289        assert_eq!(calls.get(), 1);
290        assert!(start.elapsed() >= Duration::from_millis(100));
291    }
292
293    /// STATEMENT: An outer `time::timeout` bounds a pipeline call whose service never becomes ready.
294    ///
295    /// HOW:
296    /// - Wrap a never-ready service with a 1 ms execution timeout.
297    /// - Bound `Pipeline::call` with a 100 ms `time::timeout` and verify it elapses with `Err(())`.
298    /// - Check the wrapped service was never called.
299    #[ntex::test]
300    async fn test_outer_timeout_bounds_readiness() {
301        let calls = Rc::new(Cell::new(0));
302        let srv = GatedService {
303            ready_delay: None,
304            calls: calls.clone(),
305        };
306        let pl = Pipeline::new((), TimeoutService::new(Millis(1), srv));
307
308        assert_eq!(timeout(Millis(100), pl.call(())).await, Err(()));
309        assert_eq!(calls.get(), 0);
310    }
311
312    /// STATEMENT: Factory-applied timeout middleware enforces its configured deadline.
313    ///
314    /// HOW:
315    /// - Apply cloned timeout middleware to a factory producing a slower service.
316    /// - Create its pipeline and verify the call returns the timeout variant.
317    #[ntex::test]
318    #[allow(clippy::redundant_clone)]
319    async fn test_timeout_middleware() {
320        let resolution = Duration::from_millis(100);
321        let wait_time = Duration::from_millis(500);
322
323        let timeout = apply(
324            Timeout::new(resolution).clone(),
325            fn_factory(async move |()| Ok::<_, ()>(SleepService(wait_time))),
326        );
327        let srv = timeout.pipeline(()).await.unwrap();
328
329        let res = srv.call(()).await.unwrap_err();
330        assert_eq!(res, TimeoutError::Timeout);
331    }
332
333    /// STATEMENT: Timeout errors distinguish elapsed deadlines from wrapped service errors.
334    ///
335    /// HOW:
336    /// - Format a timeout variant and a converted service error.
337    /// - Check their debug variants and human-readable messages.
338    #[test]
339    fn test_error() {
340        let err1 = TimeoutError::<SrvError>::Timeout;
341        assert!(format!("{err1:?}").contains("TimeoutError::Timeout"));
342        assert!(format!("{err1}").contains("Service call timeout"));
343
344        let err2: TimeoutError<_> = SrvError.into();
345        assert!(format!("{err2:?}").contains("TimeoutError::Service"));
346        assert!(format!("{err2}").contains("SrvError"));
347    }
348
349    /// STATEMENT: Timeout-error equality compares both the variant and any service error.
350    ///
351    /// HOW:
352    /// - Compare matching and differing service errors, mixed variants, and two timeout variants.
353    #[test]
354    fn timeout_error_eq() {
355        assert_eq!(TimeoutError::Service(1), TimeoutError::Service(1));
356        assert_ne!(TimeoutError::Service(1), TimeoutError::Service(2));
357        assert_ne!(TimeoutError::Service(1), TimeoutError::Timeout);
358        assert_ne!(TimeoutError::Timeout, TimeoutError::Service(1));
359        assert_eq!(TimeoutError::<u8>::Timeout, TimeoutError::Timeout);
360    }
361}