do-over 0.1.0

Async resilience policies for Rust inspired by Polly
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
//! Integration tests for do_over policies.

use do_over::bulkhead::Bulkhead;
use do_over::circuit_breaker::CircuitBreaker;
use do_over::error::DoOverError;
use do_over::hedge::Hedge;
use do_over::policy::Policy;
use do_over::rate_limit::RateLimiter;
use do_over::retry::RetryPolicy;
use do_over::timeout::TimeoutPolicy;
use do_over::wrap::Wrap;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;

// =============================================================================
// Retry Policy Tests
// =============================================================================

#[tokio::test]
async fn retry_eventually_succeeds() {
    let counter = AtomicUsize::new(0);

    let retry = RetryPolicy::fixed(3, Duration::from_millis(10));

    let result = retry
        .execute(|| async {
            let c = counter.fetch_add(1, Ordering::SeqCst);
            if c < 2 {
                Err("fail")
            } else {
                Ok("ok")
            }
        })
        .await;

    assert_eq!(result.unwrap(), "ok");
    assert_eq!(counter.load(Ordering::SeqCst), 3);
}

#[tokio::test]
async fn retry_exhausts_all_attempts() {
    let counter = AtomicUsize::new(0);
    let retry = RetryPolicy::fixed(2, Duration::from_millis(10));

    let result: Result<&str, &str> = retry
        .execute(|| async {
            counter.fetch_add(1, Ordering::SeqCst);
            Err("permanent failure")
        })
        .await;

    assert!(result.is_err());
    assert_eq!(counter.load(Ordering::SeqCst), 3); // Initial + 2 retries
}

#[tokio::test]
async fn retry_zero_retries_executes_once() {
    let counter = AtomicUsize::new(0);
    let retry = RetryPolicy::fixed(0, Duration::from_millis(10));

    let result: Result<&str, &str> = retry
        .execute(|| async {
            counter.fetch_add(1, Ordering::SeqCst);
            Err("fail")
        })
        .await;

    assert!(result.is_err());
    assert_eq!(counter.load(Ordering::SeqCst), 1);
}

#[tokio::test]
async fn retry_exponential_backoff() {
    let counter = AtomicUsize::new(0);
    let retry = RetryPolicy::exponential(3, Duration::from_millis(10), 2.0);

    let start = std::time::Instant::now();
    let result: Result<&str, &str> = retry
        .execute(|| async {
            counter.fetch_add(1, Ordering::SeqCst);
            Err("fail")
        })
        .await;

    let elapsed = start.elapsed();
    assert!(result.is_err());
    // Delays: 20ms + 40ms + 80ms = 140ms minimum
    assert!(elapsed >= Duration::from_millis(100));
}

// =============================================================================
// Timeout Policy Tests
// =============================================================================

#[tokio::test]
async fn timeout_succeeds_within_limit() {
    let timeout = TimeoutPolicy::new(Duration::from_millis(100));

    let result: Result<&str, DoOverError<&str>> = timeout
        .execute(|| async {
            tokio::time::sleep(Duration::from_millis(10)).await;
            Ok("success")
        })
        .await;

    assert_eq!(result.unwrap(), "success");
}

#[tokio::test]
async fn timeout_fails_when_exceeded() {
    let timeout = TimeoutPolicy::new(Duration::from_millis(50));

    let result: Result<&str, DoOverError<&str>> = timeout
        .execute(|| async {
            tokio::time::sleep(Duration::from_millis(200)).await;
            Ok("success")
        })
        .await;

    assert!(matches!(result, Err(DoOverError::Timeout)));
}

#[tokio::test]
async fn timeout_zero_duration() {
    let timeout = TimeoutPolicy::new(Duration::ZERO);

    let result: Result<&str, DoOverError<&str>> = timeout
        .execute(|| async { Ok("instant") })
        .await;

    // Zero timeout should still allow instant operations to complete
    // (behavior may vary based on implementation)
    assert!(result.is_ok() || matches!(result, Err(DoOverError::Timeout)));
}

// =============================================================================
// Circuit Breaker Tests
// =============================================================================

#[tokio::test]
async fn circuit_breaker_opens_after_threshold() {
    let breaker = CircuitBreaker::new(3, Duration::from_secs(60));

    // Trigger 3 failures
    for _ in 0..3 {
        let _: Result<(), DoOverError<&str>> = breaker
            .execute(|| async { Err(DoOverError::Inner("error")) })
            .await;
    }

    // Next request should fail with CircuitOpen
    let result: Result<(), DoOverError<&str>> = breaker
        .execute(|| async { Ok(()) })
        .await;

    assert!(matches!(result, Err(DoOverError::CircuitOpen)));
}

#[tokio::test]
async fn circuit_breaker_resets_on_success() {
    let breaker = CircuitBreaker::new(3, Duration::from_secs(60));

    // Two failures
    for _ in 0..2 {
        let _: Result<(), DoOverError<&str>> = breaker
            .execute(|| async { Err(DoOverError::Inner("error")) })
            .await;
    }

    // Success resets counter
    let _: Result<(), DoOverError<&str>> = breaker.execute(|| async { Ok(()) }).await;

    // Two more failures
    for _ in 0..2 {
        let _: Result<(), DoOverError<&str>> = breaker
            .execute(|| async { Err(DoOverError::Inner("error")) })
            .await;
    }

    // Should still be closed (only 2 failures since last success)
    let result: Result<(), DoOverError<&str>> = breaker.execute(|| async { Ok(()) }).await;

    assert!(result.is_ok());
}

// =============================================================================
// Bulkhead Tests
// =============================================================================

#[tokio::test]
async fn bulkhead_limits_concurrency() {
    let bulkhead = Arc::new(Bulkhead::new(2));
    let concurrent = Arc::new(AtomicUsize::new(0));
    let max_concurrent = Arc::new(AtomicUsize::new(0));

    let mut handles = vec![];
    for _ in 0..5 {
        let bh = Arc::clone(&bulkhead);
        let conc = Arc::clone(&concurrent);
        let max = Arc::clone(&max_concurrent);

        handles.push(tokio::spawn(async move {
            let result: Result<(), DoOverError<()>> = bh
                .execute(|| async {
                    let c = conc.fetch_add(1, Ordering::SeqCst) + 1;
                    max.fetch_max(c, Ordering::SeqCst);
                    tokio::time::sleep(Duration::from_millis(50)).await;
                    conc.fetch_sub(1, Ordering::SeqCst);
                    Ok(())
                })
                .await;
            result
        }));
    }

    let results: Vec<_> = futures::future::join_all(handles)
        .await
        .into_iter()
        .map(|r| r.unwrap())
        .collect();

    let successes = results.iter().filter(|r| r.is_ok()).count();
    let rejections = results
        .iter()
        .filter(|r| matches!(r, Err(DoOverError::BulkheadFull)))
        .count();

    // With no queue timeout, excess requests should be rejected
    assert_eq!(successes, 2);
    assert_eq!(rejections, 3);
}

#[tokio::test]
async fn bulkhead_with_queue_allows_waiting() {
    let bulkhead = Arc::new(Bulkhead::new(1).with_queue_timeout(Duration::from_millis(200)));
    let counter = Arc::new(AtomicUsize::new(0));

    let mut handles = vec![];
    for _ in 0..3 {
        let bh = Arc::clone(&bulkhead);
        let cnt = Arc::clone(&counter);

        handles.push(tokio::spawn(async move {
            let result: Result<(), DoOverError<()>> = bh
                .execute(|| async {
                    cnt.fetch_add(1, Ordering::SeqCst);
                    tokio::time::sleep(Duration::from_millis(50)).await;
                    Ok(())
                })
                .await;
            result
        }));
        tokio::time::sleep(Duration::from_millis(10)).await;
    }

    let results: Vec<_> = futures::future::join_all(handles)
        .await
        .into_iter()
        .map(|r| r.unwrap())
        .collect();

    let successes = results.iter().filter(|r| r.is_ok()).count();
    // With queue timeout, requests should wait and succeed
    assert!(successes >= 2);
}

// =============================================================================
// Rate Limiter Tests
// =============================================================================

#[tokio::test]
async fn rate_limiter_allows_burst() {
    let limiter = RateLimiter::new(5, Duration::from_secs(1));
    let mut successes = 0;

    for _ in 0..5 {
        let result: Result<(), DoOverError<()>> = limiter.execute(|| async { Ok(()) }).await;
        if result.is_ok() {
            successes += 1;
        }
    }

    assert_eq!(successes, 5);
}

#[tokio::test]
async fn rate_limiter_rejects_excess() {
    let limiter = RateLimiter::new(3, Duration::from_secs(1));
    let mut successes = 0;
    let mut rejections = 0;

    for _ in 0..5 {
        let result: Result<(), DoOverError<()>> = limiter.execute(|| async { Ok(()) }).await;
        match result {
            Ok(()) => successes += 1,
            Err(DoOverError::BulkheadFull) => rejections += 1,
            _ => {}
        }
    }

    assert_eq!(successes, 3);
    assert_eq!(rejections, 2);
}

#[tokio::test]
async fn rate_limiter_refills_after_interval() {
    let limiter = RateLimiter::new(2, Duration::from_millis(100));

    // Use up tokens
    for _ in 0..2 {
        let _: Result<(), DoOverError<()>> = limiter.execute(|| async { Ok(()) }).await;
    }

    // Should be rejected
    let result: Result<(), DoOverError<()>> = limiter.execute(|| async { Ok(()) }).await;
    assert!(matches!(result, Err(DoOverError::BulkheadFull)));

    // Wait for refill
    tokio::time::sleep(Duration::from_millis(110)).await;

    // Should succeed
    let result: Result<(), DoOverError<()>> = limiter.execute(|| async { Ok(()) }).await;
    assert!(result.is_ok());
}

// =============================================================================
// Hedge Policy Tests
// =============================================================================

#[tokio::test]
async fn hedge_returns_first_result() {
    let hedge = Hedge::new(Duration::from_millis(50));

    let result: Result<&str, DoOverError<&str>> =
        hedge.execute(|| async { Ok("result") }).await;

    assert_eq!(result.unwrap(), "result");
}

#[tokio::test]
async fn hedge_starts_backup_after_delay() {
    let hedge = Hedge::new(Duration::from_millis(50));
    let call_count = Arc::new(AtomicUsize::new(0));

    let cc = Arc::clone(&call_count);
    let _: Result<&str, DoOverError<&str>> = hedge
        .execute(|| {
            let count = Arc::clone(&cc);
            async move {
                count.fetch_add(1, Ordering::SeqCst);
                tokio::time::sleep(Duration::from_millis(200)).await;
                Ok("slow")
            }
        })
        .await;

    // Both primary and hedge should have been started
    assert!(call_count.load(Ordering::SeqCst) >= 1);
}

// =============================================================================
// Policy Composition Tests
// =============================================================================

#[tokio::test]
async fn wrap_retry_with_timeout() {
    let policy = Wrap::new(
        RetryPolicy::fixed(2, Duration::from_millis(50)),
        TimeoutPolicy::new(Duration::from_millis(100)),
    );

    let counter = Arc::new(AtomicUsize::new(0));
    let cc = Arc::clone(&counter);

    let result: Result<&str, DoOverError<&str>> = policy
        .execute(|| {
            let count = Arc::clone(&cc);
            async move {
                let c = count.fetch_add(1, Ordering::SeqCst);
                if c < 2 {
                    // First two attempts timeout
                    tokio::time::sleep(Duration::from_millis(200)).await;
                }
                Ok("success")
            }
        })
        .await;

    assert_eq!(result.unwrap(), "success");
    assert_eq!(counter.load(Ordering::SeqCst), 3);
}

#[tokio::test]
async fn wrap_bulkhead_with_retry() {
    let policy = Wrap::new(
        Bulkhead::new(5),
        RetryPolicy::fixed(2, Duration::from_millis(10)),
    );

    let counter = Arc::new(AtomicUsize::new(0));
    let cc = Arc::clone(&counter);

    let result: Result<&str, DoOverError<&str>> = policy
        .execute(|| {
            let count = Arc::clone(&cc);
            async move {
                let c = count.fetch_add(1, Ordering::SeqCst);
                if c < 1 {
                    Err(DoOverError::Inner("transient"))
                } else {
                    Ok("success")
                }
            }
        })
        .await;

    assert_eq!(result.unwrap(), "success");
}

// =============================================================================
// Edge Cases
// =============================================================================

#[tokio::test]
async fn retry_with_immediate_success() {
    let retry = RetryPolicy::fixed(5, Duration::from_millis(100));
    let counter = AtomicUsize::new(0);

    let result: Result<&str, &str> = retry
        .execute(|| async {
            counter.fetch_add(1, Ordering::SeqCst);
            Ok("immediate")
        })
        .await;

    assert_eq!(result.unwrap(), "immediate");
    assert_eq!(counter.load(Ordering::SeqCst), 1);
}

#[tokio::test]
async fn circuit_breaker_threshold_one() {
    let breaker = CircuitBreaker::new(1, Duration::from_secs(60));

    // Single failure opens circuit
    let _: Result<(), DoOverError<&str>> = breaker
        .execute(|| async { Err(DoOverError::Inner("error")) })
        .await;

    let result: Result<(), DoOverError<&str>> = breaker.execute(|| async { Ok(()) }).await;

    assert!(matches!(result, Err(DoOverError::CircuitOpen)));
}

#[tokio::test]
async fn bulkhead_single_slot() {
    let bulkhead = Bulkhead::new(1);

    let result: Result<&str, DoOverError<&str>> =
        bulkhead.execute(|| async { Ok("success") }).await;

    assert_eq!(result.unwrap(), "success");
}