use super::{into_boxed, BoxedMiddleware, Middleware};
use std::sync::{OnceLock, RwLock};
static GLOBAL_MIDDLEWARE: OnceLock<RwLock<Vec<BoxedMiddleware>>> = OnceLock::new();
static GLOBAL_MIDDLEWARE_NAMES: OnceLock<RwLock<Vec<String>>> = OnceLock::new();
pub fn register_global_middleware<M: Middleware + 'static>(middleware: M) {
let type_name = std::any::type_name::<M>();
let short_name = type_name.rsplit("::").next().unwrap_or(type_name);
let names_registry = GLOBAL_MIDDLEWARE_NAMES.get_or_init(|| RwLock::new(Vec::new()));
if let Ok(mut names) = names_registry.write() {
names.push(short_name.to_string());
}
let registry = GLOBAL_MIDDLEWARE.get_or_init(|| RwLock::new(Vec::new()));
if let Ok(mut vec) = registry.write() {
vec.push(into_boxed(middleware));
}
}
pub fn get_global_middleware_info() -> Vec<String> {
GLOBAL_MIDDLEWARE_NAMES
.get()
.and_then(|lock| lock.read().ok())
.map(|vec| vec.clone())
.unwrap_or_default()
}
pub fn get_global_middleware() -> Vec<BoxedMiddleware> {
GLOBAL_MIDDLEWARE
.get()
.and_then(|lock| lock.read().ok())
.map(|vec| vec.clone())
.unwrap_or_default()
}
pub struct MiddlewareRegistry {
global: Vec<BoxedMiddleware>,
}
impl MiddlewareRegistry {
pub fn new() -> Self {
Self { global: Vec::new() }
}
pub fn from_global() -> Self {
Self {
global: get_global_middleware(),
}
}
pub fn append<M: Middleware + 'static>(mut self, middleware: M) -> Self {
self.global.push(into_boxed(middleware));
self
}
pub fn global_middleware(&self) -> &[BoxedMiddleware] {
&self.global
}
}
impl Default for MiddlewareRegistry {
fn default() -> Self {
Self::new()
}
}