Skip to main content

next_rust_server/
context.rs

1//! Render context and extractors.
2//!
3//! Page, layout and metadata functions declare what they need as arguments;
4//! the generated route glue resolves each argument through [`FromContext`]:
5//!
6//! ```ignore
7//! pub async fn Page(Path(p): Path<PostParams>, cookies: Cookies) -> Result<impl View> { .. }
8//! ```
9//!
10//! Arguments that read request data (cookies, headers, query, ...) make the
11//! route dynamic under `rendering = "auto"`.
12
13use std::collections::BTreeMap;
14use std::net::SocketAddr;
15use std::sync::atomic::{AtomicU16, Ordering};
16use std::sync::{Arc, Mutex};
17
18use http::{HeaderMap, Method, Uri};
19use next_rust_core::Config;
20use next_rust_router::Params;
21use serde::de::DeserializeOwned;
22
23use crate::cookies::Cookies;
24use crate::error::{Error, ErrorKind, Result, not_found};
25
26/// Whether a render serves a live request or runs at build/revalidation time.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum RenderMode {
29    Request,
30    Static,
31}
32
33/// Everything known about the request being rendered.
34pub struct RequestContext {
35    pub method: Method,
36    pub uri: Uri,
37    pub headers: HeaderMap,
38    pub params: Params,
39    pub cookies: Cookies,
40    pub extensions: http::Extensions,
41    pub remote_addr: Option<SocketAddr>,
42    /// Per-request CSP nonce.
43    pub nonce: String,
44    pub mode: RenderMode,
45    /// Development mode: detailed error messages.
46    pub dev: bool,
47    pub config: Arc<Config>,
48    pub(crate) status: AtomicU16,
49    pub(crate) response_headers: Mutex<HeaderMap>,
50}
51
52/// Shared handle to the context.
53pub type Ctx = Arc<RequestContext>;
54
55impl RequestContext {
56    pub fn path(&self) -> &str {
57        self.uri.path()
58    }
59
60    pub fn is_static(&self) -> bool {
61        self.mode == RenderMode::Static
62    }
63
64    /// Override the response status (e.g. 201, 410).
65    pub fn set_status(&self, code: u16) {
66        self.status.store(code, Ordering::Relaxed);
67    }
68
69    pub fn status(&self) -> u16 {
70        self.status.load(Ordering::Relaxed)
71    }
72
73    pub(crate) fn raise_status(&self, code: u16) {
74        // Error statuses from boundaries win over 200, first one sticks.
75        let _ = self.status.compare_exchange(200, code, Ordering::Relaxed, Ordering::Relaxed);
76    }
77
78    fn require_request(&self, what: &'static str) -> Result<()> {
79        if self.is_static() { Err(Error::new(ErrorKind::DynamicUsage(what))) } else { Ok(()) }
80    }
81
82    /// Build a context for tests or static rendering.
83    pub fn for_static(path: &str, params: Params, config: Arc<Config>) -> Ctx {
84        Self::for_static_with(path, params, config, crate::is_dev())
85    }
86
87    pub(crate) fn for_static_with(path: &str, params: Params, config: Arc<Config>, dev: bool) -> Ctx {
88        Arc::new(RequestContext {
89            method: Method::GET,
90            uri: path.parse().unwrap_or_else(|_| Uri::from_static("/")),
91            headers: HeaderMap::new(),
92            params,
93            cookies: Cookies::default(),
94            extensions: http::Extensions::new(),
95            remote_addr: None,
96            nonce: crate::random_hex(16),
97            mode: RenderMode::Static,
98            dev,
99            config,
100            status: AtomicU16::new(200),
101            response_headers: Mutex::new(HeaderMap::new()),
102        })
103    }
104
105    pub(crate) fn from_request(req: &crate::Request, config: Arc<Config>, nonce: String, dev: bool) -> Ctx {
106        Arc::new(RequestContext {
107            method: req.method().clone(),
108            uri: req.uri().clone(),
109            headers: req.headers().clone(),
110            params: req.params().clone(),
111            cookies: req.cookies().clone(),
112            extensions: req.extensions().clone(),
113            remote_addr: req.remote_addr(),
114            nonce,
115            mode: RenderMode::Request,
116            dev,
117            config,
118            status: AtomicU16::new(200),
119            response_headers: Mutex::new(HeaderMap::new()),
120        })
121    }
122}
123
124/// Resolve a function argument from the render context.
125pub trait FromContext: Sized {
126    fn from_context(ctx: &Ctx) -> Result<Self>;
127}
128
129impl FromContext for Ctx {
130    fn from_context(ctx: &Ctx) -> Result<Self> {
131        Ok(ctx.clone())
132    }
133}
134
135impl FromContext for Params {
136    fn from_context(ctx: &Ctx) -> Result<Self> {
137        Ok(ctx.params.clone())
138    }
139}
140
141/// Typed route parameters: `Path(p): Path<BlogParams>`. A parameter that
142/// fails to parse (e.g. `/users/abc` for `id: u64`) renders the 404 page.
143#[derive(Debug, Clone)]
144pub struct Path<T>(pub T);
145
146impl<T: DeserializeOwned> FromContext for Path<T> {
147    fn from_context(ctx: &Ctx) -> Result<Self> {
148        crate::params_de::from_params(&ctx.params).map(Path).map_err(|_| not_found())
149    }
150}
151
152/// Parsed query string: `Query(q): Query` (a map) or `Query<T>` (typed).
153#[derive(Debug, Clone)]
154pub struct Query<T = QueryMap>(pub T);
155
156/// Query parameters as a multi-map.
157#[derive(Debug, Clone, Default, PartialEq, Eq)]
158pub struct QueryMap(pub Vec<(String, String)>);
159
160impl QueryMap {
161    pub fn get(&self, name: &str) -> Option<&str> {
162        self.0.iter().find(|(k, _)| k == name).map(|(_, v)| v.as_str())
163    }
164
165    pub fn get_all(&self, name: &str) -> Vec<&str> {
166        self.0.iter().filter(|(k, _)| k == name).map(|(_, v)| v.as_str()).collect()
167    }
168}
169
170impl<'de> serde::Deserialize<'de> for QueryMap {
171    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
172        Vec::<(String, String)>::deserialize(d).map(QueryMap)
173    }
174}
175
176impl<T: DeserializeOwned> FromContext for Query<T> {
177    fn from_context(ctx: &Ctx) -> Result<Self> {
178        ctx.require_request("Query")?;
179        serde_urlencoded::from_str(ctx.uri.query().unwrap_or(""))
180            .map(Query)
181            .map_err(|e| Error::http(400, format!("invalid query string: {e}")))
182    }
183}
184
185impl FromContext for Cookies {
186    fn from_context(ctx: &Ctx) -> Result<Self> {
187        ctx.require_request("Cookies")?;
188        Ok(ctx.cookies.clone())
189    }
190}
191
192/// Request headers.
193#[derive(Debug, Clone)]
194pub struct Headers(pub HeaderMap);
195
196impl Headers {
197    pub fn get(&self, name: &str) -> Option<&str> {
198        self.0.get(name).and_then(|v| v.to_str().ok())
199    }
200}
201
202impl FromContext for Headers {
203    fn from_context(ctx: &Ctx) -> Result<Self> {
204        ctx.require_request("Headers")?;
205        Ok(Headers(ctx.headers.clone()))
206    }
207}
208
209/// The client's IP address, read as [`crate::Request::client_ip`] reads it:
210/// the first `X-Forwarded-For` entry when `[server] trust_proxy` is on, the
211/// peer address otherwise. `None` when neither is known (tests, pre-rendering).
212///
213/// ```ignore
214/// pub async fn load(ClientIp(ip): ClientIp) -> Result<Quota> { quota_for(ip).await }
215/// ```
216#[derive(Debug, Clone, Copy, PartialEq, Eq)]
217pub struct ClientIp(pub Option<std::net::IpAddr>);
218
219impl FromContext for ClientIp {
220    fn from_context(ctx: &Ctx) -> Result<Self> {
221        ctx.require_request("ClientIp")?;
222        Ok(ClientIp(crate::request::client_ip_from(&ctx.headers, ctx.remote_addr, crate::trust_proxy())))
223    }
224}
225
226/// Basic request information.
227#[derive(Debug, Clone)]
228pub struct RequestInfo {
229    pub method: Method,
230    pub uri: Uri,
231    pub remote_addr: Option<SocketAddr>,
232}
233
234impl FromContext for RequestInfo {
235    fn from_context(ctx: &Ctx) -> Result<Self> {
236        ctx.require_request("RequestInfo")?;
237        Ok(RequestInfo { method: ctx.method.clone(), uri: ctx.uri.clone(), remote_addr: ctx.remote_addr })
238    }
239}
240
241/// A value inserted by middleware (`req.insert_extension(user)`), e.g. the
242/// authenticated user: `Extension(user): Extension<User>`. Missing values
243/// produce a 500 in development with a clear message; use
244/// `Option<Extension<T>>` for optional values.
245#[derive(Debug, Clone)]
246pub struct Extension<T>(pub T);
247
248impl<T: Clone + Send + Sync + 'static> FromContext for Extension<T> {
249    fn from_context(ctx: &Ctx) -> Result<Self> {
250        ctx.require_request("Extension")?;
251        ctx.extensions.get::<T>().cloned().map(Extension).ok_or_else(|| {
252            Error::msg(format!(
253                "Extension<{}> is not set; insert it in middleware with `req.insert_extension(..)`",
254                std::any::type_name::<T>()
255            ))
256        })
257    }
258}
259
260impl<T: Clone + Send + Sync + 'static> FromContext for Option<Extension<T>> {
261    fn from_context(ctx: &Ctx) -> Result<Self> {
262        ctx.require_request("Extension")?;
263        Ok(ctx.extensions.get::<T>().cloned().map(Extension))
264    }
265}
266
267/// Authentication context primitive: set by your auth middleware, read by
268/// pages. `Auth<T>` is `Option`-like: `auth.user()` is `None` for guests.
269#[derive(Debug, Clone)]
270pub struct Auth<T>(pub Option<T>);
271
272impl<T> Auth<T> {
273    pub fn user(&self) -> Option<&T> {
274        self.0.as_ref()
275    }
276
277    pub fn is_authenticated(&self) -> bool {
278        self.0.is_some()
279    }
280
281    /// The user, or a redirect to `login`.
282    pub fn require(self, login: &str) -> Result<T> {
283        self.0.ok_or_else(|| crate::error::redirect(login))
284    }
285}
286
287/// Wrapper middleware inserts: `req.insert_extension(AuthUser(user))`.
288#[derive(Debug, Clone)]
289pub struct AuthUser<T>(pub T);
290
291impl<T: Clone + Send + Sync + 'static> FromContext for Auth<T> {
292    fn from_context(ctx: &Ctx) -> Result<Self> {
293        ctx.require_request("Auth")?;
294        Ok(Auth(ctx.extensions.get::<AuthUser<T>>().map(|u| u.0.clone())))
295    }
296}
297
298/// The per-request CSP nonce (for your own inline scripts).
299#[derive(Debug, Clone)]
300pub struct Nonce(pub String);
301
302impl FromContext for Nonce {
303    fn from_context(ctx: &Ctx) -> Result<Self> {
304        Ok(Nonce(ctx.nonce.clone()))
305    }
306}
307
308/// Add headers to the page response.
309#[derive(Clone)]
310pub struct ResponseHeaders(Ctx);
311
312impl ResponseHeaders {
313    pub fn set(&self, name: &str, value: &str) {
314        if let (Ok(n), Ok(v)) = (http::HeaderName::from_bytes(name.as_bytes()), http::HeaderValue::from_str(value)) {
315            self.0.response_headers.lock().unwrap_or_else(|e| e.into_inner()).insert(n, v);
316        }
317    }
318}
319
320impl FromContext for ResponseHeaders {
321    fn from_context(ctx: &Ctx) -> Result<Self> {
322        ctx.require_request("ResponseHeaders")?;
323        Ok(ResponseHeaders(ctx.clone()))
324    }
325}
326
327/// Result of the route's `load` function: `Data(posts): Data<Vec<Post>>`.
328#[derive(Debug, Clone)]
329pub struct Data<T>(pub T);
330
331/// CSRF token for forms when `csrf()` middleware or `[security] csrf = "token"` is used.
332#[derive(Debug, Clone, PartialEq, Eq)]
333pub struct CsrfToken(pub String);
334
335impl CsrfToken {
336    /// Hidden input carrying the token.
337    pub fn field(&self) -> next_rust_view::Element {
338        next_rust_view::Element::new_void("input")
339            .with(next_rust_view::attrs::type_("hidden"))
340            .with(next_rust_view::attrs::name("_csrf"))
341            .with(next_rust_view::attrs::value(self.0.clone()))
342    }
343}
344
345impl FromContext for CsrfToken {
346    fn from_context(ctx: &Ctx) -> Result<Self> {
347        ctx.require_request("CsrfToken")?;
348        Ok(ctx
349            .extensions
350            .get::<CsrfToken>()
351            .cloned()
352            .or_else(|| ctx.cookies.get(crate::CSRF_COOKIE).map(CsrfToken))
353            .unwrap_or_else(|| {
354                let t = crate::random_hex(32);
355                ctx.cookies.set(crate::Cookie::new(crate::CSRF_COOKIE, t.clone()).http_only(false));
356                CsrfToken(t)
357            }))
358    }
359}
360
361/// Result of the last progressive-enhancement form submission (validation
362/// errors / error message), read once from a short-lived flash cookie.
363#[derive(Debug, Clone, Default, PartialEq, Eq)]
364pub struct FormState {
365    pub errors: BTreeMap<String, String>,
366    pub message: Option<String>,
367    pub values: BTreeMap<String, String>,
368}
369
370impl FormState {
371    pub fn error(&self, field: &str) -> Option<&str> {
372        self.errors.get(field).map(String::as_str)
373    }
374
375    pub fn value(&self, field: &str) -> &str {
376        self.values.get(field).map(String::as_str).unwrap_or("")
377    }
378
379    pub fn has_errors(&self) -> bool {
380        !self.errors.is_empty() || self.message.is_some()
381    }
382}
383
384impl FromContext for FormState {
385    fn from_context(ctx: &Ctx) -> Result<Self> {
386        ctx.require_request("FormState")?;
387        let Some(raw) = ctx.cookies.get_decoded(crate::actions::FLASH_COOKIE) else { return Ok(FormState::default()) };
388        ctx.cookies.delete(crate::actions::FLASH_COOKIE);
389        Ok(crate::actions::decode_flash(&raw))
390    }
391}