chrono-machines 0.3.2

Exponential, constant, and Fibonacci backoff retry library with full jitter support - no_std compatible
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
//! Backoff strategy implementations for retry mechanisms
//!
//! This module provides various backoff strategies to control delay timing
//! between retry attempts.

use rand::Rng;
use rand::RngExt;

/// Calculate the nth Fibonacci number (1-indexed): 1, 1, 2, 3, 5, 8, 13, ...
pub fn fibonacci(n: u8) -> u64 {
    match n {
        0 => 0,
        1 | 2 => 1,
        _ => {
            let mut a = 1u64;
            let mut b = 1u64;
            for _ in 2..n {
                let next = a.saturating_add(b);
                a = b;
                b = next;
            }
            b
        }
    }
}

/// Blend a base delay with jitter using the full-jitter algorithm.
///
/// `jitter_factor` is clamped to `[0.0, 1.0]`: `0.0` returns `base` unchanged,
/// `1.0` yields a uniform value in `[0, base]`.
fn apply_jitter<R: Rng>(base: f64, jitter_factor: f64, rng: &mut R) -> u64 {
    let jitter_factor = jitter_factor.clamp(0.0, 1.0);
    let random_scalar: f64 = rng.random_range(0.0..=1.0);
    let jitter_blend = 1.0 - jitter_factor + random_scalar * jitter_factor;
    (base * jitter_blend) as u64
}

/// Trait for backoff strategies that calculate delays between retry attempts
pub trait BackoffStrategy {
    /// Calculate the delay in milliseconds for the given attempt number
    ///
    /// # Arguments
    ///
    /// * `attempt` - Current attempt number (1-indexed)
    /// * `rng` - Random number generator for jitter
    ///
    /// # Returns
    ///
    /// Delay in milliseconds, or `None` if retries should stop
    fn delay<R: Rng>(&self, attempt: u8, rng: &mut R) -> Option<u64>;

    /// Check if another retry should be attempted
    ///
    /// # Arguments
    ///
    /// * `attempt` - Current attempt number (1-indexed)
    ///
    /// # Returns
    ///
    /// `true` if another retry is allowed, `false` otherwise
    fn should_retry(&self, attempt: u8) -> bool;

    /// Maximum number of retry attempts permitted by this strategy.
    fn max_attempts(&self) -> u8;
}

/// Exponential backoff strategy with configurable jitter
///
/// Delays grow exponentially: base_delay * multiplier^(attempt-1)
///
/// # Example
///
/// ```rust
/// use chrono_machines::ExponentialBackoff;
///
/// let backoff = ExponentialBackoff::new()
///     .base_delay_ms(100)
///     .multiplier(2.0)
///     .max_delay_ms(10_000)
///     .max_attempts(5)
///     .jitter_factor(1.0); // Full jitter
/// ```
#[derive(Debug, Clone, Copy)]
pub struct ExponentialBackoff {
    /// Maximum number of retry attempts
    pub max_attempts: u8,
    /// Base delay in milliseconds
    pub base_delay_ms: u64,
    /// Exponential backoff multiplier
    pub multiplier: f64,
    /// Maximum delay cap in milliseconds
    pub max_delay_ms: u64,
    /// Jitter factor (0.0 = no jitter, 1.0 = full jitter)
    pub jitter_factor: f64,
}

impl ExponentialBackoff {
    /// Create a new exponential backoff builder with default values
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the base delay in milliseconds
    pub fn base_delay_ms(mut self, ms: u64) -> Self {
        self.base_delay_ms = ms;
        self
    }

    /// Set the exponential multiplier
    pub fn multiplier(mut self, multiplier: f64) -> Self {
        self.multiplier = multiplier;
        self
    }

    /// Set the maximum delay cap in milliseconds
    pub fn max_delay_ms(mut self, ms: u64) -> Self {
        self.max_delay_ms = ms;
        self
    }

    /// Set the maximum number of attempts
    pub fn max_attempts(mut self, attempts: u8) -> Self {
        self.max_attempts = attempts;
        self
    }

    /// Set the jitter factor (0.0 = no jitter, 1.0 = full jitter)
    pub fn jitter_factor(mut self, factor: f64) -> Self {
        self.jitter_factor = factor.clamp(0.0, 1.0);
        self
    }
}

impl Default for ExponentialBackoff {
    fn default() -> Self {
        Self {
            max_attempts: 3,
            base_delay_ms: 100,
            multiplier: 2.0,
            max_delay_ms: 10_000,
            jitter_factor: 1.0, // Full jitter by default
        }
    }
}

impl BackoffStrategy for ExponentialBackoff {
    fn delay<R: Rng>(&self, attempt: u8, rng: &mut R) -> Option<u64> {
        if attempt >= self.max_attempts {
            return None;
        }

        let exponent = attempt.saturating_sub(1) as i32;
        let base_exponential = (self.base_delay_ms as f64) * self.multiplier.powi(exponent);
        let capped = base_exponential.min(self.max_delay_ms as f64);

        Some(apply_jitter(capped, self.jitter_factor, rng))
    }

    fn should_retry(&self, attempt: u8) -> bool {
        attempt < self.max_attempts
    }

    fn max_attempts(&self) -> u8 {
        self.max_attempts
    }
}

/// Constant backoff strategy with fixed delay
///
/// All retry delays are the same constant value.
///
/// # Example
///
/// ```rust
/// use chrono_machines::ConstantBackoff;
///
/// let backoff = ConstantBackoff::new()
///     .delay_ms(500)
///     .max_attempts(5)
///     .jitter_factor(0.1); // 10% jitter
/// ```
#[derive(Debug, Clone, Copy)]
pub struct ConstantBackoff {
    /// Fixed delay in milliseconds
    pub delay_ms: u64,
    /// Maximum number of retry attempts
    pub max_attempts: u8,
    /// Jitter factor (0.0 = no jitter, 1.0 = full jitter)
    pub jitter_factor: f64,
}

impl ConstantBackoff {
    /// Create a new constant backoff builder with default values
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the constant delay in milliseconds
    pub fn delay_ms(mut self, ms: u64) -> Self {
        self.delay_ms = ms;
        self
    }

    /// Set the maximum number of attempts
    pub fn max_attempts(mut self, attempts: u8) -> Self {
        self.max_attempts = attempts;
        self
    }

    /// Set the jitter factor (0.0 = no jitter, 1.0 = full jitter)
    pub fn jitter_factor(mut self, factor: f64) -> Self {
        self.jitter_factor = factor.clamp(0.0, 1.0);
        self
    }
}

impl Default for ConstantBackoff {
    fn default() -> Self {
        Self {
            delay_ms: 100,
            max_attempts: 3,
            jitter_factor: 0.0, // No jitter for constant by default
        }
    }
}

impl BackoffStrategy for ConstantBackoff {
    fn delay<R: Rng>(&self, attempt: u8, rng: &mut R) -> Option<u64> {
        if attempt >= self.max_attempts {
            return None;
        }

        Some(apply_jitter(self.delay_ms as f64, self.jitter_factor, rng))
    }

    fn should_retry(&self, attempt: u8) -> bool {
        attempt < self.max_attempts
    }

    fn max_attempts(&self) -> u8 {
        self.max_attempts
    }
}

/// Fibonacci backoff strategy
///
/// Delays follow the Fibonacci sequence: 1, 1, 2, 3, 5, 8, 13, ...
/// Each delay is base_delay_ms * fibonacci(attempt).
///
/// # Example
///
/// ```rust
/// use chrono_machines::FibonacciBackoff;
///
/// let backoff = FibonacciBackoff::new()
///     .base_delay_ms(100)  // 100ms, 100ms, 200ms, 300ms, 500ms...
///     .max_delay_ms(5_000)
///     .max_attempts(8)
///     .jitter_factor(0.5); // 50% jitter
/// ```
#[derive(Debug, Clone, Copy)]
pub struct FibonacciBackoff {
    /// Base delay in milliseconds (multiplied by Fibonacci number)
    pub base_delay_ms: u64,
    /// Maximum delay cap in milliseconds
    pub max_delay_ms: u64,
    /// Maximum number of retry attempts
    pub max_attempts: u8,
    /// Jitter factor (0.0 = no jitter, 1.0 = full jitter)
    pub jitter_factor: f64,
}

impl FibonacciBackoff {
    /// Create a new Fibonacci backoff builder with default values
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the base delay in milliseconds
    pub fn base_delay_ms(mut self, ms: u64) -> Self {
        self.base_delay_ms = ms;
        self
    }

    /// Set the maximum delay cap in milliseconds
    pub fn max_delay_ms(mut self, ms: u64) -> Self {
        self.max_delay_ms = ms;
        self
    }

    /// Set the maximum number of attempts
    pub fn max_attempts(mut self, attempts: u8) -> Self {
        self.max_attempts = attempts;
        self
    }

    /// Set the jitter factor (0.0 = no jitter, 1.0 = full jitter)
    pub fn jitter_factor(mut self, factor: f64) -> Self {
        self.jitter_factor = factor.clamp(0.0, 1.0);
        self
    }
}

impl Default for FibonacciBackoff {
    fn default() -> Self {
        Self {
            base_delay_ms: 100,
            max_delay_ms: 10_000,
            max_attempts: 8,
            jitter_factor: 1.0, // Full jitter by default
        }
    }
}

impl BackoffStrategy for FibonacciBackoff {
    fn delay<R: Rng>(&self, attempt: u8, rng: &mut R) -> Option<u64> {
        if attempt >= self.max_attempts {
            return None;
        }

        let fib = fibonacci(attempt);
        let base = ((self.base_delay_ms as f64) * (fib as f64)).min(self.max_delay_ms as f64);

        Some(apply_jitter(base, self.jitter_factor, rng))
    }

    fn should_retry(&self, attempt: u8) -> bool {
        attempt < self.max_attempts
    }

    fn max_attempts(&self) -> u8 {
        self.max_attempts
    }
}

/// Backoff policy that can represent any supported strategy.
///
/// The enum form makes it possible to store heterogeneous strategies in a
/// registry or configuration without heap allocation or dynamic dispatch.
#[derive(Debug, Clone, Copy)]
pub enum BackoffPolicy {
    /// Exponential backoff policy
    Exponential(ExponentialBackoff),
    /// Constant backoff policy
    Constant(ConstantBackoff),
    /// Fibonacci backoff policy
    Fibonacci(FibonacciBackoff),
}

impl BackoffPolicy {
    /// Return the maximum retry attempts for the wrapped strategy.
    pub fn max_attempts(&self) -> u8 {
        match self {
            BackoffPolicy::Exponential(policy) => policy.max_attempts,
            BackoffPolicy::Constant(policy) => policy.max_attempts,
            BackoffPolicy::Fibonacci(policy) => policy.max_attempts,
        }
    }
}

impl BackoffStrategy for BackoffPolicy {
    fn delay<R: Rng>(&self, attempt: u8, rng: &mut R) -> Option<u64> {
        match self {
            BackoffPolicy::Exponential(policy) => policy.delay(attempt, rng),
            BackoffPolicy::Constant(policy) => policy.delay(attempt, rng),
            BackoffPolicy::Fibonacci(policy) => policy.delay(attempt, rng),
        }
    }

    fn should_retry(&self, attempt: u8) -> bool {
        match self {
            BackoffPolicy::Exponential(policy) => policy.should_retry(attempt),
            BackoffPolicy::Constant(policy) => policy.should_retry(attempt),
            BackoffPolicy::Fibonacci(policy) => policy.should_retry(attempt),
        }
    }

    fn max_attempts(&self) -> u8 {
        match self {
            BackoffPolicy::Exponential(policy) => policy.max_attempts(),
            BackoffPolicy::Constant(policy) => policy.max_attempts(),
            BackoffPolicy::Fibonacci(policy) => policy.max_attempts(),
        }
    }
}

impl From<ExponentialBackoff> for BackoffPolicy {
    fn from(value: ExponentialBackoff) -> Self {
        BackoffPolicy::Exponential(value)
    }
}

impl From<ConstantBackoff> for BackoffPolicy {
    fn from(value: ConstantBackoff) -> Self {
        BackoffPolicy::Constant(value)
    }
}

impl From<FibonacciBackoff> for BackoffPolicy {
    fn from(value: FibonacciBackoff) -> Self {
        BackoffPolicy::Fibonacci(value)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rand::rngs::StdRng;
    use rand::SeedableRng;

    #[test]
    fn test_exponential_backoff_builder() {
        let backoff = ExponentialBackoff::new()
            .base_delay_ms(200)
            .multiplier(3.0)
            .max_delay_ms(5000)
            .max_attempts(5)
            .jitter_factor(0.5);

        assert_eq!(backoff.base_delay_ms, 200);
        assert_eq!(backoff.multiplier, 3.0);
        assert_eq!(backoff.max_delay_ms, 5000);
        assert_eq!(backoff.max_attempts, 5);
        assert_eq!(backoff.jitter_factor, 0.5);
    }

    #[test]
    fn test_exponential_delays() {
        let backoff = ExponentialBackoff::new()
            .base_delay_ms(100)
            .multiplier(2.0)
            .jitter_factor(0.0); // No jitter for predictable testing

        let mut rng = StdRng::seed_from_u64(42);

        assert_eq!(backoff.delay(1, &mut rng), Some(100));
        assert_eq!(backoff.delay(2, &mut rng), Some(200));
        assert_eq!(backoff.delay(3, &mut rng), None); // Exceeds max_attempts (default 3)
    }

    #[test]
    fn test_constant_backoff() {
        let backoff = ConstantBackoff::new()
            .delay_ms(500)
            .max_attempts(4)
            .jitter_factor(0.0);

        let mut rng = StdRng::seed_from_u64(42);

        assert_eq!(backoff.delay(1, &mut rng), Some(500));
        assert_eq!(backoff.delay(2, &mut rng), Some(500));
        assert_eq!(backoff.delay(3, &mut rng), Some(500));
        assert_eq!(backoff.delay(4, &mut rng), None);
    }

    #[test]
    fn test_fibonacci_sequence() {
        assert_eq!(fibonacci(1), 1);
        assert_eq!(fibonacci(2), 1);
        assert_eq!(fibonacci(3), 2);
        assert_eq!(fibonacci(4), 3);
        assert_eq!(fibonacci(5), 5);
        assert_eq!(fibonacci(6), 8);
        assert_eq!(fibonacci(7), 13);
    }

    #[test]
    fn test_fibonacci_backoff() {
        let backoff = FibonacciBackoff::new()
            .base_delay_ms(100)
            .max_attempts(5)
            .jitter_factor(0.0);

        let mut rng = StdRng::seed_from_u64(42);

        assert_eq!(backoff.delay(1, &mut rng), Some(100)); // 100 * 1
        assert_eq!(backoff.delay(2, &mut rng), Some(100)); // 100 * 1
        assert_eq!(backoff.delay(3, &mut rng), Some(200)); // 100 * 2
        assert_eq!(backoff.delay(4, &mut rng), Some(300)); // 100 * 3
        assert_eq!(backoff.delay(5, &mut rng), None); // Exceeds max_attempts
    }

    #[test]
    fn test_jitter_application() {
        let backoff = ConstantBackoff::new().delay_ms(1000).jitter_factor(1.0); // Full jitter

        let mut rng = StdRng::seed_from_u64(42);
        let delays: Vec<u64> = (1..10).filter_map(|i| backoff.delay(i, &mut rng)).collect();

        // With full jitter, delays should vary
        let all_different = delays.windows(2).any(|w| w[0] != w[1]);
        assert!(all_different, "Full jitter should produce varying delays");

        // All delays should be <= base delay
        assert!(delays.iter().all(|&d| d <= 1000));
    }
}