1use std::{fmt, marker::PhantomData};
25
26use ntex_service::{Ctx, IntoService, Middleware, Service};
27
28use crate::time::{Millis, timeout};
29
30#[derive(Debug)]
36pub struct Timeout<St> {
37 timeout: Millis,
38 _t: PhantomData<St>,
39}
40
41pub enum TimeoutError<E> {
43 Service(E),
45 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 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#[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 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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}