Skip to main content

aws_smithy_types/
retry.rs

1/*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! This module defines types that describe when to retry given a response.
7
8use crate::config_bag::value::Value;
9use crate::config_bag::{ItemIter, Storable, Store, StoreReplace};
10use std::fmt;
11use std::str::FromStr;
12use std::time::Duration;
13
14const VALID_RETRY_MODES: &[RetryMode] = &[RetryMode::Standard];
15
16/// Type of error that occurred when making a request.
17#[derive(Clone, Copy, Eq, PartialEq, Debug)]
18#[non_exhaustive]
19pub enum ErrorKind {
20    /// A connection-level error.
21    ///
22    /// A `TransientError` can represent conditions such as socket timeouts, socket connection errors, or TLS negotiation timeouts.
23    ///
24    /// `TransientError` is not modeled by Smithy and is instead determined through client-specific heuristics and response status codes.
25    ///
26    /// Typically these should never be applied for non-idempotent request types
27    /// since in this scenario, it's impossible to know whether the operation had
28    /// a side effect on the server.
29    ///
30    /// TransientErrors are not currently modeled. They are determined based on specific provider
31    /// level errors & response status code.
32    TransientError,
33
34    /// An error where the server explicitly told the client to back off, such as a 429 or 503 HTTP error.
35    ThrottlingError,
36
37    /// Server error that isn't explicitly throttling but is considered by the client
38    /// to be something that should be retried.
39    ServerError,
40
41    /// Doesn't count against any budgets. This could be something like a 401 challenge in Http.
42    ClientError,
43}
44
45impl fmt::Display for ErrorKind {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        match self {
48            Self::TransientError => write!(f, "transient error"),
49            Self::ThrottlingError => write!(f, "throttling error"),
50            Self::ServerError => write!(f, "server error"),
51            Self::ClientError => write!(f, "client error"),
52        }
53    }
54}
55
56/// Trait that provides an `ErrorKind` and an error code.
57pub trait ProvideErrorKind {
58    /// Returns the `ErrorKind` when the error is modeled as retryable
59    ///
60    /// If the error kind cannot be determined (e.g. the error is unmodeled at the error kind depends
61    /// on an HTTP status code, return `None`.
62    fn retryable_error_kind(&self) -> Option<ErrorKind>;
63
64    /// Returns the `code` for this error if one exists
65    fn code(&self) -> Option<&str>;
66}
67
68/// `RetryKind` describes how a request MAY be retried for a given response
69///
70/// A `RetryKind` describes how a response MAY be retried; it does not mandate retry behavior.
71/// The actual retry behavior is at the sole discretion of the RetryStrategy in place.
72/// A RetryStrategy may ignore the suggestion for a number of reasons including but not limited to:
73/// - Number of retry attempts exceeded
74/// - The required retry delay exceeds the maximum backoff configured by the client
75/// - No retry tokens are available due to service health
76#[non_exhaustive]
77#[derive(Eq, PartialEq, Debug)]
78pub enum RetryKind {
79    /// Retry the associated request due to a known `ErrorKind`.
80    Error(ErrorKind),
81
82    /// An Explicit retry (e.g. from `x-amz-retry-after`).
83    ///
84    /// Note: The specified `Duration` is considered a suggestion and may be replaced or ignored.
85    Explicit(Duration),
86
87    /// The response was a failure that should _not_ be retried.
88    UnretryableFailure,
89
90    /// The response was successful, so no retry is necessary.
91    Unnecessary,
92}
93
94/// Specifies how failed requests should be retried.
95#[non_exhaustive]
96#[derive(Eq, PartialEq, Debug, Clone, Copy)]
97pub enum RetryMode {
98    /// The standard set of retry rules across AWS SDKs. This mode includes a standard set of errors
99    /// that are retried, and support for retry quotas. The default maximum number of attempts
100    /// with this mode is three, unless otherwise explicitly configured with [`RetryConfig`].
101    Standard,
102
103    /// An experimental retry mode that includes the functionality of standard mode but includes
104    /// automatic client-side throttling. Because this mode is experimental, it might change
105    /// behavior in the future.
106    Adaptive,
107}
108
109impl FromStr for RetryMode {
110    type Err = RetryModeParseError;
111
112    fn from_str(string: &str) -> Result<Self, Self::Err> {
113        let string = string.trim();
114
115        // eq_ignore_ascii_case is OK here because the only strings we need to check for are ASCII
116        if string.eq_ignore_ascii_case("standard") {
117            Ok(RetryMode::Standard)
118        } else if string.eq_ignore_ascii_case("adaptive") {
119            Ok(RetryMode::Adaptive)
120        } else {
121            Err(RetryModeParseError::new(string))
122        }
123    }
124}
125
126/// Failure to parse a `RetryMode` from string.
127#[derive(Debug)]
128pub struct RetryModeParseError {
129    message: String,
130}
131
132impl RetryModeParseError {
133    pub(super) fn new(message: impl Into<String>) -> Self {
134        Self {
135            message: message.into(),
136        }
137    }
138}
139
140impl fmt::Display for RetryModeParseError {
141    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142        write!(
143            f,
144            "error parsing string '{}' as RetryMode, valid options are: {:#?}",
145            self.message, VALID_RETRY_MODES
146        )
147    }
148}
149
150impl std::error::Error for RetryModeParseError {}
151
152/// Builder for [`RetryConfig`].
153#[non_exhaustive]
154#[derive(Debug, Default, Clone, PartialEq)]
155pub struct RetryConfigBuilder {
156    mode: Option<RetryMode>,
157    max_attempts: Option<u32>,
158    initial_backoff: Option<Duration>,
159    max_backoff: Option<Duration>,
160    reconnect_mode: Option<ReconnectMode>,
161}
162
163impl RetryConfigBuilder {
164    /// Creates a new builder.
165    pub fn new() -> Self {
166        Default::default()
167    }
168
169    /// Sets the retry mode.
170    pub fn set_mode(&mut self, retry_mode: Option<RetryMode>) -> &mut Self {
171        self.mode = retry_mode;
172        self
173    }
174
175    /// Sets the retry mode.
176    pub fn mode(mut self, mode: RetryMode) -> Self {
177        self.set_mode(Some(mode));
178        self
179    }
180
181    /// Set the [`ReconnectMode`] for the retry strategy
182    ///
183    /// By default, when a transient error is encountered, the connection in use will be poisoned.
184    /// This prevents reusing a connection to a potentially bad host but may increase the load on
185    /// the server.
186    ///
187    /// This behavior can be disabled by setting [`ReconnectMode::ReuseAllConnections`] instead.
188    ///
189    /// Clients on Retry Behavior 2.1 (`BehaviorVersion` `v2026_11_10` or later) default to
190    /// `ReuseAllConnections`, but an explicit setting here still takes effect.
191    pub fn reconnect_mode(mut self, reconnect_mode: ReconnectMode) -> Self {
192        self.set_reconnect_mode(Some(reconnect_mode));
193        self
194    }
195
196    /// Set the [`ReconnectMode`] for the retry strategy
197    ///
198    /// By default, when a transient error is encountered, the connection in use will be poisoned.
199    /// This prevents reusing a connection to a potentially bad host but may increase the load on
200    /// the server.
201    ///
202    /// This behavior can be disabled by setting [`ReconnectMode::ReuseAllConnections`] instead.
203    ///
204    /// Clients on Retry Behavior 2.1 (`BehaviorVersion` `v2026_11_10` or later) default to
205    /// `ReuseAllConnections`, but an explicit setting here still takes effect.
206    pub fn set_reconnect_mode(&mut self, reconnect_mode: Option<ReconnectMode>) -> &mut Self {
207        self.reconnect_mode = reconnect_mode;
208        self
209    }
210
211    /// Sets the max attempts. This value must be greater than zero.
212    pub fn set_max_attempts(&mut self, max_attempts: Option<u32>) -> &mut Self {
213        self.max_attempts = max_attempts;
214        self
215    }
216
217    /// Sets the max attempts. This value must be greater than zero.
218    pub fn max_attempts(mut self, max_attempts: u32) -> Self {
219        self.set_max_attempts(Some(max_attempts));
220        self
221    }
222
223    /// Set the initial_backoff duration. This duration should be non-zero.
224    pub fn set_initial_backoff(&mut self, initial_backoff: Option<Duration>) -> &mut Self {
225        self.initial_backoff = initial_backoff;
226        self
227    }
228
229    /// Set the initial_backoff duration. This duration should be non-zero.
230    pub fn initial_backoff(mut self, initial_backoff: Duration) -> Self {
231        self.set_initial_backoff(Some(initial_backoff));
232        self
233    }
234
235    /// Set the max_backoff duration. This duration should be non-zero.
236    pub fn set_max_backoff(&mut self, max_backoff: Option<Duration>) -> &mut Self {
237        self.max_backoff = max_backoff;
238        self
239    }
240
241    /// Set the max_backoff duration. This duration should be non-zero.
242    pub fn max_backoff(mut self, max_backoff: Duration) -> Self {
243        self.set_max_backoff(Some(max_backoff));
244        self
245    }
246
247    /// Merge two builders together. Values from `other` will only be used as a fallback for values
248    /// from `self` Useful for merging configs from different sources together when you want to
249    /// handle "precedence" per value instead of at the config level
250    ///
251    /// # Example
252    ///
253    /// ```rust
254    /// # use aws_smithy_types::retry::{RetryMode, RetryConfigBuilder};
255    /// let a = RetryConfigBuilder::new().max_attempts(1);
256    /// let b = RetryConfigBuilder::new().max_attempts(5).mode(RetryMode::Adaptive);
257    /// let retry_config = a.take_unset_from(b).build();
258    /// // A's value take precedence over B's value
259    /// assert_eq!(retry_config.max_attempts(), 1);
260    /// // A never set a retry mode so B's value was used
261    /// assert_eq!(retry_config.mode(), RetryMode::Adaptive);
262    /// ```
263    pub fn take_unset_from(self, other: Self) -> Self {
264        Self {
265            mode: self.mode.or(other.mode),
266            max_attempts: self.max_attempts.or(other.max_attempts),
267            initial_backoff: self.initial_backoff.or(other.initial_backoff),
268            max_backoff: self.max_backoff.or(other.max_backoff),
269            reconnect_mode: self.reconnect_mode.or(other.reconnect_mode),
270        }
271    }
272
273    /// Builds a `RetryConfig`.
274    pub fn build(self) -> RetryConfig {
275        RetryConfig {
276            mode: self.mode.unwrap_or(RetryMode::Standard),
277            max_attempts: self.max_attempts.unwrap_or(3),
278            initial_backoff: self
279                .initial_backoff
280                .unwrap_or_else(|| Duration::from_secs(1)),
281            reconnect_mode: self.reconnect_mode,
282            max_backoff: self.max_backoff.unwrap_or_else(|| Duration::from_secs(20)),
283            use_static_exponential_base: false,
284            retry_spec: None,
285        }
286    }
287}
288
289/// Retry configuration for requests.
290#[non_exhaustive]
291#[derive(Debug, Clone, PartialEq)]
292pub struct RetryConfig {
293    mode: RetryMode,
294    max_attempts: u32,
295    initial_backoff: Duration,
296    max_backoff: Duration,
297    reconnect_mode: Option<ReconnectMode>,
298    use_static_exponential_base: bool,
299    retry_spec: Option<RetrySpec>,
300}
301
302impl Storable for RetryConfig {
303    type Storer = StoreReplace<RetryConfig>;
304}
305
306/// Mode for connection re-establishment
307///
308/// By default, when a transient error is encountered, the connection in use will be poisoned. This
309/// behavior can be disabled by setting [`ReconnectMode::ReuseAllConnections`] instead.
310///
311/// Clients on Retry Behavior 2.1 (`BehaviorVersion` `v2026_11_10` or later) default to
312/// `ReuseAllConnections`, but an explicit setting still takes effect.
313#[derive(Debug, Clone, PartialEq, Copy)]
314pub enum ReconnectMode {
315    /// Reconnect on [`ErrorKind::TransientError`]
316    ReconnectOnTransientError,
317
318    /// Disable reconnect on error
319    ///
320    /// When this setting is applied, 503s, timeouts, and other transient errors will _not_
321    /// lead to a new connection being established unless the connection is closed by the remote.
322    ReuseAllConnections,
323}
324
325impl Storable for ReconnectMode {
326    type Storer = StoreReplace<ReconnectMode>;
327}
328
329/// Version tag for [`RetrySpec`], enabling zero-cost comparisons without
330/// exposing the internal representation.
331///
332/// New versions must be appended at the end — `PartialOrd` is derived from
333/// declaration order. If a version needs to be interleaved between
334/// existing variants (e.g., adding `V2_1_1` after `V2_2` already exists),
335/// replace the derived `Ord`/`PartialOrd` with a manual implementation
336/// that maps each variant to an explicit rank.
337#[doc(hidden)]
338#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
339#[non_exhaustive]
340pub enum RetrySpecVersion {
341    /// Retry Behavior 2.0 (legacy).
342    V2_0,
343    /// Retry Behavior 2.1.
344    V2_1,
345}
346
347/// Version-gated retry parameters derived from `BehaviorVersion`.
348///
349/// `RetrySpec` exists because `BehaviorVersion` lives in
350/// `aws-smithy-runtime-api` while `RetryConfig` lives in `aws-smithy-types`.
351/// `RetryConfig` cannot depend on `BehaviorVersion` directly without
352/// creating a circular crate dependency. Inferring the spec version from
353/// the presence or absence of individual fields would be fragile and
354/// error-prone.
355///
356/// Instead, `BehaviorVersion` is converted into a `RetrySpec` and stored
357/// alongside `RetryConfig` in the config bag. The retry strategy reads
358/// `RetrySpec` to determine version-gated behavior (backoff timing, token
359/// costs, `x-amz-retry-after` bounds) without ever depending on
360/// `BehaviorVersion`.
361///
362/// [`BehaviorVersion`]: crate::config_bag::Storable
363#[doc(hidden)]
364#[derive(Clone, Debug, PartialEq)]
365#[non_exhaustive]
366pub struct RetrySpec {
367    version: RetrySpecVersion,
368    non_throttling_initial_backoff: Duration,
369    long_polling: Option<bool>,
370}
371
372impl RetrySpec {
373    /// The version corresponding to Retry Behavior 2.0 (legacy).
374    pub const V2_0: RetrySpecVersion = RetrySpecVersion::V2_0;
375    /// The version corresponding to Retry Behavior 2.1.
376    pub const V2_1: RetrySpecVersion = RetrySpecVersion::V2_1;
377
378    /// Returns true if this spec's version is at least the given version.
379    pub fn is_at_least(&self, version: RetrySpecVersion) -> bool {
380        self.version >= version
381    }
382
383    /// Create a `RetrySpec` corresponding to Retry Behavior 2.0 (legacy).
384    pub fn v2_0() -> Self {
385        Self {
386            version: Self::V2_0,
387            non_throttling_initial_backoff: Duration::from_secs(1),
388            long_polling: None,
389        }
390    }
391
392    /// Create a `RetrySpec` corresponding to Retry Behavior 2.1.
393    pub fn v2_1() -> Self {
394        Self {
395            version: Self::V2_1,
396            non_throttling_initial_backoff: Duration::from_millis(50),
397            long_polling: None,
398        }
399    }
400
401    /// Set the base backoff for non-throttling errors.
402    pub fn with_non_throttling_initial_backoff(mut self, duration: Duration) -> Self {
403        self.non_throttling_initial_backoff = duration;
404        self
405    }
406
407    /// Get the base backoff for non-throttling errors.
408    pub fn non_throttling_initial_backoff(&self) -> Duration {
409        self.non_throttling_initial_backoff
410    }
411
412    /// Set whether this is a long-polling operation.
413    pub fn with_long_polling(mut self, long_polling: bool) -> Self {
414        self.long_polling = Some(long_polling);
415        self
416    }
417
418    /// Returns whether this is a long-polling operation.
419    pub fn long_polling(&self) -> bool {
420        self.long_polling.unwrap_or(false)
421    }
422
423    fn take_defaults_from(&mut self, other: &RetrySpec) {
424        if self.long_polling.is_none() {
425            self.long_polling = other.long_polling;
426        }
427    }
428}
429
430impl RetryConfig {
431    /// Creates a default `RetryConfig` with `RetryMode::Standard` and max attempts of three.
432    pub fn standard() -> Self {
433        Self {
434            mode: RetryMode::Standard,
435            max_attempts: 3,
436            initial_backoff: Duration::from_secs(1),
437            reconnect_mode: None,
438            max_backoff: Duration::from_secs(20),
439            use_static_exponential_base: false,
440            retry_spec: None,
441        }
442    }
443
444    /// Creates a default `RetryConfig` with `RetryMode::Adaptive` and max attempts of three.
445    pub fn adaptive() -> Self {
446        Self {
447            mode: RetryMode::Adaptive,
448            max_attempts: 3,
449            initial_backoff: Duration::from_secs(1),
450            reconnect_mode: None,
451            max_backoff: Duration::from_secs(20),
452            use_static_exponential_base: false,
453            retry_spec: None,
454        }
455    }
456
457    /// Creates a `RetryConfig` that has retries disabled.
458    pub fn disabled() -> Self {
459        Self::standard().with_max_attempts(1)
460    }
461
462    /// Set this config's [retry mode](RetryMode).
463    pub fn with_retry_mode(mut self, retry_mode: RetryMode) -> Self {
464        self.mode = retry_mode;
465        self
466    }
467
468    /// Set the maximum number of times a request should be tried, including the initial attempt.
469    /// This value must be greater than zero.
470    pub fn with_max_attempts(mut self, max_attempts: u32) -> Self {
471        self.max_attempts = max_attempts;
472        self
473    }
474
475    /// Set the [`ReconnectMode`] for the retry strategy
476    ///
477    /// By default, when a transient error is encountered, the connection in use will be poisoned.
478    /// This prevents reusing a connection to a potentially bad host but may increase the load on
479    /// the server.
480    ///
481    /// This behavior can be disabled by setting [`ReconnectMode::ReuseAllConnections`] instead.
482    ///
483    /// Clients on Retry Behavior 2.1 (`BehaviorVersion` `v2026_11_10` or later) default to
484    /// `ReuseAllConnections`, but an explicit setting here still takes effect.
485    pub fn with_reconnect_mode(mut self, reconnect_mode: ReconnectMode) -> Self {
486        self.reconnect_mode = Some(reconnect_mode);
487        self
488    }
489
490    /// Set the multiplier used when calculating backoff times as part of an
491    /// [exponential backoff with jitter](https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/)
492    /// strategy. Most services should work fine with the default duration of 1 second, but if you
493    /// find that your requests are taking too long due to excessive retry backoff, try lowering
494    /// this value.
495    ///
496    /// ## Example
497    ///
498    /// *For a request that gets retried 3 times, when initial_backoff is 1 seconds:*
499    /// - the first retry will occur after 0 to 1 seconds
500    /// - the second retry will occur after 0 to 2 seconds
501    /// - the third retry will occur after 0 to 4 seconds
502    ///
503    /// *For a request that gets retried 3 times, when initial_backoff is 30 milliseconds:*
504    /// - the first retry will occur after 0 to 30 milliseconds
505    /// - the second retry will occur after 0 to 60 milliseconds
506    /// - the third retry will occur after 0 to 120 milliseconds
507    pub fn with_initial_backoff(mut self, initial_backoff: Duration) -> Self {
508        self.initial_backoff = initial_backoff;
509        self
510    }
511
512    /// Set the maximum backoff time.
513    pub fn with_max_backoff(mut self, max_backoff: Duration) -> Self {
514        self.max_backoff = max_backoff;
515        self
516    }
517
518    /// Hint to the retry strategy whether to use a static exponential base.
519    ///
520    /// When a retry strategy uses exponential backoff, it calculates a random base. This causes the
521    /// retry delay to be slightly random, and helps prevent "thundering herd" scenarios. However,
522    /// it's often useful during testing to know exactly how long the delay will be.
523    ///
524    /// Therefore, if you're writing a test and asserting an expected retry delay,
525    /// set this to `true`.
526    #[cfg(feature = "test-util")]
527    pub fn with_use_static_exponential_base(mut self, use_static_exponential_base: bool) -> Self {
528        self.use_static_exponential_base = use_static_exponential_base;
529        self
530    }
531
532    /// Returns the retry mode.
533    pub fn mode(&self) -> RetryMode {
534        self.mode
535    }
536
537    /// Returns the [`ReconnectMode`]
538    pub fn reconnect_mode(&self) -> ReconnectMode {
539        self.reconnect_mode
540            .unwrap_or(ReconnectMode::ReconnectOnTransientError)
541    }
542
543    /// Returns the max attempts.
544    pub fn max_attempts(&self) -> u32 {
545        self.max_attempts
546    }
547
548    /// Returns the backoff multiplier duration.
549    pub fn initial_backoff(&self) -> Duration {
550        self.initial_backoff
551    }
552
553    /// Returns the max backoff duration.
554    pub fn max_backoff(&self) -> Duration {
555        self.max_backoff
556    }
557
558    /// Returns true if retry is enabled with this config
559    pub fn has_retry(&self) -> bool {
560        self.max_attempts > 1
561    }
562
563    /// Returns `true` if retry strategies should use a static exponential base instead of the
564    /// default random base.
565    ///
566    /// To set this value, the `test-util` feature must be enabled.
567    pub fn use_static_exponential_base(&self) -> bool {
568        self.use_static_exponential_base
569    }
570
571    /// Set the SDK-internal retry spec.
572    #[doc(hidden)]
573    pub fn with_retry_spec(mut self, retry_spec: RetrySpec) -> Self {
574        self.retry_spec = Some(retry_spec);
575        self
576    }
577
578    /// Returns the SDK-internal retry spec, if set.
579    #[doc(hidden)]
580    pub fn retry_spec(&self) -> Option<&RetrySpec> {
581        self.retry_spec.as_ref()
582    }
583
584    fn take_defaults_from(&mut self, other: &RetryConfig) {
585        if self.retry_spec.is_none() {
586            self.retry_spec = other.retry_spec.clone();
587        } else if let (Some(mine), Some(theirs)) = (self.retry_spec.as_mut(), &other.retry_spec) {
588            mine.take_defaults_from(theirs);
589        }
590        if self.reconnect_mode.is_none() {
591            self.reconnect_mode = other.reconnect_mode;
592        }
593    }
594}
595
596/// Merges [`RetryConfig`] from multiple layers in the config bag.
597///
598/// This follows the same pattern as [`MergeTimeoutConfig`](crate::timeout::MergeTimeoutConfig):
599/// the highest-priority `RetryConfig` wins, but unset fields (like `retry_spec`) are
600/// filled in from lower-priority layers via `RetryConfig::take_defaults_from`.
601#[doc(hidden)]
602#[derive(Debug)]
603pub struct MergeRetryConfig;
604
605impl Storable for MergeRetryConfig {
606    type Storer = MergeRetryConfig;
607}
608
609impl Store for MergeRetryConfig {
610    type ReturnedType<'a> = RetryConfig;
611    type StoredType = <StoreReplace<RetryConfig> as Store>::StoredType;
612
613    fn merge_iter(iter: ItemIter<'_, Self>) -> Self::ReturnedType<'_> {
614        let mut result: Option<RetryConfig> = None;
615        for rc in iter {
616            match (result.as_mut(), rc) {
617                (Some(result), Value::Set(rc)) => {
618                    result.take_defaults_from(rc);
619                }
620                (None, Value::Set(rc)) => {
621                    result = Some(rc.clone());
622                }
623                (_, Value::ExplicitlyUnset(_)) => {
624                    result = Some(RetryConfig::disabled());
625                }
626            }
627        }
628        result.unwrap_or_else(RetryConfig::disabled)
629    }
630}
631
632#[cfg(test)]
633mod tests {
634    use crate::retry::{RetryConfigBuilder, RetryMode};
635    use std::str::FromStr;
636
637    #[test]
638    fn retry_config_builder_merge_with_favors_self_values_over_other_values() {
639        let self_builder = RetryConfigBuilder::new()
640            .max_attempts(1)
641            .mode(RetryMode::Adaptive);
642        let other_builder = RetryConfigBuilder::new()
643            .max_attempts(5)
644            .mode(RetryMode::Standard);
645        let retry_config = self_builder.take_unset_from(other_builder).build();
646
647        assert_eq!(retry_config.max_attempts, 1);
648        assert_eq!(retry_config.mode, RetryMode::Adaptive);
649    }
650
651    #[test]
652    fn retry_mode_from_str_parses_valid_strings_regardless_of_casing() {
653        assert_eq!(
654            RetryMode::from_str("standard").ok(),
655            Some(RetryMode::Standard)
656        );
657        assert_eq!(
658            RetryMode::from_str("STANDARD").ok(),
659            Some(RetryMode::Standard)
660        );
661        assert_eq!(
662            RetryMode::from_str("StAnDaRd").ok(),
663            Some(RetryMode::Standard)
664        );
665        // assert_eq!(
666        //     RetryMode::from_str("adaptive").ok(),
667        //     Some(RetryMode::Adaptive)
668        // );
669        // assert_eq!(
670        //     RetryMode::from_str("ADAPTIVE").ok(),
671        //     Some(RetryMode::Adaptive)
672        // );
673        // assert_eq!(
674        //     RetryMode::from_str("aDaPtIvE").ok(),
675        //     Some(RetryMode::Adaptive)
676        // );
677    }
678
679    #[test]
680    fn retry_mode_from_str_ignores_whitespace_before_and_after() {
681        assert_eq!(
682            RetryMode::from_str("  standard ").ok(),
683            Some(RetryMode::Standard)
684        );
685        assert_eq!(
686            RetryMode::from_str("   STANDARD  ").ok(),
687            Some(RetryMode::Standard)
688        );
689        assert_eq!(
690            RetryMode::from_str("  StAnDaRd   ").ok(),
691            Some(RetryMode::Standard)
692        );
693        // assert_eq!(
694        //     RetryMode::from_str("  adaptive  ").ok(),
695        //     Some(RetryMode::Adaptive)
696        // );
697        // assert_eq!(
698        //     RetryMode::from_str("   ADAPTIVE ").ok(),
699        //     Some(RetryMode::Adaptive)
700        // );
701        // assert_eq!(
702        //     RetryMode::from_str("  aDaPtIvE    ").ok(),
703        //     Some(RetryMode::Adaptive)
704        // );
705    }
706
707    #[test]
708    fn retry_mode_from_str_wont_parse_invalid_strings() {
709        assert_eq!(RetryMode::from_str("std").ok(), None);
710        assert_eq!(RetryMode::from_str("aws").ok(), None);
711        assert_eq!(RetryMode::from_str("s t a n d a r d").ok(), None);
712        assert_eq!(RetryMode::from_str("a d a p t i v e").ok(), None);
713    }
714
715    #[test]
716    fn merge_retry_config_preserves_retry_spec_from_lower_layer() {
717        use crate::config_bag::{ConfigBag, Layer};
718        use crate::retry::{MergeRetryConfig, RetryConfig, RetrySpec};
719
720        let mut lower = Layer::new("sdk_defaults");
721        lower.store_put(RetryConfig::standard().with_retry_spec(RetrySpec::v2_1()));
722        let mut upper = Layer::new("customer");
723        upper.store_put(RetryConfig::standard().with_max_attempts(5));
724        let bag = ConfigBag::of_layers(vec![lower, upper]);
725
726        let merged = bag.load::<MergeRetryConfig>();
727        assert_eq!(merged.max_attempts(), 5);
728        assert_eq!(merged.retry_spec(), Some(&RetrySpec::v2_1()));
729    }
730
731    #[test]
732    fn merge_retry_config_customer_explicit_retry_spec_wins() {
733        use crate::config_bag::{ConfigBag, Layer};
734        use crate::retry::{MergeRetryConfig, RetryConfig, RetrySpec};
735
736        let mut lower = Layer::new("sdk_defaults");
737        lower.store_put(RetryConfig::standard().with_retry_spec(RetrySpec::v2_1()));
738        let mut upper = Layer::new("customer");
739        upper.store_put(RetryConfig::standard().with_retry_spec(RetrySpec::v2_0()));
740        let bag = ConfigBag::of_layers(vec![lower, upper]);
741
742        let merged = bag.load::<MergeRetryConfig>();
743        assert_eq!(merged.retry_spec(), Some(&RetrySpec::v2_0()));
744    }
745
746    #[test]
747    fn merge_retry_config_long_polling_from_operation_layer() {
748        use crate::config_bag::{ConfigBag, Layer};
749        use crate::retry::{MergeRetryConfig, RetryConfig, RetrySpec};
750
751        let mut lower = Layer::new("sdk_defaults");
752        lower.store_put(RetryConfig::standard().with_retry_spec(RetrySpec::v2_1()));
753        let mut upper = Layer::new("operation");
754        upper.store_put(
755            RetryConfig::standard().with_retry_spec(RetrySpec::v2_1().with_long_polling(true)),
756        );
757        let bag = ConfigBag::of_layers(vec![lower, upper]);
758
759        let merged = bag.load::<MergeRetryConfig>();
760        assert!(merged.retry_spec().unwrap().long_polling());
761    }
762}