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