Skip to main content

ntex_util/services/
retry.rs

1use ntex_service::{Ctx, Middleware, Service};
2
3/// Determines whether and how a failed service call is retried.
4pub trait Policy<S: Service<St, Req>, St, Req>: Sized + Clone {
5    /// Returns whether the call should be retried.
6    async fn retry(&mut self, req: &Req, res: &Result<S::Res, S::Error>) -> bool;
7
8    /// Clones or reconstructs a request for a possible retry.
9    ///
10    /// Returning `None` prevents retries for this request.
11    fn clone_request(&self, req: &Req) -> Option<Req>;
12}
13
14#[derive(Clone, Debug)]
15/// Middleware that retries service calls according to a [`Policy`].
16///
17/// The policy is cloned for each request.
18pub struct Retry<P> {
19    policy: P,
20}
21
22#[derive(Clone, Debug)]
23/// A service that retries calls according to a [`Policy`].
24pub struct RetryService<P, S> {
25    policy: P,
26    service: S,
27}
28
29impl<P> Retry<P> {
30    /// Creates retry middleware with the specified policy.
31    pub fn new(policy: P) -> Self {
32        Retry { policy }
33    }
34}
35
36impl<P: Clone, S, St> Middleware<S, St> for Retry<P> {
37    type Service = RetryService<P, S>;
38
39    fn create(&self, _: &St, service: S) -> Self::Service {
40        RetryService {
41            service,
42            policy: self.policy.clone(),
43        }
44    }
45}
46
47impl<P, S> RetryService<P, S> {
48    /// Wraps a service with the specified retry policy.
49    pub fn new(policy: P, service: S) -> Self {
50        RetryService { policy, service }
51    }
52}
53
54impl<P, S, St, Req> Service<St, Req> for RetryService<P, S>
55where
56    P: Policy<S, St, Req>,
57    S: Service<St, Req>,
58{
59    type Res = S::Res;
60    type Error = S::Error;
61
62    async fn call(&self, mut req: Req, ctx: Ctx<'_, Self, St>) -> Result<S::Res, S::Error> {
63        let mut policy = self.policy.clone();
64        let mut cloned = policy.clone_request(&req);
65
66        loop {
67            let result = ctx.call(&self.service, req).await;
68
69            cloned = if let Some(r) = cloned.take() {
70                if policy.retry(&r, &result).await {
71                    req = r;
72                    policy.clone_request(&req)
73                } else {
74                    return result;
75                }
76            } else {
77                return result;
78            }
79        }
80    }
81
82    ntex_service::forward_ready!(St, service);
83    ntex_service::forward_shutdown!(St, service);
84}
85
86#[derive(Copy, Clone, Debug)]
87/// A retry policy that retries every service error.
88///
89/// The default policy permits up to three retries after the initial call.
90pub struct DefaultRetryPolicy(u16);
91
92impl DefaultRetryPolicy {
93    /// Creates a policy that permits up to `retry` retries.
94    pub fn new(retry: u16) -> Self {
95        DefaultRetryPolicy(retry)
96    }
97}
98
99impl Default for DefaultRetryPolicy {
100    fn default() -> Self {
101        DefaultRetryPolicy::new(3)
102    }
103}
104
105impl<S, St, Req> Policy<S, St, Req> for DefaultRetryPolicy
106where
107    S: Service<St, Req>,
108    Req: Clone,
109{
110    async fn retry(&mut self, _: &Req, res: &Result<S::Res, S::Error>) -> bool {
111        if res.is_err() {
112            if self.0 == 0 {
113                false
114            } else {
115                self.0 -= 1;
116                true
117            }
118        } else {
119            false
120        }
121    }
122
123    fn clone_request(&self, req: &Req) -> Option<Req> {
124        Some(req.clone())
125    }
126}
127
128#[cfg(test)]
129mod tests {
130    #![allow(clippy::unused_async_trait_impl)]
131    use std::{cell::Cell, rc::Rc};
132
133    use ntex_service::{Pipeline, apply, fn_factory};
134
135    use super::*;
136
137    #[derive(Clone, Debug, PartialEq)]
138    struct TestService(Rc<Cell<usize>>);
139
140    impl Service<(), ()> for TestService {
141        type Res = ();
142        type Error = ();
143
144        async fn call(&self, _r: (), _: Ctx<'_, Self>) -> Result<(), ()> {
145            let cnt = self.0.get();
146            if cnt == 0 {
147                Ok(())
148            } else {
149                self.0.set(cnt - 1);
150                Err(())
151            }
152        }
153    }
154
155    #[ntex::test]
156    async fn test_retry() {
157        let cnt = Rc::new(Cell::new(5));
158        let svc = Pipeline::new(
159            (),
160            RetryService::new(DefaultRetryPolicy::default(), TestService(cnt.clone())).clone(),
161        );
162        assert_eq!(svc.call(()).await, Err(()));
163        assert_eq!(svc.ready().await, Ok(()));
164        svc.shutdown().await;
165        assert_eq!(cnt.get(), 1);
166
167        let factory = apply(
168            Retry::new(DefaultRetryPolicy::new(3)).clone(),
169            fn_factory(|(): &()| async { Ok::<_, ()>(TestService(Rc::new(Cell::new(2)))) }),
170        );
171        let srv = factory.pipeline(()).await.unwrap();
172        assert_eq!(srv.call(()).await, Ok(()));
173
174        let factory = apply(
175            Retry::new(DefaultRetryPolicy::new(3)).clone(),
176            fn_factory(|(): &()| async { Ok::<_, ()>(TestService(Rc::new(Cell::new(2)))) }),
177        );
178        let srv = factory.pipeline(()).await.unwrap();
179        assert_eq!(srv.call(()).await, Ok(()));
180    }
181
182    #[derive(Clone)]
183    struct CloneOnce(Rc<Cell<usize>>);
184
185    impl Policy<TestService, (), ()> for CloneOnce {
186        async fn retry(&mut self, (): &(), res: &Result<(), ()>) -> bool {
187            res.is_err()
188        }
189
190        fn clone_request(&self, (): &()) -> Option<()> {
191            let n = self.0.get();
192            self.0.set(n + 1);
193            if n == 0 { Some(()) } else { None }
194        }
195    }
196
197    #[ntex::test]
198    async fn test_retry_without_clone() {
199        // the retried request cannot be cloned again, its result is returned
200        let cnt = Rc::new(Cell::new(5));
201        let clones = Rc::new(Cell::new(0));
202        let svc = Pipeline::new(
203            (),
204            RetryService::new(CloneOnce(clones.clone()), TestService(cnt.clone())),
205        );
206        assert_eq!(svc.call(()).await, Err(()));
207        assert_eq!(cnt.get(), 3);
208        assert_eq!(clones.get(), 2);
209    }
210}