Skip to main content

connpool/resilience/
retry.rs

1//! Retry policy: exponential backoff with jitter for `factory.create()`.
2
3use std::error::Error;
4use std::sync::Arc;
5
6use crate::core::errors::PoolError;
7use crate::rng::Rng;
8
9/// A predicate deciding whether a given factory error is retryable.
10type RetryOn = Arc<dyn Fn(&(dyn Error + 'static)) -> bool + Send + Sync>;
11
12/// How to retry `factory.create()`: exponential backoff with jitter.
13///
14/// `jitter` in `[0, 1]`: `0` = deterministic delays, `1` = "full jitter" (uniform in
15/// `[0, delay]`). `retry_on` narrows what is retryable (e.g. don't retry auth failures);
16/// `None` means retry everything.
17#[derive(Clone)]
18pub struct RetryPolicy {
19    /// Maximum attempts (including the first). `1` = no retries.
20    pub max_attempts: u32,
21    /// Base delay in seconds for the first retry.
22    pub base_delay: f64,
23    /// Upper bound on any single delay, in seconds.
24    pub max_delay: f64,
25    /// Exponential growth factor between attempts.
26    pub multiplier: f64,
27    /// Jitter fraction in `[0, 1]`.
28    pub jitter: f64,
29    /// Optional predicate: retry only when it returns `true`. `None` = retry everything.
30    pub retry_on: Option<RetryOn>,
31}
32
33impl std::fmt::Debug for RetryPolicy {
34    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35        f.debug_struct("RetryPolicy")
36            .field("max_attempts", &self.max_attempts)
37            .field("base_delay", &self.base_delay)
38            .field("max_delay", &self.max_delay)
39            .field("multiplier", &self.multiplier)
40            .field("jitter", &self.jitter)
41            .field("retry_on", &self.retry_on.as_ref().map(|_| "<fn>"))
42            .finish()
43    }
44}
45
46impl Default for RetryPolicy {
47    fn default() -> Self {
48        Self {
49            max_attempts: 3,
50            base_delay: 0.1,
51            max_delay: 5.0,
52            multiplier: 2.0,
53            jitter: 0.5,
54            retry_on: None,
55        }
56    }
57}
58
59impl RetryPolicy {
60    /// A policy that never retries (one attempt only).
61    pub fn no_retry() -> Self {
62        Self {
63            max_attempts: 1,
64            ..Self::default()
65        }
66    }
67
68    /// Returns a copy with `retry_on` set to `predicate`.
69    pub fn with_retry_on<F>(mut self, predicate: F) -> Self
70    where
71        F: Fn(&(dyn Error + 'static)) -> bool + Send + Sync + 'static,
72    {
73        self.retry_on = Some(Arc::new(predicate));
74        self
75    }
76
77    /// Checks the policy's invariants.
78    pub fn validate(&self) -> Result<(), PoolError> {
79        if self.max_attempts < 1 {
80            return Err(PoolError::Config("retry.max_attempts must be >= 1".into()));
81        }
82        if self.base_delay < 0.0 || self.max_delay < 0.0 || self.multiplier < 1.0 {
83            return Err(PoolError::Config(
84                "retry delays must be >= 0 and multiplier >= 1".into(),
85            ));
86        }
87        if self.jitter < 0.0 || self.jitter > 1.0 {
88            return Err(PoolError::Config("retry.jitter must be within [0, 1]".into()));
89        }
90        Ok(())
91    }
92
93    /// Reports whether `err` is retryable under this policy.
94    pub fn should_retry(&self, err: &(dyn Error + 'static)) -> bool {
95        match &self.retry_on {
96            None => true,
97            Some(p) => p(err),
98        }
99    }
100
101    /// The delay before the next attempt, given how many attempts have failed so far
102    /// (`failed_attempts` is 1-based: pass `1` after the first failure).
103    pub fn delay_for(&self, failed_attempts: u32, rng: &mut dyn Rng) -> f64 {
104        let ceiling = self
105            .max_delay
106            .min(self.base_delay * self.multiplier.powi(failed_attempts as i32 - 1));
107        ceiling * (1.0 - self.jitter + self.jitter * rng.next_f64())
108    }
109}
110
111#[cfg(test)]
112mod tests {
113    use super::*;
114    use crate::rng::SystemRng;
115
116    #[test]
117    fn defaults_and_no_retry() {
118        let p = RetryPolicy::default();
119        assert_eq!(p.max_attempts, 3);
120        assert_eq!(p.base_delay, 0.1);
121        assert_eq!(p.max_delay, 5.0);
122        assert_eq!(p.multiplier, 2.0);
123        assert_eq!(p.jitter, 0.5);
124        assert!(p.retry_on.is_none());
125        assert_eq!(RetryPolicy::no_retry().max_attempts, 1);
126        assert!(format!("{p:?}").contains("RetryPolicy"));
127        assert!(format!("{:?}", p.clone().with_retry_on(|_| true)).contains("<fn>"));
128    }
129
130    #[test]
131    fn validate_rules() {
132        assert!(RetryPolicy::default().validate().is_ok());
133        let bad = RetryPolicy {
134            max_attempts: 0,
135            ..Default::default()
136        };
137        assert!(matches!(bad.validate(), Err(PoolError::Config(_))));
138        let bad = RetryPolicy {
139            base_delay: -1.0,
140            ..Default::default()
141        };
142        assert!(bad.validate().is_err());
143        let bad = RetryPolicy {
144            multiplier: 0.5,
145            ..Default::default()
146        };
147        assert!(bad.validate().is_err());
148        let bad = RetryPolicy {
149            jitter: 1.5,
150            ..Default::default()
151        };
152        assert!(bad.validate().is_err());
153    }
154
155    #[test]
156    fn should_retry_predicate() {
157        let p = RetryPolicy::default();
158        let err: Box<dyn Error + Send + Sync> = "x".into();
159        assert!(p.should_retry(&*err));
160        let p = RetryPolicy::default().with_retry_on(|e| e.to_string() == "retry");
161        let yes: Box<dyn Error + Send + Sync> = "retry".into();
162        let no: Box<dyn Error + Send + Sync> = "stop".into();
163        assert!(p.should_retry(&*yes));
164        assert!(!p.should_retry(&*no));
165    }
166
167    #[test]
168    fn delay_backoff_and_jitter_bounds() {
169        let mut rng = SystemRng::with_seed(7);
170        let p = RetryPolicy::default();
171        // failed_attempts=1 -> ceiling 0.1; jitter 0.5 -> delay in [0.05, 0.1].
172        for _ in 0..1000 {
173            let d = p.delay_for(1, &mut rng);
174            assert!((0.05..=0.1).contains(&d), "delay {d}");
175        }
176        // failed_attempts=2 -> ceiling 0.2.
177        let d = p.delay_for(2, &mut rng);
178        assert!((0.1..=0.2).contains(&d));
179        // Ceiling is capped at max_delay.
180        let capped = RetryPolicy {
181            base_delay: 10.0,
182            max_delay: 1.0,
183            jitter: 0.0,
184            ..Default::default()
185        };
186        assert_eq!(capped.delay_for(5, &mut rng), 1.0);
187        // jitter=0 -> deterministic == ceiling.
188        let det = RetryPolicy {
189            jitter: 0.0,
190            ..Default::default()
191        };
192        assert_eq!(det.delay_for(1, &mut rng), 0.1);
193    }
194}