1use std::hash::{BuildHasher, RandomState};
5use std::time::{Duration, SystemTime, UNIX_EPOCH};
6
7use crate::client::Reply;
8use crate::Error;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub struct RetryPolicy {
43 max_attempts: u32,
44 base_delay: Duration,
45 max_delay: Duration,
46}
47
48impl Default for RetryPolicy {
49 fn default() -> Self {
50 RetryPolicy {
51 max_attempts: Self::DEFAULT_MAX_ATTEMPTS,
52 base_delay: Self::DEFAULT_BASE_DELAY,
53 max_delay: Self::DEFAULT_MAX_DELAY,
54 }
55 }
56}
57
58impl RetryPolicy {
59 pub const DEFAULT_MAX_ATTEMPTS: u32 = 3;
61 pub const DEFAULT_BASE_DELAY: Duration = Duration::from_millis(200);
63 pub const DEFAULT_MAX_DELAY: Duration = Duration::from_secs(5);
66
67 pub fn new() -> Self {
69 Self::default()
70 }
71
72 pub fn with_max_attempts(mut self, attempts: u32) -> Self {
75 self.max_attempts = attempts.max(1);
76 self
77 }
78
79 pub fn with_base_delay(mut self, delay: Duration) -> Self {
82 self.base_delay = delay;
83 self
84 }
85
86 pub fn with_max_delay(mut self, delay: Duration) -> Self {
89 self.max_delay = delay;
90 self
91 }
92
93 pub fn max_attempts(&self) -> u32 {
95 self.max_attempts
96 }
97
98 pub fn base_delay(&self) -> Duration {
100 self.base_delay
101 }
102
103 pub fn max_delay(&self) -> Duration {
105 self.max_delay
106 }
107
108 pub(crate) fn backoff(&self, retry: u32, random: u64) -> Duration {
112 let shift = retry.saturating_sub(1).min(31);
113 let ceiling = self
114 .base_delay
115 .saturating_mul(1 << shift)
116 .min(self.max_delay);
117 let half = ceiling / 2;
118 let span = (ceiling - half).as_nanos();
119 let extra = u64::try_from(u128::from(random) % (span + 1)).unwrap_or(u64::MAX);
120 half.saturating_add(Duration::from_nanos(extra))
121 }
122
123 pub(crate) fn next_wait(
126 &self,
127 attempt: u32,
128 outcome: &Result<Reply, Error>,
129 now: SystemTime,
130 random: u64,
131 ) -> Option<Duration> {
132 if attempt >= self.max_attempts {
133 return None;
134 }
135 match outcome {
136 Err(Error::Transport(_)) => Some(self.backoff(attempt, random)),
137 Ok(reply) if matches!(reply.status, 429 | 503) => {
138 self.server_wait(reply, attempt, now, random)
139 }
140 _ => None,
141 }
142 }
143
144 fn server_wait(
147 &self,
148 reply: &Reply,
149 attempt: u32,
150 now: SystemTime,
151 random: u64,
152 ) -> Option<Duration> {
153 match reply
154 .retry_after
155 .as_deref()
156 .and_then(|v| retry_after(v, now))
157 {
158 Some(wait) if wait > self.max_delay => None,
159 Some(wait) => Some(wait),
160 None => Some(self.backoff(attempt, random)),
161 }
162 }
163}
164
165pub(crate) fn run<A, S>(policy: &RetryPolicy, mut attempt: A, mut sleep: S) -> Result<Reply, Error>
168where
169 A: FnMut() -> Result<Reply, Error>,
170 S: FnMut(Duration),
171{
172 let mut made = 1;
173 loop {
174 let outcome = attempt();
175 match policy.next_wait(made, &outcome, SystemTime::now(), random()) {
176 Some(wait) => sleep(wait),
177 None => return outcome,
178 }
179 made += 1;
180 }
181}
182
183fn random() -> u64 {
186 RandomState::new().hash_one(SystemTime::now())
187}
188
189pub(crate) fn retry_after(value: &str, now: SystemTime) -> Option<Duration> {
192 let value = value.trim();
193 if !value.is_empty() && value.bytes().all(|b| b.is_ascii_digit()) {
194 return Some(Duration::from_secs(value.parse().unwrap_or(u64::MAX)));
195 }
196 let at = http_date(value)?;
197 Some(at.duration_since(now).unwrap_or(Duration::ZERO))
198}
199
200const MONTHS: [&str; 12] = [
201 "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
202];
203
204fn http_date(value: &str) -> Option<SystemTime> {
207 let fields: Vec<&str> = value.split(' ').collect();
208 let [_weekday, day, month, year, time, "GMT"] = fields.as_slice() else {
209 return None;
210 };
211 let month = MONTHS.iter().position(|m| m == month)?;
212 let year = i64::from(year.parse::<u16>().ok()?);
214 let day = i64::from(day.parse::<u8>().ok()?);
215 let seconds = days_from_civil(year, month, day) * 86_400 + seconds_of_day(time)?;
216 u64::try_from(seconds)
217 .ok()
218 .map(|s| UNIX_EPOCH + Duration::from_secs(s))
219}
220
221fn seconds_of_day(time: &str) -> Option<i64> {
223 let fields: Vec<&str> = time.split(':').collect();
224 let [hours, minutes, seconds] = fields.as_slice() else {
225 return None;
226 };
227 let [hours, minutes, seconds] =
228 [hours, minutes, seconds].map(|f| f.parse::<u8>().ok().map(i64::from));
229 Some(hours? * 3600 + minutes? * 60 + seconds?)
230}
231
232fn days_from_civil(year: i64, month0: usize, day: i64) -> i64 {
235 let march = i64::try_from((month0 + 10) % 12).unwrap_or(0);
237 let year = if march >= 10 { year - 1 } else { year };
238 let era = year.div_euclid(400);
239 let year_of_era = year - era * 400;
240 let day_of_year = (153 * march + 2) / 5 + day - 1;
241 let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
242 era * 146_097 + day_of_era - 719_468
243}
244
245#[cfg(test)]
246mod tests;