Skip to main content

error_forge/recovery/
retry.rs

1use crate::error::ForgeError;
2use crate::recovery::backoff::{Backoff, ExponentialBackoff, FixedBackoff, LinearBackoff};
3use std::marker::PhantomData;
4use std::thread;
5use std::time::Duration;
6
7/// Predicate function to determine if an error is retryable
8pub type RetryPredicate<E> = Box<dyn Fn(&E) -> bool + Send + Sync + 'static>;
9
10/// Whether the exponential executors jitter by default: on when the
11/// `jitter` cargo feature is enabled.
12const DEFAULT_JITTER: bool = cfg!(feature = "jitter");
13
14/// Enum to hold different backoff strategy types
15pub enum BackoffStrategy {
16    Exponential(ExponentialBackoff),
17    Linear(LinearBackoff),
18    Fixed(FixedBackoff),
19    /// Any [`Backoff`], set with [`RetryExecutor::with_backoff`].
20    Custom(Box<dyn Backoff>),
21}
22
23impl BackoffStrategy {
24    fn next_delay(&self, attempt: usize) -> Duration {
25        match self {
26            BackoffStrategy::Exponential(b) => b.next_delay(attempt),
27            BackoffStrategy::Linear(b) => b.next_delay(attempt),
28            BackoffStrategy::Fixed(b) => b.next_delay(attempt),
29            BackoffStrategy::Custom(b) => b.next_delay(attempt),
30        }
31    }
32}
33
34/// Executor for retry operations
35pub struct RetryExecutor<E> {
36    max_retries: usize,
37    backoff: BackoffStrategy,
38    retry_if: Option<RetryPredicate<E>>,
39    _marker: PhantomData<E>,
40}
41
42impl<E> RetryExecutor<E>
43where
44    E: std::error::Error + 'static,
45{
46    /// Create a new retry executor with an exponential backoff strategy.
47    ///
48    /// Delays start at 100 ms and double each attempt, up to 30 s. With
49    /// the `jitter` cargo feature on, each delay is jittered by ±20%
50    /// (see [`ExponentialBackoff::with_jitter`]) so retriers across a
51    /// fleet do not wake in step; use [`with_jitter`](Self::with_jitter)
52    /// or [`with_backoff`](Self::with_backoff) to choose explicitly.
53    pub fn new_exponential() -> Self {
54        Self {
55            max_retries: 3,
56            backoff: BackoffStrategy::Exponential(
57                ExponentialBackoff::default().with_jitter(DEFAULT_JITTER),
58            ),
59            retry_if: None,
60            _marker: PhantomData,
61        }
62    }
63
64    /// Create a new retry executor with a linear backoff strategy
65    pub fn new_linear() -> Self {
66        Self {
67            max_retries: 3,
68            backoff: BackoffStrategy::Linear(LinearBackoff::default()),
69            retry_if: None,
70            _marker: PhantomData,
71        }
72    }
73
74    /// Create a new retry executor with a fixed backoff strategy
75    pub fn new_fixed(delay_ms: u64) -> Self {
76        Self {
77            max_retries: 3,
78            backoff: BackoffStrategy::Fixed(FixedBackoff::new(delay_ms)),
79            retry_if: None,
80            _marker: PhantomData,
81        }
82    }
83
84    /// Set the maximum number of retries
85    pub fn with_max_retries(mut self, max_retries: usize) -> Self {
86        self.max_retries = max_retries;
87        self
88    }
89
90    /// Use `backoff` for the delay before each retry, replacing the
91    /// built-in schedule. Any [`Backoff`] works, including a configured
92    /// [`ExponentialBackoff`] (initial delay, factor, cap, jitter).
93    ///
94    /// # Example
95    ///
96    /// ```
97    /// use error_forge::recovery::{ExponentialBackoff, RetryExecutor};
98    ///
99    /// let executor = RetryExecutor::<std::io::Error>::new_exponential().with_backoff(
100    ///     ExponentialBackoff::new()
101    ///         .with_initial_delay(1)
102    ///         .with_max_delay(5)
103    ///         .with_jitter(true),
104    /// );
105    /// let result = executor.retry(|| Ok::<_, std::io::Error>(7));
106    /// assert_eq!(result.unwrap(), 7);
107    /// ```
108    #[must_use]
109    pub fn with_backoff(mut self, backoff: impl Backoff) -> Self {
110        self.backoff = BackoffStrategy::Custom(Box::new(backoff));
111        self
112    }
113
114    /// Turn ±20% jitter on or off for an exponential executor (see
115    /// [`ExponentialBackoff::with_jitter`]). Has no effect on linear,
116    /// fixed, or custom backoff.
117    ///
118    /// # Example
119    ///
120    /// ```
121    /// use error_forge::recovery::RetryExecutor;
122    ///
123    /// let executor = RetryExecutor::<std::io::Error>::new_exponential().with_jitter(true);
124    /// assert!(executor.retry(|| Ok::<_, std::io::Error>(())).is_ok());
125    /// ```
126    #[must_use]
127    pub fn with_jitter(mut self, jitter: bool) -> Self {
128        if let BackoffStrategy::Exponential(backoff) = &mut self.backoff {
129            *backoff = backoff.clone().with_jitter(jitter);
130        }
131        self
132    }
133
134    /// Set a predicate to determine if an error should be retried
135    pub fn with_retry_if<F>(mut self, predicate: F) -> Self
136    where
137        F: Fn(&E) -> bool + Send + Sync + 'static,
138    {
139        self.retry_if = Some(Box::new(predicate));
140        self
141    }
142
143    /// Execute a fallible operation with retries
144    pub fn retry<F, T>(&self, mut operation: F) -> Result<T, E>
145    where
146        F: FnMut() -> Result<T, E>,
147    {
148        let mut attempt = 0;
149        loop {
150            match operation() {
151                Ok(value) => return Ok(value),
152                Err(err) => {
153                    // Check if we've reached max retries
154                    if attempt >= self.max_retries {
155                        return Err(err);
156                    }
157
158                    // Check if this error is retryable
159                    let should_retry = match &self.retry_if {
160                        Some(predicate) => predicate(&err),
161                        None => true,
162                    };
163
164                    if !should_retry {
165                        return Err(err);
166                    }
167
168                    // Wait according to backoff strategy
169                    let delay = self.backoff.next_delay(attempt);
170                    thread::sleep(delay);
171
172                    attempt += 1;
173                }
174            }
175        }
176    }
177
178    /// Execute a fallible operation with retries using a custom error handler
179    pub fn retry_with_handler<F, H, T>(&self, mut operation: F, mut on_error: H) -> Result<T, E>
180    where
181        F: FnMut() -> Result<T, E>,
182        H: FnMut(&E, usize, Duration),
183    {
184        let mut attempt = 0;
185        loop {
186            match operation() {
187                Ok(value) => return Ok(value),
188                Err(err) => {
189                    // Check if we've reached max retries
190                    if attempt >= self.max_retries {
191                        return Err(err);
192                    }
193
194                    // Check if this error is retryable
195                    let should_retry = match &self.retry_if {
196                        Some(predicate) => predicate(&err),
197                        None => true,
198                    };
199
200                    if !should_retry {
201                        return Err(err);
202                    }
203
204                    // Get the delay for this attempt
205                    let delay = self.backoff.next_delay(attempt);
206
207                    // Call the error handler
208                    on_error(&err, attempt, delay);
209
210                    // Wait according to backoff strategy
211                    thread::sleep(delay);
212
213                    attempt += 1;
214                }
215            }
216        }
217    }
218}
219
220/// Policy for retrying operations
221pub struct RetryPolicy {
222    max_retries: usize,
223    backoff_type: BackoffType,
224    jitter: bool,
225}
226
227/// Available backoff types for retry policy
228pub enum BackoffType {
229    Exponential,
230    Linear,
231    Fixed(u64),
232}
233
234impl RetryPolicy {
235    /// Create a new retry policy with exponential backoff
236    pub fn new_exponential() -> Self {
237        Self {
238            max_retries: 3,
239            backoff_type: BackoffType::Exponential,
240            jitter: DEFAULT_JITTER,
241        }
242    }
243
244    /// Create a new retry policy with linear backoff
245    pub fn new_linear() -> Self {
246        Self {
247            max_retries: 3,
248            backoff_type: BackoffType::Linear,
249            jitter: DEFAULT_JITTER,
250        }
251    }
252
253    /// Create a new retry policy with fixed backoff
254    pub fn new_fixed(delay_ms: u64) -> Self {
255        Self {
256            max_retries: 3,
257            backoff_type: BackoffType::Fixed(delay_ms),
258            jitter: DEFAULT_JITTER,
259        }
260    }
261
262    /// Set the maximum number of retries
263    pub fn with_max_retries(mut self, max_retries: usize) -> Self {
264        self.max_retries = max_retries;
265        self
266    }
267
268    /// Turn ±20% jitter on or off for an exponential policy (see
269    /// [`ExponentialBackoff::with_jitter`]). On by default with the
270    /// `jitter` cargo feature, off without it. Has no effect on linear
271    /// or fixed backoff.
272    ///
273    /// # Example
274    ///
275    /// ```
276    /// use error_forge::recovery::RetryPolicy;
277    ///
278    /// let policy = RetryPolicy::new_exponential().with_jitter(true);
279    /// let result: Result<(), std::io::Error> = policy.retry(|| Ok(()));
280    /// assert!(result.is_ok());
281    /// ```
282    #[must_use]
283    pub fn with_jitter(mut self, jitter: bool) -> Self {
284        self.jitter = jitter;
285        self
286    }
287
288    /// Create a retry executor for the given error type
289    pub fn executor<E>(&self) -> RetryExecutor<E>
290    where
291        E: std::error::Error + 'static,
292    {
293        let executor = match self.backoff_type {
294            BackoffType::Exponential => RetryExecutor::new_exponential().with_jitter(self.jitter),
295            BackoffType::Linear => RetryExecutor::new_linear(),
296            BackoffType::Fixed(delay_ms) => RetryExecutor::new_fixed(delay_ms),
297        };
298
299        executor.with_max_retries(self.max_retries)
300    }
301
302    /// Create a retry executor specifically for ForgeError types
303    pub fn forge_executor<E>(&self) -> RetryExecutor<E>
304    where
305        E: ForgeError,
306    {
307        self.executor::<E>().with_retry_if(|err| err.is_retryable())
308    }
309
310    /// Execute a fallible operation with retries
311    pub fn retry<F, T, E>(&self, operation: F) -> Result<T, E>
312    where
313        F: FnMut() -> Result<T, E>,
314        E: std::error::Error + 'static,
315    {
316        self.executor::<E>().retry(operation)
317    }
318}
319
320impl Default for RetryPolicy {
321    fn default() -> Self {
322        Self::new_exponential()
323    }
324}