Skip to main content

aws_config/default_provider/
retry_config.rs

1/*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6use crate::provider_config::ProviderConfig;
7use crate::retry::error::{RetryConfigError, RetryConfigErrorKind};
8use aws_runtime::env_config::{EnvConfigError, EnvConfigValue};
9use aws_smithy_types::error::display::DisplayErrorContext;
10use aws_smithy_types::retry::{RetryConfig, RetryMode};
11use aws_types::origin::Origin;
12use std::str::FromStr;
13
14/// Default RetryConfig Provider chain
15///
16/// Unlike other "providers" `RetryConfig` has no related `RetryConfigProvider` trait. Instead,
17/// a builder struct is returned which has a similar API.
18///
19/// This provider will check the following sources in order:
20/// 1. Environment variables: `AWS_MAX_ATTEMPTS` & `AWS_RETRY_MODE`
21/// 2. Profile file: `max_attempts` and `retry_mode`
22///
23/// # Example
24///
25/// When running [`aws_config::from_env()`](crate::from_env()), a [`ConfigLoader`](crate::ConfigLoader)
26/// is created that will then create a [`RetryConfig`] from the default_provider. There is no
27/// need to call `default_provider` and the example below is only for illustration purposes.
28///
29/// ```no_run
30/// # use std::error::Error;
31/// # #[tokio::main]
32/// # async fn main() -> Result<(), Box<dyn Error>> {
33/// use aws_config::default_provider::retry_config;
34///
35/// // Load a retry config from a specific profile
36/// let retry_config = retry_config::default_provider()
37///     .profile_name("other_profile")
38///     .retry_config()
39///     .await;
40/// let config = aws_config::from_env()
41///     // Override the retry config set by the default profile
42///     .retry_config(retry_config)
43///     .load()
44///     .await;
45/// // instantiate a service client:
46/// // <my_aws_service>::Client::new(&config);
47/// #     Ok(())
48/// # }
49/// ```
50pub fn default_provider() -> Builder {
51    Builder::default()
52}
53
54mod env {
55    pub(super) const MAX_ATTEMPTS: &str = "AWS_MAX_ATTEMPTS";
56    pub(super) const RETRY_MODE: &str = "AWS_RETRY_MODE";
57}
58
59mod profile_keys {
60    pub(super) const MAX_ATTEMPTS: &str = "max_attempts";
61    pub(super) const RETRY_MODE: &str = "retry_mode";
62}
63
64/// Builder for RetryConfig that checks the environment and aws profile for configuration
65#[derive(Debug, Default)]
66pub struct Builder {
67    provider_config: ProviderConfig,
68}
69
70impl Builder {
71    /// Configure the default chain
72    ///
73    /// Exposed for overriding the environment when unit-testing providers
74    pub fn configure(mut self, configuration: &ProviderConfig) -> Self {
75        self.provider_config = configuration.clone();
76        self
77    }
78
79    /// Override the profile name used by this provider
80    pub fn profile_name(mut self, name: &str) -> Self {
81        self.provider_config = self.provider_config.with_profile_name(name.to_string());
82        self
83    }
84
85    /// Attempt to create a [`RetryConfig`] from following sources in order:
86    /// 1. Environment variables: `AWS_MAX_ATTEMPTS` & `AWS_RETRY_MODE`
87    /// 2. Profile file: `max_attempts` and `retry_mode`
88    /// 3. [RetryConfig::standard()](aws_smithy_types::retry::RetryConfig::standard)
89    ///
90    /// Precedence is considered on a per-field basis
91    ///
92    /// # Panics
93    ///
94    /// - Panics if the `AWS_MAX_ATTEMPTS` env var or `max_attempts` profile var is set to 0
95    /// - Panics if the `AWS_RETRY_MODE` env var or `retry_mode` profile var is set to "adaptive" (it's not yet supported)
96    pub async fn retry_config(self) -> RetryConfig {
97        self.retry_config_with_origin().await.0
98    }
99
100    // The origin is where `max_attempts` came from.
101    pub(crate) async fn retry_config_with_origin(self) -> (RetryConfig, Origin) {
102        match self.try_retry_config().await {
103            Ok(conf) => conf,
104            Err(e) => panic!("{}", DisplayErrorContext(e)),
105        }
106    }
107
108    pub(crate) async fn try_retry_config(
109        self,
110    ) -> Result<(RetryConfig, Origin), EnvConfigError<RetryConfigError>> {
111        let env = self.provider_config.env();
112        let profiles = self.provider_config.profile().await;
113        // Both of these can return errors due to invalid config settings, and we want to surface those as early as possible
114        // hence, we'll panic if any config values are invalid (missing values are OK though)
115        // We match this instead of unwrapping, so we can print the error with the `Display` impl instead of the `Debug` impl that unwrap uses
116        let mut retry_config = RetryConfig::standard();
117        let max_attempts = EnvConfigValue::new()
118            .env(env::MAX_ATTEMPTS)
119            .profile(profile_keys::MAX_ATTEMPTS)
120            .validate_and_return_origin(&env, profiles, validate_max_attempts);
121
122        let retry_mode = EnvConfigValue::new()
123            .env(env::RETRY_MODE)
124            .profile(profile_keys::RETRY_MODE)
125            .validate(&env, profiles, |s| {
126                RetryMode::from_str(s)
127                    .map_err(|err| RetryConfigErrorKind::InvalidRetryMode { source: err }.into())
128            });
129
130        let (max_attempts, max_attempts_origin) = max_attempts?;
131        if let Some(max_attempts) = max_attempts {
132            retry_config = retry_config.with_max_attempts(max_attempts);
133        }
134
135        if let Some(retry_mode) = retry_mode? {
136            retry_config = retry_config.with_retry_mode(retry_mode);
137        }
138
139        Ok((retry_config, max_attempts_origin))
140    }
141}
142
143fn validate_max_attempts(max_attempts: &str) -> Result<u32, RetryConfigError> {
144    match max_attempts.parse::<u32>() {
145        Ok(0) => Err(RetryConfigErrorKind::MaxAttemptsMustNotBeZero.into()),
146        Ok(max_attempts) => Ok(max_attempts),
147        Err(source) => Err(RetryConfigErrorKind::FailedToParseMaxAttempts { source }.into()),
148    }
149}
150
151#[cfg(test)]
152mod test {
153    use crate::default_provider::retry_config::env;
154    use crate::provider_config::ProviderConfig;
155    use crate::retry::{
156        error::RetryConfigError, error::RetryConfigErrorKind, RetryConfig, RetryMode,
157    };
158    use aws_runtime::env_config::EnvConfigError;
159    use aws_types::os_shim_internal::{Env, Fs};
160
161    async fn test_provider(
162        vars: &[(&str, &str)],
163    ) -> Result<RetryConfig, EnvConfigError<RetryConfigError>> {
164        super::Builder::default()
165            .configure(&ProviderConfig::no_configuration().with_env(Env::from_slice(vars)))
166            .try_retry_config()
167            .await
168            .map(|(retry_config, _)| retry_config)
169    }
170
171    #[tokio::test]
172    async fn test_returns_default_retry_config_from_empty_profile() {
173        let env = Env::from_slice(&[("AWS_CONFIG_FILE", "config")]);
174        let fs = Fs::from_slice(&[("config", "[default]\n")]);
175
176        let provider_config = ProviderConfig::no_configuration().with_env(env).with_fs(fs);
177
178        let actual_retry_config = super::default_provider()
179            .configure(&provider_config)
180            .retry_config()
181            .await;
182
183        let expected_retry_config = RetryConfig::standard();
184
185        assert_eq!(actual_retry_config, expected_retry_config);
186        // This is redundant, but it's really important to make sure that
187        // we're setting these exact values by default, so we check twice
188        assert_eq!(actual_retry_config.max_attempts(), 3);
189        assert_eq!(actual_retry_config.mode(), RetryMode::Standard);
190    }
191
192    #[tokio::test]
193    async fn test_no_retry_config_in_empty_profile() {
194        let env = Env::from_slice(&[("AWS_CONFIG_FILE", "config")]);
195        let fs = Fs::from_slice(&[("config", "[default]\n")]);
196
197        let provider_config = ProviderConfig::no_configuration().with_env(env).with_fs(fs);
198
199        let actual_retry_config = super::default_provider()
200            .configure(&provider_config)
201            .retry_config()
202            .await;
203
204        let expected_retry_config = RetryConfig::standard();
205
206        assert_eq!(actual_retry_config, expected_retry_config)
207    }
208
209    #[tokio::test]
210    async fn test_creation_of_retry_config_from_profile() {
211        let env = Env::from_slice(&[("AWS_CONFIG_FILE", "config")]);
212        // TODO(https://github.com/awslabs/aws-sdk-rust/issues/247): standard is the default mode;
213        // this test would be better if it was setting it to adaptive mode
214        // adaptive mode is currently unsupported so that would panic
215        let fs = Fs::from_slice(&[(
216            "config",
217            // If the lines with the vars have preceding spaces, they don't get read
218            r#"[default]
219max_attempts = 1
220retry_mode = standard
221            "#,
222        )]);
223
224        let provider_config = ProviderConfig::no_configuration().with_env(env).with_fs(fs);
225
226        let actual_retry_config = super::default_provider()
227            .configure(&provider_config)
228            .retry_config()
229            .await;
230
231        let expected_retry_config = RetryConfig::standard().with_max_attempts(1);
232
233        assert_eq!(actual_retry_config, expected_retry_config)
234    }
235
236    #[tokio::test]
237    async fn test_env_retry_config_takes_precedence_over_profile_retry_config() {
238        let env = Env::from_slice(&[
239            ("AWS_CONFIG_FILE", "config"),
240            ("AWS_MAX_ATTEMPTS", "42"),
241            ("AWS_RETRY_MODE", "standard"),
242        ]);
243        // TODO(https://github.com/awslabs/aws-sdk-rust/issues/247) standard is the default mode;
244        // this test would be better if it was setting it to adaptive mode
245        // adaptive mode is currently unsupported so that would panic
246        let fs = Fs::from_slice(&[(
247            "config",
248            // If the lines with the vars have preceding spaces, they don't get read
249            r#"[default]
250max_attempts = 88
251retry_mode = standard
252            "#,
253        )]);
254
255        let provider_config = ProviderConfig::no_configuration().with_env(env).with_fs(fs);
256
257        let actual_retry_config = super::default_provider()
258            .configure(&provider_config)
259            .retry_config()
260            .await;
261
262        let expected_retry_config = RetryConfig::standard().with_max_attempts(42);
263
264        assert_eq!(actual_retry_config, expected_retry_config)
265    }
266
267    #[tokio::test]
268    #[should_panic = "failed to parse max attempts. source: global profile (`default`) key: `max_attempts`: invalid digit found in string"]
269    async fn test_invalid_profile_retry_config_panics() {
270        let env = Env::from_slice(&[("AWS_CONFIG_FILE", "config")]);
271        let fs = Fs::from_slice(&[(
272            "config",
273            // If the lines with the vars have preceding spaces, they don't get read
274            r#"[default]
275max_attempts = potato
276            "#,
277        )]);
278
279        let provider_config = ProviderConfig::no_configuration().with_env(env).with_fs(fs);
280
281        let _ = super::default_provider()
282            .configure(&provider_config)
283            .retry_config()
284            .await;
285    }
286
287    #[tokio::test]
288    async fn defaults() {
289        let built = test_provider(&[]).await.unwrap();
290
291        assert_eq!(built.mode(), RetryMode::Standard);
292        assert_eq!(built.max_attempts(), 3);
293    }
294
295    #[tokio::test]
296    async fn max_attempts_is_read_correctly() {
297        assert_eq!(
298            test_provider(&[(env::MAX_ATTEMPTS, "88")]).await.unwrap(),
299            RetryConfig::standard().with_max_attempts(88)
300        );
301    }
302
303    #[tokio::test]
304    async fn max_attempts_errors_when_it_cant_be_parsed_as_an_integer() {
305        assert!(matches!(
306            test_provider(&[(env::MAX_ATTEMPTS, "not an integer")])
307                .await
308                .unwrap_err()
309                .err(),
310            RetryConfigError {
311                kind: RetryConfigErrorKind::FailedToParseMaxAttempts { .. }
312            }
313        ));
314    }
315
316    #[tokio::test]
317    async fn retry_mode_is_read_correctly() {
318        assert_eq!(
319            test_provider(&[(env::RETRY_MODE, "standard")])
320                .await
321                .unwrap(),
322            RetryConfig::standard()
323        );
324    }
325
326    #[tokio::test]
327    async fn both_fields_can_be_set_at_once() {
328        assert_eq!(
329            test_provider(&[(env::RETRY_MODE, "standard"), (env::MAX_ATTEMPTS, "13")])
330                .await
331                .unwrap(),
332            RetryConfig::standard().with_max_attempts(13)
333        );
334    }
335
336    #[tokio::test]
337    async fn disallow_zero_max_attempts() {
338        let err = test_provider(&[(env::MAX_ATTEMPTS, "0")])
339            .await
340            .unwrap_err();
341        let err = err.err();
342        assert!(matches!(
343            err,
344            RetryConfigError {
345                kind: RetryConfigErrorKind::MaxAttemptsMustNotBeZero
346            }
347        ));
348    }
349}