Skip to main content

next_rust_server/
request.rs

1//! Incoming HTTP request.
2
3use std::net::SocketAddr;
4
5use bytes::Bytes;
6use http::request::Parts;
7use http::{HeaderMap, Method, Uri};
8use http_body_util::combinators::UnsyncBoxBody;
9use http_body_util::{BodyExt, Empty, Full};
10use next_rust_router::Params;
11use serde::de::DeserializeOwned;
12
13use crate::cookies::Cookies;
14use crate::error::{Error, Result};
15
16pub type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
17/// Request body type (streaming).
18pub type RequestBody = UnsyncBoxBody<Bytes, BoxError>;
19
20/// An HTTP request as seen by middleware, API routes and server actions.
21pub struct Request {
22    parts: Parts,
23    // Mutex makes `Request: Sync` (the body stream is only `Send`); all access
24    // goes through `&mut self`, so it is never contended.
25    body: std::sync::Mutex<Option<RequestBody>>,
26    buffered: Option<Bytes>,
27    params: Params,
28    cookies: Cookies,
29    remote_addr: Option<SocketAddr>,
30    body_limit: usize,
31}
32
33impl std::fmt::Debug for Request {
34    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35        f.debug_struct("Request").field("method", &self.parts.method).field("uri", &self.parts.uri).finish()
36    }
37}
38
39impl Request {
40    pub fn from_parts(
41        parts: Parts,
42        body: RequestBody,
43        remote_addr: Option<SocketAddr>,
44        body_limit: usize,
45        secure_cookies: bool,
46    ) -> Self {
47        let cookies = Cookies::from_headers(&parts.headers, secure_cookies);
48        Request {
49            parts,
50            body: std::sync::Mutex::new(Some(body)),
51            buffered: None,
52            params: Params::new(),
53            cookies,
54            remote_addr,
55            body_limit,
56        }
57    }
58
59    /// Build a request from any `http::Request` with a buffered body
60    /// (useful in tests and serverless adapters).
61    pub fn from_http(req: http::Request<Bytes>) -> Self {
62        let (parts, body) = req.into_parts();
63        let body = Full::new(body).map_err(|never| match never {}).boxed_unsync();
64        Request::from_parts(parts, body, None, usize::MAX, false)
65    }
66
67    /// A body-less GET request for `uri` (tests, static rendering).
68    pub fn get(uri: &str) -> Self {
69        let req = http::Request::get(uri).body(Bytes::new()).expect("valid uri");
70        Request::from_http(req)
71    }
72
73    pub fn method(&self) -> &Method {
74        &self.parts.method
75    }
76
77    pub fn uri(&self) -> &Uri {
78        &self.parts.uri
79    }
80
81    pub fn path(&self) -> &str {
82        self.parts.uri.path()
83    }
84
85    pub fn query_string(&self) -> &str {
86        self.parts.uri.query().unwrap_or("")
87    }
88
89    /// Deserialize the query string into `T`.
90    pub fn query<T: DeserializeOwned>(&self) -> Result<T> {
91        serde_urlencoded::from_str(self.query_string())
92            .map_err(|e| Error::http(400, format!("invalid query string: {e}")))
93    }
94
95    /// A single query parameter.
96    pub fn query_param(&self, name: &str) -> Option<String> {
97        serde_urlencoded::from_str::<Vec<(String, String)>>(self.query_string())
98            .ok()?
99            .into_iter()
100            .find(|(k, _)| k == name)
101            .map(|(_, v)| v)
102    }
103
104    pub fn headers(&self) -> &HeaderMap {
105        &self.parts.headers
106    }
107
108    pub fn headers_mut(&mut self) -> &mut HeaderMap {
109        &mut self.parts.headers
110    }
111
112    /// Header value as text (`None` if missing or not visible ASCII).
113    pub fn header(&self, name: &str) -> Option<&str> {
114        self.parts.headers.get(name).and_then(|v| v.to_str().ok())
115    }
116
117    pub fn params(&self) -> &Params {
118        &self.params
119    }
120
121    pub fn param(&self, name: &str) -> Option<&str> {
122        self.params.get(name)
123    }
124
125    pub(crate) fn set_params(&mut self, params: Params) {
126        self.params = params;
127    }
128
129    pub fn cookies(&self) -> &Cookies {
130        &self.cookies
131    }
132
133    pub fn remote_addr(&self) -> Option<SocketAddr> {
134        self.remote_addr
135    }
136
137    pub fn extensions(&self) -> &http::Extensions {
138        &self.parts.extensions
139    }
140
141    pub fn extensions_mut(&mut self) -> &mut http::Extensions {
142        &mut self.parts.extensions
143    }
144
145    /// Typed request-scoped value inserted by middleware (e.g. the current user).
146    pub fn extension<T: Send + Sync + 'static>(&self) -> Option<&T> {
147        self.parts.extensions.get::<T>()
148    }
149
150    pub fn insert_extension<T: Clone + Send + Sync + 'static>(&mut self, value: T) {
151        self.parts.extensions.insert(value);
152    }
153
154    /// Rewrite the request path (middleware only; routing happens afterwards).
155    pub fn set_path(&mut self, path_and_query: &str) -> Result<()> {
156        let uri: Uri = path_and_query.parse().map_err(|_| Error::http(400, "invalid rewrite target"))?;
157        self.parts.uri = uri;
158        Ok(())
159    }
160
161    /// Lower the body limit to `limit` if it is currently higher.
162    pub(crate) fn limit_body(&mut self, limit: usize) {
163        self.body_limit = self.body_limit.min(limit);
164    }
165
166    /// Override the maximum body size for this request.
167    pub fn set_body_limit(&mut self, limit: usize) {
168        self.body_limit = limit;
169    }
170
171    pub fn is_websocket_upgrade(&self) -> bool {
172        self.header("upgrade").is_some_and(|u| u.eq_ignore_ascii_case("websocket"))
173    }
174
175    /// Whether the connection (or the trusted proxy) used HTTPS.
176    pub fn is_secure(&self) -> bool {
177        self.parts.uri.scheme_str() == Some("https") || self.header("x-forwarded-proto") == Some("https")
178    }
179
180    /// Read the whole body (enforcing the body limit: 413 when exceeded).
181    /// Can be called repeatedly; the body is buffered on first read.
182    pub async fn bytes(&mut self) -> Result<Bytes> {
183        if let Some(b) = &self.buffered {
184            return Ok(b.clone());
185        }
186        if let Some(len) = self.header("content-length").and_then(|l| l.parse::<usize>().ok())
187            && len > self.body_limit
188        {
189            return Err(Error::http(413, "request body too large"));
190        }
191        let limit = self.body_limit;
192        let mut body = self
193            .body
194            .get_mut()
195            .unwrap_or_else(|e| e.into_inner())
196            .take()
197            .unwrap_or_else(|| Empty::new().map_err(|never| match never {}).boxed_unsync());
198        let mut buf: Vec<u8> = Vec::new();
199        while let Some(frame) = body.frame().await {
200            let frame = match frame {
201                Ok(f) => f,
202                Err(e) => return Err(read_error(&*e)),
203            };
204            if let Ok(data) = frame.into_data() {
205                if buf.len() + data.len() > limit {
206                    return Err(Error::http(413, "request body too large"));
207                }
208                buf.extend_from_slice(&data);
209            }
210        }
211        let bytes = Bytes::from(buf);
212        self.buffered = Some(bytes.clone());
213        Ok(bytes)
214    }
215
216    /// Raw body — use for webhook signature verification.
217    pub async fn raw_body(&mut self) -> Result<Bytes> {
218        self.bytes().await
219    }
220
221    pub async fn text(&mut self) -> Result<String> {
222        let b = self.bytes().await?;
223        String::from_utf8(b.to_vec()).map_err(|_| Error::http(400, "request body is not valid UTF-8"))
224    }
225
226    pub async fn json<T: DeserializeOwned>(&mut self) -> Result<T> {
227        let b = self.bytes().await?;
228        serde_json::from_slice(&b).map_err(|e| Error::http(400, format!("invalid JSON body: {e}")))
229    }
230
231    /// `application/x-www-form-urlencoded` body.
232    pub async fn form<T: DeserializeOwned>(&mut self) -> Result<T> {
233        let b = self.bytes().await?;
234        serde_urlencoded::from_bytes(&b).map_err(|e| Error::http(400, format!("invalid form body: {e}")))
235    }
236
237    /// Take the streaming body (for large uploads). Returns `None` if the
238    /// body was already consumed.
239    pub fn take_body(&mut self) -> Option<RequestBody> {
240        if let Some(b) = self.buffered.clone() {
241            return Some(Full::new(b).map_err(|never| match never {}).boxed_unsync());
242        }
243        self.body.get_mut().unwrap_or_else(|e| e.into_inner()).take()
244    }
245
246    pub fn parts(&self) -> &Parts {
247        &self.parts
248    }
249
250    #[cfg_attr(not(feature = "websocket"), allow(dead_code))]
251    pub(crate) fn parts_mut(&mut self) -> &mut Parts {
252        &mut self.parts
253    }
254}
255
256fn read_error(e: &(dyn std::error::Error + Send + Sync)) -> Error {
257    Error::http(400, format!("failed to read request body: {e}"))
258}