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;
46mod security_headers;
47
48pub use metrics::MetricsMiddleware;
49pub use security_headers::SecurityHeaders;
50
51pub use chain::MiddlewareChain;
52pub use rate_limit::{Limit, LimiterResponse, RateLimiter, Throttle};
53pub use registry::get_global_middleware_info;
54pub use registry::register_global_middleware;
55pub use registry::MiddlewareRegistry;
56
57use crate::http::{Request, Response};
58use async_trait::async_trait;
59use std::future::Future;
60use std::pin::Pin;
61use std::sync::Arc;
62
63/// Type alias for the boxed future returned by middleware
64pub type MiddlewareFuture = Pin<Box<dyn Future<Output = Response> + Send>>;
65
66/// Type alias for the next handler in the middleware chain
67///
68/// Call `next(request).await` to pass control to the next middleware or the route handler.
69pub type Next = Arc<dyn Fn(Request) -> MiddlewareFuture + Send + Sync>;
70
71/// Type alias for boxed middleware handlers (internal use)
72pub type BoxedMiddleware = Arc<dyn Fn(Request, Next) -> MiddlewareFuture + Send + Sync>;
73
74/// Trait for implementing middleware
75///
76/// Middleware can inspect/modify requests, short-circuit responses, or pass control
77/// to the next middleware in the chain by calling `next(request).await`.
78///
79/// # Example
80///
81/// ```rust,ignore
82/// use ferro_rs::{async_trait, Middleware, Next, Request, Response, HttpResponse};
83///
84/// pub struct LoggingMiddleware;
85///
86/// #[async_trait]
87/// impl Middleware for LoggingMiddleware {
88/// async fn handle(&self, request: Request, next: Next) -> Response {
89/// println!("--> {} {}", request.method(), request.path());
90/// let response = next(request).await;
91/// println!("<-- complete");
92/// response
93/// }
94/// }
95/// ```
96#[async_trait]
97pub trait Middleware: Send + Sync {
98 /// Handle the request
99 ///
100 /// - Call `next(request).await` to pass control to the next middleware
101 /// - Return `Err(HttpResponse)` to short-circuit and respond immediately
102 /// - Modify the response after calling `next()` for post-processing
103 async fn handle(&self, request: Request, next: Next) -> Response;
104}
105
106/// Convert a Middleware trait object into a BoxedMiddleware
107pub fn into_boxed<M: Middleware + 'static>(middleware: M) -> BoxedMiddleware {
108 let middleware = Arc::new(middleware);
109 Arc::new(move |req, next| {
110 let mw = middleware.clone();
111 Box::pin(async move { mw.handle(req, next).await })
112 })
113}