-
Notifications
You must be signed in to change notification settings - Fork 212
feat(retry): allow customized retry policy #841
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
dentiny
wants to merge
2
commits into
apache:main
Choose a base branch
from
dentiny:hjiang/feat-retry-policy
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+107
−6
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -25,6 +25,7 @@ use futures_util::future::BoxFuture; | |
| use http::StatusCode; | ||
| use http::header::LOCATION; | ||
| use http::{Method, Uri}; | ||
| use std::sync::Arc; | ||
| #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))] | ||
| use std::time::{Duration, Instant}; | ||
| use tracing::info; | ||
|
|
@@ -81,6 +82,7 @@ pub(crate) struct RetryContext { | |
| retries: usize, | ||
| max_retries: usize, | ||
| retry_timeout: Duration, | ||
| retry_status_policy: Option<RetryStatusPolicy>, | ||
| start: Instant, | ||
| } | ||
|
|
||
|
|
@@ -89,6 +91,7 @@ impl RetryContext { | |
| Self { | ||
| max_retries: config.max_retries, | ||
| retry_timeout: config.retry_timeout, | ||
| retry_status_policy: config.retry_status_policy.clone(), | ||
| backoff: Backoff::new(&config.backoff), | ||
| retries: 0, | ||
| start: Instant::now(), | ||
|
|
@@ -103,6 +106,16 @@ impl RetryContext { | |
| self.retries += 1; | ||
| self.backoff.next() | ||
| } | ||
|
|
||
| fn should_retry_status(&self, status: StatusCode, retry_on_conflict: bool) -> bool { | ||
| match &self.retry_status_policy { | ||
| Some(policy) => policy(status), | ||
| None => { | ||
| RetryConfig::default_should_retry_status(status) | ||
| || (retry_on_conflict && status == StatusCode::CONFLICT) | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// The reason a request failed | ||
|
|
@@ -212,6 +225,9 @@ impl From<RetryError> for std::io::Error { | |
|
|
||
| pub(crate) type Result<T, E = RetryError> = std::result::Result<T, E>; | ||
|
|
||
| /// A function that determines whether a response status should be retried | ||
| pub type RetryStatusPolicy = Arc<dyn Fn(StatusCode) -> bool + Send + Sync>; | ||
|
|
||
| /// The configuration for how to respond to request errors | ||
| /// | ||
| /// The following categories of error will be retried: | ||
|
|
@@ -225,7 +241,7 @@ pub(crate) type Result<T, E = RetryError> = std::result::Result<T, E>; | |
| /// backoff with jitter. See [`BackoffConfig`] for more information | ||
| /// | ||
| /// [safe]: https://datatracker.ietf.org/doc/html/rfc7231#section-4.2.1 | ||
| #[derive(Debug, Clone)] | ||
| #[derive(Clone)] | ||
| pub struct RetryConfig { | ||
| /// The backoff configuration | ||
| pub backoff: BackoffConfig, | ||
|
|
@@ -247,6 +263,58 @@ pub struct RetryConfig { | |
| /// below 5 minutes to avoid errors due to expired credentials | ||
| /// and/or request payloads | ||
| pub retry_timeout: Duration, | ||
|
|
||
| /// An optional function that determines whether a response status should be retried | ||
| /// | ||
| /// When set, this replaces the default status policy, including any provider-specific | ||
| /// status handling. Successful responses, redirects, and `304 Not Modified` responses | ||
| /// are handled before this policy is invoked. | ||
| /// | ||
| /// Transport errors are classified separately and are not affected by this policy. | ||
| pub retry_status_policy: Option<RetryStatusPolicy>, | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. since this is new field in a struct with all public fields, this is breaking API change
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes, it's intentional :) |
||
| } | ||
|
|
||
| impl std::fmt::Debug for RetryConfig { | ||
| fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
| f.debug_struct("RetryConfig") | ||
| .field("backoff", &self.backoff) | ||
| .field("max_retries", &self.max_retries) | ||
| .field("retry_timeout", &self.retry_timeout) | ||
| .field( | ||
| "retry_status_policy", | ||
| &self.retry_status_policy.as_ref().map(|_| "<custom>"), | ||
| ) | ||
| .finish() | ||
| } | ||
| } | ||
|
|
||
| impl RetryConfig { | ||
|
dentiny marked this conversation as resolved.
|
||
| fn default_should_retry_status(status: StatusCode) -> bool { | ||
| status.is_server_error() | ||
| || status == StatusCode::TOO_MANY_REQUESTS | ||
| || status == StatusCode::REQUEST_TIMEOUT | ||
| } | ||
|
|
||
| /// Set a custom function that determines whether a response status should be retried | ||
| /// | ||
| /// This replaces the default policy of retrying server errors, `429 Too Many Requests`, | ||
| /// and `408 Request Timeout`. | ||
| /// | ||
| /// ``` | ||
| /// # use http::StatusCode; | ||
| /// # use object_store::RetryConfig; | ||
| /// let config = RetryConfig::default().with_retry_status_policy(|status| { | ||
| /// status == StatusCode::SERVICE_UNAVAILABLE | ||
| /// }); | ||
| /// ``` | ||
| #[must_use] | ||
| pub fn with_retry_status_policy<F>(mut self, policy: F) -> Self | ||
| where | ||
| F: Fn(StatusCode) -> bool + Send + Sync + 'static, | ||
| { | ||
| self.retry_status_policy = Some(Arc::new(policy)); | ||
| self | ||
| } | ||
| } | ||
|
|
||
| impl Default for RetryConfig { | ||
|
|
@@ -255,6 +323,7 @@ impl Default for RetryConfig { | |
| backoff: Default::default(), | ||
| max_retries: 10, | ||
| retry_timeout: Duration::from_secs(3 * 60), | ||
| retry_status_policy: None, | ||
| } | ||
| } | ||
| } | ||
|
|
@@ -405,10 +474,7 @@ impl RetryableRequest { | |
| } else { | ||
| let status = r.status(); | ||
| if ctx.exhausted() | ||
| || !(status.is_server_error() | ||
| || status == StatusCode::TOO_MANY_REQUESTS | ||
| || status == StatusCode::REQUEST_TIMEOUT | ||
| || (self.retry_on_conflict && status == StatusCode::CONFLICT)) | ||
| || !ctx.should_retry_status(status, self.retry_on_conflict) | ||
|
dentiny marked this conversation as resolved.
|
||
| { | ||
| let source = match r.into_body().text().await { | ||
| Ok(body) => RequestError::Status { | ||
|
|
@@ -550,6 +616,7 @@ mod tests { | |
| backoff: Default::default(), | ||
| max_retries: 2, | ||
| retry_timeout: Duration::from_secs(1000), | ||
| retry_status_policy: None, | ||
| }; | ||
|
|
||
| let client = HttpClient::new( | ||
|
|
@@ -630,6 +697,35 @@ mod tests { | |
| let r = do_request().await.unwrap(); | ||
| assert_eq!(r.status(), StatusCode::OK); | ||
|
|
||
| let custom_retry = retry | ||
| .clone() | ||
| .with_retry_status_policy(|status| status == StatusCode::IM_A_TEAPOT); | ||
| let do_custom_request = || { | ||
| client | ||
| .request(Method::GET, mock.url()) | ||
| .send_retry(&custom_retry) | ||
| }; | ||
|
|
||
| // A custom policy can retry an otherwise non-retryable status | ||
| mock.push( | ||
| Response::builder() | ||
| .status(StatusCode::IM_A_TEAPOT) | ||
| .body(String::new()) | ||
| .unwrap(), | ||
| ); | ||
| let r = do_custom_request().await.unwrap(); | ||
| assert_eq!(r.status(), StatusCode::OK); | ||
|
|
||
| // A custom policy replaces the default status policy | ||
| mock.push( | ||
| Response::builder() | ||
| .status(StatusCode::BAD_GATEWAY) | ||
| .body(String::new()) | ||
| .unwrap(), | ||
| ); | ||
| let e = do_custom_request().await.unwrap_err(); | ||
| assert_eq!(e.status(), Some(StatusCode::BAD_GATEWAY)); | ||
|
|
||
| // Accepts 204 status code | ||
| mock.push( | ||
| Response::builder() | ||
|
|
@@ -858,6 +954,7 @@ mod tests { | |
| backoff: Default::default(), | ||
| max_retries: 0, | ||
| retry_timeout: Duration::from_secs(1000), | ||
| retry_status_policy: None, | ||
| }; | ||
|
|
||
| let client = HttpClient::new(Client::builder().build().unwrap()); | ||
|
|
@@ -895,6 +992,7 @@ mod tests { | |
| backoff: Default::default(), | ||
| max_retries: 2, | ||
| retry_timeout: Duration::from_secs(1), | ||
| retry_status_policy: None, | ||
| }; | ||
| assert!(retry.max_retries > 0); | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.