Skip to main content

luxid_core/
context.rs

1//! `HttpContext` — the single argument every Luxid action receives.
2
3use std::any::{Any, TypeId};
4use std::collections::HashMap;
5
6use serde::de::DeserializeOwned;
7
8use crate::auth::Auth;
9use crate::config::Config;
10use crate::container::Container;
11use crate::error::{Error, Result};
12use crate::http::{Request, Response};
13use crate::session::Session;
14
15/// Route parameters captured from the path (`/users/{id}`).
16#[derive(Debug, Default, Clone)]
17pub struct Params(HashMap<String, String>);
18
19impl Params {
20    pub(crate) fn new(inner: HashMap<String, String>) -> Self {
21        Self(inner)
22    }
23
24    pub fn raw(&self, key: &str) -> Option<&str> {
25        self.0.get(key).map(String::as_str)
26    }
27
28    /// A parameter the route declares. Absence means the route pattern and the
29    /// action disagree, which is a bug in the app rather than bad input.
30    pub fn get<T: DeserializeOwned>(&self, key: &str) -> Result<T> {
31        let raw = self
32            .raw(key)
33            .ok_or_else(|| Error::BadRequest(format!("route parameter `{key}` is missing")))?;
34
35        crate::http::decode_param(key, raw)
36    }
37
38    pub fn try_get<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>> {
39        match self.raw(key) {
40            Some(raw) => crate::http::decode_param(key, raw).map(Some),
41            None => Ok(None),
42        }
43    }
44}
45
46/// A typed, request-scoped bag.
47///
48/// This is the mechanism middleware uses to hand values to downstream
49/// middleware and to the action — and the substrate the `auth`, `db` and
50/// `services` fields will be built on. It works precisely because the context
51/// is owned and threaded through one chain rather than rebuilt per step.
52#[derive(Default)]
53pub struct Extensions(HashMap<TypeId, Box<dyn Any + Send + Sync>>);
54
55impl Extensions {
56    pub fn new() -> Self {
57        Self::default()
58    }
59
60    /// Insert a value, returning any previous value of the same type.
61    pub fn insert<T: Any + Send + Sync>(&mut self, value: T) -> Option<T> {
62        self.0
63            .insert(TypeId::of::<T>(), Box::new(value))
64            .and_then(|previous| previous.downcast().ok().map(|boxed| *boxed))
65    }
66
67    pub fn get<T: Any + Send + Sync>(&self) -> Option<&T> {
68        self.0
69            .get(&TypeId::of::<T>())
70            .and_then(|value| value.downcast_ref())
71    }
72
73    pub fn get_mut<T: Any + Send + Sync>(&mut self) -> Option<&mut T> {
74        self.0
75            .get_mut(&TypeId::of::<T>())
76            .and_then(|value| value.downcast_mut())
77    }
78
79    pub fn take<T: Any + Send + Sync>(&mut self) -> Option<T> {
80        self.0
81            .remove(&TypeId::of::<T>())
82            .and_then(|value| value.downcast().ok().map(|boxed| *boxed))
83    }
84
85    pub fn contains<T: Any + Send + Sync>(&self) -> bool {
86        self.0.contains_key(&TypeId::of::<T>())
87    }
88
89    pub fn len(&self) -> usize {
90        self.0.len()
91    }
92
93    pub fn is_empty(&self) -> bool {
94        self.0.is_empty()
95    }
96}
97
98impl std::fmt::Debug for Extensions {
99    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100        f.debug_struct("Extensions")
101            .field("entries", &self.0.len())
102            .finish()
103    }
104}
105
106/// Everything an action needs, owned.
107///
108/// `#[non_exhaustive]` is load-bearing: it forces downstream crates to write
109/// `..` in struct patterns (E0638), which makes adding fields — `auth`, `db`,
110/// `inertia` — permanently non-breaking.
111#[non_exhaustive]
112#[derive(Debug)]
113pub struct HttpContext {
114    pub request: Request,
115    pub response: Response,
116    pub params: Params,
117    pub extensions: Extensions,
118    /// Request-scoped view of the application's services.
119    pub services: Container,
120    /// Who the request is. Anonymous unless a guard set it.
121    pub auth: Auth,
122    /// Merged configuration: `luxid.toml` with the environment over it.
123    pub config: Config,
124    /// The request's session. Detached unless `Auth::session()` is active.
125    pub session: Session,
126    /// Inertia protocol state. Detached unless the `Inertia` middleware ran.
127    pub inertia: crate::inertia::InertiaRequest,
128}
129
130impl HttpContext {
131    /// Enforce a policy, or fail with a 403.
132    ///
133    /// A policy is any function of `(&Auth, &T) -> bool`, so it is an ordinary
134    /// function in an ordinary `impl` — no trait to implement, no registry to
135    /// populate:
136    ///
137    /// ```ignore
138    /// ctx.authorize(PostPolicy::update, &post)?;
139    /// ```
140    ///
141    /// Returning `bool` rather than `Result` keeps policies about *permission*.
142    /// A policy that needs to fail some other way — a missing row is a 404, not
143    /// a 403 — should say so before the authorization check, not inside it.
144    pub fn authorize<T>(&self, policy: impl FnOnce(&Auth, &T) -> bool, subject: &T) -> Result<()> {
145        if policy(&self.auth, subject) {
146            return Ok(());
147        }
148
149        Err(Error::Forbidden)
150    }
151
152    /// The same question without the consequence, for deciding what to render.
153    pub fn can<T>(&self, policy: impl FnOnce(&Auth, &T) -> bool, subject: &T) -> bool {
154        policy(&self.auth, subject)
155    }
156
157    pub(crate) fn new(
158        request: Request,
159        params: Params,
160        services: Container,
161        config: Config,
162    ) -> Self {
163        Self {
164            request,
165            response: Response::default(),
166            params,
167            extensions: Extensions::new(),
168            services,
169            auth: Auth::default(),
170            config,
171            session: Session::detached(),
172            inertia: crate::inertia::InertiaRequest::default(),
173        }
174    }
175}
176
177#[cfg(test)]
178mod tests {
179    use super::*;
180
181    #[derive(Debug, PartialEq)]
182    struct CurrentUser(i64);
183
184    #[derive(Debug, PartialEq)]
185    struct RequestId(String);
186
187    #[test]
188    fn stores_and_reads_values_by_type() {
189        let mut extensions = Extensions::new();
190        extensions.insert(CurrentUser(7));
191        extensions.insert(RequestId("abc".into()));
192
193        assert_eq!(extensions.get::<CurrentUser>(), Some(&CurrentUser(7)));
194        assert_eq!(
195            extensions.get::<RequestId>(),
196            Some(&RequestId("abc".into()))
197        );
198        assert_eq!(extensions.len(), 2);
199    }
200
201    #[test]
202    fn inserting_the_same_type_returns_the_previous_value() {
203        let mut extensions = Extensions::new();
204        assert_eq!(extensions.insert(CurrentUser(1)), None);
205        assert_eq!(extensions.insert(CurrentUser(2)), Some(CurrentUser(1)));
206        assert_eq!(extensions.get::<CurrentUser>(), Some(&CurrentUser(2)));
207    }
208
209    #[test]
210    fn missing_types_read_as_none() {
211        let extensions = Extensions::new();
212        assert_eq!(extensions.get::<CurrentUser>(), None);
213        assert!(!extensions.contains::<CurrentUser>());
214        assert!(extensions.is_empty());
215    }
216
217    #[test]
218    fn take_removes_the_value() {
219        let mut extensions = Extensions::new();
220        extensions.insert(CurrentUser(9));
221
222        assert_eq!(extensions.take::<CurrentUser>(), Some(CurrentUser(9)));
223        assert_eq!(extensions.take::<CurrentUser>(), None);
224        assert!(extensions.is_empty());
225    }
226}