1use crate::util::errors::{GitCliError, HttpNotSuccessful};
45use crate::util::network::http_async;
46use crate::{CargoResult, GlobalContext};
47use anyhow::Error;
48use rand::RngExt;
49use std::cmp::min;
50use std::time::Duration;
51
52pub struct Retry<'a> {
54 gctx: &'a GlobalContext,
55 retries: u64,
59 max_retries: u64,
63}
64
65pub enum RetryResult<T> {
67 Success(T),
71 Err(anyhow::Error),
73 Retry(u64),
79}
80
81pub const MAX_RETRY_DEFAULT: u32 = 3;
83pub const MAX_RETRY_SLEEP_S: u64 = 10;
85const MAX_RETRY_SLEEP_MS: u64 = MAX_RETRY_SLEEP_S * 1000;
87const INITIAL_RETRY_SLEEP_BASE_MS: u64 = 500;
91const INITIAL_RETRY_JITTER_MS: u64 = 1000;
96
97impl<'a> Retry<'a> {
98 pub fn new(gctx: &'a GlobalContext) -> CargoResult<Retry<'a>> {
99 Ok(Retry {
100 gctx,
101 retries: 0,
102 max_retries: gctx.net_config()?.retry.unwrap_or(MAX_RETRY_DEFAULT) as u64,
103 })
104 }
105
106 pub fn r#try<T>(&mut self, f: impl FnOnce() -> CargoResult<T>) -> RetryResult<T> {
110 match f() {
111 Err(ref e) if maybe_spurious(e) && self.retries < self.max_retries => {
112 let err = e.downcast_ref::<HttpNotSuccessful>();
113 let err_msg = err
114 .map(|http_err| http_err.display_short())
115 .unwrap_or_else(|| e.root_cause().to_string());
116 let left_retries = self.max_retries - self.retries;
117 let msg = format!(
118 "spurious network error ({} {} remaining): {err_msg}",
119 left_retries,
120 if left_retries != 1 { "tries" } else { "try" }
121 );
122 if let Err(e) = self.gctx.shell().warn(msg) {
123 return RetryResult::Err(e);
124 }
125 self.retries += 1;
126 let sleep = err
127 .and_then(|v| Self::parse_retry_after(v, &jiff::Timestamp::now()))
128 .map(|retry_after| retry_after.min(MAX_RETRY_SLEEP_MS))
130 .unwrap_or_else(|| self.next_sleep_ms());
131 RetryResult::Retry(sleep)
132 }
133 Err(e) => RetryResult::Err(e),
134 Ok(r) => RetryResult::Success(r),
135 }
136 }
137
138 fn next_sleep_ms(&self) -> u64 {
140 if let Ok(sleep) = self.gctx.get_env("__CARGO_TEST_FIXED_RETRY_SLEEP_MS") {
141 return sleep.parse().expect("a u64");
142 }
143
144 if self.retries == 1 {
145 let mut rng = rand::rng();
146 INITIAL_RETRY_SLEEP_BASE_MS + rng.random_range(0..INITIAL_RETRY_JITTER_MS)
147 } else {
148 min(
149 ((self.retries - 1) * 3) * 1000 + INITIAL_RETRY_SLEEP_BASE_MS,
150 MAX_RETRY_SLEEP_MS,
151 )
152 }
153 }
154
155 fn parse_retry_after(response: &HttpNotSuccessful, now: &jiff::Timestamp) -> Option<u64> {
158 if !matches!(response.code, 429 | 503) {
160 return None;
161 }
162
163 let retry_after = response
165 .headers
166 .iter()
167 .filter_map(|h| h.split_once(':'))
168 .map(|(k, v)| (k.trim(), v.trim()))
169 .find(|(k, _)| k.eq_ignore_ascii_case("retry-after"))?
170 .1;
171
172 if let Ok(delay_secs) = retry_after.parse::<u32>() {
174 return Some(delay_secs as u64 * 1000);
175 }
176
177 if let Ok(retry_time) = jiff::fmt::rfc2822::parse(retry_after) {
179 let diff_ms = now
180 .until(&retry_time)
181 .unwrap()
182 .total(jiff::Unit::Millisecond)
183 .unwrap();
184 if diff_ms > 0.0 {
185 return Some(diff_ms as u64);
186 }
187 }
188 None
189 }
190}
191
192fn maybe_spurious(err: &Error) -> bool {
193 fn maybe_spurious_curl(curl_err: &curl::Error) -> bool {
194 curl_err.is_couldnt_connect()
195 || curl_err.is_couldnt_resolve_proxy()
196 || curl_err.is_couldnt_resolve_host()
197 || curl_err.is_operation_timedout()
198 || curl_err.is_recv_error()
199 || curl_err.is_send_error()
200 || curl_err.is_http2_error()
201 || curl_err.is_http2_stream_error()
202 || curl_err.is_ssl_connect_error()
203 || curl_err.is_partial_file()
204 }
205 if let Some(async_http_error) = err.downcast_ref::<http_async::Error>() {
206 match async_http_error {
207 http_async::Error::Easy(error) => return maybe_spurious_curl(error),
208 http_async::Error::TooSlow { .. } => return true,
209 http_async::Error::Multi(_) => {}
210 http_async::Error::BadHeader { .. } => {}
211 }
212 }
213 if let Some(git_err) = err.downcast_ref::<git2::Error>() {
214 match git_err.class() {
215 git2::ErrorClass::Net
216 | git2::ErrorClass::Os
217 | git2::ErrorClass::Zlib
218 | git2::ErrorClass::Http => return git_err.code() != git2::ErrorCode::Certificate,
219 _ => (),
220 }
221 }
222 if let Some(curl_err) = err.downcast_ref::<curl::Error>() {
223 if maybe_spurious_curl(curl_err) {
224 return true;
225 }
226 }
227 if let Some(not_200) = err.downcast_ref::<HttpNotSuccessful>() {
228 if 500 <= not_200.code && not_200.code < 600 || not_200.code == 429 {
229 return true;
230 }
231 }
232
233 use gix::protocol::transport::IsSpuriousError;
234
235 if let Some(err) = err.downcast_ref::<crate::sources::git::fetch::Error>() {
236 if err.is_spurious() {
237 return true;
238 }
239 }
240
241 if let Some(err) = err.downcast_ref::<GitCliError>() {
242 if err.is_spurious() {
243 return true;
244 }
245 }
246
247 false
248}
249
250pub fn with_retry<T, F>(gctx: &GlobalContext, mut callback: F) -> CargoResult<T>
267where
268 F: FnMut() -> CargoResult<T>,
269{
270 let mut retry = Retry::new(gctx)?;
271 loop {
272 match retry.r#try(&mut callback) {
273 RetryResult::Success(r) => return Ok(r),
274 RetryResult::Err(e) => return Err(e),
275 RetryResult::Retry(sleep) => std::thread::sleep(Duration::from_millis(sleep)),
276 }
277 }
278}
279
280#[test]
281fn with_retry_repeats_the_call_then_works() {
282 use cargo_util_terminal::Shell;
283
284 let error1 = HttpNotSuccessful {
286 code: 501,
287 url: "Uri".to_string(),
288 ip: None,
289 body: Vec::new(),
290 headers: Vec::new(),
291 }
292 .into();
293 let error2 = HttpNotSuccessful {
294 code: 502,
295 url: "Uri".to_string(),
296 ip: None,
297 body: Vec::new(),
298 headers: Vec::new(),
299 }
300 .into();
301 let mut results: Vec<CargoResult<()>> = vec![Ok(()), Err(error1), Err(error2)];
302 let gctx = GlobalContext::default().unwrap();
303 *gctx.shell() = Shell::from_write(Box::new(Vec::new()));
304 let result = with_retry(&gctx, || results.pop().unwrap());
305 assert!(result.is_ok())
306}
307
308#[test]
309fn with_retry_finds_nested_spurious_errors() {
310 use cargo_util_terminal::Shell;
311
312 let error1 = anyhow::Error::from(HttpNotSuccessful {
315 code: 501,
316 url: "Uri".to_string(),
317 ip: None,
318 body: Vec::new(),
319 headers: Vec::new(),
320 });
321 let error1 = anyhow::Error::from(error1.context("a non-spurious wrapping err"));
322 let error2 = anyhow::Error::from(HttpNotSuccessful {
323 code: 502,
324 url: "Uri".to_string(),
325 ip: None,
326 body: Vec::new(),
327 headers: Vec::new(),
328 });
329 let error2 = anyhow::Error::from(error2.context("a second chained error"));
330 let mut results: Vec<CargoResult<()>> = vec![Ok(()), Err(error1), Err(error2)];
331 let gctx = GlobalContext::default().unwrap();
332 *gctx.shell() = Shell::from_write(Box::new(Vec::new()));
333 let result = with_retry(&gctx, || results.pop().unwrap());
334 assert!(result.is_ok())
335}
336
337#[test]
338fn default_retry_schedule() {
339 use cargo_util_terminal::Shell;
340
341 let spurious = || -> CargoResult<()> {
342 Err(anyhow::Error::from(HttpNotSuccessful {
343 code: 500,
344 url: "Uri".to_string(),
345 ip: None,
346 body: Vec::new(),
347 headers: Vec::new(),
348 }))
349 };
350 let gctx = GlobalContext::default().unwrap();
351 *gctx.shell() = Shell::from_write(Box::new(Vec::new()));
352 let mut retry = Retry::new(&gctx).unwrap();
353 match retry.r#try(|| spurious()) {
354 RetryResult::Retry(sleep) => {
355 assert!(
356 sleep >= INITIAL_RETRY_SLEEP_BASE_MS
357 && sleep < INITIAL_RETRY_SLEEP_BASE_MS + INITIAL_RETRY_JITTER_MS
358 );
359 }
360 _ => panic!("unexpected non-retry"),
361 }
362 match retry.r#try(|| spurious()) {
363 RetryResult::Retry(sleep) => assert_eq!(sleep, 3500),
364 _ => panic!("unexpected non-retry"),
365 }
366 match retry.r#try(|| spurious()) {
367 RetryResult::Retry(sleep) => assert_eq!(sleep, 6500),
368 _ => panic!("unexpected non-retry"),
369 }
370 match retry.r#try(|| spurious()) {
371 RetryResult::Err(_) => {}
372 _ => panic!("unexpected non-retry"),
373 }
374}
375
376#[test]
377fn curle_http2_stream_is_spurious() {
378 let code = curl_sys::CURLE_HTTP2_STREAM;
379 let err = curl::Error::new(code);
380 assert!(maybe_spurious(&err.into()));
381}
382
383#[test]
384fn retry_after_parsing() {
385 use cargo_util_terminal::Shell;
386 fn spurious(code: u32, header: &str) -> HttpNotSuccessful {
387 HttpNotSuccessful {
388 code,
389 url: "Uri".to_string(),
390 ip: None,
391 body: Vec::new(),
392 headers: vec![header.to_string()],
393 }
394 }
395
396 let now = jiff::Timestamp::new(1735689600, 0).unwrap();
398 let headers = spurious(429, "Retry-After: 10");
399 assert_eq!(Retry::parse_retry_after(&headers, &now), Some(10_000));
400 let headers = spurious(429, "retry-after: Wed, 01 Jan 2025 00:00:10 GMT");
401 let actual = Retry::parse_retry_after(&headers, &now).unwrap();
402 assert_eq!(10000, actual);
403
404 let headers = spurious(429, "Content-Type: text/html");
405 assert_eq!(Retry::parse_retry_after(&headers, &now), None);
406
407 let headers = spurious(429, "retry-after: Fri, 01 Jan 2000 00:00:00 GMT");
408 assert_eq!(Retry::parse_retry_after(&headers, &now), None);
409
410 let headers = spurious(429, "retry-after: -1");
411 assert_eq!(Retry::parse_retry_after(&headers, &now), None);
412
413 let headers = spurious(400, "retry-after: 1");
414 assert_eq!(Retry::parse_retry_after(&headers, &now), None);
415
416 let gctx = GlobalContext::default().unwrap();
417 *gctx.shell() = Shell::from_write(Box::new(Vec::new()));
418 let mut retry = Retry::new(&gctx).unwrap();
419 match retry
420 .r#try(|| -> CargoResult<()> { Err(anyhow::Error::from(spurious(429, "Retry-After: 7"))) })
421 {
422 RetryResult::Retry(sleep) => assert_eq!(sleep, 7_000),
423 _ => panic!("unexpected non-retry"),
424 }
425}
426
427#[test]
428fn git_cli_error_spurious() {
429 let error = GitCliError::new(Error::msg("test-git-cli-error")).spurious(false);
430 assert!(!maybe_spurious(&error.into()));
431
432 let error = GitCliError::new(Error::msg("test-git-cli-error")).spurious(true);
433 assert!(maybe_spurious(&error.into()));
434}