1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

//! HTTP specific retry behaviors
//!
//! For protocol agnostic retries, see `aws_smithy_types::Retry`.

use crate::operation::Response;
use crate::result::SdkError;
use aws_smithy_types::retry::{ErrorKind, ProvideErrorKind, RetryKind};

/// Classifies what kind of retry is needed for a given `response`.
pub trait ClassifyRetry<T, E>: Clone {
    /// Run this classifier against a response to determine if it should be retried.
    fn classify_retry(&self, response: Result<&T, &E>) -> RetryKind;
}

const TRANSIENT_ERROR_STATUS_CODES: &[u16] = &[500, 502, 503, 504];

/// The default implementation of [`ClassifyRetry`] for generated clients.
#[derive(Clone, Debug, Default)]
pub struct DefaultResponseRetryClassifier;

impl DefaultResponseRetryClassifier {
    /// Creates a new `DefaultResponseRetryClassifier`
    pub fn new() -> Self {
        Default::default()
    }

    /// Matches on the given `result` and, if possible, returns the underlying cause and the operation response
    /// that can be used for further classification logic. Otherwise, it returns a `RetryKind` that should be used
    /// for the result.
    //
    // IMPORTANT: This function is used by the AWS SDK in `aws-http` for the SDK's own response classification logic
    #[doc(hidden)]
    pub fn try_extract_err_response<'a, T, E>(
        result: Result<&T, &'a SdkError<E>>,
    ) -> Result<(&'a E, &'a Response), RetryKind> {
        match result {
            Ok(_) => Err(RetryKind::Unnecessary),
            Err(SdkError::ServiceError(context)) => Ok((context.err(), context.raw())),
            Err(SdkError::TimeoutError(_err)) => Err(RetryKind::Error(ErrorKind::TransientError)),
            Err(SdkError::DispatchFailure(err)) => {
                if err.is_timeout() || err.is_io() {
                    Err(RetryKind::Error(ErrorKind::TransientError))
                } else if let Some(ek) = err.is_other() {
                    Err(RetryKind::Error(ek))
                } else {
                    Err(RetryKind::UnretryableFailure)
                }
            }
            Err(SdkError::ResponseError { .. }) => Err(RetryKind::Error(ErrorKind::TransientError)),
            Err(SdkError::ConstructionFailure(_)) => Err(RetryKind::UnretryableFailure),
        }
    }
}

impl<T, E> ClassifyRetry<T, SdkError<E>> for DefaultResponseRetryClassifier
where
    E: ProvideErrorKind,
{
    fn classify_retry(&self, result: Result<&T, &SdkError<E>>) -> RetryKind {
        let (err, response) = match Self::try_extract_err_response(result) {
            Ok(extracted) => extracted,
            Err(retry_kind) => return retry_kind,
        };
        if let Some(kind) = err.retryable_error_kind() {
            return RetryKind::Error(kind);
        };
        if TRANSIENT_ERROR_STATUS_CODES.contains(&response.http().status().as_u16()) {
            return RetryKind::Error(ErrorKind::TransientError);
        };
        RetryKind::UnretryableFailure
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::body::SdkBody;
    use crate::operation;
    use crate::result::{SdkError, SdkSuccess};
    use crate::retry::ClassifyRetry;
    use aws_smithy_types::retry::{ErrorKind, ProvideErrorKind, RetryKind};
    use std::fmt;

    #[derive(Debug)]
    struct UnmodeledError;
    impl fmt::Display for UnmodeledError {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "UnmodeledError")
        }
    }
    impl std::error::Error for UnmodeledError {}

    struct CodedError {
        code: &'static str,
    }

    impl ProvideErrorKind for UnmodeledError {
        fn retryable_error_kind(&self) -> Option<ErrorKind> {
            None
        }

        fn code(&self) -> Option<&str> {
            None
        }
    }

    impl ProvideErrorKind for CodedError {
        fn retryable_error_kind(&self) -> Option<ErrorKind> {
            None
        }

        fn code(&self) -> Option<&str> {
            Some(self.code)
        }
    }

    fn make_err<E>(
        err: E,
        raw: http::Response<&'static str>,
    ) -> Result<SdkSuccess<()>, SdkError<E>> {
        Err(SdkError::service_error(
            err,
            operation::Response::new(raw.map(SdkBody::from)),
        ))
    }

    #[test]
    fn not_an_error() {
        let policy = DefaultResponseRetryClassifier::new();
        let test_response = http::Response::new("OK");
        assert_eq!(
            policy.classify_retry(make_err(UnmodeledError, test_response).as_ref()),
            RetryKind::UnretryableFailure
        );
    }

    #[test]
    fn classify_by_response_status() {
        let policy = DefaultResponseRetryClassifier::new();
        let test_resp = http::Response::builder()
            .status(500)
            .body("error!")
            .unwrap();
        assert_eq!(
            policy.classify_retry(make_err(UnmodeledError, test_resp).as_ref()),
            RetryKind::Error(ErrorKind::TransientError)
        );
    }

    #[test]
    fn classify_by_response_status_not_retryable() {
        let policy = DefaultResponseRetryClassifier::new();
        let test_resp = http::Response::builder()
            .status(408)
            .body("error!")
            .unwrap();
        assert_eq!(
            policy.classify_retry(make_err(UnmodeledError, test_resp).as_ref()),
            RetryKind::UnretryableFailure
        );
    }

    #[test]
    fn classify_by_error_kind() {
        struct ModeledRetries;
        let test_response = http::Response::new("OK");
        impl ProvideErrorKind for ModeledRetries {
            fn retryable_error_kind(&self) -> Option<ErrorKind> {
                Some(ErrorKind::ClientError)
            }

            fn code(&self) -> Option<&str> {
                // code should not be called when `error_kind` is provided
                unimplemented!()
            }
        }

        let policy = DefaultResponseRetryClassifier::new();

        assert_eq!(
            policy.classify_retry(make_err(ModeledRetries, test_response).as_ref()),
            RetryKind::Error(ErrorKind::ClientError)
        );
    }

    #[test]
    fn classify_response_error() {
        let policy = DefaultResponseRetryClassifier::new();
        assert_eq!(
            policy.classify_retry(
                Result::<SdkSuccess<()>, SdkError<UnmodeledError>>::Err(SdkError::response_error(
                    UnmodeledError,
                    operation::Response::new(http::Response::new("OK").map(SdkBody::from)),
                ))
                .as_ref()
            ),
            RetryKind::Error(ErrorKind::TransientError)
        );
    }

    #[test]
    fn test_timeout_error() {
        let policy = DefaultResponseRetryClassifier::new();
        let err: Result<(), SdkError<UnmodeledError>> = Err(SdkError::timeout_error("blah"));
        assert_eq!(
            policy.classify_retry(err.as_ref()),
            RetryKind::Error(ErrorKind::TransientError)
        );
    }
}