Skip to main content

luxid_core/
middleware.rs

1//! The middleware chain.
2//!
3//! Luxid owns the chain rather than delegating to salvo's hoops. The reason is
4//! the owning `HttpContext`: salvo's middleware receive borrowed request parts,
5//! so a mutation made there (setting the authenticated user, say) could not be
6//! carried into an action that owns its context. Building the context once and
7//! threading it through a Luxid-owned chain keeps one context per request and
8//! makes mutations visible downstream.
9//!
10//! Middleware and actions share the same `HttpContext` type, so there is one
11//! mental model for the whole framework.
12
13use std::future::Future;
14use std::pin::Pin;
15use std::sync::Arc;
16
17use crate::context::HttpContext;
18use crate::error::Result;
19use crate::http::Response;
20
21pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
22
23/// The terminal step of a chain: a controller action.
24///
25/// Implemented by the zero-sized types `#[luxid::controller]` generates.
26pub trait Action: Send + Sync + 'static {
27    fn call(&self, ctx: HttpContext) -> BoxFuture<'static, Result<Response>>;
28
29    /// What `luxid routes` prints for this action.
30    ///
31    /// `#[luxid::controller]` overrides this with `Controller::action`; the
32    /// default is the generated type's name, which is at least findable.
33    fn name(&self) -> &'static str {
34        std::any::type_name::<Self>()
35    }
36
37    /// What `#[openapi(..)]` recorded, if anything.
38    ///
39    /// The action owns its documentation rather than a global registry owning
40    /// it, so the spec is assembled from the routes that actually exist.
41    fn openapi(&self) -> Option<crate::openapi::Operation> {
42        None
43    }
44}
45
46/// A step in the chain.
47///
48/// Code before `next.run()` runs on the way in, code after runs on the way out,
49/// and returning early short-circuits — so there is no separate before/after
50/// API to learn.
51pub trait Middleware: Send + Sync + 'static {
52    fn handle<'a>(&'a self, ctx: HttpContext, next: Next) -> BoxFuture<'a, Result<Response>>;
53}
54
55/// The remainder of the chain, handed to each middleware.
56pub struct Next {
57    stack: Arc<[Arc<dyn Middleware>]>,
58    index: usize,
59    action: Arc<dyn Action>,
60}
61
62impl Next {
63    pub(crate) fn new(stack: Arc<[Arc<dyn Middleware>]>, action: Arc<dyn Action>) -> Self {
64        Self {
65            stack,
66            index: 0,
67            action,
68        }
69    }
70
71    /// Run the rest of the chain. Recursion terminates in the action.
72    pub async fn run(mut self, ctx: HttpContext) -> Result<Response> {
73        // The type recursion this would otherwise create is broken by the
74        // trait objects, whose futures are already boxed.
75        match self.stack.get(self.index).cloned() {
76            Some(middleware) => {
77                self.index += 1;
78                middleware.handle(ctx, self).await
79            }
80            None => self.action.call(ctx).await,
81        }
82    }
83}
84
85impl std::fmt::Debug for Next {
86    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87        f.debug_struct("Next")
88            .field("remaining", &(self.stack.len().saturating_sub(self.index)))
89            .finish()
90    }
91}