1use std::{fmt, marker::PhantomData};
6
7use ntex_service::{Ctx, IntoService, Middleware, Service};
8
9use crate::future::{Either, select};
10use crate::time::{Millis, sleep};
11
12#[derive(Debug)]
16pub struct Timeout<St> {
17 timeout: Millis,
18 _t: PhantomData<St>,
19}
20
21pub enum TimeoutError<E> {
23 Service(E),
25 Timeout,
27}
28
29impl<E> From<E> for TimeoutError<E> {
30 fn from(err: E) -> Self {
31 TimeoutError::Service(err)
32 }
33}
34
35impl<E: fmt::Debug> fmt::Debug for TimeoutError<E> {
36 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37 match self {
38 TimeoutError::Service(e) => write!(f, "TimeoutError::Service({e:?})"),
39 TimeoutError::Timeout => write!(f, "TimeoutError::Timeout"),
40 }
41 }
42}
43
44impl<E: fmt::Display> fmt::Display for TimeoutError<E> {
45 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46 match self {
47 TimeoutError::Service(e) => e.fmt(f),
48 TimeoutError::Timeout => write!(f, "Service call timeout"),
49 }
50 }
51}
52
53impl<E: fmt::Display + fmt::Debug> std::error::Error for TimeoutError<E> {}
54
55impl<E: PartialEq> PartialEq for TimeoutError<E> {
56 fn eq(&self, other: &TimeoutError<E>) -> bool {
57 match self {
58 TimeoutError::Service(e1) => match other {
59 TimeoutError::Service(e2) => e1 == e2,
60 TimeoutError::Timeout => false,
61 },
62 TimeoutError::Timeout => match other {
63 TimeoutError::Service(_) => false,
64 TimeoutError::Timeout => true,
65 },
66 }
67 }
68}
69
70impl<St> Timeout<St> {
71 pub fn new<T: Into<Millis>>(timeout: T) -> Self {
73 Timeout {
74 timeout: timeout.into(),
75 _t: PhantomData,
76 }
77 }
78}
79
80impl<St> Clone for Timeout<St> {
81 fn clone(&self) -> Self {
82 Timeout {
83 timeout: self.timeout,
84 _t: PhantomData,
85 }
86 }
87}
88
89impl<S, St> Middleware<S, St> for Timeout<St> {
90 type Service = TimeoutService<S, St>;
91
92 fn create(&self, _: &St, service: S) -> Self::Service {
93 TimeoutService {
94 service,
95 timeout: self.timeout,
96 st: PhantomData,
97 }
98 }
99}
100
101#[derive(Debug, Clone)]
103pub struct TimeoutService<S, St> {
104 service: S,
105 timeout: Millis,
106 st: PhantomData<St>,
107}
108
109impl<S, St> TimeoutService<S, St> {
110 pub fn new<T, Req>(timeout: T, service: impl IntoService<S, St, Req>) -> Self
112 where
113 T: Into<Millis>,
114 S: Service<St, Req>,
115 {
116 TimeoutService {
117 service: service.into_service(),
118 timeout: timeout.into(),
119 st: PhantomData,
120 }
121 }
122}
123
124impl<S, St, Req> Service<St, Req> for TimeoutService<S, St>
125where
126 S: Service<St, Req>,
127{
128 type Res = S::Res;
129 type Error = TimeoutError<S::Error>;
130
131 async fn call(&self, req: Req, ctx: Ctx<'_, Self, St>) -> Result<S::Res, Self::Error> {
132 if self.timeout.is_zero() {
133 ctx.call(&self.service, req)
134 .await
135 .map_err(TimeoutError::Service)
136 } else {
137 match select(sleep(self.timeout), ctx.call(&self.service, req)).await {
138 Either::Left(()) => Err(TimeoutError::Timeout),
139 Either::Right(res) => res.map_err(TimeoutError::Service),
140 }
141 }
142 }
143
144 ntex_service::forward_ready!(St, service, TimeoutError::Service);
145 ntex_service::forward_shutdown!(St, service);
146}
147
148#[cfg(test)]
149mod tests {
150 use std::time::Duration;
151
152 use ntex_service::{Pipeline, apply, fn_factory};
153
154 use super::*;
155
156 #[derive(Clone, Debug, PartialEq)]
157 struct SleepService(Duration);
158
159 #[derive(Clone, Debug, PartialEq)]
160 struct SrvError;
161
162 impl fmt::Display for SrvError {
163 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164 write!(f, "SrvError")
165 }
166 }
167
168 impl Service<(), ()> for SleepService {
169 type Res = ();
170 type Error = SrvError;
171
172 async fn call(&self, (): (), _: Ctx<'_, Self>) -> Result<(), SrvError> {
173 crate::time::sleep(self.0).await;
174 Ok::<_, SrvError>(())
175 }
176 }
177
178 #[ntex::test]
179 async fn test_success() {
180 let resolution = Duration::from_millis(100);
181 let wait_time = Duration::from_millis(50);
182
183 let timeout = Pipeline::new(
184 (),
185 TimeoutService::new(resolution, SleepService(wait_time)).clone(),
186 );
187 assert_eq!(timeout.call(()).await, Ok(()));
188 assert_eq!(timeout.ready().await, Ok(()));
189 timeout.shutdown().await;
190 }
191
192 #[ntex::test]
193 async fn test_zero() {
194 let wait_time = Duration::from_millis(50);
195 let resolution = Duration::from_millis(0);
196
197 let timeout = Pipeline::new((), TimeoutService::new(resolution, SleepService(wait_time)));
198 assert_eq!(timeout.call(()).await, Ok(()));
199 assert_eq!(timeout.ready().await, Ok(()));
200 }
201
202 #[ntex::test]
203 async fn test_timeout() {
204 let resolution = Duration::from_millis(100);
205 let wait_time = Duration::from_millis(500);
206
207 let timeout = Pipeline::new((), TimeoutService::new(resolution, SleepService(wait_time)));
208 assert_eq!(timeout.call(()).await, Err(TimeoutError::Timeout));
209 }
210
211 #[ntex::test]
212 #[allow(clippy::redundant_clone)]
213 async fn test_timeout_middleware() {
214 let resolution = Duration::from_millis(100);
215 let wait_time = Duration::from_millis(500);
216
217 let timeout = apply(
218 Timeout::new(resolution).clone(),
219 fn_factory(async move |()| Ok::<_, ()>(SleepService(wait_time))),
220 );
221 let srv = timeout.pipeline(()).await.unwrap();
222
223 let res = srv.call(()).await.unwrap_err();
224 assert_eq!(res, TimeoutError::Timeout);
225 }
226
227 #[test]
228 fn test_error() {
229 let err1 = TimeoutError::<SrvError>::Timeout;
230 assert!(format!("{err1:?}").contains("TimeoutError::Timeout"));
231 assert!(format!("{err1}").contains("Service call timeout"));
232
233 let err2: TimeoutError<_> = SrvError.into();
234 assert!(format!("{err2:?}").contains("TimeoutError::Service"));
235 assert!(format!("{err2}").contains("SrvError"));
236 }
237}