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<B> TryInto<http_1x::Request<B>> for Request<B> {
191    type Error = HttpError;
192
193    fn try_into(self) -> Result<http_1x::Request<B>, Self::Error> {
194        self.try_into_http1x()
195    }
196}
197
198impl<B> Request<B> {
199    /// Converts this request into an http 0.x request.
200    ///
201    /// Depending on the internal storage type, this operation may be free or it may have an internal
202    /// cost.
203    #[cfg(feature = "http-02x")]
204    pub fn try_into_http02x(self) -> Result<http_02x::Request<B>, HttpError> {
205        let mut req = http_02x::Request::builder()
206            .uri(self.uri.into_h0())
207            .method(self.method)
208            .body(self.body)
209            .expect("known valid");
210        *req.headers_mut() = self.headers.http0_headermap();
211        *req.extensions_mut() = self.extensions.try_into()?;
212        Ok(req)
213    }
214
215    /// Converts this request into an http 1.x request.
216    ///
217    /// Depending on the internal storage type, this operation may be free or it may have an internal
218    /// cost.
219    #[cfg(feature = "http-1x")]
220    pub fn try_into_http1x(self) -> Result<http_1x::Request<B>, HttpError> {
221        let mut req = http_1x::Request::builder()
222            .uri(self.uri.as_string)
223            .method(self.method.as_str())
224            .body(self.body)
225            .expect("known valid");
226        *req.headers_mut() = self.headers.http1_headermap();
227        *req.extensions_mut() = self.extensions.try_into()?;
228        Ok(req)
229    }
230
231    /// Update the body of this request to be a new body.
232    pub fn map<U>(self, f: impl Fn(B) -> U) -> Request<U> {
233        Request {
234            body: f(self.body),
235            uri: self.uri,
236            method: self.method,
237            extensions: self.extensions,
238            headers: self.headers,
239        }
240    }
241
242    /// Returns a GET request with no URI
243    pub fn new(body: B) -> Self {
244        Self {
245            body,
246            uri: Uri::from_http0x_uri(http_02x::Uri::from_static("/")),
247            method: http_02x::Method::GET,
248            extensions: Default::default(),
249            headers: Default::default(),
250        }
251    }
252
253    /// Convert this request into its parts.
254    pub fn into_parts(self) -> RequestParts<B> {
255        RequestParts {
256            uri: self.uri,
257            headers: self.headers,
258            body: self.body,
259        }
260    }
261
262    /// Returns a reference to the header map
263    pub fn headers(&self) -> &Headers {
264        &self.headers
265    }
266
267    /// Returns a mutable reference to the header map
268    pub fn headers_mut(&mut self) -> &mut Headers {
269        &mut self.headers
270    }
271
272    /// Returns the body associated with the request
273    pub fn body(&self) -> &B {
274        &self.body
275    }
276
277    /// Returns a mutable reference to the body
278    pub fn body_mut(&mut self) -> &mut B {
279        &mut self.body
280    }
281
282    /// Converts this request into the request body.
283    pub fn into_body(self) -> B {
284        self.body
285    }
286
287    /// Returns the method associated with this request
288    pub fn method(&self) -> &str {
289        self.method.as_str()
290    }
291
292    /// Returns the URI associated with this request
293    pub fn uri(&self) -> &str {
294        &self.uri.as_string
295    }
296
297    /// Returns a mutable reference the the URI of this http::Request
298    pub fn uri_mut(&mut self) -> &mut Uri {
299        &mut self.uri
300    }
301
302    /// Sets the URI of this request
303    pub fn set_uri<U>(&mut self, uri: U) -> Result<(), U::Error>
304    where
305        U: TryInto<Uri>,
306    {
307        let uri = uri.try_into()?;
308        self.uri = uri;
309        Ok(())
310    }
311
312    /// Adds an extension to the request extensions
313    pub fn add_extension<T: Send + Sync + Clone + 'static>(&mut self, extension: T) {
314        self.extensions.insert(extension.clone());
315    }
316}
317
318impl Request<SdkBody> {
319    /// Attempts to clone this request
320    ///
321    /// On clone, any extensions will be cleared.
322    ///
323    /// If the body is cloneable, this will clone the request. Otherwise `None` will be returned
324    pub fn try_clone(&self) -> Option<Self> {
325        let body = self.body().try_clone()?;
326        Some(Self {
327            body,
328            uri: self.uri.clone(),
329            method: self.method.clone(),
330            extensions: Extensions::new(),
331            headers: self.headers.clone(),
332        })
333    }
334
335    /// Replaces this request's body with [`SdkBody::taken()`]
336    pub fn take_body(&mut self) -> SdkBody {
337        std::mem::replace(self.body_mut(), SdkBody::taken())
338    }
339
340    /// Create a GET request to `/` with an empty body
341    pub fn empty() -> Self {
342        Self::new(SdkBody::empty())
343    }
344
345    /// Creates a GET request to `uri` with an empty body
346    pub fn get(uri: impl AsRef<str>) -> Result<Self, HttpError> {
347        let mut req = Self::new(SdkBody::empty());
348        req.set_uri(uri.as_ref())?;
349        Ok(req)
350    }
351}
352
353#[cfg(feature = "http-02x")]
354impl<B> TryFrom<http_02x::Request<B>> for Request<B> {
355    type Error = HttpError;
356
357    fn try_from(value: http_02x::Request<B>) -> Result<Self, Self::Error> {
358        let (parts, body) = value.into_parts();
359        let headers = Headers::try_from(parts.headers)?;
360        Ok(Self {
361            body,
362            uri: parts.uri.into(),
363            method: parts.method,
364            extensions: parts.extensions.into(),
365            headers,
366        })
367    }
368}
369
370#[cfg(feature = "http-1x")]
371impl<B> TryFrom<http_1x::Request<B>> for Request<B> {
372    type Error = HttpError;
373
374    fn try_from(value: http_1x::Request<B>) -> Result<Self, Self::Error> {
375        let (parts, body) = value.into_parts();
376        let headers = Headers::try_from(parts.headers)?;
377        Ok(Self {
378            body,
379            uri: Uri::from_http1x_uri(parts.uri),
380            method: http_02x::Method::from_bytes(parts.method.as_str().as_bytes()).expect("valid"),
381            extensions: parts.extensions.into(),
382            headers,
383        })
384    }
385}
386
387#[cfg(all(test, feature = "http-02x", feature = "http-1x"))]
388mod test {
389    use aws_smithy_types::body::SdkBody;
390    use http_02x::header::{AUTHORIZATION, CONTENT_LENGTH};
391
392    #[test]
393    fn non_ascii_requests() {
394        let request = http_02x::Request::builder()
395            .header("k", "😹")
396            .body(SdkBody::empty())
397            .unwrap();
398        let request: super::Request = request
399            .try_into()
400            .expect("failed to convert a non-string header");
401        assert_eq!(request.headers().get("k"), Some("😹"))
402    }
403
404    #[test]
405    fn request_can_be_created() {
406        let req = http_02x::Request::builder()
407            .uri("http://foo.com")
408            .body(SdkBody::from("hello"))
409            .unwrap();
410        let mut req = super::Request::try_from(req).unwrap();
411        req.headers_mut().insert("a", "b");
412        assert_eq!(req.headers().get("a").unwrap(), "b");
413        req.headers_mut().append("a", "c");
414        assert_eq!(req.headers().get("a").unwrap(), "b");
415        let http0 = req.try_into_http02x().unwrap();
416        assert_eq!(http0.uri(), "http://foo.com");
417    }
418
419    #[test]
420    fn uri_mutations() {
421        let req = http_02x::Request::builder()
422            .uri("http://foo.com")
423            .body(SdkBody::from("hello"))
424            .unwrap();
425        let mut req = super::Request::try_from(req).unwrap();
426        assert_eq!(req.uri(), "http://foo.com/");
427        req.set_uri("http://bar.com").unwrap();
428        assert_eq!(req.uri(), "http://bar.com");
429        let http0 = req.try_into_http02x().unwrap();
430        assert_eq!(http0.uri(), "http://bar.com");
431    }
432
433    #[test]
434    #[should_panic]
435    fn header_panics() {
436        let req = http_02x::Request::builder()
437            .uri("http://foo.com")
438            .body(SdkBody::from("hello"))
439            .unwrap();
440        let mut req = super::Request::try_from(req).unwrap();
441        let _ = req
442            .headers_mut()
443            .try_insert("a\nb", "a\nb")
444            .expect_err("invalid header");
445        let _ = req.headers_mut().insert("a\nb", "a\nb");
446    }
447
448    #[test]
449    fn try_clone_clones_all_data() {
450        let request = http_02x::Request::builder()
451            .uri(http_02x::Uri::from_static("https://www.amazon.com"))
452            .method("POST")
453            .header(CONTENT_LENGTH, 456)
454            .header(AUTHORIZATION, "Token: hello")
455            .body(SdkBody::from("hello world!"))
456            .expect("valid request");
457
458        let request: super::Request = request.try_into().unwrap();
459        let cloned = request.try_clone().expect("request is cloneable");
460
461        assert_eq!("https://www.amazon.com/", cloned.uri());
462        assert_eq!("POST", cloned.method());
463        assert_eq!(2, cloned.headers().len());
464        assert_eq!("Token: hello", cloned.headers().get(AUTHORIZATION).unwrap(),);
465        assert_eq!("456", cloned.headers().get(CONTENT_LENGTH).unwrap());
466        assert_eq!("hello world!".as_bytes(), cloned.body().bytes().unwrap());
467    }
468
469    #[test]
470    fn valid_round_trips() {
471        let request = || {
472            http_02x::Request::builder()
473                .uri(http_02x::Uri::from_static("https://www.amazon.com"))
474                .method("POST")
475                .header(CONTENT_LENGTH, 456)
476                .header(AUTHORIZATION, "Token: hello")
477                .header("multi", "v1")
478                .header("multi", "v2")
479                .body(SdkBody::from("hello world!"))
480                .expect("valid request")
481        };
482
483        check_roundtrip(request);
484    }
485
486    macro_rules! req_eq {
487        ($a: expr, $b: expr) => {{
488            assert_eq!($a.uri(), $b.uri(), "status code mismatch");
489            assert_eq!($a.headers(), $b.headers(), "header mismatch");
490            assert_eq!($a.method(), $b.method(), "header mismatch");
491            assert_eq!($a.body().bytes(), $b.body().bytes(), "data mismatch");
492            assert_eq!(
493                $a.extensions().len(),
494                $b.extensions().len(),
495                "extensions size mismatch"
496            );
497        }};
498    }
499
500    #[track_caller]
501    fn check_roundtrip(req: impl Fn() -> http_02x::Request<SdkBody>) {
502        let mut container = super::Request::try_from(req()).unwrap();
503        container.add_extension(5_u32);
504        let mut h1 = container
505            .try_into_http1x()
506            .expect("failed converting to http1x");
507        assert_eq!(h1.extensions().get::<u32>(), Some(&5));
508        h1.extensions_mut().remove::<u32>();
509
510        let mut container = super::Request::try_from(h1).expect("failed converting from http1x");
511        container.add_extension(5_u32);
512        let mut h0 = container
513            .try_into_http02x()
514            .expect("failed converting back to http0x");
515        assert_eq!(h0.extensions().get::<u32>(), Some(&5));
516        h0.extensions_mut().remove::<u32>();
517        req_eq!(h0, req());
518    }
519}