qubit-retry 0.2.2

Retry module, providing a feature-complete, type-safe retry management system with support for multiple delay strategies and event listeners
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
/*******************************************************************************
 *
 *    Copyright (c) 2025 - 2026.
 *    Haixing Hu, Qubit Co. Ltd.
 *
 *    All rights reserved.
 *
 ******************************************************************************/
//! # Retry Delay Strategy
//!
//! Defines the delay calculation methods used in the retry mechanism.
//!
//! # Author
//!
//! Haixing Hu

use rand::RngExt;
use std::time::Duration;

/// Retry delay strategy enum
///
/// This enum is used to explicitly specify the delay calculation method used in the retry mechanism, avoiding ambiguity and redundancy in parameter configuration.
/// Each strategy corresponds to different delay calculation logic and parameter requirements.
///
/// # Author
///
/// Haixing Hu
#[derive(Debug, PartialEq)]
pub enum RetryDelayStrategy {
    /// No delay strategy
    ///
    /// Retry immediately without waiting. This is the most aggressive retry strategy, suitable for:
    /// - Very low-latency operation requirements
    /// - Fast retries for atomic operations like CAS (Compare-And-Swap)
    /// - Resolving data races in memory
    /// - Scenarios requiring maximum retry frequency
    ///
    /// **Precautions:**
    /// - May cause CPU resource waste, use with caution
    /// - Not suitable for retrying network or IO operations
    /// - Recommended to use with a lower maximum retry count
    None,

    /// Fixed delay strategy
    ///
    /// Wait the same amount of time between each retry. This is the simplest delay strategy, suitable for:
    /// - Scenarios where error recovery time is relatively fixed
    /// - Low system load situations that don't require yielding
    /// - Need for simple and predictable retry behavior
    Fixed {
        /// Fixed delay time
        delay: Duration,
    },

    /// Random delay strategy
    ///
    /// Wait a random amount of time within the specified range between each retry. Suitable for:
    /// - High-concurrency scenarios requiring avoidance of "thundering herd effect"
    /// - Distributed systems with multiple clients retrying simultaneously
    /// - Scenarios with uncertain error recovery time
    Random {
        /// Minimum value for random delay
        min_delay: Duration,
        /// Maximum value for random delay
        max_delay: Duration,
    },

    /// Exponential backoff strategy
    ///
    /// The delay time for each retry increases exponentially until reaching a maximum value. This is the best strategy for handling system load and
    /// transient failures, suitable for:
    /// - High system load requiring gradual reduction in retry frequency
    /// - Transient failure scenarios for networks or services
    /// - Situations requiring more time for system recovery
    /// - Most distributed systems and microservice architectures
    ///
    /// **Calculation Formula:**
    /// ```text
    /// Next delay = min(current delay × multiplier, max_delay)
    /// ```
    ExponentialBackoff {
        /// Initial delay for exponential backoff
        initial_delay: Duration,
        /// Maximum delay ceiling for exponential backoff
        max_delay: Duration,
        /// Delay multiplier for exponential backoff
        multiplier: f64,
    },
}

impl RetryDelayStrategy {
    /// Create no delay strategy
    ///
    /// Create a no-delay retry strategy that retries immediately without waiting.
    ///
    /// # Returns
    ///
    /// Returns a `RetryDelayStrategy::None` instance
    ///
    /// # Example
    ///
    /// ```rust
    /// use qubit_retry::RetryDelayStrategy;
    ///
    /// let strategy = RetryDelayStrategy::none();
    /// let delay = strategy.calculate_delay(1, 0.0);
    /// assert_eq!(delay.as_nanos(), 0);
    /// ```
    #[inline]
    pub fn none() -> Self {
        RetryDelayStrategy::None
    }

    /// Create fixed delay strategy
    ///
    /// Create a fixed delay retry strategy that waits the same amount of time between each retry.
    ///
    /// # Parameters
    ///
    /// * `delay` - Fixed delay time
    ///
    /// # Returns
    ///
    /// Returns a `RetryDelayStrategy::Fixed` instance
    ///
    /// # Example
    ///
    /// ```rust
    /// use qubit_retry::RetryDelayStrategy;
    /// use std::time::Duration;
    ///
    /// let strategy = RetryDelayStrategy::fixed(Duration::from_secs(1));
    /// let delay = strategy.calculate_delay(1, 0.0);
    /// assert_eq!(delay, Duration::from_secs(1));
    /// ```
    #[inline]
    pub fn fixed(delay: Duration) -> Self {
        RetryDelayStrategy::Fixed { delay }
    }

    /// Create random delay strategy
    ///
    /// Create a random delay retry strategy that waits a random amount of time within the specified range between each retry.
    ///
    /// # Parameters
    ///
    /// * `min_delay` - Minimum value for random delay
    /// * `max_delay` - Maximum value for random delay
    ///
    /// # Returns
    ///
    /// Returns a `RetryDelayStrategy::Random` instance
    ///
    /// # Example
    ///
    /// ```rust
    /// use qubit_retry::RetryDelayStrategy;
    /// use std::time::Duration;
    ///
    /// let strategy = RetryDelayStrategy::random(
    ///     Duration::from_millis(100),
    ///     Duration::from_millis(1000)
    /// );
    /// let delay = strategy.calculate_delay(1, 0.0);
    /// assert!(delay >= Duration::from_millis(100));
    /// assert!(delay <= Duration::from_millis(1000));
    /// ```
    #[inline]
    pub fn random(min_delay: Duration, max_delay: Duration) -> Self {
        RetryDelayStrategy::Random {
            min_delay,
            max_delay,
        }
    }

    /// Create exponential backoff strategy
    ///
    /// Create an exponential backoff retry strategy where the delay time increases exponentially for each retry until reaching a maximum value.
    ///
    /// # Parameters
    ///
    /// * `initial_delay` - Initial delay for exponential backoff
    /// * `max_delay` - Maximum delay ceiling for exponential backoff
    /// * `multiplier` - Delay multiplier for exponential backoff (must be greater than 1.0)
    ///
    /// # Returns
    ///
    /// Returns a `RetryDelayStrategy::ExponentialBackoff` instance
    ///
    /// # Example
    ///
    /// ```rust
    /// use qubit_retry::RetryDelayStrategy;
    /// use std::time::Duration;
    ///
    /// let strategy = RetryDelayStrategy::exponential_backoff(
    ///     Duration::from_millis(100),
    ///     Duration::from_secs(10),
    ///     2.0
    /// );
    /// let delay1 = strategy.calculate_delay(1, 0.0);
    /// let delay2 = strategy.calculate_delay(2, 0.0);
    /// assert_eq!(delay1, Duration::from_millis(100));
    /// assert_eq!(delay2, Duration::from_millis(200));
    /// ```
    #[inline]
    pub fn exponential_backoff(
        initial_delay: Duration,
        max_delay: Duration,
        multiplier: f64,
    ) -> Self {
        RetryDelayStrategy::ExponentialBackoff {
            initial_delay,
            max_delay,
            multiplier,
        }
    }

    /// Calculate delay time for a specified attempt number
    ///
    /// # Parameters
    ///
    /// * `attempt` - Current attempt number (starting from 1)
    /// * `jitter_factor` - Jitter factor (0.0-1.0) for adding randomness
    ///
    /// # Returns
    ///
    /// Returns the calculated delay time
    ///
    /// # Example
    ///
    /// ```rust
    /// use qubit_retry::RetryDelayStrategy;
    /// use std::time::Duration;
    ///
    /// let strategy = RetryDelayStrategy::fixed(Duration::from_secs(1));
    /// let delay = strategy.calculate_delay(1, 0.1);
    /// assert!(delay >= Duration::from_millis(900));
    /// assert!(delay <= Duration::from_millis(1100));
    /// ```
    pub fn calculate_delay(&self, attempt: u32, jitter_factor: f64) -> Duration {
        let base_delay = match self {
            RetryDelayStrategy::None => Duration::ZERO,
            RetryDelayStrategy::Fixed { delay } => *delay,
            RetryDelayStrategy::Random {
                min_delay,
                max_delay,
            } => {
                let mut rng = rand::rng();
                let min_nanos = min_delay.as_nanos() as u64;
                let max_nanos = max_delay.as_nanos() as u64;
                let random_nanos = rng.random_range(min_nanos..=max_nanos);
                Duration::from_nanos(random_nanos)
            }
            RetryDelayStrategy::ExponentialBackoff {
                initial_delay,
                max_delay,
                multiplier,
            } => {
                let delay_nanos = initial_delay.as_nanos() as f64;
                let calculated_nanos = delay_nanos * multiplier.powi((attempt - 1) as i32);
                let max_nanos = max_delay.as_nanos() as f64;
                let final_nanos = calculated_nanos.min(max_nanos);
                Duration::from_nanos(final_nanos as u64)
            }
        };

        // Apply jitter
        if jitter_factor > 0.0 && base_delay > Duration::ZERO {
            let mut rng = rand::rng();
            let jitter_range = base_delay.as_nanos() as f64 * jitter_factor;
            let jitter_nanos = rng.random_range(0.0..=jitter_range);
            let total_nanos = base_delay.as_nanos() as f64 + jitter_nanos;
            Duration::from_nanos(total_nanos as u64)
        } else {
            base_delay
        }
    }

    /// Validate the validity of strategy parameters
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` if parameters are valid, otherwise returns error message
    pub fn validate(&self) -> Result<(), String> {
        match self {
            RetryDelayStrategy::None => Ok(()),
            RetryDelayStrategy::Fixed { delay } => {
                if delay.is_zero() {
                    Err("Fixed delay cannot be zero".to_string())
                } else {
                    Ok(())
                }
            }
            RetryDelayStrategy::Random {
                min_delay,
                max_delay,
            } => {
                if min_delay.is_zero() {
                    Err("Random delay minimum cannot be zero".to_string())
                } else if *min_delay >= *max_delay {
                    Err("Random delay minimum must be less than maximum".to_string())
                } else {
                    Ok(())
                }
            }
            RetryDelayStrategy::ExponentialBackoff {
                initial_delay,
                max_delay,
                multiplier,
            } => {
                if initial_delay.is_zero() {
                    Err("Exponential backoff initial delay cannot be zero".to_string())
                } else if *initial_delay >= *max_delay {
                    Err(
                        "Exponential backoff initial delay must be less than maximum delay"
                            .to_string(),
                    )
                } else if *multiplier <= 1.0 {
                    Err("Exponential backoff multiplier must be greater than 1.0".to_string())
                } else {
                    Ok(())
                }
            }
        }
    }
}

impl Clone for RetryDelayStrategy {
    /// Clone retry delay strategy
    ///
    /// Create a new instance of the retry delay strategy with the same configuration parameters as the original instance.
    /// Since strategy configuration typically doesn't contain mutable state, cloning is a lightweight operation.
    ///
    /// # Returns
    ///
    /// Returns a cloned instance of the strategy
    ///
    /// # Example
    ///
    /// ```rust
    /// use qubit_retry::RetryDelayStrategy;
    /// use std::time::Duration;
    ///
    /// let original = RetryDelayStrategy::fixed(Duration::from_secs(1));
    /// let cloned = original.clone();
    /// assert_eq!(original, cloned);
    /// ```
    fn clone(&self) -> Self {
        match self {
            RetryDelayStrategy::None => RetryDelayStrategy::None,
            RetryDelayStrategy::Fixed { delay } => RetryDelayStrategy::Fixed { delay: *delay },
            RetryDelayStrategy::Random {
                min_delay,
                max_delay,
            } => RetryDelayStrategy::Random {
                min_delay: *min_delay,
                max_delay: *max_delay,
            },
            RetryDelayStrategy::ExponentialBackoff {
                initial_delay,
                max_delay,
                multiplier,
            } => RetryDelayStrategy::ExponentialBackoff {
                initial_delay: *initial_delay,
                max_delay: *max_delay,
                multiplier: *multiplier,
            },
        }
    }
}

impl Default for RetryDelayStrategy {
    /// Create default retry delay strategy
    ///
    /// Returns an exponential backoff strategy as the default strategy with the following parameters:
    /// - Initial delay: 1000 milliseconds
    /// - Maximum delay: 60 seconds
    /// - Multiplier: 2.0
    ///
    /// This default configuration is suitable for most distributed systems and microservice architecture scenarios.
    ///
    /// # Returns
    ///
    /// Returns a default exponential backoff strategy instance
    ///
    /// # Example
    ///
    /// ```rust
    /// use qubit_retry::RetryDelayStrategy;
    /// use std::time::Duration;
    ///
    /// let strategy = RetryDelayStrategy::default();
    /// let delay = strategy.calculate_delay(1, 0.0);
    /// assert_eq!(delay, Duration::from_millis(1000));
    /// ```
    fn default() -> Self {
        RetryDelayStrategy::ExponentialBackoff {
            initial_delay: Duration::from_millis(1000),
            max_delay: Duration::from_secs(60),
            multiplier: 2.0,
        }
    }
}