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
use super::*;
/// Default construction for [`RetryPolicy`].
impl Default for RetryPolicy {
/// Creates a standard retry policy (`3` retries, `100 ms` base, `30 s` max, `2.0x`, full jitter).
///
/// # Returns
///
/// - `Self` - Default retry policy.
fn default() -> Self {
Self {
max_retries: DEFAULT_MAX_RETRIES,
initial_delay_ms: DEFAULT_INITIAL_DELAY_MS,
max_delay_ms: DEFAULT_MAX_DELAY_MS,
multiplier_tenths: 20,
jitter: JitterMode::Full,
total_timeout_ms: 0,
}
}
}
/// Builder and delay calculation methods for [`RetryPolicy`].
impl RetryPolicy {
/// Creates a policy with explicit `max_retries`, `initial_delay_ms`, and `max_delay_ms`.
///
/// # Arguments
///
/// - `u32` - Maximum number of retries after the initial attempt.
/// - `u64` - Initial base delay in milliseconds.
/// - `u64` - Maximum delay cap in milliseconds.
///
/// # Returns
///
/// - `Self` - Configured retry policy.
pub const fn new(max_retries: u32, initial_delay_ms: u64, max_delay_ms: u64) -> Self {
Self {
max_retries,
initial_delay_ms,
max_delay_ms,
multiplier_tenths: 20,
jitter: JitterMode::Full,
total_timeout_ms: 0,
}
}
/// Sets the jitter mode for this policy.
///
/// # Arguments
///
/// - `JitterMode` - Desired jitter strategy.
///
/// # Returns
///
/// - `Self` - Updated policy.
pub const fn with_jitter(self, jitter: JitterMode) -> Self {
Self { jitter, ..self }
}
/// Sets the exponential backoff factor in tenths (e.g. `15` = `1.5x`, `20` = `2.0x`, clamped `>= 10`).
///
/// # Arguments
///
/// - `u32` - Backoff factor multiplied by 10.
///
/// # Returns
///
/// - `Self` - Updated policy.
pub const fn with_multiplier_tenths(self, tenths: u32) -> Self {
let multiplier_tenths: u32 = if tenths < 10 { 10 } else { tenths };
Self {
multiplier_tenths,
..self
}
}
/// Sets an overall deadline budget across all attempts and sleeps (`0` = no total deadline).
///
/// # Arguments
///
/// - `u64` - Total deadline budget in milliseconds.
///
/// # Returns
///
/// - `Self` - Updated policy.
pub const fn with_total_timeout_ms(self, total_timeout_ms: u64) -> Self {
Self {
total_timeout_ms,
..self
}
}
/// Returns the configured maximum retries.
///
/// # Returns
///
/// - `u32` - Maximum retry count.
#[inline(always)]
pub const fn get_max_retries(&self) -> u32 {
let Self { max_retries, .. } = self;
*max_retries
}
/// Returns the initial delay in milliseconds.
///
/// # Returns
///
/// - `u64` - Base delay in milliseconds.
#[inline(always)]
pub const fn get_initial_delay_ms(&self) -> u64 {
let Self {
initial_delay_ms, ..
} = self;
*initial_delay_ms
}
/// Returns the maximum delay cap in milliseconds.
///
/// # Returns
///
/// - `u64` - Delay cap in milliseconds.
#[inline(always)]
pub const fn get_max_delay_ms(&self) -> u64 {
let Self { max_delay_ms, .. } = self;
*max_delay_ms
}
/// Returns the deterministic uncapped-jitter exponential delay in milliseconds for `attempt`.
///
/// # Arguments
///
/// - `u32` - Zero-based retry index (`0` = first retry).
///
/// # Returns
///
/// - `u64` - Delay in milliseconds clamped to `max_delay_ms`.
#[inline]
pub fn raw_delay_ms(&self, attempt: u32) -> u64 {
let Self {
initial_delay_ms,
max_delay_ms,
multiplier_tenths,
..
} = self;
let cap: u64 = (*max_delay_ms).max(*initial_delay_ms);
let shift: u32 = attempt.min(31);
if *multiplier_tenths == 20 {
let shifted: u128 = u128::from(*initial_delay_ms) << shift;
return shifted.min(u128::from(cap)) as u64;
}
if *multiplier_tenths == 10 {
return *initial_delay_ms;
}
let mut delay: u128 = u128::from(*initial_delay_ms);
let mult: u128 = u128::from(*multiplier_tenths);
let capped: u128 = u128::from(cap);
for _ in 0..shift {
delay = delay.saturating_mul(mult) / 10;
if delay >= capped {
return cap;
}
}
(delay as u64).min(cap)
}
/// Starts a stateful [`RetrySchedule`] seeded from system time.
///
/// # Returns
///
/// - `RetrySchedule` - Active retry schedule.
#[inline]
pub fn start(&self) -> RetrySchedule {
let seed: u64 = match SystemTime::now().duration_since(UNIX_EPOCH) {
Ok(d) => d.as_nanos() as u64,
Err(_) => JITTER_MIX_INC,
};
self.start_with_seed(seed)
}
/// Starts a deterministic [`RetrySchedule`] with an explicit PRNG `seed`.
///
/// # Arguments
///
/// - `u64` - Explicit PRNG seed for reproducible jitter.
///
/// # Returns
///
/// - `RetrySchedule` - Active retry schedule.
#[inline]
pub fn start_with_seed(&self, seed: u64) -> RetrySchedule {
let Self {
initial_delay_ms,
total_timeout_ms,
..
} = self;
let started_at: Option<Instant> = if *total_timeout_ms > 0 {
Some(Instant::now())
} else {
None
};
RetrySchedule {
policy: *self,
attempts_used: 0,
prev_delay_ms: *initial_delay_ms,
rng_state: splitmix_rand(seed),
started_at,
}
}
/// Executes a synchronous fallible operation with backoff sleeps until success or retry exhaustion.
///
/// # Arguments
///
/// - `F` - Fallible operation invoked for each attempt.
/// - `P` - Predicate returning `true` when an error is retryable.
///
/// # Returns
///
/// - `Result<T, E>` - First `Ok(value)` or the final error when exhausted or non-retryable.
pub fn execute_sync<T, E, F, P>(&self, mut operation: F, mut is_retryable: P) -> Result<T, E>
where
F: FnMut() -> Result<T, E>,
P: FnMut(&E) -> bool,
{
let mut schedule: RetrySchedule = self.start();
loop {
match operation() {
Ok(value) => return Ok(value),
Err(error) => {
if !is_retryable(&error) {
return Err(error);
}
let Some(delay) = schedule.next_delay() else {
return Err(error);
};
if !delay.is_zero() {
thread::sleep(delay);
}
}
}
}
}
}
/// Step-by-step delay computation for [`RetrySchedule`].
impl RetrySchedule {
/// Returns the delay before the next retry, or `None` if retries or total timeout are exhausted.
///
/// # Returns
///
/// - `Option<Duration>` - Backoff duration to sleep before retrying, or `None` to stop.
#[inline(always)]
pub fn next_delay(&mut self) -> Option<Duration> {
self.next_delay_with_hint(None)
}
/// Returns the delay before the next retry, honoring an optional server `Retry-After` hint.
///
/// # Arguments
///
/// - `Option<Duration>` - Optional minimum delay requested by the remote server.
///
/// # Returns
///
/// - `Option<Duration>` - Effective delay within budget, or `None` if exhausted or past deadline.
#[inline]
pub fn next_delay_with_hint(&mut self, retry_after: Option<Duration>) -> Option<Duration> {
let Self {
policy,
attempts_used,
prev_delay_ms,
rng_state,
started_at,
} = self;
if *attempts_used >= policy.max_retries {
return None;
}
let attempt: u32 = *attempts_used;
*attempts_used += 1;
let jittered_ms: u64 = match policy.jitter {
JitterMode::None => policy.raw_delay_ms(attempt),
JitterMode::Full => {
let base_ms: u64 = policy.raw_delay_ms(attempt);
let entropy: u64 = splitmix_rand(*rng_state);
*rng_state = entropy;
rand_inclusive(entropy, base_ms)
}
JitterMode::Equal => {
let base_ms: u64 = policy.raw_delay_ms(attempt);
let entropy: u64 = splitmix_rand(*rng_state);
*rng_state = entropy;
let half: u64 = base_ms >> 1;
half + rand_inclusive(entropy, base_ms - half)
}
JitterMode::Decorrelated => {
let entropy: u64 = splitmix_rand(*rng_state);
*rng_state = entropy;
let lo: u64 = policy.initial_delay_ms;
let hi: u64 = (*prev_delay_ms).saturating_mul(3).max(lo);
let span: u64 = hi.saturating_sub(lo);
let sampled: u64 = lo.saturating_add(rand_inclusive(entropy, span));
let cap: u64 = policy.max_delay_ms.max(lo);
let val: u64 = sampled.min(cap);
*prev_delay_ms = val.max(lo);
val
}
};
let chosen_ms: u64 = match retry_after {
Some(dur) => {
let hint_ms: u64 = u64::try_from(dur.as_millis())
.unwrap_or(policy.max_delay_ms)
.min(policy.max_delay_ms.max(policy.initial_delay_ms));
jittered_ms.max(hint_ms)
}
None => jittered_ms,
};
if policy.total_timeout_ms > 0
&& let Some(start) = started_at
{
let elapsed_ms: u64 = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX);
if elapsed_ms.saturating_add(chosen_ms) >= policy.total_timeout_ms {
return None;
}
}
Some(Duration::from_millis(chosen_ms))
}
/// Returns the number of retries consumed so far.
///
/// # Returns
///
/// - `u32` - Consumed retry count.
#[inline(always)]
pub fn attempts_used(&self) -> u32 {
let Self { attempts_used, .. } = self;
*attempts_used
}
}