Skip to content

Commit

Permalink
Fix retries (#1573)
Browse files Browse the repository at this point in the history
  • Loading branch information
trask authored Nov 27, 2024
1 parent c9d5d0d commit 034fd12
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
24 changes: 24 additions & 0 deletions lychee-bin/tests/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1880,4 +1880,28 @@ mod cli {

Ok(())
}

#[tokio::test]
async fn test_retry() -> Result<()> {
let mock_server = wiremock::MockServer::start().await;

wiremock::Mock::given(wiremock::matchers::method("GET"))
.respond_with(ResponseTemplate::new(429))
.up_to_n_times(1)
.mount(&mock_server)
.await;

wiremock::Mock::given(wiremock::matchers::method("GET"))
.respond_with(ResponseTemplate::new(200))
.mount(&mock_server)
.await;

let mut cmd = main_command();
cmd.arg("-")
.write_stdin(mock_server.uri())
.assert()
.success();

Ok(())
}
}
21 changes: 19 additions & 2 deletions lychee-lib/src/retry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ pub(crate) trait RetryExt {
fn should_retry(&self) -> bool;
}

impl RetryExt for reqwest::Response {
impl RetryExt for reqwest::StatusCode {
/// Try to map a `reqwest` response into `Retryable`.
#[allow(clippy::if_same_then_else)]
fn should_retry(&self) -> bool {
let status = self.status();
let status = *self;
if status.is_server_error() {
true
} else if status.is_client_error()
Expand Down Expand Up @@ -71,6 +71,8 @@ impl RetryExt for reqwest::Error {
} else {
false
}
} else if let Some(status) = self.status() {
status.should_retry()
} else {
// We omit checking if error.is_status() since we check that already.
// However, if Response::error_for_status is used the status will still
Expand Down Expand Up @@ -148,3 +150,18 @@ fn get_source_error_type<T: std::error::Error + 'static>(
}
None
}

#[cfg(test)]
mod tests {
use http::StatusCode;

use super::RetryExt;

#[test]
fn test_should_retry() {
assert!(StatusCode::REQUEST_TIMEOUT.should_retry());
assert!(StatusCode::TOO_MANY_REQUESTS.should_retry());
assert!(!StatusCode::FORBIDDEN.should_retry());
assert!(StatusCode::INTERNAL_SERVER_ERROR.should_retry());
}
}

0 comments on commit 034fd12

Please sign in to comment.