Skip to main content

ullun/
request.rs

1//! Request types and extractors
2
3use crate::cookies::Cookies;
4use crate::error::{Error, Result};
5use serde::de::DeserializeOwned;
6use std::collections::HashMap;
7use std::sync::OnceLock;
8
9/// Path parameters extracted from route
10#[derive(Debug, Clone)]
11pub struct Params {
12    inner: HashMap<String, String>,
13}
14
15impl Params {
16    pub fn new() -> Self {
17        Self {
18            inner: HashMap::new(),
19        }
20    }
21
22    pub fn insert(&mut self, key: String, value: String) {
23        self.inner.insert(key, value);
24    }
25
26    pub fn get(&self, key: &str) -> Result<&str> {
27        self.inner
28            .get(key)
29            .map(|s| s.as_str())
30            .ok_or_else(|| Error::bad_request(format!("Missing param: {}", key)))
31    }
32
33    pub fn get_opt(&self, key: &str) -> Option<&str> {
34        self.inner.get(key).map(|s| s.as_str())
35    }
36
37    /// Parse a path parameter into any `FromStr` type, e.g. `params.parse::<u64>("id")?`
38    ///
39    /// Answers `400` naming the parameter when it does not parse.
40    pub fn parse<T: std::str::FromStr>(&self, key: &str) -> Result<T> {
41        self.get(key)?
42            .parse()
43            .map_err(|_| Error::bad_request(format!("Invalid path parameter '{}'", key)))
44    }
45}
46
47impl Default for Params {
48    fn default() -> Self {
49        Self::new()
50    }
51}
52
53/// Query parameters from URL (also used for `application/x-www-form-urlencoded` bodies)
54#[derive(Debug, Clone)]
55pub struct Query {
56    inner: HashMap<String, String>,
57    raw: String,
58}
59
60impl Query {
61    pub fn new() -> Self {
62        Self {
63            inner: HashMap::new(),
64            raw: String::new(),
65        }
66    }
67
68    /// Parse `a=1&b=two`. Keys and values are percent-decoded and `+` is a
69    /// space. Pairs without `=` are kept with an empty value; if a key repeats,
70    /// the last value wins.
71    pub fn parse_query_string(query: &str) -> Self {
72        let mut q = Query {
73            inner: HashMap::new(),
74            raw: query.to_string(),
75        };
76        for pair in query.split('&').filter(|p| !p.is_empty()) {
77            let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
78            q.inner
79                .insert(decode_component(key), decode_component(value));
80        }
81        q
82    }
83
84    pub fn get(&self, key: &str) -> Option<&str> {
85        self.inner.get(key).map(|s| s.as_str())
86    }
87
88    pub fn contains(&self, key: &str) -> bool {
89        self.inner.contains_key(key)
90    }
91
92    pub fn is_empty(&self) -> bool {
93        self.inner.is_empty()
94    }
95
96    /// Deserialize into a struct; numbers, booleans and `Option` are converted
97    /// from their string form.
98    pub fn parse<T: DeserializeOwned>(&self) -> Result<T> {
99        serde_urlencoded::from_str(&self.raw)
100            .map_err(|e| Error::bad_request(format!("Invalid query params: {}", e)))
101    }
102}
103
104fn decode_component(s: &str) -> String {
105    let s = s.replace('+', " ");
106    urlencoding::decode(&s).map(|c| c.into_owned()).unwrap_or(s)
107}
108
109impl Default for Query {
110    fn default() -> Self {
111        Self::new()
112    }
113}
114
115/// Type-keyed storage for shared application state
116#[derive(Default)]
117pub(crate) struct StateMap {
118    values: HashMap<std::any::TypeId, Box<dyn std::any::Any + Send + Sync>>,
119}
120
121impl StateMap {
122    pub(crate) fn insert<T: Send + Sync + 'static>(&mut self, value: T) {
123        self.values
124            .insert(std::any::TypeId::of::<T>(), Box::new(value));
125    }
126
127    pub(crate) fn get<T: Send + Sync + 'static>(&self) -> Option<&T> {
128        self.values
129            .get(&std::any::TypeId::of::<T>())
130            .and_then(|v| v.downcast_ref::<T>())
131    }
132}
133
134/// HTTP Request wrapper
135pub struct Request {
136    pub method: http::Method,
137    pub uri: http::Uri,
138    pub headers: http::HeaderMap,
139    pub body: bytes::Bytes,
140    pub params: Params,
141    pub query: Query,
142    /// Typed per-request data; middleware can attach values for handlers
143    /// (authenticated user, request id, ...).
144    pub extensions: http::Extensions,
145    /// Address of the connected peer (the proxy when behind one)
146    pub remote_addr: Option<std::net::SocketAddr>,
147    /// The route pattern that matched, e.g. `/users/{id}`; `None` when no route
148    /// matched. Use it, not the raw path, as a metrics label or log field: it
149    /// stays the same for every id.
150    pub matched_path: Option<std::sync::Arc<str>>,
151    pub(crate) state: Option<std::sync::Arc<StateMap>>,
152    pub(crate) shutdown: Option<crate::shutdown::Shutdown>,
153    cookies: OnceLock<Cookies>,
154}
155
156impl Request {
157    pub fn new(
158        method: http::Method,
159        uri: http::Uri,
160        headers: http::HeaderMap,
161        body: bytes::Bytes,
162    ) -> Self {
163        let query = uri
164            .query()
165            .map(Query::parse_query_string)
166            .unwrap_or_default();
167
168        Self {
169            method,
170            uri,
171            headers,
172            body,
173            params: Params::new(),
174            query,
175            extensions: http::Extensions::new(),
176            remote_addr: None,
177            matched_path: None,
178            state: None,
179            shutdown: None,
180            cookies: OnceLock::new(),
181        }
182    }
183
184    /// Shared application state registered with `App::state`
185    ///
186    /// Answers `500` when no value of type `T` was registered: that is a
187    /// programming error, not something the client can fix.
188    pub fn state<T: Send + Sync + 'static>(&self) -> Result<&T> {
189        self.try_state().ok_or_else(|| {
190            Error::internal(format!(
191                "State of type {} is not registered",
192                std::any::type_name::<T>()
193            ))
194        })
195    }
196
197    /// Signal that fires when the server begins shutting down
198    ///
199    /// Long-lived handlers (SSE streams, polling loops) select on it to end
200    /// promptly: `tokio::select! { _ = req.shutdown_signal().wait() => break, ... }`.
201    pub fn shutdown_signal(&self) -> crate::shutdown::Shutdown {
202        self.shutdown
203            .clone()
204            .unwrap_or_else(crate::shutdown::Shutdown::never)
205    }
206
207    /// Like [`Request::state`], `None` when the type is not registered
208    pub fn try_state<T: Send + Sync + 'static>(&self) -> Option<&T> {
209        self.state.as_ref()?.get::<T>()
210    }
211
212    /// Get cookies from the request
213    pub fn cookies(&self) -> &Cookies {
214        self.cookies.get_or_init(|| {
215            if let Some(cookie_header) = self.headers.get("cookie") {
216                if let Ok(cookie_str) = cookie_header.to_str() {
217                    Cookies::parse(cookie_str)
218                } else {
219                    Cookies::new()
220                }
221            } else {
222                Cookies::new()
223            }
224        })
225    }
226
227    /// Parse an `application/x-www-form-urlencoded` body into a struct
228    ///
229    /// Answers `415` for other content types and `400` for values that do not
230    /// fit the target type.
231    pub fn form<T: DeserializeOwned>(&self) -> Result<T> {
232        self.require_form_content_type()?;
233        serde_urlencoded::from_bytes(&self.body)
234            .map_err(|e| Error::bad_request(format!("Invalid form data: {}", e)))
235    }
236
237    /// The same body as decoded key/value access (`+` and `%XX` decoded)
238    pub fn form_data(&self) -> Result<Query> {
239        self.require_form_content_type()?;
240        let text = std::str::from_utf8(&self.body)
241            .map_err(|_| Error::bad_request("Form data is not valid UTF-8"))?;
242        Ok(Query::parse_query_string(text))
243    }
244
245    fn require_form_content_type(&self) -> Result<()> {
246        let is_form = self
247            .headers
248            .get(http::header::CONTENT_TYPE)
249            .and_then(|v| v.to_str().ok())
250            .map(|v| {
251                v.split(';')
252                    .next()
253                    .unwrap_or("")
254                    .trim()
255                    .eq_ignore_ascii_case("application/x-www-form-urlencoded")
256            })
257            .unwrap_or(false);
258        if is_form {
259            Ok(())
260        } else {
261            Err(Error::custom(
262                415,
263                "Expected content-type application/x-www-form-urlencoded",
264            ))
265        }
266    }
267
268    /// Parse JSON body
269    pub fn json<T: DeserializeOwned>(&self) -> Result<T> {
270        serde_json::from_slice(&self.body)
271            .map_err(|e| Error::bad_request(format!("Invalid JSON: {}", e)))
272    }
273}
274
275#[cfg(test)]
276mod tests {
277    use super::*;
278
279    fn form_request(content_type: Option<&str>, body: &'static str) -> Request {
280        let mut headers = http::HeaderMap::new();
281        if let Some(ct) = content_type {
282            headers.insert(http::header::CONTENT_TYPE, ct.parse().unwrap());
283        }
284        Request::new(
285            http::Method::POST,
286            "/".parse().unwrap(),
287            headers,
288            bytes::Bytes::from_static(body.as_bytes()),
289        )
290    }
291
292    #[derive(Debug, serde::Deserialize, PartialEq)]
293    struct Signup {
294        name: String,
295        age: u8,
296        newsletter: Option<bool>,
297    }
298
299    #[test]
300    fn params_parse_typed_values() {
301        let mut p = Params::new();
302        p.insert("id".into(), "42".into());
303        p.insert("name".into(), "x".into());
304        assert_eq!(p.parse::<u64>("id").unwrap(), 42);
305        assert_eq!(p.parse::<String>("name").unwrap(), "x");
306        let bad = p.parse::<u64>("name").unwrap_err();
307        assert_eq!(bad.status_code(), 400);
308        assert_eq!(bad.message(), "Invalid path parameter 'name'");
309        assert_eq!(p.parse::<u64>("missing").unwrap_err().status_code(), 400);
310        assert!(p.parse::<u8>("id").is_ok());
311        p.insert("big".into(), "300".into());
312        assert!(p.parse::<u8>("big").is_err());
313    }
314
315    #[test]
316    fn query_decodes_keys_values_and_plus() {
317        let q = Query::parse_query_string("q=rust+web&na%20me=a%26b&flag&&x=1");
318        assert_eq!(q.get("q"), Some("rust web"));
319        assert_eq!(q.get("na me"), Some("a&b"));
320        assert_eq!(q.get("flag"), Some(""));
321        assert!(q.contains("x") && !q.is_empty());
322    }
323
324    #[test]
325    fn query_parse_converts_types() {
326        let q = Query::parse_query_string("name=Ann&age=31&newsletter=true");
327        assert_eq!(
328            q.parse::<Signup>().unwrap(),
329            Signup {
330                name: "Ann".into(),
331                age: 31,
332                newsletter: Some(true)
333            }
334        );
335        let bad = Query::parse_query_string("name=Ann&age=old");
336        assert_eq!(bad.parse::<Signup>().unwrap_err().status_code(), 400);
337    }
338
339    #[test]
340    fn form_typed_and_untyped() {
341        let req = form_request(
342            Some("application/x-www-form-urlencoded; charset=UTF-8"),
343            "name=Ann+Lee&age=31",
344        );
345        let signup: Signup = req.form().unwrap();
346        assert_eq!(
347            signup,
348            Signup {
349                name: "Ann Lee".into(),
350                age: 31,
351                newsletter: None
352            }
353        );
354        assert_eq!(req.form_data().unwrap().get("name"), Some("Ann Lee"));
355    }
356
357    #[test]
358    fn form_rejects_wrong_content_type_and_bad_values() {
359        let json = form_request(Some("application/json"), "name=Ann&age=1");
360        assert_eq!(json.form::<Signup>().unwrap_err().status_code(), 415);
361        let none = form_request(None, "name=Ann&age=1");
362        assert_eq!(none.form_data().unwrap_err().status_code(), 415);
363
364        let bad = form_request(
365            Some("application/x-www-form-urlencoded"),
366            "name=Ann&age=300",
367        );
368        assert_eq!(bad.form::<Signup>().unwrap_err().status_code(), 400);
369    }
370}