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
//! Hedge policy for reducing tail latency.
//!
//! The hedge policy starts a backup request if the primary request is slow,
//! returning whichever completes first. This reduces tail latency at the cost
//! of potentially sending more requests.
//!
//! # How It Works
//!
//! 1. Start the primary request
//! 2. After a configured delay, start a hedged (backup) request
//! 3. Return whichever completes first
//! 4. Cancel the slower request
//!
//! # Important
//!
//! Only use hedging with **idempotent** operations (safe to execute multiple times).
//!
//! # Examples
//!
//! ```rust
//! use do_over::{policy::Policy, hedge::Hedge, error::DoOverError};
//! use std::time::Duration;
//!
//! # async fn example() -> Result<(), DoOverError<std::io::Error>> {
//! // Start backup request after 100ms if primary hasn't completed
//! let hedge = Hedge::new(Duration::from_millis(100));
//!
//! let result = hedge.execute(|| async {
//! Ok::<_, DoOverError<std::io::Error>>("completed")
//! }).await?;
//! # Ok(())
//! # }
//! ```
use Duration;
use sleep;
use crate::;
/// A policy that sends backup requests to reduce tail latency.
///
/// After a configured delay, if the primary request hasn't completed,
/// a hedge (backup) request is started. The first response wins.
///
/// # Warning
///
/// Only use with idempotent operations. Using hedging with non-idempotent
/// operations (like payment processing) can cause duplicate effects.
///
/// # Examples
///
/// ```rust
/// use do_over::{policy::Policy, hedge::Hedge, error::DoOverError};
/// use std::time::Duration;
///
/// # async fn example() {
/// // Good use case: read operations
/// let hedge = Hedge::new(Duration::from_millis(100));
///
/// // The hedge request starts if primary takes > 100ms
/// let result: Result<String, DoOverError<String>> = hedge.execute(|| async {
/// Ok("data".to_string())
/// }).await;
/// # }
/// ```