Skip to main content

rws_server/middleware/
mod.rs

1//! Composable middleware pipeline.
2//!
3//! [`Middleware`] is a single layer that wraps request dispatch. Implement it
4//! to add cross-cutting behaviour — logging, authentication, rate limiting,
5//! header injection — without editing the inner application.
6//!
7//! [`WithMiddleware`] stacks one or more middleware layers around any
8//! [`Application`]. Layers run in registration order on the way in and in
9//! reverse order on the way out.
10//!
11//! # Example
12//!
13//! ```rust,no_run
14//! # extern crate rws_server as rust_web_server;
15//! use rust_web_server::middleware::{Middleware, WithMiddleware};
16//! use rust_web_server::application::Application;
17//! use rust_web_server::request::Request;
18//! use rust_web_server::response::Response;
19//! use rust_web_server::server::ConnectionInfo;
20//! use rust_web_server::app::App;
21//! use rust_web_server::core::New;
22//!
23//! pub struct LoggingMiddleware;
24//!
25//! impl Middleware for LoggingMiddleware {
26//!     fn handle(
27//!         &self,
28//!         request: &Request,
29//!         connection: &ConnectionInfo,
30//!         next: &dyn Application,
31//!     ) -> Result<Response, String> {
32//!         println!("{} {}", request.method, request.request_uri);
33//!         let response = next.execute(request, connection)?;
34//!         println!("  → {}", response.status_code);
35//!         Ok(response)
36//!     }
37//! }
38//!
39//! let app = WithMiddleware::new(App::new())
40//!     .wrap(LoggingMiddleware);
41//! ```
42
43#[cfg(test)]
44mod tests;
45
46use std::sync::Arc;
47
48use crate::application::Application;
49use crate::request::Request;
50use crate::response::Response;
51use crate::header::Header;
52use crate::server::ConnectionInfo;
53
54/// Built-in middleware that enforces the process-wide rate limit
55/// (configured via `RWS_CONFIG_RATE_LIMIT_MAX_REQUESTS` and
56/// `RWS_CONFIG_RATE_LIMIT_WINDOW_SECS`).
57///
58/// Returns `429 Too Many Requests` when the sliding-window budget for the
59/// client IP is exhausted; otherwise passes the request to the next layer.
60///
61/// # Example
62///
63/// ```rust,no_run
64/// # extern crate rws_server as rust_web_server;
65/// use rust_web_server::app::App;
66/// use rust_web_server::middleware::{WithMiddleware, RateLimitLayer};
67/// use rust_web_server::core::New;
68///
69/// let app = App::new().wrap(RateLimitLayer);
70/// ```
71pub struct RateLimitLayer;
72
73impl Middleware for RateLimitLayer {
74    /// Headers only: a streamed body passes through untouched.
75    fn accepts_streamed_body(&self, _request: &Request, _connection: &ConnectionInfo) -> bool {
76        true
77    }
78
79
80    fn handle(
81        &self,
82        request: &Request,
83        connection: &ConnectionInfo,
84        next: &dyn Application,
85    ) -> Result<Response, String> {
86        use crate::error::{AppError, IntoResponse};
87        if crate::rate_limit::global().check(&connection.client.ip) {
88            next.execute(request, connection)
89        } else {
90            let mut response = AppError::TooManyRequests.into_response();
91            let retry_after = crate::rate_limit::global().retry_after(&connection.client.ip);
92            response.headers.push(Header {
93                name: Header::_RETRY_AFTER.into(),
94                value: retry_after.to_string().into(),
95            });
96            Ok(response)
97        }
98    }
99
100    /// In-memory only: safe on the event loop.
101    fn runs_inline(&self, _request: &Request, _connection: &ConnectionInfo) -> bool {
102        true
103    }
104}
105
106/// A single middleware layer.
107///
108/// Receive the request, call `next.execute(request, connection)` to pass
109/// control to the next layer (or the inner application), and optionally
110/// inspect or transform the resulting response.
111///
112/// Short-circuit by returning a `Response` (or `Err`) without calling `next`.
113pub trait Middleware: Send + Sync {
114    fn handle(
115        &self,
116        request: &Request,
117        connection: &ConnectionInfo,
118        next: &dyn Application,
119    ) -> Result<Response, String>;
120
121    /// `true` when this layer's own work for `request` never blocks (in-memory
122    /// state, atomics, short mutexes) — see [`Application::runs_inline`]. A
123    /// [`WithMiddleware`] stack runs inline only if every layer and the inner
124    /// application agree. Default `false`.
125    fn runs_inline(&self, _request: &Request, _connection: &ConnectionInfo) -> bool {
126        false
127    }
128
129    /// `true` when `handle` would do nothing for `request` but call `next`
130    /// (e.g. a rate limit that isn't configured). A [`WithMiddleware`] stack
131    /// offers the inner application's `execute_async` only if every layer
132    /// passes the request through. Default `false`.
133    fn is_passthrough(&self, _request: &Request, _connection: &ConnectionInfo) -> bool {
134        false
135    }
136
137    /// `true` when this layer never reads `request.body`, so the inner
138    /// application may receive it as a stream ([`Application::streams_body`]).
139    /// A layer that inspects the body (CSRF tokens in a form, request
140    /// signatures, rewriting) must keep the default `false`: it would see an
141    /// empty body.
142    fn accepts_streamed_body(&self, _request: &Request, _connection: &ConnectionInfo) -> bool {
143        false
144    }
145
146    /// `true` when this layer answers `request` itself — it doesn't call
147    /// `next` — and reads its body as a stream (a proxy forwarding it as it
148    /// arrives). The body is then streamed whatever the layers after it and
149    /// the application would say. Requires `accepts_streamed_body`. Since
150    /// 18.3.0.
151    fn answers_streamed_body(&self, _request: &Request, _connection: &ConnectionInfo) -> bool {
152        false
153    }
154}
155
156/// An [`Application`] that applies a stack of [`Middleware`] layers before
157/// dispatching to an inner application.
158///
159/// Layers are applied in registration order: the first `.wrap()`ed middleware
160/// runs first on the request path and last on the response path.
161pub struct WithMiddleware<A> {
162    inner: A,
163    /// Built once; shared by every clone (the servers clone the app per
164    /// request, so a `Vec` here was an allocation per request).
165    layers: Arc<[Arc<dyn Middleware>]>,
166}
167
168impl<A: Application> WithMiddleware<A> {
169    /// Wrap `app` with no initial middleware.
170    pub fn new(app: A) -> Self {
171        WithMiddleware { inner: app, layers: Arc::new([]) }
172    }
173
174    /// Add a middleware layer. Layers run in registration order.
175    pub fn wrap(mut self, layer: impl Middleware + 'static) -> Self {
176        let mut layers = self.layers.to_vec();
177        layers.push(Arc::new(layer));
178        self.layers = layers.into();
179        self
180    }
181}
182
183impl<A: Application + Send + Sync + Clone + 'static> WithMiddleware<A> {
184    /// Attach an MCP server that handles `POST /mcp`; all other requests fall
185    /// through to this middleware stack.
186    pub fn mcp(self, name: impl Into<String>, version: impl Into<String>) -> crate::mcp::McpServer {
187        crate::mcp::McpServer::new(name, version).wrap(self)
188    }
189}
190
191impl<A: Clone> Clone for WithMiddleware<A> {
192    fn clone(&self) -> Self {
193        WithMiddleware { inner: self.inner.clone(), layers: Arc::clone(&self.layers) }
194    }
195}
196
197impl<A: Application> Application for WithMiddleware<A> {
198    fn execute(&self, request: &Request, connection: &ConnectionInfo) -> Result<Response, String> {
199        Chain { app: &self.inner, layers: &self.layers, index: 0 }.execute(request, connection)
200    }
201
202    fn runs_inline(&self, request: &Request, connection: &ConnectionInfo) -> bool {
203        self.layers.iter().all(|l| l.runs_inline(request, connection)) && self.inner.runs_inline(request, connection)
204    }
205
206    #[cfg(feature = "http2")]
207    fn execute_async<'a>(&'a self, request: &'a Request, connection: &'a ConnectionInfo) -> Option<crate::application::AsyncResponse<'a>> {
208        if self.layers.iter().all(|l| l.is_passthrough(request, connection)) {
209            self.inner.execute_async(request, connection)
210        } else {
211            None
212        }
213    }
214    fn streams_body(&self, request: &Request, connection: &ConnectionInfo) -> bool {
215        for layer in self.layers.iter() {
216            if !layer.accepts_streamed_body(request, connection) {
217                return false;
218            }
219            if layer.answers_streamed_body(request, connection) {
220                return true;
221            }
222        }
223        self.inner.streams_body(request, connection)
224    }
225}
226
227// Internal chain that carries the remaining layers and the final app.
228struct Chain<'a> {
229    app: &'a dyn Application,
230    layers: &'a [Arc<dyn Middleware>],
231    index: usize,
232}
233
234impl<'a> Application for Chain<'a> {
235    fn execute(&self, request: &Request, connection: &ConnectionInfo) -> Result<Response, String> {
236        if self.index < self.layers.len() {
237            let next = Chain { app: self.app, layers: self.layers, index: self.index + 1 };
238            self.layers[self.index].handle(request, connection, &next)
239        } else {
240            self.app.execute(request, connection)
241        }
242    }
243}