1use std::fmt;
8use std::num::NonZeroU32;
9use std::sync::Arc;
10use std::time::Duration;
11
12type RandomSource = Arc<dyn Fn() -> f64 + Send + Sync>;
13
14fn default_random() -> RandomSource {
15 Arc::new(rand::random::<f64>)
16}
17
18#[derive(Debug, Clone, PartialEq, Eq)]
22#[non_exhaustive]
23pub struct BackoffContext {
24 pub attempt: NonZeroU32,
26 pub elapsed: Duration,
28 pub last_delay: Option<Duration>,
30}
31
32impl BackoffContext {
33 pub fn new(attempt: NonZeroU32) -> Self {
35 Self {
36 attempt,
37 elapsed: Duration::ZERO,
38 last_delay: None,
39 }
40 }
41
42 #[must_use]
44 pub fn with_elapsed(mut self, elapsed: Duration) -> Self {
45 self.elapsed = elapsed;
46 self
47 }
48
49 #[must_use]
51 pub fn with_last_delay(mut self, last_delay: Duration) -> Self {
52 self.last_delay = Some(last_delay);
53 self
54 }
55}
56
57pub trait BackoffStrategy: Send + Sync + 'static {
59 fn next_delay(&self, context: &BackoffContext) -> Duration;
61}
62
63#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
65#[non_exhaustive]
66pub enum JitterKind {
67 None,
69 #[default]
71 Full,
72 Equal,
74 Decorrelated,
77}
78
79fn nanos(duration: Duration) -> f64 {
80 duration.as_nanos() as f64
81}
82
83fn from_nanos(nanos: f64) -> Duration {
85 if nanos.is_nan() || nanos <= 0.0 {
86 return Duration::ZERO;
87 }
88 Duration::from_nanos(nanos.round() as u64)
89}
90
91struct JitterInput {
92 raw: Duration,
93 kind: JitterKind,
94 base: Duration,
95 max: Duration,
96 last_delay: Option<Duration>,
97}
98
99fn jitter(input: &JitterInput, random: f64) -> Duration {
100 let raw = nanos(input.raw);
101 let full = || from_nanos(random * raw);
102 match input.kind {
103 JitterKind::None => input.raw,
104 JitterKind::Full => full(),
105 JitterKind::Equal => from_nanos(raw / 2.0 + random * (raw / 2.0)),
106 JitterKind::Decorrelated => {
107 let Some(last_delay) = input.last_delay else {
108 return full();
109 };
110 let base = nanos(input.base);
112 let upper = base.max(nanos(input.max).min(nanos(last_delay) * 3.0));
113 from_nanos(base + random * (upper - base))
114 }
115 }
116}
117
118#[derive(Debug, Clone, Copy, PartialEq, Eq, bon::Builder)]
120pub struct ConstantBackoffOptions {
121 #[builder(default = Duration::from_secs(1))]
123 pub delay: Duration,
124}
125
126impl Default for ConstantBackoffOptions {
127 fn default() -> Self {
128 Self::builder().build()
129 }
130}
131
132#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
134pub struct ConstantBackoff {
135 options: ConstantBackoffOptions,
136}
137
138impl ConstantBackoff {
139 pub fn new(options: ConstantBackoffOptions) -> Self {
141 Self { options }
142 }
143}
144
145impl BackoffStrategy for ConstantBackoff {
146 fn next_delay(&self, _context: &BackoffContext) -> Duration {
147 self.options.delay
148 }
149}
150
151#[derive(Debug, Clone, Copy, PartialEq, Eq, bon::Builder)]
153pub struct LinearBackoffOptions {
154 #[builder(default = Duration::from_secs(1))]
156 pub base: Duration,
157 #[builder(default = Duration::from_secs(30))]
159 pub max: Duration,
160 #[builder(default)]
162 pub jitter: JitterKind,
163}
164
165impl Default for LinearBackoffOptions {
166 fn default() -> Self {
167 Self::builder().build()
168 }
169}
170
171#[derive(Clone)]
173pub struct LinearBackoff {
174 options: LinearBackoffOptions,
175 random: RandomSource,
176}
177
178impl LinearBackoff {
179 pub fn new(options: LinearBackoffOptions) -> Self {
181 Self {
182 options,
183 random: default_random(),
184 }
185 }
186
187 #[must_use]
189 pub fn with_random(mut self, random: impl Fn() -> f64 + Send + Sync + 'static) -> Self {
190 self.random = Arc::new(random);
191 self
192 }
193}
194
195impl Default for LinearBackoff {
196 fn default() -> Self {
197 Self::new(LinearBackoffOptions::default())
198 }
199}
200
201impl fmt::Debug for LinearBackoff {
202 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
203 f.debug_struct("LinearBackoff")
204 .field("options", &self.options)
205 .finish_non_exhaustive()
206 }
207}
208
209impl BackoffStrategy for LinearBackoff {
210 fn next_delay(&self, context: &BackoffContext) -> Duration {
211 let options = &self.options;
212 let raw = from_nanos(nanos(options.base) * f64::from(context.attempt.get())).min(options.max);
213 let input = JitterInput {
214 raw,
215 kind: options.jitter,
216 base: options.base,
217 max: options.max,
218 last_delay: context.last_delay,
219 };
220 jitter(&input, (self.random)())
221 }
222}
223
224#[derive(Debug, Clone, Copy, PartialEq, bon::Builder)]
226pub struct ExponentialBackoffOptions {
227 #[builder(default = Duration::from_secs(1))]
229 pub base: Duration,
230 #[builder(default = Duration::from_secs(30))]
232 pub max: Duration,
233 #[builder(default = 2.0)]
235 pub multiplier: f64,
236 #[builder(default)]
238 pub jitter: JitterKind,
239}
240
241impl Default for ExponentialBackoffOptions {
242 fn default() -> Self {
243 Self::builder().build()
244 }
245}
246
247#[derive(Clone)]
250pub struct ExponentialBackoff {
251 options: ExponentialBackoffOptions,
252 random: RandomSource,
253}
254
255impl ExponentialBackoff {
256 pub fn new(options: ExponentialBackoffOptions) -> Self {
258 Self {
259 options,
260 random: default_random(),
261 }
262 }
263
264 #[must_use]
266 pub fn with_random(mut self, random: impl Fn() -> f64 + Send + Sync + 'static) -> Self {
267 self.random = Arc::new(random);
268 self
269 }
270}
271
272impl Default for ExponentialBackoff {
273 fn default() -> Self {
274 Self::new(ExponentialBackoffOptions::default())
275 }
276}
277
278impl fmt::Debug for ExponentialBackoff {
279 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280 f.debug_struct("ExponentialBackoff")
281 .field("options", &self.options)
282 .finish_non_exhaustive()
283 }
284}
285
286impl BackoffStrategy for ExponentialBackoff {
287 fn next_delay(&self, context: &BackoffContext) -> Duration {
288 let options = &self.options;
289 let exponent = i32::try_from(context.attempt.get() - 1).unwrap_or(i32::MAX);
290 let raw = from_nanos(nanos(options.base) * options.multiplier.powi(exponent)).min(options.max);
291 let input = JitterInput {
292 raw,
293 kind: options.jitter,
294 base: options.base,
295 max: options.max,
296 last_delay: context.last_delay,
297 };
298 jitter(&input, (self.random)())
299 }
300}
301
302#[cfg(test)]
304mod tests {
305 use super::*;
306
307 fn ms(millis: u64) -> Duration {
308 Duration::from_millis(millis)
309 }
310
311 fn ctx(attempt: u32) -> BackoffContext {
312 BackoffContext::new(NonZeroU32::new(attempt).unwrap())
313 }
314
315 fn linear(options: LinearBackoffOptions) -> LinearBackoff {
316 LinearBackoff::new(options).with_random(|| 0.5)
317 }
318
319 fn exponential(options: ExponentialBackoffOptions) -> ExponentialBackoff {
320 ExponentialBackoff::new(options).with_random(|| 0.5)
321 }
322
323 #[test]
324 fn returns_the_configured_delay_regardless_of_attempt() {
325 let backoff = ConstantBackoff::new(ConstantBackoffOptions { delay: ms(250) });
326 assert_eq!(backoff.next_delay(&ctx(1)), ms(250));
327 assert_eq!(backoff.next_delay(&ctx(5)), ms(250));
328 }
329
330 #[test]
331 fn defaults_delay_ms_to_1000() {
332 assert_eq!(ConstantBackoff::default().next_delay(&ctx(1)), ms(1000));
333 }
334
335 #[test]
336 fn grows_as_base_ms_times_attempt() {
337 let backoff = linear(
338 LinearBackoffOptions::builder()
339 .base(ms(100))
340 .jitter(JitterKind::None)
341 .build(),
342 );
343 assert_eq!(backoff.next_delay(&ctx(1)), ms(100));
344 assert_eq!(backoff.next_delay(&ctx(2)), ms(200));
345 assert_eq!(backoff.next_delay(&ctx(3)), ms(300));
346 }
347
348 #[test]
349 fn clamps_to_max_ms_before_jitter() {
350 let backoff = linear(
351 LinearBackoffOptions::builder()
352 .base(ms(1000))
353 .max(ms(2500))
354 .jitter(JitterKind::None)
355 .build(),
356 );
357 assert_eq!(backoff.next_delay(&ctx(10)), ms(2500));
358 }
359
360 #[test]
361 fn applies_full_jitter_by_default_math_random_times_raw() {
362 let backoff = linear(LinearBackoffOptions::builder().base(ms(100)).build());
363 assert_eq!(backoff.next_delay(&ctx(4)), ms(200));
364 }
365
366 #[test]
367 fn grows_as_base_ms_times_multiplier_to_the_attempt_minus_1() {
368 let backoff = exponential(
369 ExponentialBackoffOptions::builder()
370 .base(ms(100))
371 .jitter(JitterKind::None)
372 .build(),
373 );
374 let delays: Vec<_> = (1..=4).map(|attempt| backoff.next_delay(&ctx(attempt))).collect();
375 assert_eq!(delays, [ms(100), ms(200), ms(400), ms(800)]);
376 }
377
378 #[test]
379 fn honors_custom_multiplier() {
380 let backoff = exponential(
381 ExponentialBackoffOptions::builder()
382 .base(ms(100))
383 .multiplier(3.0)
384 .jitter(JitterKind::None)
385 .build(),
386 );
387 assert_eq!(backoff.next_delay(&ctx(3)), ms(900));
388 }
389
390 #[test]
391 fn clamps_to_max_ms() {
392 let backoff = exponential(
393 ExponentialBackoffOptions::builder()
394 .base(ms(100))
395 .max(ms(500))
396 .jitter(JitterKind::None)
397 .build(),
398 );
399 assert_eq!(backoff.next_delay(&ctx(10)), ms(500));
400 }
401
402 #[test]
403 fn applies_full_jitter_by_default() {
404 let backoff = exponential(ExponentialBackoffOptions::builder().base(ms(100)).build());
405 assert_eq!(backoff.next_delay(&ctx(3)), ms(200));
406 }
407
408 #[test]
409 fn applies_equal_jitter_as_raw_half_plus_random_times_raw_half() {
410 let backoff = exponential(
411 ExponentialBackoffOptions::builder()
412 .base(ms(100))
413 .jitter(JitterKind::Equal)
414 .build(),
415 );
416 assert_eq!(backoff.next_delay(&ctx(2)), ms(150));
417 }
418
419 #[test]
420 fn applies_no_jitter_when_set_to_none() {
421 let backoff = exponential(
422 ExponentialBackoffOptions::builder()
423 .base(ms(100))
424 .jitter(JitterKind::None)
425 .build(),
426 );
427 assert_eq!(backoff.next_delay(&ctx(3)), ms(400));
428 }
429
430 #[test]
431 fn falls_back_to_full_jitter_for_decorrelated_when_last_delay_ms_missing() {
432 let backoff = exponential(
433 ExponentialBackoffOptions::builder()
434 .base(ms(100))
435 .jitter(JitterKind::Decorrelated)
436 .build(),
437 );
438 assert_eq!(backoff.next_delay(&ctx(3)), ms(200));
439 }
440
441 #[test]
442 fn applies_decorrelated_jitter_as_uniform_base_ms_to_min_max_ms_last_delay_ms_times_3() {
443 let backoff = exponential(
444 ExponentialBackoffOptions::builder()
445 .base(ms(100))
446 .max(ms(10_000))
447 .jitter(JitterKind::Decorrelated)
448 .build(),
449 );
450 assert_eq!(backoff.next_delay(&ctx(2).with_last_delay(ms(200))), ms(350));
451 }
452
453 #[test]
454 fn caps_decorrelated_upper_at_max_ms() {
455 let backoff = exponential(
456 ExponentialBackoffOptions::builder()
457 .base(ms(100))
458 .max(ms(500))
459 .jitter(JitterKind::Decorrelated)
460 .build(),
461 );
462 assert_eq!(backoff.next_delay(&ctx(2).with_last_delay(ms(1000))), ms(300));
463 }
464
465 #[test]
466 fn floors_decorrelated_upper_at_base_ms_when_last_delay_times_3_is_below_base_ms() {
467 let backoff = exponential(
468 ExponentialBackoffOptions::builder()
469 .base(ms(100))
470 .max(ms(500))
471 .jitter(JitterKind::Decorrelated)
472 .build(),
473 );
474 assert_eq!(backoff.next_delay(&ctx(2).with_last_delay(ms(10))), ms(100));
475 }
476
477 #[test]
478 fn saturates_instead_of_overflowing_for_huge_attempts() {
479 let backoff = exponential(ExponentialBackoffOptions::builder().jitter(JitterKind::None).build());
480 assert_eq!(backoff.next_delay(&ctx(u32::MAX)), Duration::from_secs(30));
481 }
482
483 #[test]
484 fn default_jitter_stays_within_the_raw_delay() {
485 let backoff = ExponentialBackoff::default();
486 for attempt in 1..=10 {
487 assert!(backoff.next_delay(&ctx(attempt)) <= Duration::from_secs(30));
488 }
489 }
490}