nautilus_polymarket/common/
retry.rs1use std::time::Duration;
19
20use rand::RngExt;
21
22pub(crate) const AUTO_LOAD_RETRY_JITTER_FRACTION: f64 = 0.25;
23
24#[must_use]
31pub fn auto_load_retry_delay(attempt: u32, base_secs: f64, max_secs: f64) -> Duration {
32 auto_load_retry_delay_with_jitter(
33 attempt,
34 base_secs,
35 max_secs,
36 rand::rng().random_range(0.0..1.0),
37 )
38}
39
40#[must_use]
41pub(crate) fn auto_load_retry_delay_with_jitter(
42 attempt: u32,
43 base_secs: f64,
44 max_secs: f64,
45 jitter_unit: f64,
46) -> Duration {
47 let base = base_secs.max(0.0);
48 let max = max_secs.max(base);
49 let raw = base * 2f64.powi(attempt.min(30) as i32);
50 let capped = raw.min(max);
51 let total = capped + capped * AUTO_LOAD_RETRY_JITTER_FRACTION * jitter_unit.clamp(0.0, 1.0);
52 Duration::from_secs_f64(total.max(0.0))
53}
54
55#[cfg(test)]
56mod tests {
57 use rstest::rstest;
58
59 use super::*;
60
61 #[rstest]
62 fn test_attempt_zero_no_jitter_returns_base() {
63 let d = auto_load_retry_delay_with_jitter(0, 5.0, 15.0, 0.0);
64 assert_eq!(d, Duration::from_secs_f64(5.0));
65 }
66
67 #[rstest]
68 fn test_attempt_zero_full_jitter_returns_base_plus_25_percent() {
69 let d = auto_load_retry_delay_with_jitter(0, 5.0, 15.0, 1.0);
70 assert!((d.as_secs_f64() - 6.25).abs() < 1e-9);
71 }
72
73 #[rstest]
74 fn test_attempt_exponentiates_until_max_cap() {
75 let d = auto_load_retry_delay_with_jitter(2, 5.0, 15.0, 0.0);
76 assert_eq!(d, Duration::from_secs_f64(15.0));
77 }
78
79 #[rstest]
80 fn test_capped_delay_still_takes_jitter() {
81 let d = auto_load_retry_delay_with_jitter(2, 5.0, 15.0, 1.0);
82 assert!((d.as_secs_f64() - 18.75).abs() < 1e-9);
83 }
84
85 #[rstest]
86 fn test_high_attempt_count_does_not_overflow() {
87 let d = auto_load_retry_delay_with_jitter(50, 5.0, 15.0, 0.0);
88 assert_eq!(d, Duration::from_secs_f64(15.0));
89 }
90
91 #[rstest]
92 fn test_zero_base_returns_zero() {
93 let d = auto_load_retry_delay_with_jitter(3, 0.0, 15.0, 0.5);
94 assert_eq!(d, Duration::ZERO);
95 }
96}