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 let ip = crate::ip_filter::client_ip(request, &connection.client.ip);
88 if crate::rate_limit::global().check(&ip) {
89 next.execute(request, connection)
90 } else {
91 let mut response = AppError::TooManyRequests.into_response();
92 let retry_after = crate::rate_limit::global().retry_after(&ip);
93 response.headers.push(Header {
94 name: Header::_RETRY_AFTER.into(),
95 value: retry_after.to_string().into(),
96 });
97 Ok(response)
98 }
99 }
100
101 /// In-memory only: safe on the event loop.
102 fn runs_inline(&self, _request: &Request, _connection: &ConnectionInfo) -> bool {
103 true
104 }
105}
106
107/// A single middleware layer.
108///
109/// Receive the request, call `next.execute(request, connection)` to pass
110/// control to the next layer (or the inner application), and optionally
111/// inspect or transform the resulting response.
112///
113/// Short-circuit by returning a `Response` (or `Err`) without calling `next`.
114pub trait Middleware: Send + Sync {
115 fn handle(
116 &self,
117 request: &Request,
118 connection: &ConnectionInfo,
119 next: &dyn Application,
120 ) -> Result<Response, String>;
121
122 /// `true` when this layer's own work for `request` never blocks (in-memory
123 /// state, atomics, short mutexes) — see [`Application::runs_inline`]. A
124 /// [`WithMiddleware`] stack runs inline only if every layer and the inner
125 /// application agree. Default `false`.
126 fn runs_inline(&self, _request: &Request, _connection: &ConnectionInfo) -> bool {
127 false
128 }
129
130 /// `true` when `handle` would do nothing for `request` but call `next`
131 /// (e.g. a rate limit that isn't configured). A [`WithMiddleware`] stack
132 /// offers the inner application's `execute_async` only if every layer
133 /// passes the request through. Default `false`.
134 fn is_passthrough(&self, _request: &Request, _connection: &ConnectionInfo) -> bool {
135 false
136 }
137
138 /// `true` when this layer never reads `request.body`, so the inner
139 /// application may receive it as a stream ([`Application::streams_body`]).
140 /// A layer that inspects the body (CSRF tokens in a form, request
141 /// signatures, rewriting) must keep the default `false`: it would see an
142 /// empty body.
143 fn accepts_streamed_body(&self, _request: &Request, _connection: &ConnectionInfo) -> bool {
144 false
145 }
146
147 /// `true` when this layer answers `request` itself — it doesn't call
148 /// `next` — and reads its body as a stream (a proxy forwarding it as it
149 /// arrives). The body is then streamed whatever the layers after it and
150 /// the application would say. Requires `accepts_streamed_body`. Since
151 /// 18.3.0.
152 fn answers_streamed_body(&self, _request: &Request, _connection: &ConnectionInfo) -> bool {
153 false
154 }
155}
156
157/// An [`Application`] that applies a stack of [`Middleware`] layers before
158/// dispatching to an inner application.
159///
160/// Layers are applied in registration order: the first `.wrap()`ed middleware
161/// runs first on the request path and last on the response path.
162pub struct WithMiddleware<A> {
163 inner: A,
164 /// Built once; shared by every clone (the servers clone the app per
165 /// request, so a `Vec` here was an allocation per request).
166 layers: Arc<[Arc<dyn Middleware>]>,
167}
168
169impl<A: Application> WithMiddleware<A> {
170 /// Wrap `app` with no initial middleware.
171 pub fn new(app: A) -> Self {
172 WithMiddleware { inner: app, layers: Arc::new([]) }
173 }
174
175 /// Add a middleware layer. Layers run in registration order.
176 pub fn wrap(mut self, layer: impl Middleware + 'static) -> Self {
177 let mut layers = self.layers.to_vec();
178 layers.push(Arc::new(layer));
179 self.layers = layers.into();
180 self
181 }
182}
183
184impl<A: Application + Send + Sync + Clone + 'static> WithMiddleware<A> {
185 /// Attach an MCP server that handles `POST /mcp`; all other requests fall
186 /// through to this middleware stack.
187 pub fn mcp(self, name: impl Into<String>, version: impl Into<String>) -> crate::mcp::McpServer {
188 crate::mcp::McpServer::new(name, version).wrap(self)
189 }
190}
191
192impl<A: Clone> Clone for WithMiddleware<A> {
193 fn clone(&self) -> Self {
194 WithMiddleware { inner: self.inner.clone(), layers: Arc::clone(&self.layers) }
195 }
196}
197
198impl<A: Application> Application for WithMiddleware<A> {
199 fn execute(&self, request: &Request, connection: &ConnectionInfo) -> Result<Response, String> {
200 Chain { app: &self.inner, layers: &self.layers, index: 0 }.execute(request, connection)
201 }
202
203 fn runs_inline(&self, request: &Request, connection: &ConnectionInfo) -> bool {
204 self.layers.iter().all(|l| l.runs_inline(request, connection)) && self.inner.runs_inline(request, connection)
205 }
206
207 #[cfg(feature = "http2")]
208 fn execute_async<'a>(&'a self, request: &'a Request, connection: &'a ConnectionInfo) -> Option<crate::application::AsyncResponse<'a>> {
209 if self.layers.iter().all(|l| l.is_passthrough(request, connection)) {
210 self.inner.execute_async(request, connection)
211 } else {
212 None
213 }
214 }
215 fn streams_body(&self, request: &Request, connection: &ConnectionInfo) -> bool {
216 for layer in self.layers.iter() {
217 if !layer.accepts_streamed_body(request, connection) {
218 return false;
219 }
220 if layer.answers_streamed_body(request, connection) {
221 return true;
222 }
223 }
224 self.inner.streams_body(request, connection)
225 }
226}
227
228// Internal chain that carries the remaining layers and the final app.
229struct Chain<'a> {
230 app: &'a dyn Application,
231 layers: &'a [Arc<dyn Middleware>],
232 index: usize,
233}
234
235impl<'a> Application for Chain<'a> {
236 fn execute(&self, request: &Request, connection: &ConnectionInfo) -> Result<Response, String> {
237 if self.index < self.layers.len() {
238 let next = Chain { app: self.app, layers: self.layers, index: self.index + 1 };
239 self.layers[self.index].handle(request, connection, &next)
240 } else {
241 self.app.execute(request, connection)
242 }
243 }
244}