use axum::Router;
pub struct MiddlewareEntry {
pub name: String,
pub priority: i32,
pub apply: Box<dyn FnOnce(Router) -> Router + Send>,
}
impl MiddlewareEntry {
pub fn new(
name: impl Into<String>,
priority: i32,
apply: impl FnOnce(Router) -> Router + Send + 'static,
) -> Self {
Self {
name: name.into(),
priority,
apply: Box::new(apply),
}
}
}
pub mod priorities {
pub const REQUEST_ID: i32 = 0;
pub const CLIENT_IDENTITY: i32 = 10;
pub const REQUEST_LOG: i32 = 20;
pub const SECURITY_HEADERS: i32 = 30;
pub const CORS: i32 = 40;
pub const COMPRESSION: i32 = 50;
pub const BODY_LIMIT: i32 = 55;
pub const RATE_LIMIT: i32 = 60;
pub const SESSION_RESOLVER: i32 = 70;
pub const TENANT_CONTEXT: i32 = 80;
pub const AUDIT: i32 = 85;
pub const REQUIRE_AUTH: i32 = 90;
pub const PERMISSION_CHECK: i32 = 100;
pub const NONCE: i32 = 110;
}
pub fn apply_chain(mut router: Router, mut entries: Vec<MiddlewareEntry>) -> (Router, Vec<String>) {
entries.sort_by_key(|e| e.priority);
let order: Vec<String> = entries
.iter()
.map(|e| format!("{}({})", e.name, e.priority))
.collect();
for entry in entries.into_iter().rev() {
router = (entry.apply)(router);
}
(router, order)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn chain_applies_smaller_priority_outermost() {
use std::sync::{Arc, Mutex};
let order: Arc<Mutex<Vec<&'static str>>> = Arc::new(Mutex::new(Vec::new()));
let mk = |name: &'static str, priority: i32| {
let order = order.clone();
MiddlewareEntry::new(name, priority, move |r: Router| {
let o = order.clone();
r.layer(axum::middleware::from_fn(
move |req: axum::extract::Request, next: axum::middleware::Next| {
let o = o.clone();
async move {
o.lock().unwrap().push(name);
next.run(req).await
}
},
))
})
};
let entries = vec![mk("inner", 900), mk("outer", 0), mk("mid", 500)];
let (router, names) = apply_chain(Router::new(), entries);
assert_eq!(names, vec!["outer(0)", "mid(500)", "inner(900)"]);
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
rt.block_on(async {
use tower::ServiceExt;
let req = axum::http::Request::builder()
.uri("/")
.body(axum::body::Body::empty())
.unwrap();
let _ = router.oneshot(req).await.unwrap();
});
assert_eq!(*order.lock().unwrap(), vec!["outer", "mid", "inner"]);
}
#[test]
fn same_priority_keeps_registration_order() {
let entries = vec![
MiddlewareEntry::new("a", 100, |r| r),
MiddlewareEntry::new("b", 100, |r| r),
MiddlewareEntry::new("c", 50, |r| r),
];
let (_router, names) = apply_chain(Router::new(), entries);
assert_eq!(names, vec!["c(50)", "a(100)", "b(100)"]);
}
}