1use crate::handler::{BoxFuture, Handler};
2use crate::request::Request;
3use crate::response::Response;
4use std::future::Future;
5use std::sync::Arc;
6
7pub type Next = Box<dyn FnOnce(Request) -> BoxFuture<Response> + Send>;
9
10pub type Middleware = Arc<dyn Fn(Request, Next) -> BoxFuture<Response> + Send + Sync>;
12
13#[derive(Clone)]
15pub struct MwEntry {
16 pub name: String,
17 pub mw: Middleware,
18}
19
20pub fn named(name: impl Into<String>, mw: impl IntoMiddleware) -> MwEntry {
22 MwEntry {
23 name: name.into(),
24 mw: mw.into_middleware(),
25 }
26}
27
28pub(crate) fn abbreviate_type_name(full: &str) -> String {
29 let trimmed = full
30 .trim_end_matches(">::{{closure}}")
31 .trim_end_matches("::{{closure}}")
32 .trim_end_matches("{{closure}}");
33 let base = trimmed.rsplit("::").next().unwrap_or(trimmed);
34 if base.is_empty() || base == "{{closure}}" {
35 "closure".into()
36 } else {
37 base.to_string()
38 }
39}
40
41pub trait IntoMiddleware {
42 fn into_middleware(self) -> Middleware;
43}
44
45pub trait IntoMwEntry {
47 fn into_mw_entry(self) -> MwEntry;
48}
49
50impl<F, Fut> IntoMiddleware for F
51where
52 F: Fn(Request, Next) -> Fut + Send + Sync + 'static,
53 Fut: Future<Output = Response> + Send + 'static,
54{
55 fn into_middleware(self) -> Middleware {
56 Arc::new(move |req, next| Box::pin(self(req, next)))
57 }
58}
59
60impl IntoMiddleware for Middleware {
61 fn into_middleware(self) -> Middleware {
62 self
63 }
64}
65
66impl IntoMwEntry for MwEntry {
67 fn into_mw_entry(self) -> MwEntry {
68 self
69 }
70}
71
72impl IntoMwEntry for Middleware {
73 fn into_mw_entry(self) -> MwEntry {
74 MwEntry {
75 name: "mw".into(),
76 mw: self,
77 }
78 }
79}
80
81impl<F, Fut> IntoMwEntry for F
82where
83 F: Fn(Request, Next) -> Fut + Send + Sync + 'static,
84 Fut: Future<Output = Response> + Send + 'static,
85{
86 fn into_mw_entry(self) -> MwEntry {
87 MwEntry {
88 name: abbreviate_type_name(std::any::type_name::<F>()),
89 mw: self.into_middleware(),
90 }
91 }
92}
93
94pub fn with_state<S, F, Fut>(state: S, f: F) -> Middleware
100where
101 S: Send + Sync + 'static,
102 F: Fn(Arc<S>, Request, Next) -> Fut + Send + Sync + 'static,
103 Fut: Future<Output = Response> + Send + 'static,
104{
105 let state = Arc::new(state);
106 Arc::new(move |req, next| Box::pin(f(Arc::clone(&state), req, next)))
107}
108
109pub fn with_leaked<S, F, Fut>(state: S, f: F) -> Middleware
114where
115 S: Send + Sync + 'static,
116 F: Fn(&'static S, Request, Next) -> Fut + Send + Sync + 'static,
117 Fut: Future<Output = Response> + Send + 'static,
118{
119 let state: &'static S = Box::leak(Box::new(state));
120 Arc::new(move |req, next| Box::pin(f(state, req, next)))
121}
122
123pub fn before<F, Fut>(name: impl Into<String>, f: F) -> MwEntry
125where
126 F: Fn(Request) -> Fut + Send + Sync + 'static,
127 Fut: Future<Output = Request> + Send + 'static,
128{
129 let f = Arc::new(f);
130 named(name, move |req, next: Next| {
131 let f = Arc::clone(&f);
132 async move {
133 let req = f(req).await;
134 next(req).await
135 }
136 })
137}
138
139pub fn after<F, Fut>(name: impl Into<String>, f: F) -> MwEntry
141where
142 F: Fn(Response) -> Fut + Send + Sync + 'static,
143 Fut: Future<Output = Response> + Send + 'static,
144{
145 let f = Arc::new(f);
146 named(name, move |req, next: Next| {
147 let f = Arc::clone(&f);
148 async move {
149 let res = next(req).await;
150 f(res).await
151 }
152 })
153}
154
155pub fn around<B, BF, A, AF>(name: impl Into<String>, before_fn: B, after_fn: A) -> MwEntry
157where
158 B: Fn(Request) -> BF + Send + Sync + 'static,
159 BF: Future<Output = Request> + Send + 'static,
160 A: Fn(Response) -> AF + Send + Sync + 'static,
161 AF: Future<Output = Response> + Send + 'static,
162{
163 let before_fn = Arc::new(before_fn);
164 let after_fn = Arc::new(after_fn);
165 named(name, move |req, next: Next| {
166 let before_fn = Arc::clone(&before_fn);
167 let after_fn = Arc::clone(&after_fn);
168 async move {
169 let req = before_fn(req).await;
170 let res = next(req).await;
171 after_fn(res).await
172 }
173 })
174}
175
176pub fn map_html<F>(name: impl Into<String>, transform: F) -> MwEntry
180where
181 F: Fn(&str) -> Option<String> + Send + Sync + 'static,
182{
183 let transform = Arc::new(transform);
184 after(name, move |mut res| {
185 let transform = Arc::clone(&transform);
186 async move {
187 res.map_buffered_html(|html| transform(html));
188 res
189 }
190 })
191}
192
193pub fn build_chain(middleware: &[Middleware], handler: Handler) -> Handler {
195 let mut next = handler;
196
197 for mw in middleware.iter().rev() {
198 let mw = Arc::clone(mw);
199 let inner = next;
200 next = Arc::new(move |req| {
201 let inner = Arc::clone(&inner);
202 let mw = Arc::clone(&mw);
203 mw(
204 req,
205 Box::new(move |r| {
206 let inner = Arc::clone(&inner);
207 inner(r)
208 }),
209 )
210 });
211 }
212
213 next
214}
215
216pub(crate) fn chain_from_entries(entries: &[MwEntry], handler: Handler) -> Handler {
217 let mws: Vec<Middleware> = entries.iter().map(|e| Arc::clone(&e.mw)).collect();
218 build_chain(&mws, handler)
219}
220
221pub fn logger() -> MwEntry {
224 named("logger", |req: Request, next: Next| async move {
225 let method = req.method.as_str().to_string();
226 let path = req.path.clone();
227 let quiet = logger_should_skip(&path);
228 let request_id = req
229 .get::<crate::request_id::RequestId>()
230 .map(|r| r.0.clone())
231 .unwrap_or_default();
232 let start = std::time::Instant::now();
233 let res = next(req).await;
234 if quiet {
235 return res;
236 }
237 let status = res.status_code().as_u16();
238 let latency_ms = start.elapsed().as_millis() as u64;
239 if request_id.is_empty() {
240 tracing::info!(
241 method = %method,
242 path = %path,
243 status,
244 latency_ms,
245 "request"
246 );
247 } else {
248 tracing::info!(
249 request_id = %request_id,
250 method = %method,
251 path = %path,
252 status,
253 latency_ms,
254 "request"
255 );
256 }
257 res
258 })
259}
260
261static LOGGER_SKIP_PREFIXES: std::sync::OnceLock<std::sync::Mutex<Vec<String>>> =
262 std::sync::OnceLock::new();
263
264fn logger_skip_list() -> &'static std::sync::Mutex<Vec<String>> {
265 LOGGER_SKIP_PREFIXES.get_or_init(|| {
266 std::sync::Mutex::new(vec!["/favicon.ico".into()])
268 })
269}
270
271pub fn logger_skip_path(prefix: impl Into<String>) {
274 let p = prefix.into();
275 if p.is_empty() {
276 return;
277 }
278 let mut g = logger_skip_list().lock().unwrap();
279 if !g.iter().any(|x| x == &p) {
280 g.push(p);
281 }
282}
283
284pub fn logger_skip_paths(prefixes: impl IntoIterator<Item = impl Into<String>>) {
286 for p in prefixes {
287 logger_skip_path(p);
288 }
289}
290
291pub fn logger_should_skip(path: &str) -> bool {
293 let g = logger_skip_list().lock().unwrap();
294 g.iter()
295 .any(|p| path == p.as_str() || path.starts_with(&format!("{p}/")))
296}
297
298#[cfg(any(test, feature = "testing"))]
299pub fn logger_clear_skip_paths() {
300 *logger_skip_list().lock().unwrap() = vec!["/favicon.ico".into()];
301}
302
303#[cfg(test)]
304mod tests {
305 use super::*;
306 use http::Method;
307
308 fn ok_handler() -> Handler {
309 Arc::new(|_req: Request| Box::pin(async { Response::text("ok") }))
310 }
311
312 #[tokio::test]
313 async fn onion_order() {
314 let leaf = ok_handler();
315 let outer = |req: Request, next: Next| async move {
316 let mut res = next(req).await;
317 res = res.header("x-outer", "1");
318 res
319 };
320 let inner = |req: Request, next: Next| async move {
321 let mut res = next(req).await;
322 res = res.header("x-inner", "1");
323 res
324 };
325 let chain = build_chain(
326 &[outer.into_middleware(), inner.into_middleware()],
327 leaf,
328 );
329 let res = chain(Request::new(Method::GET, "/")).await;
330 assert_eq!(res.body_bytes(), Some(b"ok".as_slice()));
331 assert_eq!(res.headers.get("x-outer").map(|v| v.to_str().unwrap()), Some("1"));
332 assert_eq!(res.headers.get("x-inner").map(|v| v.to_str().unwrap()), Some("1"));
333 }
334
335 #[tokio::test]
336 async fn with_state_runs() {
337 let leaf = ok_handler();
338 let mw = with_state(7u32, |n, req, next| async move {
339 assert_eq!(*n, 7);
340 next(req).await
341 });
342 let chain = build_chain(&[mw], leaf);
343 assert_eq!(
344 chain(Request::new(Method::GET, "/")).await.body_bytes(),
345 Some(b"ok".as_slice())
346 );
347 }
348
349 #[test]
350 fn logger_skip_favicon_by_default() {
351 logger_clear_skip_paths();
352 assert!(logger_should_skip("/favicon.ico"));
353 assert!(!logger_should_skip("/favicon"));
354 logger_clear_skip_paths();
355 }
356
357 #[test]
358 fn logger_skip_matches_prefixes() {
359 logger_clear_skip_paths();
360 logger_skip_path("/_devtools");
361 logger_skip_path("/healthz");
362 assert!(logger_should_skip("/_devtools"));
363 assert!(logger_should_skip("/_devtools/config"));
364 assert!(logger_should_skip("/_devtools/requests/dt-1"));
365 assert!(logger_should_skip("/healthz"));
366 assert!(!logger_should_skip("/api/users"));
367 assert!(!logger_should_skip("/health"));
368 logger_clear_skip_paths();
369 }
370
371 #[test]
372 fn abbreviate_closure() {
373 let n = abbreviate_type_name("foo::bar::{{closure}}");
374 assert_eq!(n, "bar");
375 }
376}