Skip to main content

webx_core/
middleware.rs

1//! Middleware trait: IMiddleware.
2
3use crate::error::Result;
4use crate::http::IHttpContext;
5use std::ops::ControlFlow;
6
7/// Where a user middleware runs relative to the framework's built-in stages.
8///
9/// The default for [`HostBuilder::use_middleware`] is [`MiddlewareSlot::AfterAuth`],
10/// so a middleware that reads the authenticated principal (`ctx.claims()`)
11/// actually sees it: authentication runs before the slot. Use
12/// [`MiddlewareSlot::BeforeCors`] only when the middleware must observe requests
13/// that CORS would otherwise short-circuit (e.g. preflight accounting), and
14/// [`MiddlewareSlot::AfterSpa`] for post-static-file hooks.
15///
16/// [`HostBuilder::use_middleware`]: https://docs.rs/rust-webx-host
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum MiddlewareSlot {
19    /// After `RequestId`, before CORS/preflight handling.
20    BeforeCors,
21    /// After authentication, before the SPA static-file middleware (default).
22    AfterAuth,
23    /// After the SPA middleware, immediately before the router.
24    AfterSpa,
25}
26
27/// Middleware component in the HTTP request pipeline.
28///
29/// Middlewares are called in registration order. Each middleware can:
30/// - Inspect/modify the request before passing through
31/// - Short-circuit by returning `ControlFlow::Break(())`
32/// - The pipeline continues to the next middleware on `ControlFlow::Continue(())`
33///
34/// On short-circuit, remaining middleware and the final handler are skipped,
35/// but `after` hooks on already-executed middleware still run in reverse order.
36///
37/// `after` also runs when a middleware's `invoke` or the handler returns an
38/// error: the pipeline unwinds the middleware that already entered, so
39/// metrics, tracing and cleanup never miss a failed request.
40///
41/// Analogous to ASP.NET Core's IMiddleware.
42#[async_trait::async_trait]
43pub trait IMiddleware: Send + Sync {
44    /// Process an HTTP request (before hook).
45    ///
46    /// Return `Ok(ControlFlow::Continue(()))` to continue the pipeline,
47    /// or `Ok(ControlFlow::Break(()))` to short-circuit (skip remaining
48    /// middleware and the final handler; `after` hooks on already-executed
49    /// middleware still run in reverse order).
50    async fn invoke(&self, ctx: &mut dyn IHttpContext) -> Result<ControlFlow<()>>;
51
52    /// Called after the final handler has executed.
53    ///
54    /// Middleware post-processing, logging, response modification.
55    /// Default: no-op.
56    async fn after(&self, _ctx: &mut dyn IHttpContext) -> Result<()> {
57        Ok(())
58    }
59}