1use std::time::Duration;
12
13use serde::Deserialize;
14
15pub const ATTEMPTS: u32 = 3;
17pub const MAX_RETRY_AFTER: Duration = Duration::from_secs(60);
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22#[non_exhaustive]
23pub enum Code {
24 Unauthenticated,
26 KeyExpired,
28 KeyRevoked,
30 ForbiddenRole,
32 KeyIdMismatch,
34 RewriteInProgress,
36 LeaseHeld,
38 RewriteIncomplete,
40 RewriteEnded,
42 QuotaExceeded,
44 ItemTooLarge,
46 ContentMismatch,
48 NotFound,
50 InvalidId,
52 InvalidRequest,
54 RateLimited,
56 ServiceUnavailable,
58 Unknown,
60}
61
62impl Code {
63 pub fn parse(code: &str) -> Self {
65 match code {
66 "UNAUTHENTICATED" => Self::Unauthenticated,
67 "KEY_EXPIRED" => Self::KeyExpired,
68 "KEY_REVOKED" => Self::KeyRevoked,
69 "FORBIDDEN_ROLE" => Self::ForbiddenRole,
70 "KEY_ID_MISMATCH" => Self::KeyIdMismatch,
71 "REWRITE_IN_PROGRESS" => Self::RewriteInProgress,
72 "LEASE_HELD" => Self::LeaseHeld,
73 "REWRITE_INCOMPLETE" => Self::RewriteIncomplete,
74 "REWRITE_ENDED" => Self::RewriteEnded,
75 "QUOTA_EXCEEDED" => Self::QuotaExceeded,
76 "ITEM_TOO_LARGE" => Self::ItemTooLarge,
77 "CONTENT_MISMATCH" => Self::ContentMismatch,
78 "NOT_FOUND" => Self::NotFound,
79 "INVALID_ID" => Self::InvalidId,
80 "INVALID_REQUEST" => Self::InvalidRequest,
81 "RATE_LIMITED" => Self::RateLimited,
82 "SERVICE_UNAVAILABLE" => Self::ServiceUnavailable,
83 _ => Self::Unknown,
84 }
85 }
86}
87
88#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
90#[serde(rename_all = "camelCase")]
91pub struct Problem {
92 pub code: String,
94 pub status: u16,
96 pub title: String,
98 #[serde(default)]
100 pub detail: Option<String>,
101 #[serde(default)]
103 pub retryable: bool,
104 #[serde(default)]
106 pub lease_expires_at: Option<String>,
107}
108
109impl Problem {
110 pub fn code(&self) -> Code {
112 Code::parse(&self.code)
113 }
114}
115
116#[derive(Debug, thiserror::Error)]
118#[non_exhaustive]
119pub enum HttpsError {
120 #[error("the server refused ({}): {}", .problem.code, describe(.problem))]
122 Refused {
123 problem: Problem,
125 retry_after: Option<Duration>,
127 },
128 #[error("cannot reach {url}: {reason}")]
130 Transport {
131 url: String,
133 reason: String,
135 retryable: bool,
137 },
138 #[error("unexpected answer from the server: {0}")]
140 Protocol(String),
141}
142
143impl HttpsError {
144 pub fn code(&self) -> Option<Code> {
146 match self {
147 Self::Refused { problem, .. } => Some(problem.code()),
148 _ => None,
149 }
150 }
151}
152
153fn describe(problem: &Problem) -> String {
155 let mut text = problem
156 .detail
157 .clone()
158 .unwrap_or_else(|| problem.title.clone());
159 if let Some(until) = &problem.lease_expires_at {
160 text.push_str(&format!(" (until {until})"));
161 }
162 text
163}
164
165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
167pub enum Next {
168 Stop,
170 RetryAfter(Duration),
172}
173
174pub fn next(err: &HttpsError, attempts: u32) -> Next {
176 if attempts >= ATTEMPTS {
177 return Next::Stop;
178 }
179 let backoff = Duration::from_secs(1 << (attempts.max(1) - 1));
180 match err {
181 HttpsError::Refused {
182 problem,
183 retry_after,
184 } => match problem.code() {
185 Code::RateLimited => match retry_after {
186 Some(wait) if *wait <= MAX_RETRY_AFTER => Next::RetryAfter(*wait),
187 Some(_) => Next::Stop,
188 None => Next::RetryAfter(backoff),
189 },
190 _ if problem.status == 401 => Next::Stop,
191 _ if problem.retryable => Next::RetryAfter(backoff),
192 _ => Next::Stop,
193 },
194 HttpsError::Transport { retryable, .. } if *retryable => Next::RetryAfter(backoff),
195 _ => Next::Stop,
196 }
197}
198
199#[cfg(test)]
200mod tests {
201 use super::*;
202
203 const CODES: [&str; 17] = [
204 "CONTENT_MISMATCH",
205 "FORBIDDEN_ROLE",
206 "INVALID_ID",
207 "INVALID_REQUEST",
208 "ITEM_TOO_LARGE",
209 "KEY_EXPIRED",
210 "KEY_ID_MISMATCH",
211 "KEY_REVOKED",
212 "LEASE_HELD",
213 "NOT_FOUND",
214 "QUOTA_EXCEEDED",
215 "RATE_LIMITED",
216 "REWRITE_ENDED",
217 "REWRITE_INCOMPLETE",
218 "REWRITE_IN_PROGRESS",
219 "SERVICE_UNAVAILABLE",
220 "UNAUTHENTICATED",
221 ];
222
223 fn refused(code: &str, status: u16, retryable: bool) -> HttpsError {
224 HttpsError::Refused {
225 problem: Problem {
226 code: code.to_owned(),
227 status,
228 title: "t".to_owned(),
229 detail: None,
230 retryable,
231 lease_expires_at: None,
232 },
233 retry_after: None,
234 }
235 }
236
237 #[test]
238 fn every_documented_code_is_known_and_a_new_one_is_not_an_error() {
239 for code in CODES {
240 assert_ne!(Code::parse(code), Code::Unknown, "{code}");
241 }
242 assert_eq!(Code::parse("SOMETHING_NEW"), Code::Unknown);
243 }
244
245 #[test]
246 fn a_problem_parses_with_or_without_its_optional_fields() {
247 let full: Problem = serde_json::from_str(
248 r#"{"code":"LEASE_HELD","status":409,"title":"held","detail":"another key holds it","retryable":true,"leaseExpiresAt":"2026-09-19T16:00:00Z","extra":1}"#,
249 )
250 .unwrap();
251 assert_eq!(full.code(), Code::LeaseHeld);
252 let err = HttpsError::Refused {
253 problem: full,
254 retry_after: None,
255 };
256 assert_eq!(
257 err.to_string(),
258 "the server refused (LEASE_HELD): another key holds it (until 2026-09-19T16:00:00Z)"
259 );
260 let bare: Problem =
261 serde_json::from_str(r#"{"code":"NOT_FOUND","status":404,"title":"no such item"}"#)
262 .unwrap();
263 assert!(!bare.retryable);
264 assert_eq!(
265 HttpsError::Refused {
266 problem: bare,
267 retry_after: None
268 }
269 .to_string(),
270 "the server refused (NOT_FOUND): no such item"
271 );
272 }
273
274 #[test]
275 fn retries_follow_the_server_and_never_repeat_a_401() {
276 assert_eq!(
277 next(&refused("SERVICE_UNAVAILABLE", 503, true), 1),
278 Next::RetryAfter(Duration::from_secs(1))
279 );
280 assert_eq!(
281 next(&refused("REWRITE_IN_PROGRESS", 409, true), 2),
282 Next::RetryAfter(Duration::from_secs(2))
283 );
284 assert_eq!(
285 next(&refused("SERVICE_UNAVAILABLE", 503, true), 3),
286 Next::Stop
287 );
288 for (code, status) in [
289 ("UNAUTHENTICATED", 401),
290 ("KEY_EXPIRED", 401),
291 ("KEY_REVOKED", 401),
292 ] {
293 assert_eq!(next(&refused(code, status, true), 1), Next::Stop, "{code}");
295 }
296 assert_eq!(next(&refused("NOT_FOUND", 404, false), 1), Next::Stop);
297 assert_eq!(next(&refused("QUOTA_EXCEEDED", 413, false), 1), Next::Stop);
298 }
299
300 #[test]
301 fn a_rate_limit_waits_out_a_short_retry_after_only() {
302 let limited = |after: Option<u64>| HttpsError::Refused {
303 problem: Problem {
304 code: "RATE_LIMITED".to_owned(),
305 status: 429,
306 title: "slow down".to_owned(),
307 detail: None,
308 retryable: true,
309 lease_expires_at: None,
310 },
311 retry_after: after.map(Duration::from_secs),
312 };
313 assert_eq!(
314 next(&limited(Some(30)), 1),
315 Next::RetryAfter(Duration::from_secs(30))
316 );
317 assert_eq!(next(&limited(Some(600)), 1), Next::Stop);
318 assert_eq!(
319 next(&limited(None), 1),
320 Next::RetryAfter(Duration::from_secs(1))
321 );
322 }
323
324 #[test]
325 fn broken_connections_are_retried_and_protocol_errors_are_not() {
326 let transport = |retryable| HttpsError::Transport {
327 url: "https://x".to_owned(),
328 reason: "reset".to_owned(),
329 retryable,
330 };
331 assert_eq!(
332 next(&transport(true), 1),
333 Next::RetryAfter(Duration::from_secs(1))
334 );
335 assert_eq!(next(&transport(false), 1), Next::Stop);
336 assert_eq!(
337 next(&HttpsError::Protocol("garbage".to_owned()), 1),
338 Next::Stop
339 );
340 }
341}