Skip to main content

rocket/local/asynchronous/
request.rs

1use std::fmt;
2
3use rocket_http::HttpVersion;
4
5use crate::{Request, Data};
6use crate::request::RequestError;
7use crate::http::Method;
8use crate::http::uri::Origin;
9
10use super::{Client, LocalResponse};
11
12/// An `async` local request as returned by [`Client`](super::Client).
13///
14/// For details, see [the top-level documentation](../index.html#localrequest).
15///
16/// ## Example
17///
18/// The following snippet uses the available builder methods to construct and
19/// dispatch a `POST` request to `/` with a JSON body:
20///
21/// ```rust,no_run
22/// use rocket::local::asynchronous::{Client, LocalRequest};
23/// use rocket::http::{ContentType, Cookie};
24///
25/// # rocket::async_test(async {
26/// let client = Client::tracked(rocket::build()).await.expect("valid rocket");
27/// let req = client.post("/")
28///     .header(ContentType::JSON)
29///     .remote("127.0.0.1:8000")
30///     .cookie(("name", "value"))
31///     .body(r#"{ "value": 42 }"#);
32///
33/// let response = req.dispatch().await;
34/// # });
35/// ```
36pub struct LocalRequest<'c> {
37    pub(in super) client: &'c Client,
38    pub(in super) request: Request<'c>,
39    data: Vec<u8>,
40    // The `Origin` on the right is INVALID! It should _not_ be used!
41    uri: Result<Origin<'c>, Origin<'static>>,
42}
43
44impl<'c> LocalRequest<'c> {
45    pub(crate) fn new<'u: 'c, U>(client: &'c Client, method: Method, uri: U) -> Self
46        where U: TryInto<Origin<'u>> + fmt::Display
47    {
48        // Try to parse `uri` into an `Origin`, storing whether it's good.
49        let uri_str = uri.to_string();
50        let try_origin = uri.try_into().map_err(|_| Origin::path_only(uri_str));
51
52        // Create a request. We'll handle bad URIs later, in `_dispatch`.
53        let origin = try_origin.clone().unwrap_or_else(|bad| bad);
54        let mut request = Request::new(client.rocket(), method, origin, None);
55
56        // Add any cookies we know about.
57        if client.tracked {
58            client._with_raw_cookies(|jar| {
59                for cookie in jar.iter() {
60                    request.cookies_mut().add_original(cookie.clone());
61                }
62            })
63        }
64
65        LocalRequest { client, request, uri: try_origin, data: vec![] }
66    }
67
68    #[inline]
69    pub fn override_version(&mut self, version: HttpVersion) {
70        self.version = Some(version);
71    }
72
73    pub(crate) fn _request(&self) -> &Request<'c> {
74        &self.request
75    }
76
77    pub(crate) fn _request_mut(&mut self) -> &mut Request<'c> {
78        &mut self.request
79    }
80
81    pub(crate) fn _body_mut(&mut self) -> &mut Vec<u8> {
82        &mut self.data
83    }
84
85    // Performs the actual dispatch.
86    async fn _dispatch(mut self) -> LocalResponse<'c> {
87        // First, revalidate the URI, recording an error if it's invalid. As on
88        // the server, `dispatch` then answers with a `400`. If it's valid,
89        // then `request` already contains a correct URI.
90        let rocket = self.client.rocket();
91        if let Err(ref invalid) = self.uri {
92            // The user may have changed the URI in the request in which case we
93            // _shouldn't_ error. Check that now and error only if not.
94            if self.inner().uri() == invalid {
95                error!("invalid request URI: {:?}", invalid.path());
96                let error = RequestError::InvalidUri(invalid.to_string());
97                self.request.errors.push(error);
98            }
99        }
100
101        // Actually dispatch the request.
102        let mut data = Data::local(self.data);
103        let token = rocket.preprocess(&mut self.request, &mut data).await;
104        let response = LocalResponse::new(self.request, move |req| {
105            rocket.dispatch(token, req, data)
106        }).await;
107
108        // If the client is tracking cookies, updates the internal cookie jar
109        // with the changes reflected by `response`.
110        if self.client.tracked {
111            self.client._with_raw_cookies_mut(|jar| {
112                let current_time = time::OffsetDateTime::now_utc();
113                for cookie in response.cookies().iter() {
114                    if let Some(expires) = cookie.expires_datetime() {
115                        if expires <= current_time {
116                            jar.force_remove(cookie.name());
117                            continue;
118                        }
119                    }
120
121                    jar.add_original(cookie.clone());
122                }
123            })
124        }
125
126        response
127    }
128
129    pub_request_impl!("# use rocket::local::asynchronous::Client;\n\
130        use rocket::local::asynchronous::LocalRequest;" async await);
131}
132
133impl<'c> Clone for LocalRequest<'c> {
134    fn clone(&self) -> Self {
135        LocalRequest {
136            client: self.client,
137            request: self.request.clone(),
138            data: self.data.clone(),
139            uri: self.uri.clone(),
140        }
141    }
142}
143
144impl std::fmt::Debug for LocalRequest<'_> {
145    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
146        self._request().fmt(f)
147    }
148}
149
150impl<'c> std::ops::Deref for LocalRequest<'c> {
151    type Target = Request<'c>;
152
153    fn deref(&self) -> &Self::Target {
154        self.inner()
155    }
156}
157
158impl<'c> std::ops::DerefMut for LocalRequest<'c> {
159    fn deref_mut(&mut self) -> &mut Self::Target {
160        self.inner_mut()
161    }
162}