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    pub(crate) state: Option<std::sync::Arc<StateMap>>,
148    pub(crate) shutdown: Option<crate::shutdown::Shutdown>,
149    cookies: OnceLock<Cookies>,
150}
151
152impl Request {
153    pub fn new(
154        method: http::Method,
155        uri: http::Uri,
156        headers: http::HeaderMap,
157        body: bytes::Bytes,
158    ) -> Self {
159        let query = uri
160            .query()
161            .map(Query::parse_query_string)
162            .unwrap_or_default();
163
164        Self {
165            method,
166            uri,
167            headers,
168            body,
169            params: Params::new(),
170            query,
171            extensions: http::Extensions::new(),
172            remote_addr: None,
173            state: None,
174            shutdown: None,
175            cookies: OnceLock::new(),
176        }
177    }
178
179    /// Shared application state registered with `App::state`
180    ///
181    /// Answers `500` when no value of type `T` was registered: that is a
182    /// programming error, not something the client can fix.
183    pub fn state<T: Send + Sync + 'static>(&self) -> Result<&T> {
184        self.try_state().ok_or_else(|| {
185            Error::internal(format!(
186                "State of type {} is not registered",
187                std::any::type_name::<T>()
188            ))
189        })
190    }
191
192    /// Signal that fires when the server begins shutting down
193    ///
194    /// Long-lived handlers (SSE streams, polling loops) select on it to end
195    /// promptly: `tokio::select! { _ = req.shutdown_signal().wait() => break, ... }`.
196    pub fn shutdown_signal(&self) -> crate::shutdown::Shutdown {
197        self.shutdown
198            .clone()
199            .unwrap_or_else(crate::shutdown::Shutdown::never)
200    }
201
202    /// Like [`Request::state`], `None` when the type is not registered
203    pub fn try_state<T: Send + Sync + 'static>(&self) -> Option<&T> {
204        self.state.as_ref()?.get::<T>()
205    }
206
207    /// Get cookies from the request
208    pub fn cookies(&self) -> &Cookies {
209        self.cookies.get_or_init(|| {
210            if let Some(cookie_header) = self.headers.get("cookie") {
211                if let Ok(cookie_str) = cookie_header.to_str() {
212                    Cookies::parse(cookie_str)
213                } else {
214                    Cookies::new()
215                }
216            } else {
217                Cookies::new()
218            }
219        })
220    }
221
222    /// Parse an `application/x-www-form-urlencoded` body into a struct
223    ///
224    /// Answers `415` for other content types and `400` for values that do not
225    /// fit the target type.
226    pub fn form<T: DeserializeOwned>(&self) -> Result<T> {
227        self.require_form_content_type()?;
228        serde_urlencoded::from_bytes(&self.body)
229            .map_err(|e| Error::bad_request(format!("Invalid form data: {}", e)))
230    }
231
232    /// The same body as decoded key/value access (`+` and `%XX` decoded)
233    pub fn form_data(&self) -> Result<Query> {
234        self.require_form_content_type()?;
235        let text = std::str::from_utf8(&self.body)
236            .map_err(|_| Error::bad_request("Form data is not valid UTF-8"))?;
237        Ok(Query::parse_query_string(text))
238    }
239
240    fn require_form_content_type(&self) -> Result<()> {
241        let is_form = self
242            .headers
243            .get(http::header::CONTENT_TYPE)
244            .and_then(|v| v.to_str().ok())
245            .map(|v| {
246                v.split(';')
247                    .next()
248                    .unwrap_or("")
249                    .trim()
250                    .eq_ignore_ascii_case("application/x-www-form-urlencoded")
251            })
252            .unwrap_or(false);
253        if is_form {
254            Ok(())
255        } else {
256            Err(Error::custom(
257                415,
258                "Expected content-type application/x-www-form-urlencoded",
259            ))
260        }
261    }
262
263    /// Parse JSON body
264    pub fn json<T: DeserializeOwned>(&self) -> Result<T> {
265        serde_json::from_slice(&self.body)
266            .map_err(|e| Error::bad_request(format!("Invalid JSON: {}", e)))
267    }
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273
274    fn form_request(content_type: Option<&str>, body: &'static str) -> Request {
275        let mut headers = http::HeaderMap::new();
276        if let Some(ct) = content_type {
277            headers.insert(http::header::CONTENT_TYPE, ct.parse().unwrap());
278        }
279        Request::new(
280            http::Method::POST,
281            "/".parse().unwrap(),
282            headers,
283            bytes::Bytes::from_static(body.as_bytes()),
284        )
285    }
286
287    #[derive(Debug, serde::Deserialize, PartialEq)]
288    struct Signup {
289        name: String,
290        age: u8,
291        newsletter: Option<bool>,
292    }
293
294    #[test]
295    fn params_parse_typed_values() {
296        let mut p = Params::new();
297        p.insert("id".into(), "42".into());
298        p.insert("name".into(), "x".into());
299        assert_eq!(p.parse::<u64>("id").unwrap(), 42);
300        assert_eq!(p.parse::<String>("name").unwrap(), "x");
301        let bad = p.parse::<u64>("name").unwrap_err();
302        assert_eq!(bad.status_code(), 400);
303        assert_eq!(bad.message(), "Invalid path parameter 'name'");
304        assert_eq!(p.parse::<u64>("missing").unwrap_err().status_code(), 400);
305        assert!(p.parse::<u8>("id").is_ok());
306        p.insert("big".into(), "300".into());
307        assert!(p.parse::<u8>("big").is_err());
308    }
309
310    #[test]
311    fn query_decodes_keys_values_and_plus() {
312        let q = Query::parse_query_string("q=rust+web&na%20me=a%26b&flag&&x=1");
313        assert_eq!(q.get("q"), Some("rust web"));
314        assert_eq!(q.get("na me"), Some("a&b"));
315        assert_eq!(q.get("flag"), Some(""));
316        assert!(q.contains("x") && !q.is_empty());
317    }
318
319    #[test]
320    fn query_parse_converts_types() {
321        let q = Query::parse_query_string("name=Ann&age=31&newsletter=true");
322        assert_eq!(
323            q.parse::<Signup>().unwrap(),
324            Signup {
325                name: "Ann".into(),
326                age: 31,
327                newsletter: Some(true)
328            }
329        );
330        let bad = Query::parse_query_string("name=Ann&age=old");
331        assert_eq!(bad.parse::<Signup>().unwrap_err().status_code(), 400);
332    }
333
334    #[test]
335    fn form_typed_and_untyped() {
336        let req = form_request(
337            Some("application/x-www-form-urlencoded; charset=UTF-8"),
338            "name=Ann+Lee&age=31",
339        );
340        let signup: Signup = req.form().unwrap();
341        assert_eq!(
342            signup,
343            Signup {
344                name: "Ann Lee".into(),
345                age: 31,
346                newsletter: None
347            }
348        );
349        assert_eq!(req.form_data().unwrap().get("name"), Some("Ann Lee"));
350    }
351
352    #[test]
353    fn form_rejects_wrong_content_type_and_bad_values() {
354        let json = form_request(Some("application/json"), "name=Ann&age=1");
355        assert_eq!(json.form::<Signup>().unwrap_err().status_code(), 415);
356        let none = form_request(None, "name=Ann&age=1");
357        assert_eq!(none.form_data().unwrap_err().status_code(), 415);
358
359        let bad = form_request(
360            Some("application/x-www-form-urlencoded"),
361            "name=Ann&age=300",
362        );
363        assert_eq!(bad.form::<Signup>().unwrap_err().status_code(), 400);
364    }
365}