wordval-web 1.0.13

Wordval web layer: router, middleware, extractors, responses, session-based authentication
Documentation
use axum::handler::Handler;
use axum::routing::{delete, get, head, options, patch, post, put};
use axum::Router;

/// 路由守卫 —— 注册路由时一并声明的访问策略
///
/// 策略属于路由自身的一部分(与 method/path 同源):启动期由 `App` 从路由元数据
/// 派生认证、权限与审计规则。路径因此只声明一次,改名或经 `group` / `merge`
/// 加前缀后策略随路由一起走,不会出现"规则指向不存在的路径"而静默失去保护。
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RouteGuard {
    /// 所需权限标识(`None` = 不设权限要求)
    pub permission: Option<String>,
    /// 免认证公开路由
    pub public: bool,
    /// 审计动作名(`Some` = 命中该路由时落一条审计记录)
    pub audit: Option<String>,
}

impl RouteGuard {
    /// 要求指定权限
    pub fn permission(permission: impl Into<String>) -> Self {
        Self {
            permission: Some(permission.into()),
            ..Default::default()
        }
    }

    /// 免认证公开路由
    pub fn public() -> Self {
        Self {
            permission: None,
            public: true,
            audit: None,
        }
    }

    /// 需要审计留痕
    pub fn auditing(action: impl Into<String>) -> Self {
        Self {
            audit: Some(action.into()),
            ..Default::default()
        }
    }
}

/// 路由元数据 —— 记录注册的路由方法、路径与守卫策略
#[derive(Debug, Clone)]
pub struct RouteEntry {
    pub method: String,
    pub path: String,
    pub guard: RouteGuard,
}

type RouteBuilder = Box<dyn FnOnce(Router) -> Router + Send>;

/// 路由注册器 —— 延迟构建 axum Router
///
/// 所有路由以闭包形式暂存,调用 `into_axum()` 时一次性构建。
/// 支持合并(`merge`)和嵌套(`nest`)。
pub struct WordvalRouter {
    /// 路由构建闭包列表
    builders: Vec<RouteBuilder>,
    /// 已注册的路由元数据
    routes: Vec<RouteEntry>,
}

impl WordvalRouter {
    /// 创建空的路由注册器
    pub fn new() -> Self {
        Self {
            builders: Vec::new(),
            routes: Vec::new(),
        }
    }

    /// 返回已注册的路由列表
    pub fn list_routes(&self) -> &[RouteEntry] {
        &self.routes
    }

    fn record(&mut self, method: &str, path: &str, guard: RouteGuard) {
        self.routes.push(RouteEntry {
            method: method.to_string(),
            path: path.to_string(),
            guard,
        });
    }

    /// 注册 GET 路由
    pub fn add_get<H, T>(&mut self, path: &str, handler: H)
    where
        H: Handler<T, ()>,
        T: 'static,
    {
        self.add_route("GET", path, handler);
    }

    /// 注册 POST 路由
    pub fn add_post<H, T>(&mut self, path: &str, handler: H)
    where
        H: Handler<T, ()>,
        T: 'static,
    {
        self.add_route("POST", path, handler);
    }

    /// 注册 PUT 路由
    pub fn add_put<H, T>(&mut self, path: &str, handler: H)
    where
        H: Handler<T, ()>,
        T: 'static,
    {
        self.add_route("PUT", path, handler);
    }

    /// 注册 DELETE 路由
    pub fn add_delete<H, T>(&mut self, path: &str, handler: H)
    where
        H: Handler<T, ()>,
        T: 'static,
    {
        self.add_route("DELETE", path, handler);
    }

    /// 注册通用路由(指定 HTTP 方法字符串)
    ///
    /// 支持 axum 全部方法:GET/POST/PUT/PATCH/DELETE/HEAD/OPTIONS,
    /// 未知方法记录 error 且不注册(不做静默方法降级)。
    pub fn add_route<H, T>(&mut self, method: &str, path: &str, handler: H)
    where
        H: Handler<T, ()>,
        T: 'static,
    {
        self.add_route_guarded(method, path, handler, RouteGuard::default());
    }

    /// 注册带守卫策略的路由 —— 路由宏的展开目标
    pub fn add_route_guarded<H, T>(
        &mut self,
        method: &str,
        path: &str,
        handler: H,
        guard: RouteGuard,
    ) where
        H: Handler<T, ()>,
        T: 'static,
    {
        self.add_route_impl(
            method,
            path,
            handler,
            guard,
            None::<fn(axum::routing::MethodRouter<()>) -> axum::routing::MethodRouter<()>>,
        );
    }

    /// 注册带 `tower::Layer` 的通用路由(指定 HTTP 方法字符串)
    ///
    /// 仅用于无法表达成守卫的路由级拦截(如角色);权限请用 `RouteGuard::permission`。
    pub fn add_route_with_layer<H, T>(
        &mut self,
        method: &str,
        path: &str,
        handler: H,
        wrap: impl FnOnce(axum::routing::MethodRouter<()>) -> axum::routing::MethodRouter<()>
            + Send
            + 'static,
    ) where
        H: Handler<T, ()>,
        T: 'static,
    {
        self.add_route_impl(method, path, handler, RouteGuard::default(), Some(wrap));
    }

    fn add_route_impl<H, T>(
        &mut self,
        method: &str,
        path: &str,
        handler: H,
        guard: RouteGuard,
        wrap: Option<
            impl FnOnce(axum::routing::MethodRouter<()>) -> axum::routing::MethodRouter<()>
                + Send
                + 'static,
        >,
    ) where
        H: Handler<T, ()>,
        T: 'static,
    {
        let method = method.to_uppercase();
        // 未知方法记录错误且不注册(不做静默方法降级),路由元数据也不记录,
        // 保证 list_routes() 输出的就是真正生效的路由
        if !matches!(
            method.as_str(),
            "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS"
        ) {
            tracing::error!("不支持的路由方法 '{}',路由 {} 未注册", method, path);
            return;
        }
        self.record(&method, path, guard);
        let path = path.to_string();
        self.builders.push(Box::new(move |r| {
            let router = match method.as_str() {
                "GET" => get(handler),
                "POST" => post(handler),
                "PUT" => put(handler),
                "PATCH" => patch(handler),
                "DELETE" => delete(handler),
                "HEAD" => head(handler),
                "OPTIONS" => options(handler),
                // 已在上方校验,理论上不可达
                _ => return r,
            };
            let router = match wrap {
                Some(w) => w(router),
                None => router,
            };
            r.route(&path, router)
        }));
    }

    /// 合并子路由注册器(嵌套到指定前缀下)
    ///
    /// 前缀与路由路径统一用 `join_route_path` 的规范形式写入元数据(自动补 `/`),
    /// 带不带首尾斜杠结果一致,`nest` 也不会因前缀缺 `/` 而 panic。
    pub fn merge(&mut self, prefix: &str, sub: WordvalRouter) {
        let prefix = prefix.trim_matches('/');
        for r in &sub.routes {
            self.record(
                &r.method,
                &crate::middleware::auth::join_route_path(prefix, &r.path),
                r.guard.clone(),
            );
        }
        let nested = format!("/{prefix}");
        self.builders
            .push(Box::new(move |r| r.nest(&nested, sub.into_axum())));
    }

    /// 消耗注册器,构建最终的 axum Router
    pub fn into_axum(self) -> Router {
        self.builders.into_iter().fold(Router::new(), |r, f| f(r))
    }
}

impl Default for WordvalRouter {
    fn default() -> Self {
        Self::new()
    }
}