Skip to main content

aws_smithy_runtime/client/retries/
classifiers.rs

1/*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6use aws_smithy_runtime_api::client::interceptors::context::InterceptorContext;
7use aws_smithy_runtime_api::client::retries::classifiers::{
8    ClassifyRetry, RetryAction, RetryClassifierPriority, SharedRetryClassifier,
9};
10use aws_smithy_types::retry::ProvideErrorKind;
11use std::borrow::Cow;
12use std::error::Error as StdError;
13use std::marker::PhantomData;
14
15/// A retry classifier for checking if an error is modeled as retryable.
16#[derive(Debug, Default)]
17pub struct ModeledAsRetryableClassifier<E> {
18    _inner: PhantomData<E>,
19}
20
21impl<E> ModeledAsRetryableClassifier<E> {
22    /// Create a new `ModeledAsRetryableClassifier`
23    pub fn new() -> Self {
24        Self {
25            _inner: PhantomData,
26        }
27    }
28
29    /// Return the priority of this retry classifier.
30    pub fn priority() -> RetryClassifierPriority {
31        RetryClassifierPriority::modeled_as_retryable_classifier()
32    }
33}
34
35impl<E> ClassifyRetry for ModeledAsRetryableClassifier<E>
36where
37    E: StdError + ProvideErrorKind + Send + Sync + 'static,
38{
39    fn classify_retry(&self, ctx: &InterceptorContext) -> RetryAction {
40        // Check for a result
41        let output_or_error = ctx.output_or_error();
42        // Check for an error
43        let error = match output_or_error {
44            Some(Ok(_)) | None => return RetryAction::NoActionIndicated,
45            Some(Err(err)) => err,
46        };
47        // Check that the error is an operation error
48        error
49            .as_operation_error()
50            // Downcast the error
51            .and_then(|err| err.downcast_ref::<E>())
52            // Check if the error is retryable
53            .and_then(|err| err.retryable_error_kind().map(RetryAction::retryable_error))
54            .unwrap_or_default()
55    }
56
57    fn name(&self) -> &'static str {
58        "Errors Modeled As Retryable"
59    }
60
61    fn priority(&self) -> RetryClassifierPriority {
62        Self::priority()
63    }
64}
65
66/// Classifies response, timeout, and connector errors as retryable or not.
67#[derive(Debug, Default)]
68pub struct TransientErrorClassifier<E> {
69    _inner: PhantomData<E>,
70}
71
72impl<E> TransientErrorClassifier<E> {
73    /// Create a new `TransientErrorClassifier`
74    pub fn new() -> Self {
75        Self {
76            _inner: PhantomData,
77        }
78    }
79
80    /// Return the priority of this retry classifier.
81    pub fn priority() -> RetryClassifierPriority {
82        RetryClassifierPriority::transient_error_classifier()
83    }
84}
85
86impl<E> ClassifyRetry for TransientErrorClassifier<E>
87where
88    E: StdError + Send + Sync + 'static,
89{
90    fn classify_retry(&self, ctx: &InterceptorContext) -> RetryAction {
91        // Check for a result
92        let output_or_error = ctx.output_or_error();
93        // Check for an error
94        let error = match output_or_error {
95            Some(Ok(_)) | None => return RetryAction::NoActionIndicated,
96            Some(Err(err)) => err,
97        };
98
99        if error.is_response_error() || error.is_timeout_error() {
100            RetryAction::transient_error()
101        } else if let Some(error) = error.as_connector_error() {
102            if error.is_timeout() || error.is_io() {
103                RetryAction::transient_error()
104            } else {
105                error
106                    .as_other()
107                    .map(RetryAction::retryable_error)
108                    .unwrap_or_default()
109            }
110        } else {
111            RetryAction::NoActionIndicated
112        }
113    }
114
115    fn name(&self) -> &'static str {
116        "Retryable Smithy Errors"
117    }
118
119    fn priority(&self) -> RetryClassifierPriority {
120        Self::priority()
121    }
122}
123
124const TRANSIENT_ERROR_STATUS_CODES: &[u16] = &[500, 502, 503, 504];
125
126/// A retry classifier that will treat HTTP response with those status codes as retryable.
127/// The `Default` version will retry 500, 502, 503, and 504 errors.
128#[derive(Debug)]
129pub struct HttpStatusCodeClassifier {
130    retryable_status_codes: Cow<'static, [u16]>,
131}
132
133impl Default for HttpStatusCodeClassifier {
134    fn default() -> Self {
135        Self::new_from_codes(TRANSIENT_ERROR_STATUS_CODES.to_owned())
136    }
137}
138
139impl HttpStatusCodeClassifier {
140    /// Given a `Vec<u16>` where the `u16`s represent status codes, create a `HttpStatusCodeClassifier`
141    /// that will treat HTTP response with those status codes as retryable. The `Default` version
142    /// will retry 500, 502, 503, and 504 errors.
143    pub fn new_from_codes(retryable_status_codes: impl Into<Cow<'static, [u16]>>) -> Self {
144        Self {
145            retryable_status_codes: retryable_status_codes.into(),
146        }
147    }
148
149    /// Return the priority of this retry classifier.
150    pub fn priority() -> RetryClassifierPriority {
151        RetryClassifierPriority::http_status_code_classifier()
152    }
153}
154
155impl ClassifyRetry for HttpStatusCodeClassifier {
156    fn classify_retry(&self, ctx: &InterceptorContext) -> RetryAction {
157        let is_retryable = ctx
158            .response()
159            .map(|res| res.status().into())
160            .map(|status| self.retryable_status_codes.contains(&status))
161            .unwrap_or_default();
162
163        if is_retryable {
164            RetryAction::transient_error()
165        } else {
166            RetryAction::NoActionIndicated
167        }
168    }
169
170    fn name(&self) -> &'static str {
171        "HTTP Status Code"
172    }
173
174    fn priority(&self) -> RetryClassifierPriority {
175        Self::priority()
176    }
177}
178
179/// Given an iterator of retry classifiers and an interceptor context, run retry classifiers on the
180/// context. Each classifier is passed the [`RetryAction`] accumulated by the previously-run
181/// classifiers (the first classifier is passed [`RetryAction::NoActionIndicated`]) via
182/// [`ClassifyRetry::classify_retry_v2`], so a later classifier may refine an earlier verdict.
183pub fn run_classifiers_on_ctx(
184    classifiers: impl Iterator<Item = SharedRetryClassifier>,
185    ctx: &InterceptorContext,
186) -> RetryAction {
187    // By default, don't retry
188    let mut result = RetryAction::NoActionIndicated;
189
190    for classifier in classifiers {
191        let new_result = classifier.classify_retry_v2(ctx, &result);
192
193        // If the result is `NoActionIndicated`, continue to the next classifier
194        // without overriding any previously-set result.
195        if new_result == RetryAction::NoActionIndicated {
196            continue;
197        }
198
199        // Otherwise, set the result to the new result.
200        tracing::trace!(
201            "Classifier '{}' set the result of classification to '{}'",
202            classifier.name(),
203            new_result
204        );
205        result = new_result;
206
207        // If the result is `RetryForbidden`, stop running classifiers.
208        if result == RetryAction::RetryForbidden {
209            tracing::trace!("retry classification ending early because a `RetryAction::RetryForbidden` was emitted",);
210            break;
211        }
212    }
213
214    result
215}
216
217#[cfg(test)]
218mod test {
219    use crate::client::retries::classifiers::{
220        HttpStatusCodeClassifier, ModeledAsRetryableClassifier,
221    };
222    use aws_smithy_runtime_api::client::interceptors::context::{Error, Input, InterceptorContext};
223    use aws_smithy_runtime_api::client::orchestrator::OrchestratorError;
224    use aws_smithy_runtime_api::client::result::ConnectorError;
225    use aws_smithy_runtime_api::client::retries::classifiers::{
226        ClassifyRetry, RetryAction, RetryReason, SharedRetryClassifier,
227    };
228    use aws_smithy_types::body::SdkBody;
229    use aws_smithy_types::retry::{ErrorKind, ProvideErrorKind};
230    use std::fmt;
231    use std::time::Duration;
232
233    use super::{run_classifiers_on_ctx, TransientErrorClassifier};
234
235    #[derive(Debug, PartialEq, Eq, Clone)]
236    struct UnmodeledError;
237
238    impl fmt::Display for UnmodeledError {
239        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
240            write!(f, "UnmodeledError")
241        }
242    }
243
244    impl std::error::Error for UnmodeledError {}
245
246    #[test]
247    fn classify_by_response_status() {
248        let policy = HttpStatusCodeClassifier::default();
249        let res = http_1x::Response::builder()
250            .status(500)
251            .body("error!")
252            .unwrap()
253            .map(SdkBody::from);
254        let mut ctx = InterceptorContext::new(Input::doesnt_matter());
255        ctx.set_response(res.try_into().unwrap());
256        assert_eq!(policy.classify_retry(&ctx), RetryAction::transient_error());
257    }
258
259    #[test]
260    fn classify_by_response_status_not_retryable() {
261        let policy = HttpStatusCodeClassifier::default();
262        let res = http_1x::Response::builder()
263            .status(408)
264            .body("error!")
265            .unwrap()
266            .map(SdkBody::from);
267        let mut ctx = InterceptorContext::new(Input::doesnt_matter());
268        ctx.set_response(res.try_into().unwrap());
269        assert_eq!(policy.classify_retry(&ctx), RetryAction::NoActionIndicated);
270    }
271
272    #[test]
273    fn classify_by_error_kind() {
274        #[derive(Debug)]
275        struct RetryableError;
276
277        impl fmt::Display for RetryableError {
278            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
279                write!(f, "Some retryable error")
280            }
281        }
282
283        impl ProvideErrorKind for RetryableError {
284            fn retryable_error_kind(&self) -> Option<ErrorKind> {
285                Some(ErrorKind::ClientError)
286            }
287
288            fn code(&self) -> Option<&str> {
289                // code should not be called when `error_kind` is provided
290                unimplemented!()
291            }
292        }
293
294        impl std::error::Error for RetryableError {}
295
296        let policy = ModeledAsRetryableClassifier::<RetryableError>::new();
297        let mut ctx = InterceptorContext::new(Input::doesnt_matter());
298        ctx.set_output_or_error(Err(OrchestratorError::operation(Error::erase(
299            RetryableError,
300        ))));
301
302        assert_eq!(policy.classify_retry(&ctx), RetryAction::client_error(),);
303    }
304
305    #[test]
306    fn classify_response_error() {
307        let policy = TransientErrorClassifier::<UnmodeledError>::new();
308        let mut ctx = InterceptorContext::new(Input::doesnt_matter());
309        ctx.set_output_or_error(Err(OrchestratorError::response(
310            "I am a response error".into(),
311        )));
312        assert_eq!(policy.classify_retry(&ctx), RetryAction::transient_error(),);
313    }
314
315    #[test]
316    fn test_timeout_error() {
317        let policy = TransientErrorClassifier::<UnmodeledError>::new();
318        let mut ctx = InterceptorContext::new(Input::doesnt_matter());
319        ctx.set_output_or_error(Err(OrchestratorError::timeout(
320            "I am a timeout error".into(),
321        )));
322        assert_eq!(policy.classify_retry(&ctx), RetryAction::transient_error(),);
323    }
324
325    /// A connector-level timeout is retryable.
326    ///
327    /// This is the path a `read_timeout` takes, and a different branch of
328    /// `TransientErrorClassifier` from `test_timeout_error` above: that one covers
329    /// `OrchestratorError::timeout`, the operation and operation-attempt timeouts, whereas a read
330    /// timeout surfaces as a `ConnectorError` whose kind is `Timeout`.
331    #[test]
332    fn test_connector_timeout_error_is_retryable() {
333        let policy = TransientErrorClassifier::<UnmodeledError>::new();
334        let mut ctx = InterceptorContext::new(Input::doesnt_matter());
335        ctx.set_output_or_error(Err(OrchestratorError::connector(ConnectorError::timeout(
336            "I am a connector timeout error".into(),
337        ))));
338        assert_eq!(policy.classify_retry(&ctx), RetryAction::transient_error());
339    }
340
341    // A classifier that returns a fixed verdict from `classify_retry` (and thus,
342    // via the default impl, from `classify_retry_v2`).
343    #[derive(Debug)]
344    struct StaticClassifier {
345        name: &'static str,
346        action: RetryAction,
347    }
348
349    impl ClassifyRetry for StaticClassifier {
350        fn classify_retry(&self, _ctx: &InterceptorContext) -> RetryAction {
351            self.action.clone()
352        }
353
354        fn name(&self) -> &'static str {
355            self.name
356        }
357    }
358
359    // A classifier that refines an already-retryable verdict by attaching a
360    // fixed delay, mimicking how `AwsErrorCodeClassifier` tucks an
361    // `x-amz-retry-after` delay into a verdict produced by an earlier-running
362    // classifier. It only refines a retryable `previous` that has no delay yet;
363    // otherwise it abstains with `NoActionIndicated`.
364    #[derive(Debug)]
365    struct DelayRefiningClassifier;
366
367    impl ClassifyRetry for DelayRefiningClassifier {
368        fn classify_retry(&self, _ctx: &InterceptorContext) -> RetryAction {
369            RetryAction::NoActionIndicated
370        }
371
372        fn classify_retry_v2(
373            &self,
374            _ctx: &InterceptorContext,
375            previous: &RetryAction,
376        ) -> RetryAction {
377            if let RetryAction::RetryIndicated(RetryReason::RetryableError {
378                kind,
379                retry_after: None,
380            }) = previous
381            {
382                RetryAction::retryable_error_with_explicit_delay(*kind, Duration::from_secs(5))
383            } else {
384                RetryAction::NoActionIndicated
385            }
386        }
387
388        fn name(&self) -> &'static str {
389            "delay-refining"
390        }
391    }
392
393    // `run_classifiers_on_ctx` passes each classifier the verdict accumulated by
394    // the previously-run classifiers via `classify_retry_v2`, so a later
395    // classifier can refine an earlier one's verdict (attaching a delay here).
396    #[test]
397    fn run_classifiers_on_ctx_lets_later_classifier_refine_earlier_verdict() {
398        let ctx = InterceptorContext::new(Input::doesnt_matter());
399        let classifiers = vec![
400            SharedRetryClassifier::new(StaticClassifier {
401                name: "transient",
402                action: RetryAction::transient_error(),
403            }),
404            SharedRetryClassifier::new(DelayRefiningClassifier),
405        ];
406
407        assert_eq!(
408            run_classifiers_on_ctx(classifiers.into_iter(), &ctx),
409            RetryAction::retryable_error_with_explicit_delay(
410                ErrorKind::TransientError,
411                Duration::from_secs(5),
412            ),
413        );
414    }
415
416    // The refining classifier must not fabricate a retry on its own: if no
417    // earlier classifier marked the response retryable, the refinement abstains
418    // and the overall result is `NoActionIndicated`. This matches the behavior
419    // of other SDKs (e.g. Java v2), where `x-amz-retry-after` only supplies a
420    // backoff delay for an already-retryable error and never forces a retry.
421    #[test]
422    fn run_classifiers_on_ctx_refiner_does_not_fabricate_retry() {
423        let ctx = InterceptorContext::new(Input::doesnt_matter());
424        let classifiers = vec![SharedRetryClassifier::new(DelayRefiningClassifier)];
425
426        assert_eq!(
427            run_classifiers_on_ctx(classifiers.into_iter(), &ctx),
428            RetryAction::NoActionIndicated,
429        );
430    }
431
432    // When the refining classifier abstains (returns `NoActionIndicated` because
433    // the earlier verdict already carries a delay), `run_classifiers_on_ctx`
434    // preserves that earlier verdict rather than clobbering it.
435    #[test]
436    fn run_classifiers_on_ctx_preserves_earlier_verdict_when_refiner_abstains() {
437        let ctx = InterceptorContext::new(Input::doesnt_matter());
438        let already_delayed = RetryAction::retryable_error_with_explicit_delay(
439            ErrorKind::TransientError,
440            Duration::from_secs(1),
441        );
442        let classifiers = vec![
443            SharedRetryClassifier::new(StaticClassifier {
444                name: "already-delayed",
445                action: already_delayed.clone(),
446            }),
447            SharedRetryClassifier::new(DelayRefiningClassifier),
448        ];
449
450        assert_eq!(
451            run_classifiers_on_ctx(classifiers.into_iter(), &ctx),
452            already_delayed,
453        );
454    }
455}