aws_smithy_runtime_api/http/
request.rs

1/*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! Http Request Types
7
8use crate::http::extensions::Extensions;
9use crate::http::Headers;
10use crate::http::HttpError;
11use aws_smithy_types::body::SdkBody;
12use std::borrow::Cow;
13
14/// Parts struct useful for structural decomposition that the [`Request`] type can be converted into.
15#[non_exhaustive]
16pub struct RequestParts<B = SdkBody> {
17    /// Request URI.
18    pub uri: Uri,
19    /// Request headers.
20    pub headers: Headers,
21    /// Request body.
22    pub body: B,
23}
24
25#[derive(Debug)]
26/// An HTTP Request Type
27pub struct Request<B = SdkBody> {
28    body: B,
29    uri: Uri,
30    method: http_02x::Method,
31    extensions: Extensions,
32    headers: Headers,
33}
34
35/// A Request URI
36#[derive(Debug, Clone)]
37pub struct Uri {
38    as_string: String,
39    parsed: ParsedUri,
40}
41
42#[derive(Debug, Clone)]
43enum ParsedUri {
44    H0(http_02x::Uri),
45    H1(http_1x::Uri),
46}
47
48impl ParsedUri {
49    fn path_and_query(&self) -> &str {
50        match &self {
51            ParsedUri::H0(u) => u.path_and_query().map(|pq| pq.as_str()).unwrap_or(""),
52            ParsedUri::H1(u) => u.path_and_query().map(|pq| pq.as_str()).unwrap_or(""),
53        }
54    }
55
56    fn path(&self) -> &str {
57        match &self {
58            ParsedUri::H0(u) => u.path(),
59            ParsedUri::H1(u) => u.path(),
60        }
61    }
62
63    fn query(&self) -> Option<&str> {
64        match &self {
65            ParsedUri::H0(u) => u.query(),
66            ParsedUri::H1(u) => u.query(),
67        }
68    }
69}
70
71impl Uri {
72    /// Sets `endpoint` as the endpoint for a URL.
73    ///
74    /// An `endpoint` MUST contain a scheme and authority.
75    /// An `endpoint` MAY contain a port and path.
76    ///
77    /// An `endpoint` MUST NOT contain a query
78    pub fn set_endpoint(&mut self, endpoint: &str) -> Result<(), HttpError> {
79        let endpoint: http_02x::Uri = endpoint.parse().map_err(HttpError::invalid_uri)?;
80        let endpoint = endpoint.into_parts();
81        let authority = endpoint
82            .authority
83            .ok_or_else(HttpError::missing_authority)?;
84        let scheme = endpoint.scheme.ok_or_else(HttpError::missing_scheme)?;
85        let new_uri = http_02x::Uri::builder()
86            .authority(authority)
87            .scheme(scheme)
88            .path_and_query(merge_paths(endpoint.path_and_query, &self.parsed).as_ref())
89            .build()
90            .map_err(HttpError::invalid_uri_parts)?;
91        self.as_string = new_uri.to_string();
92        self.parsed = ParsedUri::H0(new_uri);
93        Ok(())
94    }
95
96    /// Returns the URI path.
97    pub fn path(&self) -> &str {
98        self.parsed.path()
99    }
100
101    /// Returns the URI query string.
102    pub fn query(&self) -> Option<&str> {
103        self.parsed.query()
104    }
105
106    fn from_http0x_uri(uri: http_02x::Uri) -> Self {
107        Self {
108            as_string: uri.to_string(),
109            parsed: ParsedUri::H0(uri),
110        }
111    }
112
113    #[allow(dead_code)]
114    fn from_http1x_uri(uri: http_1x::Uri) -> Self {
115        Self {
116            as_string: uri.to_string(),
117            parsed: ParsedUri::H1(uri),
118        }
119    }
120
121    #[allow(dead_code)]
122    fn into_h0(self) -> http_02x::Uri {
123        match self.parsed {
124            ParsedUri::H0(uri) => uri,
125            ParsedUri::H1(_uri) => self.as_string.parse().unwrap(),
126        }
127    }
128}
129
130fn merge_paths(
131    endpoint_path: Option<http_02x::uri::PathAndQuery>,
132    uri: &ParsedUri,
133) -> Cow<'_, str> {
134    let uri_path_and_query = uri.path_and_query();
135    let endpoint_path = match endpoint_path {
136        None => return Cow::Borrowed(uri_path_and_query),
137        Some(path) => path,
138    };
139    if let Some(query) = endpoint_path.query() {
140        tracing::warn!(query = %query, "query specified in endpoint will be ignored during endpoint resolution");
141    }
142    let endpoint_path = endpoint_path.path();
143    if endpoint_path.is_empty() {
144        Cow::Borrowed(uri_path_and_query)
145    } else {
146        let ep_no_slash = endpoint_path.strip_suffix('/').unwrap_or(endpoint_path);
147        let uri_path_no_slash = uri_path_and_query
148            .strip_prefix('/')
149            .unwrap_or(uri_path_and_query);
150        Cow::Owned(format!("{}/{}", ep_no_slash, uri_path_no_slash))
151    }
152}
153
154impl TryFrom<String> for Uri {
155    type Error = HttpError;
156
157    fn try_from(value: String) -> Result<Self, Self::Error> {
158        let parsed = ParsedUri::H0(value.parse().map_err(HttpError::invalid_uri)?);
159        Ok(Uri {
160            as_string: value,
161            parsed,
162        })
163    }
164}
165
166impl<'a> TryFrom<&'a str> for Uri {
167    type Error = HttpError;
168    fn try_from(value: &'a str) -> Result<Self, Self::Error> {
169        Self::try_from(value.to_string())
170    }
171}
172
173#[cfg(feature = "http-02x")]
174impl From<http_02x::Uri> for Uri {
175    fn from(value: http_02x::Uri) -> Self {
176        Uri::from_http0x_uri(value)
177    }
178}
179
180#[cfg(feature = "http-02x")]
181impl<B> TryInto<http_02x::Request<B>> for Request<B> {
182    type Error = HttpError;
183
184    fn try_into(self) -> Result<http_02x::Request<B>, Self::Error> {
185        self.try_into_http02x()
186    }
187}
188
189#[cfg(feature = "http-1x")]
190impl From<http_1x::Uri> for Uri {
191    fn from(value: http_1x::Uri) -> Self {
192        Uri::from_http1x_uri(value)
193    }
194}
195
196#[cfg(feature = "http-1x")]
197impl<B> TryInto<http_1x::Request<B>> for Request<B> {
198    type Error = HttpError;
199
200    fn try_into(self) -> Result<http_1x::Request<B>, Self::Error> {
201        self.try_into_http1x()
202    }
203}
204
205impl<B> Request<B> {
206    /// Converts this request into an http 0.x request.
207    ///
208    /// Depending on the internal storage type, this operation may be free or it may have an internal
209    /// cost.
210    #[cfg(feature = "http-02x")]
211    pub fn try_into_http02x(self) -> Result<http_02x::Request<B>, HttpError> {
212        let mut req = http_02x::Request::builder()
213            .uri(self.uri.into_h0())
214            .method(self.method)
215            .body(self.body)
216            .expect("known valid");
217        *req.headers_mut() = self.headers.http0_headermap();
218        *req.extensions_mut() = self.extensions.try_into()?;
219        Ok(req)
220    }
221
222    /// Converts this request into an http 1.x request.
223    ///
224    /// Depending on the internal storage type, this operation may be free or it may have an internal
225    /// cost.
226    #[cfg(feature = "http-1x")]
227    pub fn try_into_http1x(self) -> Result<http_1x::Request<B>, HttpError> {
228        let mut req = http_1x::Request::builder()
229            .uri(self.uri.as_string)
230            .method(self.method.as_str())
231            .body(self.body)
232            .expect("known valid");
233        *req.headers_mut() = self.headers.http1_headermap();
234        *req.extensions_mut() = self.extensions.try_into()?;
235        Ok(req)
236    }
237
238    /// Update the body of this request to be a new body.
239    pub fn map<U>(self, f: impl Fn(B) -> U) -> Request<U> {
240        Request {
241            body: f(self.body),
242            uri: self.uri,
243            method: self.method,
244            extensions: self.extensions,
245            headers: self.headers,
246        }
247    }
248
249    /// Returns a GET request with no URI
250    pub fn new(body: B) -> Self {
251        Self {
252            body,
253            uri: Uri::from_http0x_uri(http_02x::Uri::from_static("/")),
254            method: http_02x::Method::GET,
255            extensions: Default::default(),
256            headers: Default::default(),
257        }
258    }
259
260    /// Convert this request into its parts.
261    pub fn into_parts(self) -> RequestParts<B> {
262        RequestParts {
263            uri: self.uri,
264            headers: self.headers,
265            body: self.body,
266        }
267    }
268
269    /// Returns a reference to the header map
270    pub fn headers(&self) -> &Headers {
271        &self.headers
272    }
273
274    /// Returns a mutable reference to the header map
275    pub fn headers_mut(&mut self) -> &mut Headers {
276        &mut self.headers
277    }
278
279    /// Returns the body associated with the request
280    pub fn body(&self) -> &B {
281        &self.body
282    }
283
284    /// Returns a mutable reference to the body
285    pub fn body_mut(&mut self) -> &mut B {
286        &mut self.body
287    }
288
289    /// Converts this request into the request body.
290    pub fn into_body(self) -> B {
291        self.body
292    }
293
294    /// Returns the method associated with this request
295    pub fn method(&self) -> &str {
296        self.method.as_str()
297    }
298
299    /// Returns the URI associated with this request
300    pub fn uri(&self) -> &str {
301        &self.uri.as_string
302    }
303
304    /// Returns a mutable reference the the URI of this http::Request
305    pub fn uri_mut(&mut self) -> &mut Uri {
306        &mut self.uri
307    }
308
309    /// Sets the URI of this request
310    pub fn set_uri<U>(&mut self, uri: U) -> Result<(), U::Error>
311    where
312        U: TryInto<Uri>,
313    {
314        let uri = uri.try_into()?;
315        self.uri = uri;
316        Ok(())
317    }
318
319    /// Adds an extension to the request extensions
320    pub fn add_extension<T: Send + Sync + Clone + 'static>(&mut self, extension: T) {
321        self.extensions.insert(extension.clone());
322    }
323}
324
325impl Request<SdkBody> {
326    /// Attempts to clone this request
327    ///
328    /// On clone, any extensions will be cleared.
329    ///
330    /// If the body is cloneable, this will clone the request. Otherwise `None` will be returned
331    pub fn try_clone(&self) -> Option<Self> {
332        let body = self.body().try_clone()?;
333        Some(Self {
334            body,
335            uri: self.uri.clone(),
336            method: self.method.clone(),
337            extensions: Extensions::new(),
338            headers: self.headers.clone(),
339        })
340    }
341
342    /// Replaces this request's body with [`SdkBody::taken()`]
343    pub fn take_body(&mut self) -> SdkBody {
344        std::mem::replace(self.body_mut(), SdkBody::taken())
345    }
346
347    /// Create a GET request to `/` with an empty body
348    pub fn empty() -> Self {
349        Self::new(SdkBody::empty())
350    }
351
352    /// Creates a GET request to `uri` with an empty body
353    pub fn get(uri: impl AsRef<str>) -> Result<Self, HttpError> {
354        let mut req = Self::new(SdkBody::empty());
355        req.set_uri(uri.as_ref())?;
356        Ok(req)
357    }
358}
359
360#[cfg(feature = "http-02x")]
361impl<B> TryFrom<http_02x::Request<B>> for Request<B> {
362    type Error = HttpError;
363
364    fn try_from(value: http_02x::Request<B>) -> Result<Self, Self::Error> {
365        let (parts, body) = value.into_parts();
366        let headers = Headers::try_from(parts.headers)?;
367        Ok(Self {
368            body,
369            uri: parts.uri.into(),
370            method: parts.method,
371            extensions: parts.extensions.into(),
372            headers,
373        })
374    }
375}
376
377#[cfg(feature = "http-1x")]
378impl<B> TryFrom<http_1x::Request<B>> for Request<B> {
379    type Error = HttpError;
380
381    fn try_from(value: http_1x::Request<B>) -> Result<Self, Self::Error> {
382        let (parts, body) = value.into_parts();
383        let headers = Headers::try_from(parts.headers)?;
384        Ok(Self {
385            body,
386            uri: Uri::from_http1x_uri(parts.uri),
387            method: http_02x::Method::from_bytes(parts.method.as_str().as_bytes()).expect("valid"),
388            extensions: parts.extensions.into(),
389            headers,
390        })
391    }
392}
393
394#[cfg(all(test, feature = "http-02x", feature = "http-1x"))]
395mod test {
396    use aws_smithy_types::body::SdkBody;
397    use http_02x::header::{AUTHORIZATION, CONTENT_LENGTH};
398
399    #[test]
400    fn non_ascii_requests() {
401        let request = http_02x::Request::builder()
402            .header("k", "😹")
403            .body(SdkBody::empty())
404            .unwrap();
405        let request: super::Request = request
406            .try_into()
407            .expect("failed to convert a non-string header");
408        assert_eq!(request.headers().get("k"), Some("😹"))
409    }
410
411    #[test]
412    fn request_can_be_created() {
413        let req = http_02x::Request::builder()
414            .uri("http://foo.com")
415            .body(SdkBody::from("hello"))
416            .unwrap();
417        let mut req = super::Request::try_from(req).unwrap();
418        req.headers_mut().insert("a", "b");
419        assert_eq!(req.headers().get("a").unwrap(), "b");
420        req.headers_mut().append("a", "c");
421        assert_eq!(req.headers().get("a").unwrap(), "b");
422        let http0 = req.try_into_http02x().unwrap();
423        assert_eq!(http0.uri(), "http://foo.com");
424    }
425
426    #[test]
427    fn uri_mutations() {
428        let req = http_02x::Request::builder()
429            .uri("http://foo.com")
430            .body(SdkBody::from("hello"))
431            .unwrap();
432        let mut req = super::Request::try_from(req).unwrap();
433        assert_eq!(req.uri(), "http://foo.com/");
434        req.set_uri("http://bar.com").unwrap();
435        assert_eq!(req.uri(), "http://bar.com");
436        let http0 = req.try_into_http02x().unwrap();
437        assert_eq!(http0.uri(), "http://bar.com");
438    }
439
440    #[test]
441    #[should_panic]
442    fn header_panics() {
443        let req = http_02x::Request::builder()
444            .uri("http://foo.com")
445            .body(SdkBody::from("hello"))
446            .unwrap();
447        let mut req = super::Request::try_from(req).unwrap();
448        let _ = req
449            .headers_mut()
450            .try_insert("a\nb", "a\nb")
451            .expect_err("invalid header");
452        let _ = req.headers_mut().insert("a\nb", "a\nb");
453    }
454
455    #[test]
456    fn try_clone_clones_all_data() {
457        let request = http_02x::Request::builder()
458            .uri(http_02x::Uri::from_static("https://www.amazon.com"))
459            .method("POST")
460            .header(CONTENT_LENGTH, 456)
461            .header(AUTHORIZATION, "Token: hello")
462            .body(SdkBody::from("hello world!"))
463            .expect("valid request");
464
465        let request: super::Request = request.try_into().unwrap();
466        let cloned = request.try_clone().expect("request is cloneable");
467
468        assert_eq!("https://www.amazon.com/", cloned.uri());
469        assert_eq!("POST", cloned.method());
470        assert_eq!(2, cloned.headers().len());
471        assert_eq!("Token: hello", cloned.headers().get(AUTHORIZATION).unwrap(),);
472        assert_eq!("456", cloned.headers().get(CONTENT_LENGTH).unwrap());
473        assert_eq!("hello world!".as_bytes(), cloned.body().bytes().unwrap());
474    }
475
476    #[test]
477    fn valid_round_trips() {
478        let request = || {
479            http_02x::Request::builder()
480                .uri(http_02x::Uri::from_static("https://www.amazon.com"))
481                .method("POST")
482                .header(CONTENT_LENGTH, 456)
483                .header(AUTHORIZATION, "Token: hello")
484                .header("multi", "v1")
485                .header("multi", "v2")
486                .body(SdkBody::from("hello world!"))
487                .expect("valid request")
488        };
489
490        check_roundtrip(request);
491    }
492
493    macro_rules! req_eq {
494        ($a: expr, $b: expr) => {{
495            assert_eq!($a.uri(), $b.uri(), "status code mismatch");
496            assert_eq!($a.headers(), $b.headers(), "header mismatch");
497            assert_eq!($a.method(), $b.method(), "header mismatch");
498            assert_eq!($a.body().bytes(), $b.body().bytes(), "data mismatch");
499            assert_eq!(
500                $a.extensions().len(),
501                $b.extensions().len(),
502                "extensions size mismatch"
503            );
504        }};
505    }
506
507    #[track_caller]
508    fn check_roundtrip(req: impl Fn() -> http_02x::Request<SdkBody>) {
509        let mut container = super::Request::try_from(req()).unwrap();
510        container.add_extension(5_u32);
511        let mut h1 = container
512            .try_into_http1x()
513            .expect("failed converting to http1x");
514        assert_eq!(h1.extensions().get::<u32>(), Some(&5));
515        h1.extensions_mut().remove::<u32>();
516
517        let mut container = super::Request::try_from(h1).expect("failed converting from http1x");
518        container.add_extension(5_u32);
519        let mut h0 = container
520            .try_into_http02x()
521            .expect("failed converting back to http0x");
522        assert_eq!(h0.extensions().get::<u32>(), Some(&5));
523        h0.extensions_mut().remove::<u32>();
524        req_eq!(h0, req());
525    }
526}