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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

//! Http Response Types

use crate::http::extensions::Extensions;
use crate::http::{Headers, HttpError};
use aws_smithy_types::body::SdkBody;
#[allow(unused)]
use http as http0;
use std::fmt;

/// HTTP response status code
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct StatusCode(u16);

impl StatusCode {
    /// True if this is a successful response code (200, 201, etc)
    pub fn is_success(self) -> bool {
        (200..300).contains(&self.0)
    }

    /// True if this response code is a client error (4xx)
    pub fn is_client_error(self) -> bool {
        (400..500).contains(&self.0)
    }

    /// True if this response code is a server error (5xx)
    pub fn is_server_error(self) -> bool {
        (500..600).contains(&self.0)
    }

    /// Return the value of this status code as a `u16`.
    pub fn as_u16(self) -> u16 {
        self.0
    }
}

impl TryFrom<u16> for StatusCode {
    type Error = HttpError;

    fn try_from(value: u16) -> Result<Self, Self::Error> {
        if (100..1000).contains(&value) {
            Ok(StatusCode(value))
        } else {
            Err(HttpError::invalid_status_code())
        }
    }
}

#[cfg(feature = "http-02x")]
impl From<http0::StatusCode> for StatusCode {
    fn from(value: http0::StatusCode) -> Self {
        Self(value.as_u16())
    }
}

#[cfg(feature = "http-1x")]
impl From<http1::StatusCode> for StatusCode {
    fn from(value: http1::StatusCode) -> Self {
        Self(value.as_u16())
    }
}

impl From<StatusCode> for u16 {
    fn from(value: StatusCode) -> Self {
        value.0
    }
}

impl fmt::Display for StatusCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// An HTTP Response Type
#[derive(Debug)]
pub struct Response<B = SdkBody> {
    status: StatusCode,
    headers: Headers,
    body: B,
    extensions: Extensions,
}

impl<B> Response<B> {
    /// Converts this response into an http 0.x response.
    ///
    /// Depending on the internal storage type, this operation may be free or it may have an internal
    /// cost.
    #[cfg(feature = "http-02x")]
    pub fn try_into_http02x(self) -> Result<http0::Response<B>, HttpError> {
        let mut res = http::Response::builder()
            .status(
                http0::StatusCode::from_u16(self.status.into())
                    .expect("validated upon construction"),
            )
            .body(self.body)
            .expect("known valid");
        *res.headers_mut() = self.headers.http0_headermap();
        *res.extensions_mut() = self.extensions.try_into()?;
        Ok(res)
    }

    /// Converts this response into an http 1.x response.
    ///
    /// Depending on the internal storage type, this operation may be free or it may have an internal
    /// cost.
    #[cfg(feature = "http-1x")]
    pub fn try_into_http1x(self) -> Result<http1::Response<B>, HttpError> {
        let mut res = http1::Response::builder()
            .status(
                http1::StatusCode::from_u16(self.status.into())
                    .expect("validated upon construction"),
            )
            .body(self.body)
            .expect("known valid");
        *res.headers_mut() = self.headers.http1_headermap();
        *res.extensions_mut() = self.extensions.try_into()?;
        Ok(res)
    }

    /// Update the body of this response to be a new body.
    pub fn map<U>(self, f: impl Fn(B) -> U) -> Response<U> {
        Response {
            status: self.status,
            body: f(self.body),
            extensions: self.extensions,
            headers: self.headers,
        }
    }

    /// Returns a response with the given status and body
    pub fn new(status: StatusCode, body: B) -> Self {
        Self {
            status,
            body,
            extensions: Default::default(),
            headers: Default::default(),
        }
    }

    /// Returns the status code
    pub fn status(&self) -> StatusCode {
        self.status
    }

    /// Returns a mutable reference to the status code
    pub fn status_mut(&mut self) -> &mut StatusCode {
        &mut self.status
    }

    /// Returns a reference to the header map
    pub fn headers(&self) -> &Headers {
        &self.headers
    }

    /// Returns a mutable reference to the header map
    pub fn headers_mut(&mut self) -> &mut Headers {
        &mut self.headers
    }

    /// Returns the body associated with the request
    pub fn body(&self) -> &B {
        &self.body
    }

    /// Returns a mutable reference to the body
    pub fn body_mut(&mut self) -> &mut B {
        &mut self.body
    }

    /// Converts this response into the response body.
    pub fn into_body(self) -> B {
        self.body
    }

    /// Adds an extension to the response extensions
    pub fn add_extension<T: Send + Sync + Clone + 'static>(&mut self, extension: T) {
        self.extensions.insert(extension);
    }
}

impl Response<SdkBody> {
    /// Replaces this response's body with [`SdkBody::taken()`]
    pub fn take_body(&mut self) -> SdkBody {
        std::mem::replace(self.body_mut(), SdkBody::taken())
    }
}

#[cfg(feature = "http-02x")]
impl<B> TryFrom<http0::Response<B>> for Response<B> {
    type Error = HttpError;

    fn try_from(value: http0::Response<B>) -> Result<Self, Self::Error> {
        let (parts, body) = value.into_parts();
        let headers = Headers::try_from(parts.headers)?;
        Ok(Self {
            status: StatusCode::try_from(parts.status.as_u16()).expect("validated by http 0.x"),
            body,
            extensions: parts.extensions.into(),
            headers,
        })
    }
}

#[cfg(feature = "http-1x")]
impl<B> TryFrom<http1::Response<B>> for Response<B> {
    type Error = HttpError;

    fn try_from(value: http1::Response<B>) -> Result<Self, Self::Error> {
        let (parts, body) = value.into_parts();
        let headers = Headers::try_from(parts.headers)?;
        Ok(Self {
            status: StatusCode::try_from(parts.status.as_u16()).expect("validated by http 1.x"),
            body,
            extensions: parts.extensions.into(),
            headers,
        })
    }
}

#[cfg(all(test, feature = "http-02x", feature = "http-1x"))]
mod test {
    use super::*;
    use aws_smithy_types::body::SdkBody;

    #[test]
    fn non_ascii_responses() {
        let response = http::Response::builder()
            .status(200)
            .header("k", "😹")
            .body(SdkBody::empty())
            .unwrap();
        let response: Response = response
            .try_into()
            .expect("failed to convert a non-string header");
        assert_eq!(response.headers().get("k"), Some("😹"))
    }

    #[test]
    fn response_can_be_created() {
        let req = http::Response::builder()
            .status(200)
            .body(SdkBody::from("hello"))
            .unwrap();
        let mut rsp = super::Response::try_from(req).unwrap();
        rsp.headers_mut().insert("a", "b");
        assert_eq!("b", rsp.headers().get("a").unwrap());
        rsp.headers_mut().append("a", "c");
        assert_eq!("b", rsp.headers().get("a").unwrap());
        let http0 = rsp.try_into_http02x().unwrap();
        assert_eq!(200, http0.status().as_u16());
    }

    macro_rules! resp_eq {
        ($a: expr, $b: expr) => {{
            assert_eq!($a.status(), $b.status(), "status code mismatch");
            assert_eq!($a.headers(), $b.headers(), "header mismatch");
            assert_eq!($a.body().bytes(), $b.body().bytes(), "data mismatch");
            assert_eq!(
                $a.extensions().len(),
                $b.extensions().len(),
                "extensions size mismatch"
            );
        }};
    }

    #[track_caller]
    fn check_roundtrip(req: impl Fn() -> http0::Response<SdkBody>) {
        let mut container = super::Response::try_from(req()).unwrap();
        container.add_extension(5_u32);
        let mut h1 = container
            .try_into_http1x()
            .expect("failed converting to http1x");
        assert_eq!(h1.extensions().get::<u32>(), Some(&5));
        h1.extensions_mut().remove::<u32>();

        let mut container = super::Response::try_from(h1).expect("failed converting from http1x");
        container.add_extension(5_u32);
        let mut h0 = container
            .try_into_http02x()
            .expect("failed converting back to http0x");
        assert_eq!(h0.extensions().get::<u32>(), Some(&5));
        h0.extensions_mut().remove::<u32>();
        resp_eq!(h0, req());
    }

    #[test]
    fn valid_round_trips() {
        let response = || {
            http::Response::builder()
                .status(200)
                .header("k", "v")
                .header("multi", "v1")
                .header("multi", "v2")
                .body(SdkBody::from("12345"))
                .unwrap()
        };
        check_roundtrip(response);
    }

    #[test]
    #[should_panic]
    fn header_panics() {
        let res = http::Response::builder()
            .status(200)
            .body(SdkBody::from("hello"))
            .unwrap();
        let mut res = Response::try_from(res).unwrap();
        let _ = res
            .headers_mut()
            .try_insert("a\nb", "a\nb")
            .expect_err("invalid header");
        let _ = res.headers_mut().insert("a\nb", "a\nb");
    }

    #[test]
    fn cant_cross_convert_with_extensions_h0_h1() {
        let resp_h0 = || {
            http::Response::builder()
                .status(200)
                .extension(5_u32)
                .body(SdkBody::from("hello"))
                .unwrap()
        };

        let _ = Response::try_from(resp_h0())
            .unwrap()
            .try_into_http1x()
            .expect_err("cant copy extension");

        let _ = Response::try_from(resp_h0())
            .unwrap()
            .try_into_http02x()
            .expect("allowed to cross-copy");
    }

    #[test]
    fn cant_cross_convert_with_extensions_h1_h0() {
        let resp_h1 = || {
            http1::Response::builder()
                .status(200)
                .extension(5_u32)
                .body(SdkBody::from("hello"))
                .unwrap()
        };

        let _ = Response::try_from(resp_h1())
            .unwrap()
            .try_into_http02x()
            .expect_err("cant copy extension");

        let _ = Response::try_from(resp_h1())
            .unwrap()
            .try_into_http1x()
            .expect("allowed to cross-copy");
    }
}