ferro_rs/middleware/mod.rs
1//! Middleware system for Ferro framework
2//!
3//! This module provides Laravel 12.x-style middleware support with:
4//! - Global middleware (runs on all routes)
5//! - Route group middleware (shared for a group of routes)
6//! - Per-route middleware (applied to individual routes)
7//! - Rate limiting middleware for API protection
8//!
9//! # Example
10//!
11//! ```rust,ignore
12//! use ferro_rs::{async_trait, Middleware, Next, Request, Response, HttpResponse};
13//!
14//! pub struct AuthMiddleware;
15//!
16//! #[async_trait]
17//! impl Middleware for AuthMiddleware {
18//! async fn handle(&self, request: Request, next: Next) -> Response {
19//! if request.header("Authorization").is_none() {
20//! return Err(HttpResponse::text("Unauthorized").status(401));
21//! }
22//! next(request).await
23//! }
24//! }
25//! ```
26//!
27//! # Rate Limiting
28//!
29//! ```rust,ignore
30//! use ferro::middleware::{RateLimiter, Limit, Throttle};
31//!
32//! // Register named limiter
33//! RateLimiter::define("api", |req| Limit::per_minute(60));
34//!
35//! // Apply to routes
36//! get!("/api/users", handler).middleware(Throttle::named("api"))
37//!
38//! // Inline limit
39//! get!("/health", handler).middleware(Throttle::per_minute(120))
40//! ```
41
42mod chain;
43mod metrics;
44mod rate_limit;
45mod registry;
46
47pub use metrics::MetricsMiddleware;
48
49pub use chain::MiddlewareChain;
50pub use rate_limit::{Limit, LimiterResponse, RateLimiter, Throttle};
51pub use registry::get_global_middleware_info;
52pub use registry::register_global_middleware;
53pub use registry::MiddlewareRegistry;
54
55use crate::http::{Request, Response};
56use async_trait::async_trait;
57use std::future::Future;
58use std::pin::Pin;
59use std::sync::Arc;
60
61/// Type alias for the boxed future returned by middleware
62pub type MiddlewareFuture = Pin<Box<dyn Future<Output = Response> + Send>>;
63
64/// Type alias for the next handler in the middleware chain
65///
66/// Call `next(request).await` to pass control to the next middleware or the route handler.
67pub type Next = Arc<dyn Fn(Request) -> MiddlewareFuture + Send + Sync>;
68
69/// Type alias for boxed middleware handlers (internal use)
70pub type BoxedMiddleware = Arc<dyn Fn(Request, Next) -> MiddlewareFuture + Send + Sync>;
71
72/// Trait for implementing middleware
73///
74/// Middleware can inspect/modify requests, short-circuit responses, or pass control
75/// to the next middleware in the chain by calling `next(request).await`.
76///
77/// # Example
78///
79/// ```rust,ignore
80/// use ferro_rs::{async_trait, Middleware, Next, Request, Response, HttpResponse};
81///
82/// pub struct LoggingMiddleware;
83///
84/// #[async_trait]
85/// impl Middleware for LoggingMiddleware {
86/// async fn handle(&self, request: Request, next: Next) -> Response {
87/// println!("--> {} {}", request.method(), request.path());
88/// let response = next(request).await;
89/// println!("<-- complete");
90/// response
91/// }
92/// }
93/// ```
94#[async_trait]
95pub trait Middleware: Send + Sync {
96 /// Handle the request
97 ///
98 /// - Call `next(request).await` to pass control to the next middleware
99 /// - Return `Err(HttpResponse)` to short-circuit and respond immediately
100 /// - Modify the response after calling `next()` for post-processing
101 async fn handle(&self, request: Request, next: Next) -> Response;
102}
103
104/// Convert a Middleware trait object into a BoxedMiddleware
105pub fn into_boxed<M: Middleware + 'static>(middleware: M) -> BoxedMiddleware {
106 let middleware = Arc::new(middleware);
107 Arc::new(move |req, next| {
108 let mw = middleware.clone();
109 Box::pin(async move { mw.handle(req, next).await })
110 })
111}