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
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

use crate::error::Error;
use crate::frame::{Header, HeaderValue, Message};
use crate::str_bytes::StrBytes;
use aws_smithy_types::{Blob, DateTime};

macro_rules! expect_shape_fn {
    (fn $fn_name:ident[$val_typ:ident] -> $result_typ:ident { $val_name:ident -> $val_expr:expr }) => {
        #[doc = "Expects that `header` is a `"]
        #[doc = stringify!($result_typ)]
        #[doc = "`."]
        pub fn $fn_name(header: &Header) -> Result<$result_typ, Error> {
            match header.value() {
                HeaderValue::$val_typ($val_name) => Ok($val_expr),
                _ => Err(Error::Unmarshalling(format!(
                    "expected '{}' header value to be {}",
                    header.name().as_str(),
                    stringify!($val_typ)
                ))),
            }
        }
    };
}

expect_shape_fn!(fn expect_bool[Bool] -> bool { value -> *value });
expect_shape_fn!(fn expect_byte[Byte] -> i8 { value -> *value });
expect_shape_fn!(fn expect_int16[Int16] -> i16 { value -> *value });
expect_shape_fn!(fn expect_int32[Int32] -> i32 { value -> *value });
expect_shape_fn!(fn expect_int64[Int64] -> i64 { value -> *value });
expect_shape_fn!(fn expect_byte_array[ByteArray] -> Blob { bytes -> Blob::new(bytes.as_ref()) });
expect_shape_fn!(fn expect_string[String] -> String { value -> value.as_str().into() });
expect_shape_fn!(fn expect_timestamp[Timestamp] -> DateTime { value -> *value });

/// Structured header data from a [`Message`]
#[derive(Debug)]
pub struct ResponseHeaders<'a> {
    /// Content Type of the message
    ///
    /// This can be a number of things depending on the protocol. For example, if the protocol is
    /// AwsJson1, then this could be `application/json`, or `application/xml` for RestXml.
    ///
    /// It will be `application/octet-stream` if there is a Blob payload shape, and `text/plain` if
    /// there is a String payload shape.
    pub content_type: Option<&'a StrBytes>,

    /// Message Type field
    ///
    /// This field is used to distinguish between events where the value is `event` and errors where
    /// the value is `exception`
    pub message_type: &'a StrBytes,

    /// Smithy Type field
    ///
    /// This field is used to determine which of the possible union variants that this message represents
    pub smithy_type: &'a StrBytes,
}

impl<'a> ResponseHeaders<'a> {
    /// Content-Type for this message
    pub fn content_type(&self) -> Option<&str> {
        self.content_type.map(|ct| ct.as_str())
    }
}

fn expect_header_str_value<'a>(
    header: Option<&'a Header>,
    name: &str,
) -> Result<&'a StrBytes, Error> {
    match header {
        Some(header) => Ok(header.value().as_string().map_err(|value| {
            Error::Unmarshalling(format!(
                "expected response {} header to be string, received {:?}",
                name, value
            ))
        })?),
        None => Err(Error::Unmarshalling(format!(
            "expected response to include {} header, but it was missing",
            name
        ))),
    }
}

/// Parse headers from [`Message`]
///
/// `:content-type`, `:message-type`, `:event-type`, and `:exception-type` headers will be parsed.
/// If any headers are invalid or missing, an error will be returned.
pub fn parse_response_headers(message: &Message) -> Result<ResponseHeaders<'_>, Error> {
    let (mut content_type, mut message_type, mut event_type, mut exception_type) =
        (None, None, None, None);
    for header in message.headers() {
        match header.name().as_str() {
            ":content-type" => content_type = Some(header),
            ":message-type" => message_type = Some(header),
            ":event-type" => event_type = Some(header),
            ":exception-type" => exception_type = Some(header),
            _ => {}
        }
    }
    let message_type = expect_header_str_value(message_type, ":message-type")?;
    Ok(ResponseHeaders {
        content_type: content_type
            .map(|ct| expect_header_str_value(Some(ct), ":content-type"))
            .transpose()?,
        message_type,
        smithy_type: if message_type.as_str() == "event" {
            expect_header_str_value(event_type, ":event-type")?
        } else if message_type.as_str() == "exception" {
            expect_header_str_value(exception_type, ":exception-type")?
        } else {
            return Err(Error::Unmarshalling(format!(
                "unrecognized `:message-type`: {}",
                message_type.as_str()
            )));
        },
    })
}

#[cfg(test)]
mod tests {
    use super::parse_response_headers;
    use crate::frame::{Header, HeaderValue, Message};

    #[test]
    fn normal_message() {
        let message = Message::new(&b"test"[..])
            .add_header(Header::new(
                ":event-type",
                HeaderValue::String("Foo".into()),
            ))
            .add_header(Header::new(
                ":content-type",
                HeaderValue::String("application/json".into()),
            ))
            .add_header(Header::new(
                ":message-type",
                HeaderValue::String("event".into()),
            ));
        let parsed = parse_response_headers(&message).unwrap();
        assert_eq!("Foo", parsed.smithy_type.as_str());
        assert_eq!(Some("application/json"), parsed.content_type());
        assert_eq!("event", parsed.message_type.as_str());
    }

    #[test]
    fn error_message() {
        let message = Message::new(&b"test"[..])
            .add_header(Header::new(
                ":exception-type",
                HeaderValue::String("BadRequestException".into()),
            ))
            .add_header(Header::new(
                ":content-type",
                HeaderValue::String("application/json".into()),
            ))
            .add_header(Header::new(
                ":message-type",
                HeaderValue::String("exception".into()),
            ));
        let parsed = parse_response_headers(&message).unwrap();
        assert_eq!("BadRequestException", parsed.smithy_type.as_str());
        assert_eq!(Some("application/json"), parsed.content_type());
        assert_eq!("exception", parsed.message_type.as_str());
    }

    #[test]
    fn missing_exception_type() {
        let message = Message::new(&b"test"[..])
            .add_header(Header::new(
                ":content-type",
                HeaderValue::String("application/json".into()),
            ))
            .add_header(Header::new(
                ":message-type",
                HeaderValue::String("exception".into()),
            ));
        let error = parse_response_headers(&message).err().unwrap().to_string();
        assert_eq!(
            "failed to unmarshall message: expected response to include :exception-type \
             header, but it was missing",
            error
        );
    }

    #[test]
    fn missing_event_type() {
        let message = Message::new(&b"test"[..])
            .add_header(Header::new(
                ":content-type",
                HeaderValue::String("application/json".into()),
            ))
            .add_header(Header::new(
                ":message-type",
                HeaderValue::String("event".into()),
            ));
        let error = parse_response_headers(&message).err().unwrap().to_string();
        assert_eq!(
            "failed to unmarshall message: expected response to include :event-type \
             header, but it was missing",
            error
        );
    }

    #[test]
    fn missing_content_type() {
        let message = Message::new(&b"test"[..])
            .add_header(Header::new(
                ":event-type",
                HeaderValue::String("Foo".into()),
            ))
            .add_header(Header::new(
                ":message-type",
                HeaderValue::String("event".into()),
            ));
        let parsed = parse_response_headers(&message).ok().unwrap();
        assert_eq!(None, parsed.content_type);
        assert_eq!("Foo", parsed.smithy_type.as_str());
        assert_eq!("event", parsed.message_type.as_str());
    }

    #[test]
    fn content_type_wrong_type() {
        let message = Message::new(&b"test"[..])
            .add_header(Header::new(
                ":event-type",
                HeaderValue::String("Foo".into()),
            ))
            .add_header(Header::new(":content-type", HeaderValue::Int32(16)))
            .add_header(Header::new(
                ":message-type",
                HeaderValue::String("event".into()),
            ));
        let error = parse_response_headers(&message).err().unwrap().to_string();
        assert_eq!(
            "failed to unmarshall message: expected response :content-type \
             header to be string, received Int32(16)",
            error
        );
    }
}