1/*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 */
56//! Retry handling and token bucket.
7//!
8//! This code defines when and how failed requests should be retried. It also defines the behavior
9//! used to limit the rate that requests are sent.
1011pub mod classifiers;
1213use crate::box_error::BoxError;
14use crate::client::interceptors::context::InterceptorContext;
15use crate::client::runtime_components::sealed::ValidateConfig;
16use crate::client::runtime_components::RuntimeComponents;
17use aws_smithy_types::config_bag::{ConfigBag, Storable, StoreReplace};
18use std::fmt;
19use std::sync::Arc;
20use std::time::Duration;
2122use crate::impl_shared_conversions;
23pub use aws_smithy_types::retry::ErrorKind;
24#[cfg(feature = "test-util")]
25pub use test_util::AlwaysRetry;
2627#[derive(Debug, Clone, PartialEq, Eq)]
28/// An answer to the question "should I make a request attempt?"
29pub enum ShouldAttempt {
30/// Yes, an attempt should be made
31Yes,
32/// No, no attempt should be made
33No,
34/// Yes, an attempt should be made, but only after the given amount of time has passed
35YesAfterDelay(Duration),
36}
3738#[cfg(feature = "test-util")]
39impl ShouldAttempt {
40/// Returns the delay duration if this is a `YesAfterDelay` variant.
41pub fn expect_delay(self) -> Duration {
42match self {
43 ShouldAttempt::YesAfterDelay(delay) => delay,
44_ => panic!("Expected this to be the `YesAfterDelay` variant but it was the `{self:?}` variant instead"),
45 }
46 }
4748/// If this isn't a `No` variant, panic.
49pub fn expect_no(self) {
50if ShouldAttempt::No == self {
51return;
52 }
5354panic!("Expected this to be the `No` variant but it was the `{self:?}` variant instead");
55 }
56}
5758impl_shared_conversions!(convert SharedRetryStrategy from RetryStrategy using SharedRetryStrategy::new);
5960/// Decider for whether or not to attempt a request, and when.
61///
62/// The orchestrator consults the retry strategy every time before making a request.
63/// This includes the initial request, and any retry attempts thereafter. The
64/// orchestrator will retry indefinitely (until success) if the retry strategy
65/// always returns `ShouldAttempt::Yes` from `should_attempt_retry`.
66pub trait RetryStrategy: Send + Sync + fmt::Debug {
67/// Decides if the initial attempt should be made.
68fn should_attempt_initial_request(
69&self,
70 runtime_components: &RuntimeComponents,
71 cfg: &ConfigBag,
72 ) -> Result<ShouldAttempt, BoxError>;
7374/// Decides if a retry should be done.
75 ///
76 /// The previous attempt's output or error are provided in the
77 /// [`InterceptorContext`] when this is called.
78 ///
79 /// `ShouldAttempt::YesAfterDelay` can be used to add a backoff time.
80fn should_attempt_retry(
81&self,
82 context: &InterceptorContext,
83 runtime_components: &RuntimeComponents,
84 cfg: &ConfigBag,
85 ) -> Result<ShouldAttempt, BoxError>;
86}
8788/// A shared retry strategy.
89#[derive(Clone, Debug)]
90pub struct SharedRetryStrategy(Arc<dyn RetryStrategy>);
9192impl SharedRetryStrategy {
93/// Creates a new [`SharedRetryStrategy`] from a retry strategy.
94pub fn new(retry_strategy: impl RetryStrategy + 'static) -> Self {
95Self(Arc::new(retry_strategy))
96 }
97}
9899impl RetryStrategy for SharedRetryStrategy {
100fn should_attempt_initial_request(
101&self,
102 runtime_components: &RuntimeComponents,
103 cfg: &ConfigBag,
104 ) -> Result<ShouldAttempt, BoxError> {
105self.0
106.should_attempt_initial_request(runtime_components, cfg)
107 }
108109fn should_attempt_retry(
110&self,
111 context: &InterceptorContext,
112 runtime_components: &RuntimeComponents,
113 cfg: &ConfigBag,
114 ) -> Result<ShouldAttempt, BoxError> {
115self.0
116.should_attempt_retry(context, runtime_components, cfg)
117 }
118}
119120impl ValidateConfig for SharedRetryStrategy {}
121122/// A type to track the number of requests sent by the orchestrator for a given operation.
123///
124/// `RequestAttempts` is added to the `ConfigBag` by the orchestrator,
125/// and holds the current attempt number.
126#[derive(Debug, Clone, Copy)]
127pub struct RequestAttempts {
128 attempts: u32,
129}
130131impl RequestAttempts {
132/// Creates a new [`RequestAttempts`] with the given number of attempts.
133pub fn new(attempts: u32) -> Self {
134Self { attempts }
135 }
136137/// Returns the number of attempts.
138pub fn attempts(&self) -> u32 {
139self.attempts
140 }
141}
142143impl From<u32> for RequestAttempts {
144fn from(attempts: u32) -> Self {
145Self::new(attempts)
146 }
147}
148149impl From<RequestAttempts> for u32 {
150fn from(value: RequestAttempts) -> Self {
151 value.attempts()
152 }
153}
154155impl Storable for RequestAttempts {
156type Storer = StoreReplace<Self>;
157}
158159#[cfg(feature = "test-util")]
160mod test_util {
161use super::ErrorKind;
162use crate::client::interceptors::context::InterceptorContext;
163use crate::client::retries::classifiers::{ClassifyRetry, RetryAction};
164165/// A retry classifier for testing purposes. This classifier always returns
166 /// `Some(RetryAction::Error(ErrorKind))` where `ErrorKind` is the value provided when creating
167 /// this classifier.
168#[derive(Debug)]
169pub struct AlwaysRetry(pub ErrorKind);
170171impl ClassifyRetry for AlwaysRetry {
172fn classify_retry(&self, error: &InterceptorContext) -> RetryAction {
173tracing::debug!("Retrying error {:?} as an {:?}", error, self.0);
174 RetryAction::retryable_error(self.0)
175 }
176177fn name(&self) -> &'static str {
178"Always Retry"
179}
180 }
181}