use crate::util::errors::{GitCliError, HttpNotSuccessful};
use crate::util::network::http_async;
use crate::{CargoResult, GlobalContext};
use anyhow::Error;
use rand::RngExt;
use std::cmp::min;
use std::time::Duration;
pub struct Retry<'a> {
gctx: &'a GlobalContext,
retries: u64,
max_retries: u64,
}
pub enum RetryResult<T> {
Success(T),
Err(anyhow::Error),
Retry(u64),
}
const MAX_RETRY_SLEEP_MS: u64 = 10 * 1000;
const INITIAL_RETRY_SLEEP_BASE_MS: u64 = 500;
const INITIAL_RETRY_JITTER_MS: u64 = 1000;
impl<'a> Retry<'a> {
pub fn new(gctx: &'a GlobalContext) -> CargoResult<Retry<'a>> {
Ok(Retry {
gctx,
retries: 0,
max_retries: gctx.net_config()?.retry.unwrap_or(3) as u64,
})
}
pub fn r#try<T>(&mut self, f: impl FnOnce() -> CargoResult<T>) -> RetryResult<T> {
match f() {
Err(ref e) if maybe_spurious(e) && self.retries < self.max_retries => {
let err = e.downcast_ref::<HttpNotSuccessful>();
let err_msg = err
.map(|http_err| http_err.display_short())
.unwrap_or_else(|| e.root_cause().to_string());
let left_retries = self.max_retries - self.retries;
let msg = format!(
"spurious network error ({} {} remaining): {err_msg}",
left_retries,
if left_retries != 1 { "tries" } else { "try" }
);
if let Err(e) = self.gctx.shell().warn(msg) {
return RetryResult::Err(e);
}
self.retries += 1;
let sleep = err
.and_then(|v| Self::parse_retry_after(v, &jiff::Timestamp::now()))
.map(|retry_after| retry_after.min(MAX_RETRY_SLEEP_MS))
.unwrap_or_else(|| self.next_sleep_ms());
RetryResult::Retry(sleep)
}
Err(e) => RetryResult::Err(e),
Ok(r) => RetryResult::Success(r),
}
}
fn next_sleep_ms(&self) -> u64 {
if let Ok(sleep) = self.gctx.get_env("__CARGO_TEST_FIXED_RETRY_SLEEP_MS") {
return sleep.parse().expect("a u64");
}
if self.retries == 1 {
let mut rng = rand::rng();
INITIAL_RETRY_SLEEP_BASE_MS + rng.random_range(0..INITIAL_RETRY_JITTER_MS)
} else {
min(
((self.retries - 1) * 3) * 1000 + INITIAL_RETRY_SLEEP_BASE_MS,
MAX_RETRY_SLEEP_MS,
)
}
}
fn parse_retry_after(response: &HttpNotSuccessful, now: &jiff::Timestamp) -> Option<u64> {
if !matches!(response.code, 429 | 503) {
return None;
}
let retry_after = response
.headers
.iter()
.filter_map(|h| h.split_once(':'))
.map(|(k, v)| (k.trim(), v.trim()))
.find(|(k, _)| k.eq_ignore_ascii_case("retry-after"))?
.1;
if let Ok(delay_secs) = retry_after.parse::<u32>() {
return Some(delay_secs as u64 * 1000);
}
if let Ok(retry_time) = jiff::fmt::rfc2822::parse(retry_after) {
let diff_ms = now
.until(&retry_time)
.unwrap()
.total(jiff::Unit::Millisecond)
.unwrap();
if diff_ms > 0.0 {
return Some(diff_ms as u64);
}
}
None
}
}
fn maybe_spurious(err: &Error) -> bool {
fn maybe_spurious_curl(curl_err: &curl::Error) -> bool {
curl_err.is_couldnt_connect()
|| curl_err.is_couldnt_resolve_proxy()
|| curl_err.is_couldnt_resolve_host()
|| curl_err.is_operation_timedout()
|| curl_err.is_recv_error()
|| curl_err.is_send_error()
|| curl_err.is_http2_error()
|| curl_err.is_http2_stream_error()
|| curl_err.is_ssl_connect_error()
|| curl_err.is_partial_file()
}
if let Some(async_http_error) = err.downcast_ref::<http_async::Error>() {
match async_http_error {
http_async::Error::Easy(error) => return maybe_spurious_curl(error),
http_async::Error::TooSlow { .. } => return true,
http_async::Error::Multi(_) => {}
http_async::Error::BadHeader { .. } => {}
}
}
if let Some(git_err) = err.downcast_ref::<git2::Error>() {
match git_err.class() {
git2::ErrorClass::Net
| git2::ErrorClass::Os
| git2::ErrorClass::Zlib
| git2::ErrorClass::Http => return git_err.code() != git2::ErrorCode::Certificate,
_ => (),
}
}
if let Some(curl_err) = err.downcast_ref::<curl::Error>() {
if maybe_spurious_curl(curl_err) {
return true;
}
}
if let Some(not_200) = err.downcast_ref::<HttpNotSuccessful>() {
if 500 <= not_200.code && not_200.code < 600 || not_200.code == 429 {
return true;
}
}
use gix::protocol::transport::IsSpuriousError;
if let Some(err) = err.downcast_ref::<crate::sources::git::fetch::Error>() {
if err.is_spurious() {
return true;
}
}
if let Some(err) = err.downcast_ref::<GitCliError>() {
if err.is_spurious() {
return true;
}
}
false
}
pub fn with_retry<T, F>(gctx: &GlobalContext, mut callback: F) -> CargoResult<T>
where
F: FnMut() -> CargoResult<T>,
{
let mut retry = Retry::new(gctx)?;
loop {
match retry.r#try(&mut callback) {
RetryResult::Success(r) => return Ok(r),
RetryResult::Err(e) => return Err(e),
RetryResult::Retry(sleep) => std::thread::sleep(Duration::from_millis(sleep)),
}
}
}
#[test]
fn with_retry_repeats_the_call_then_works() {
use cargo_util_terminal::Shell;
let error1 = HttpNotSuccessful {
code: 501,
url: "Uri".to_string(),
ip: None,
body: Vec::new(),
headers: Vec::new(),
}
.into();
let error2 = HttpNotSuccessful {
code: 502,
url: "Uri".to_string(),
ip: None,
body: Vec::new(),
headers: Vec::new(),
}
.into();
let mut results: Vec<CargoResult<()>> = vec![Ok(()), Err(error1), Err(error2)];
let gctx = GlobalContext::default().unwrap();
*gctx.shell() = Shell::from_write(Box::new(Vec::new()));
let result = with_retry(&gctx, || results.pop().unwrap());
assert!(result.is_ok())
}
#[test]
fn with_retry_finds_nested_spurious_errors() {
use cargo_util_terminal::Shell;
let error1 = anyhow::Error::from(HttpNotSuccessful {
code: 501,
url: "Uri".to_string(),
ip: None,
body: Vec::new(),
headers: Vec::new(),
});
let error1 = anyhow::Error::from(error1.context("a non-spurious wrapping err"));
let error2 = anyhow::Error::from(HttpNotSuccessful {
code: 502,
url: "Uri".to_string(),
ip: None,
body: Vec::new(),
headers: Vec::new(),
});
let error2 = anyhow::Error::from(error2.context("a second chained error"));
let mut results: Vec<CargoResult<()>> = vec![Ok(()), Err(error1), Err(error2)];
let gctx = GlobalContext::default().unwrap();
*gctx.shell() = Shell::from_write(Box::new(Vec::new()));
let result = with_retry(&gctx, || results.pop().unwrap());
assert!(result.is_ok())
}
#[test]
fn default_retry_schedule() {
use cargo_util_terminal::Shell;
let spurious = || -> CargoResult<()> {
Err(anyhow::Error::from(HttpNotSuccessful {
code: 500,
url: "Uri".to_string(),
ip: None,
body: Vec::new(),
headers: Vec::new(),
}))
};
let gctx = GlobalContext::default().unwrap();
*gctx.shell() = Shell::from_write(Box::new(Vec::new()));
let mut retry = Retry::new(&gctx).unwrap();
match retry.r#try(|| spurious()) {
RetryResult::Retry(sleep) => {
assert!(
sleep >= INITIAL_RETRY_SLEEP_BASE_MS
&& sleep < INITIAL_RETRY_SLEEP_BASE_MS + INITIAL_RETRY_JITTER_MS
);
}
_ => panic!("unexpected non-retry"),
}
match retry.r#try(|| spurious()) {
RetryResult::Retry(sleep) => assert_eq!(sleep, 3500),
_ => panic!("unexpected non-retry"),
}
match retry.r#try(|| spurious()) {
RetryResult::Retry(sleep) => assert_eq!(sleep, 6500),
_ => panic!("unexpected non-retry"),
}
match retry.r#try(|| spurious()) {
RetryResult::Err(_) => {}
_ => panic!("unexpected non-retry"),
}
}
#[test]
fn curle_http2_stream_is_spurious() {
let code = curl_sys::CURLE_HTTP2_STREAM;
let err = curl::Error::new(code);
assert!(maybe_spurious(&err.into()));
}
#[test]
fn retry_after_parsing() {
use cargo_util_terminal::Shell;
fn spurious(code: u32, header: &str) -> HttpNotSuccessful {
HttpNotSuccessful {
code,
url: "Uri".to_string(),
ip: None,
body: Vec::new(),
headers: vec![header.to_string()],
}
}
let now = jiff::Timestamp::new(1735689600, 0).unwrap();
let headers = spurious(429, "Retry-After: 10");
assert_eq!(Retry::parse_retry_after(&headers, &now), Some(10_000));
let headers = spurious(429, "retry-after: Wed, 01 Jan 2025 00:00:10 GMT");
let actual = Retry::parse_retry_after(&headers, &now).unwrap();
assert_eq!(10000, actual);
let headers = spurious(429, "Content-Type: text/html");
assert_eq!(Retry::parse_retry_after(&headers, &now), None);
let headers = spurious(429, "retry-after: Fri, 01 Jan 2000 00:00:00 GMT");
assert_eq!(Retry::parse_retry_after(&headers, &now), None);
let headers = spurious(429, "retry-after: -1");
assert_eq!(Retry::parse_retry_after(&headers, &now), None);
let headers = spurious(400, "retry-after: 1");
assert_eq!(Retry::parse_retry_after(&headers, &now), None);
let gctx = GlobalContext::default().unwrap();
*gctx.shell() = Shell::from_write(Box::new(Vec::new()));
let mut retry = Retry::new(&gctx).unwrap();
match retry
.r#try(|| -> CargoResult<()> { Err(anyhow::Error::from(spurious(429, "Retry-After: 7"))) })
{
RetryResult::Retry(sleep) => assert_eq!(sleep, 7_000),
_ => panic!("unexpected non-retry"),
}
}
#[test]
fn git_cli_error_spurious() {
let error = GitCliError::new(Error::msg("test-git-cli-error")).spurious(false);
assert!(!maybe_spurious(&error.into()));
let error = GitCliError::new(Error::msg("test-git-cli-error")).spurious(true);
assert!(maybe_spurious(&error.into()));
}