yang-base 0.1.2

个人使用构建后端服务器
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
//! ModuleRouter - 模块路由器
//!
//! 管理单个模块的表配置和 Action 路由,负责 Action 的注册、查找和分发。
//!
//! # 示例
//!
//! ```rust,ignore
//! use yang_base::router::ModuleRouter;
//! use yang_base::table::{TableConfig, FieldConfig, FieldType};
//! use std::sync::Arc;
//!
//! // 创建表配置
//! let table_config = Arc::new(
//!     TableConfig::new("users")
//!         .field(FieldConfig::new("id", FieldType::Integer))
//!         .field(FieldConfig::new("username", FieldType::String { max_length: 50 }))
//! );
//!
//! // 创建模块路由器并注册内置 CRUD Actions
//! let router = ModuleRouter::new("user", "用户管理")
//!     .with_table_config(table_config.clone())
//!     .default_permissions(vec!["user:access".to_string()])
//!     .table_typed::<User>()?;
//!
//! // 分发请求
//! let response = router.dispatch("add", context).await?;
//! ```

/// 内置 Action 名称常量
///
/// 包含所有内置 Action 的名称,用于注册和验证
pub const BUILTIN_ACTION_NAMES: &[&str] = &["add", "put", "del", "get", "select", "table"];

use crate::action::{ActionContext, ApiResponse, DynAction, PermissionMode, User};
use crate::error::BaseError;
use crate::router::catalog::{ActionDescriptor, ModuleDescriptor, RouteDescriptor};
use crate::router::middleware::{Middleware, Next};
use crate::table::TableConfig;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use tracing::Instrument;

/// ModuleRouter - 模块路由器
///
/// 管理单个模块的表配置和 Action 路由。
///
/// # 字段
///
/// - `module_name`: 模块名称
/// - `display_name`: 模块显示名称
/// - `table_config`: 表配置(可选)
/// - `actions`: Action 注册表
/// - `default_permissions`: 默认权限要求
#[must_use = "builder 返回新实例,忽略将丢失配置"]
pub struct ModuleRouter {
    /// 模块名称
    module_name: String,

    /// 模块显示名称
    display_name: String,

    /// 表配置(如果模块关联表)
    table_config: Option<Arc<TableConfig>>,

    /// Action 注册表
    /// Key: action 名称, Value: 类型化擦除后的 DynAction 实例
    actions: HashMap<String, Arc<dyn DynAction>>,

    /// Action 名称到传输路由的只读描述源。
    routes: HashMap<String, RouteDescriptor>,

    /// 默认权限要求
    /// 所有 Action 都需要满足这些权限(除非 Action 是公开的)
    default_permissions: Vec<String>,

    /// 默认权限匹配模式(AND / OR)
    default_permission_mode: PermissionMode,

    /// 中间件链(按注册顺序构成洋葱模型,先注册的最先进入、最后离开)
    middlewares: Vec<Arc<dyn Middleware>>,
}

impl ModuleRouter {
    /// 创建新的模块路由器
    ///
    /// # 安全注意
    ///
    /// 若路由器将注册**非公开 Action**(`is_public() == false`),调用方**必须**
    /// 通过 [`.middleware()`](Self::middleware) 注册认证中间件(如
    /// `TokenAuthMiddleware`)。否则未认证请求到达非公开 Action 时,
    /// [`authorize_and_dispatch`](Self::authorize_and_dispatch) 会返回
    /// `Unauthorized`,但中间件层的短路返回可能被意外绕过。
    ///
    /// 本方法在 debug build 中会通过 `tracing::warn!` 在首次 dispatch 时
    /// 检测此配置错误。
    ///
    /// # 参数
    ///
    /// - `module_name`: 模块名称
    /// - `display_name`: 模块显示名称
    ///
    /// # 返回
    ///
    /// - 新的 ModuleRouter 实例
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::router::ModuleRouter;
    ///
    /// let router = ModuleRouter::new("user", "用户管理");
    /// ```
    pub fn new(module_name: impl Into<String>, display_name: impl Into<String>) -> Self {
        Self {
            module_name: module_name.into(),
            display_name: display_name.into(),
            table_config: None,
            actions: HashMap::new(),
            routes: HashMap::new(),
            default_permissions: Vec::new(),
            default_permission_mode: PermissionMode::default(),
            middlewares: Vec::new(),
        }
    }

    /// 设置表配置(builder setter)
    ///
    /// # 参数
    ///
    /// - `config`: 表配置
    ///
    /// # 返回
    ///
    /// - `Ok(ModuleRouter)`: 修改后的实例(支持链式调用)
    /// - `Err(BaseError::ConfigError)`: 权限名称为空
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::router::ModuleRouter;
    /// use yang_base::table::TableConfig;
    /// use std::sync::Arc;
    ///
    /// let table_config = Arc::new(TableConfig::new("users"));
    /// let router = ModuleRouter::new("user", "用户管理")
    ///     .with_table_config(table_config);
    /// ```
    pub fn with_table_config(mut self, config: Arc<TableConfig>) -> Self {
        self.table_config = Some(config);
        self
    }

    /// 设置表配置(链式 setter 别名,委托给 `with_table_config`)
    ///
    /// 与 `with_table_config` 功能相同,提供更简洁的链式调用语法。
    ///
    /// # 参数
    ///
    /// - `config`: 表配置
    ///
    /// # 返回
    ///
    /// - 修改后的 ModuleRouter 实例(支持链式调用)
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::router::ModuleRouter;
    /// use yang_base::table::TableConfig;
    /// use std::sync::Arc;
    ///
    /// let table_config = Arc::new(TableConfig::new("users"));
    /// let router = ModuleRouter::new("user", "用户管理")
    ///     .table_config(table_config);
    /// ```
    #[deprecated(note = "请用 with_table_config")]
    pub fn table_config(self, config: Arc<TableConfig>) -> Self {
        self.with_table_config(config)
    }

    /// 设置默认权限要求
    ///
    /// # 参数
    ///
    /// - `permissions`: 权限列表
    ///
    /// # 返回
    ///
    /// - 修改后的 ModuleRouter 实例(支持链式调用)
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::router::ModuleRouter;
    ///
    /// let router = ModuleRouter::new("user", "用户管理")
    ///     .default_permissions(vec!["user:access".to_string()])?;
    /// ```
    pub fn default_permissions(mut self, permissions: Vec<String>) -> Result<Self, BaseError> {
        if permissions
            .iter()
            .any(|permission| permission.trim().is_empty())
        {
            return Err(BaseError::ConfigError("默认权限名称不能为空".to_string()));
        }

        let mut seen = HashSet::with_capacity(permissions.len());
        for permission in &permissions {
            if !seen.insert(permission.as_str()) {
                return Err(BaseError::ConfigError(format!(
                    "默认权限重复: {}",
                    permission
                )));
            }
        }

        self.default_permissions = permissions;
        Ok(self)
    }

    /// 设置默认权限匹配模式(builder setter)
    ///
    /// 控制 `default_permissions` 中多个权限之间的逻辑关系:
    /// - [`PermissionMode::All`](默认):用户必须拥有全部权限(AND)
    /// - [`PermissionMode::Any`]:用户只需拥有其中任一权限(OR)
    ///
    /// # 参数
    ///
    /// - `mode`: 权限匹配模式
    ///
    /// # 返回
    ///
    /// - 修改后的 ModuleRouter 实例(支持链式调用)
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::router::ModuleRouter;
    /// use yang_base::action::PermissionMode;
    ///
    /// let router = ModuleRouter::new("user", "用户管理")
    ///     .default_permissions(vec!["user:read".to_string(), "user:write".to_string()])?
    ///     .default_permission_mode(PermissionMode::Any);
    /// ```
    pub fn default_permission_mode(mut self, mode: PermissionMode) -> Self {
        self.default_permission_mode = mode;
        self
    }

    /// 注册一个类型化 Action
    ///
    /// 接受任意实现 [`TypedAction`](crate::action::TypedAction) 的类型
    /// (通常由 `#[derive(Action)]` 派生),通过 blanket impl 自动转为
    /// `Arc<dyn DynAction>` 存入注册表。
    ///
    /// 若已存在同名 Action(含内置 CRUD:add/put/del/get/select/table),
    /// 将覆盖先前注册。
    ///
    /// # 参数
    ///
    /// - `action`: 类型化 Action 实例
    ///
    /// # 返回
    ///
    /// - 修改后的 ModuleRouter 实例(支持链式调用)
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::router::ModuleRouter;
    /// use yang_base::action::builtin::AddAction;
    ///
    /// let router = ModuleRouter::new("user", "用户管理")
    ///     .register_action(AddAction::<User>::new())?;
    /// ```
    pub fn register_action<A>(mut self, action: A) -> Result<Self, BaseError>
    where
        A: crate::action::TypedAction,
    {
        let action: Arc<dyn DynAction> = Arc::new(action);
        let meta = action.meta();
        let name = meta.name.to_string();
        if name.trim().is_empty() {
            return Err(BaseError::ConfigError("Action 名称不能为空".to_string()));
        }
        if meta
            .permissions
            .iter()
            .any(|permission| permission.name().trim().is_empty())
        {
            return Err(BaseError::ConfigError(
                "Action 权限名称不能为空".to_string(),
            ));
        }
        if self.actions.contains_key(&name) {
            return Err(BaseError::ConfigError(format!("Action 已注册: {}", name)));
        }
        self.actions.insert(name, action);
        Ok(self)
    }

    /// 为已注册 Action 绑定传输路由描述。
    pub fn register_route(
        mut self,
        action_name: impl Into<String>,
        route: RouteDescriptor,
    ) -> Result<Self, BaseError> {
        route.validate()?;
        let action_name = action_name.into();
        if !self.actions.contains_key(&action_name) {
            return Err(BaseError::ConfigError(format!(
                "route 对应的 Action 未注册: {action_name}"
            )));
        }
        if self.routes.contains_key(&action_name) {
            return Err(BaseError::ConfigError(format!(
                "Action route 已注册: {action_name}"
            )));
        }
        if self
            .routes
            .values()
            .any(|existing| existing.method == route.method && existing.path == route.path)
        {
            return Err(BaseError::ConfigError(format!(
                "route 冲突: {} {}",
                route.method, route.path
            )));
        }
        if self
            .routes
            .values()
            .any(|existing| existing.operation_id == route.operation_id)
        {
            return Err(BaseError::ConfigError(format!(
                "operation_id 冲突: {}",
                route.operation_id
            )));
        }
        self.routes.insert(action_name, route);
        Ok(self)
    }

    /// 构建与运行时注册表隔离的只读模块描述快照。
    pub fn descriptor(&self) -> Result<ModuleDescriptor, BaseError> {
        let mut action_names: Vec<&String> = self.actions.keys().collect();
        action_names.sort();
        let mut actions = Vec::with_capacity(action_names.len());
        for name in action_names {
            let action = &self.actions[name];
            let meta = action.meta();
            let route = self
                .routes
                .get(name)
                .ok_or_else(|| BaseError::ConfigError(format!("Action 缺少 route: {name}")))?;
            actions.push(ActionDescriptor {
                name: meta.name.to_string(),
                display_name: meta.display_name.to_string(),
                description: meta.description.to_string(),
                permissions: meta
                    .permissions
                    .iter()
                    .map(|permission| permission.name().to_string())
                    .collect(),
                permission_mode: meta.permission_mode,
                is_public: meta.is_public,
                input_schema: meta.input_schema.clone(),
                output_schema: meta.output_schema.clone(),
                route: route.clone(),
            });
        }
        Ok(ModuleDescriptor {
            name: self.module_name.clone(),
            display_name: self.display_name.clone(),
            default_permissions: self.default_permissions.clone(),
            default_permission_mode: self.default_permission_mode,
            actions,
        })
    }

    /// 注册一个中间件(builder setter)
    ///
    /// 中间件按注册顺序构成洋葱模型:先注册的最先进入、最后离开。
    /// 中间件位于鉴权之外的**最外层**,先于内置登录/权限检查运行
    /// (见 [`dispatch`](Self::dispatch))。这意味着中间件的短路返回会
    /// **跳过**内置鉴权,请谨慎使用。
    ///
    /// # 参数
    ///
    /// - `middleware`: 实现 [`Middleware`](crate::router::Middleware) 的实例
    ///
    /// # 返回
    ///
    /// - 修改后的 ModuleRouter 实例(支持链式调用)
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// let router = ModuleRouter::new("user", "用户管理")
    ///     .middleware(LoggingMiddleware)
    ///     .middleware(RateLimitMiddleware);
    /// ```
    pub fn middleware<M>(mut self, middleware: M) -> Self
    where
        M: Middleware,
    {
        self.middlewares.push(Arc::new(middleware));
        self
    }

    /// 为指定实体类型 `T` 注册全部六个内置 CRUD Actions
    ///
    /// 注册 add、put、del、get、select、table 六个类型化内置 Action。
    /// 调用前需先通过 `with_table_config` / `table_config` 设置表配置——
    /// 内置 Action 在 dispatch 时通过 `ActionContext::table_query()` 取用该配置。
    ///
    /// 内置 Action 名称由 [`BUILTIN_ACTION_NAMES`] 常量定义。
    ///
    /// # 类型参数
    ///
    /// - `T`: 实现 [`TableEntity`](crate::table::TableEntity) 的实体类型
    ///   (通常由 `#[derive(TableEntity)]` 派生)
    ///
    /// # 返回
    ///
    /// - `Ok(Self)`: 注册成功,返回修改后的 ModuleRouter 实例(支持链式调用)
    /// - `Err(BaseError::TableConfigNotSet)`: 未设置 table_config
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::router::ModuleRouter;
    ///
    /// let router = ModuleRouter::new("user", "用户管理")
    ///     .with_table_config(user_table_config)
    ///     .table_typed::<User>()?;
    /// ```
    #[cfg(feature = "mysql")]
    pub fn table_typed<T>(self) -> Result<Self, BaseError>
    where
        T: crate::table::TableEntity,
    {
        use crate::action::builtin::{
            AddAction, DelAction, GetAction, PutAction, SelectAction, TableAction,
        };

        if self.table_config.is_none() {
            return Err(BaseError::TableConfigNotSet);
        }

        self.register_action(AddAction::<T>::new())?
            .register_action(PutAction::<T>::new())?
            .register_action(DelAction::<T>::new())?
            .register_action(GetAction::<T>::new())?
            .register_action(SelectAction::<T>::new())?
            .register_action(TableAction::<T>::new())
    }

    /// 分发请求到对应的 Action
    ///
    /// 根据 action 名称查找对应的 Action,检查权限后执行。
    ///
    /// # 参数
    ///
    /// - `action_name`: Action 名称
    /// - `context`: Action 执行上下文
    ///
    /// # 返回
    ///
    /// - `Ok(ApiResponse)`: 执行成功
    /// - `Err(BaseError)`: 执行失败
    ///
    /// # 错误
    ///
    /// - `BaseError::ActionNotFound`: Action 不存在
    /// - `BaseError::Unauthorized`: 用户未认证(需要认证的 Action)
    /// - `BaseError::PermissionDenied`: 权限不足
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::router::ModuleRouter;
    /// use yang_base::action::ActionContext;
    ///
    /// let router = ModuleRouter::new("user", "用户管理")
    ///     .with_table_config(table_config)
    ///     .table_typed::<User>()?;
    ///
    /// let response = router.dispatch("add", context).await?;
    /// ```
    pub async fn dispatch(
        &self,
        action_name: &str,
        mut context: ActionContext,
    ) -> Result<ApiResponse, BaseError> {
        // 0. 安全检查:存在非公开 Action 但未注册任何中间件时发出警告(S-NEW-AUTH-2)
        if self.middlewares.is_empty() && self.actions.values().any(|a| !a.meta().is_public) {
            tracing::warn!(
                module = %self.module_name,
                "模块 '{}' 包含非公开 Action 但未注册认证中间件(如 TokenAuthMiddleware)",
                self.module_name,
            );
        }

        // 1. 查找 Action(克隆 Arc,便于后续移动进中间件链 / 执行)
        let action = self
            .actions
            .get(action_name)
            .ok_or_else(|| BaseError::ActionNotFound(action_name.to_string()))?
            .clone();

        // 2. 设置表配置与模块名到上下文
        if let Some(table_config) = &self.table_config {
            context = context.with_table_config(table_config.clone());
        }
        // 注入模块名,供 metrics module 标签等可观测性标注(NEW-2)
        if context.module.is_none() {
            context = context.with_module(self.module_name.clone());
        }

        // 3. 进入中间件链(最外层)。链尾执行内置鉴权 + Action 派发,
        //    使日志/限流/自定义认证等中间件能观察并干预所有请求。
        let next = Next {
            remaining: &self.middlewares,
            router: self,
            action,
        };

        // 根 span:串联整条派发链路。静态 span 名 + 借用字段,成功路径零分配;
        // request_id 以 Empty 声明——只有 Empty 字段才能被后续 record 更新,故
        // RequestIdMiddleware 透传上游 X-Request-Id 时能改写本字段(NEW-1)。
        // 同时在此先 record 一次默认值,保证未注册该中间件时根 span 也带 request_id。
        let span = tracing::info_span!(
            "dispatch",
            module = %self.module_name,
            action = %action_name,
            request_id = tracing::field::Empty,
        );
        span.record("request_id", tracing::field::display(context.request_id));
        next.run(context).instrument(span).await
    }

    /// 中间件链的终点:执行内置鉴权后派发 Action。
    ///
    /// 由 [`Next::run`] 在中间件耗尽时调用。公开 Action 跳过鉴权;非公开
    /// Action 依次校验「已登录 -> 模块默认权限 -> Action 权限」,全部通过后
    /// 调用 `action.dispatch`。
    pub(crate) async fn authorize_and_dispatch(
        &self,
        action: Arc<dyn DynAction>,
        context: ActionContext,
    ) -> Result<ApiResponse, BaseError> {
        let meta = action.meta();

        // 鉴权子 span:记录是否公开 Action 与最终放行结果
        let span = tracing::info_span!(
            "authorize",
            is_public = meta.is_public,
            granted = tracing::field::Empty,
        );
        let _enter = span.enter();

        // 公开 Action 跳过登录/权限检查
        if !meta.is_public {
            // 检查用户是否已认证
            let user = context.user.as_ref().ok_or_else(|| {
                span.record("granted", false);
                BaseError::Unauthorized("需要登录".to_string())
            })?;

            // 检查默认权限
            if !self.default_permissions.is_empty()
                && !self.check_permissions(
                    user,
                    &self.default_permissions,
                    self.default_permission_mode,
                )
            {
                span.record("granted", false);
                return Err(BaseError::PermissionDenied(format!(
                    "缺少模块权限: {:?}",
                    self.default_permissions
                )));
            }

            // 检查 Action 权限
            //
            // 热路径零分配:成功路径仅借用权限名做模式判断,不构造任何
            // 中间集合;仅当权限不足时才 collect 格式化中文错误信息。
            let action_perm_ok = match meta.permission_mode {
                PermissionMode::All => meta
                    .permissions
                    .iter()
                    .all(|p| user.has_permission(p.name())),
                PermissionMode::Any => meta
                    .permissions
                    .iter()
                    .any(|p| user.has_permission(p.name())),
            };
            if !meta.permissions.is_empty() && !action_perm_ok {
                span.record("granted", false);
                let permission_names: Vec<&str> =
                    meta.permissions.iter().map(|p| p.name()).collect();
                return Err(BaseError::PermissionDenied(format!(
                    "缺少 Action 权限: {:?}",
                    permission_names
                )));
            }
        }

        span.record("granted", true);
        // 释放鉴权 span,进入 handler 自身的 span(在 DynAction::dispatch 内开启)
        drop(_enter);

        // 执行 Action 派发
        action.dispatch(context).await
    }

    /// 使用全局单例分发请求
    ///
    /// 自动从全局单例获取 `GlobalTools`,无需手动传入。
    /// 需要先调用 `GlobalTools::init` 初始化全局单例。
    ///
    /// # 参数
    ///
    /// - `action_name`: Action 名称
    /// - `request`: 请求数据
    ///
    /// # 返回
    ///
    /// - `Ok(ApiResponse)`: 执行成功
    /// - `Err(BaseError)`: 执行失败
    ///
    /// # 错误
    ///
    /// - `BaseError::ConfigError("GlobalTools 未初始化")`: 全局单例未初始化
    /// - `BaseError::ActionNotFound`: Action 不存在
    /// - `BaseError::Unauthorized`: 用户未认证
    /// - `BaseError::PermissionDenied`: 权限不足
    ///
    /// # 示例
    ///
    /// ```rust,ignore
    /// use yang_base::router::ModuleRouter;
    /// use yang_base::action::{GlobalTools, Request};
    ///
    /// // 初始化全局单例
    /// GlobalTools::init(token_manager)?;
    ///
    /// let router = ModuleRouter::new("user", "用户管理")
    ///     .with_table_config(table_config)
    ///     .table_typed::<User>()?;
    ///
    /// // 无需传入 tools,自动从全局单例获取
    /// let response = router.dispatch_with_global("add", request).await?;
    /// ```
    pub async fn dispatch_with_global(
        &self,
        action_name: &str,
        request: crate::action::Request,
    ) -> Result<ApiResponse, BaseError> {
        // 从全局单例获取 GlobalTools,自动构建上下文
        let context = ActionContext::new_with_global_tools(request)?;
        self.dispatch(action_name, context).await
    }

    /// 检查用户权限
    ///
    /// # 参数
    ///
    /// - `user`: 用户信息
    /// - `required_permissions`: 需要的权限列表
    ///
    /// # 返回
    ///
    /// - `true`: 有权限
    /// - `false`: 无权限
    fn check_permissions(
        &self,
        user: &User,
        required_permissions: &[String],
        mode: PermissionMode,
    ) -> bool {
        match mode {
            PermissionMode::All => required_permissions
                .iter()
                .all(|perm| user.has_permission(perm)),
            PermissionMode::Any => required_permissions
                .iter()
                .any(|perm| user.has_permission(perm)),
        }
    }

    /// 获取模块名称
    ///
    /// # 返回
    ///
    /// - 模块名称
    pub fn module_name(&self) -> &str {
        &self.module_name
    }

    /// 获取模块显示名称
    ///
    /// # 返回
    ///
    /// - 模块显示名称
    pub fn display_name(&self) -> &str {
        &self.display_name
    }

    /// 获取已注册的 Action 列表
    ///
    /// # 返回
    ///
    /// - Action 名称列表
    pub fn action_names(&self) -> Vec<String> {
        let mut names: Vec<String> = self.actions.keys().cloned().collect();
        names.sort();
        names
    }

    /// 获取表配置(getter,返回借用)
    ///
    /// # 返回
    ///
    /// - `Some(&Arc<TableConfig>)`: 表配置的借用
    /// - `None`: 未设置表配置
    pub fn get_table_config(&self) -> Option<&Arc<TableConfig>> {
        self.table_config.as_ref()
    }
}