garrison 0.9.0

Garrison - 面向 Rust 生态的一站式身份认证鉴权框架
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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! `GarrisonManagerBuilder`:可组合的初始化入口。
//!
//! 构造 `GarrisonLogicDefault` / 装配依赖 / 注入全局单例 / 启动后台 task 四个职责经链式
//! setter + 两个构造入口完成:`build` 构造 logic + 注入全局单例 + 启动后台 task(handle
//! 归单例,`GarrisonUtil` 静态 API 可用);`build_explicit`(`manager-explicit` feature)
//! 构造 logic + 包装为 `Manager` + 启动后台 task(handle 归 `Manager`,Drop 时 abort,
//! 不触碰全局单例)。后台 task handle 由 `TaskHandles` 统一持有,归属构造方(`build` →
//! 单例,`build_explicit` → `Manager`),Drop 时自动 abort,无单例泄漏。

use crate::account::disable::{DefaultDisableRepository, DisableRepository};
use crate::config::GarrisonConfig;
use crate::core::auth::{AuthLogic, AuthLogicDefault};
use crate::core::permission::{PermissionChecker, PermissionCheckerDefault};
use crate::core::token::TokenStyleFactory;
use crate::dao::GarrisonDao;
use crate::error::{GarrisonError, GarrisonResult};
#[cfg(feature = "listener")]
use crate::listener::GarrisonListenerManager;
#[cfg(feature = "manager-explicit")]
use crate::manager::explicit::Manager;
use crate::manager::factory::{GarrisonLogicFactoryContext, GarrisonLogicFactoryEntry};
use crate::manager::{GarrisonManager, GARRISON_MANAGER};
use crate::plugin::GarrisonPluginManager;
use crate::session::GarrisonSession;
use crate::stp::util::spawn_cleanup_task;
use crate::stp::{GarrisonInterface, GarrisonLogicDefault};
#[cfg(feature = "anomalous-detector-dual")]
use crate::strategy::firewall::{AnomalousAnalyzerConfig, AnomalousLoginAnalyzer};
use crate::strategy::{GarrisonPermissionStrategy, GarrisonPermissionStrategyDefault, Strategy};
use parking_lot::RwLock;
use std::sync::Arc;
#[cfg(feature = "anomalous-detector-dual")]
use tokio::sync::watch;
use tokio::task::JoinHandle;

/// 后台任务句柄集合,由构造方持有(`build` → 单例,`build_explicit` → `Manager`)。
///
/// Drop 时由持有方 abort 对应 task,避免后台线程残留。
pub(crate) struct TaskHandles {
    /// 定期清理过期 token 的 task handle(interval <= 0 时为 None)。
    pub(crate) cleanup: Option<Arc<JoinHandle<()>>>,
    /// 异常登录分析器 task handle(`anomalous-detector-dual` feature 下存在)。
    #[cfg(feature = "anomalous-detector-dual")]
    pub(crate) anomalous: Option<Arc<JoinHandle<()>>>,
    /// 异常登录分析器 shutdown 信号发送端(`anomalous-detector-dual` feature 下存在)。
    ///
    /// 保存 `shutdown_tx` 使其生命周期与持有方一致,
    /// 避免 `shutdown_rx` 因 sender drop 而误触发停止。
    #[cfg(feature = "anomalous-detector-dual")]
    pub(crate) anomalous_shutdown: Option<watch::Sender<bool>>,
}

impl TaskHandles {
    /// 空句柄集合(`Manager::new` 路径使用,不启动任何 task)。
    #[cfg(feature = "manager-explicit")]
    pub(crate) fn empty() -> Self {
        Self {
            cleanup: None,
            #[cfg(feature = "anomalous-detector-dual")]
            anomalous: None,
            #[cfg(feature = "anomalous-detector-dual")]
            anomalous_shutdown: None,
        }
    }
}

/// 可组合的初始化 builder。
///
/// 通过 [`GarrisonManager::builder`] 获取新实例,链式注入必填字段
/// (`dao` / `config` / `interface`)与可选 manager,最后调用
/// [`build`](GarrisonManagerBuilder::build) 或 `build_explicit` 完成构造。
pub struct GarrisonManagerBuilder {
    // 必填
    dao: Option<Arc<dyn GarrisonDao>>,
    config: Option<Arc<GarrisonConfig>>,
    interface: Option<Arc<dyn GarrisonInterface>>,
    // 可选(None 表示用默认实现)
    plugin_manager: Option<Arc<GarrisonPluginManager>>,
    #[cfg(feature = "listener")]
    listener_manager: Option<Arc<GarrisonListenerManager>>,
    auth_logic: Option<Arc<dyn AuthLogic>>,
    permission_checker: Option<Arc<dyn PermissionChecker>>,
    disable_repository: Option<Arc<dyn DisableRepository>>,
    /// 限流运行时(`rate-limit-redis` 下按配置构造;`None` 沿用 DAO 自适应路径)。
    #[cfg(feature = "firewall")]
    limiter_runtime: Option<crate::limiteron::LimiterRuntime>,
    // three-tier-cache feature 下的用户缓存服务(None 时若 feature 启用则自动构造)
    #[cfg(feature = "three-tier-cache")]
    user_cache_service: Option<Arc<crate::cache::UserCacheService>>,
    // 扩展点
    factory: Option<&'static GarrisonLogicFactoryEntry>,
}

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

/// `build()` 全局串行锁。
///
/// 单例更新由多个独立锁保护的字段组成(logic / strategy 两次 `ArcSwapOption::store` +
/// cleanup/anomalous handle 写入),字段间非原子:两个并发 `build()` 可能交错执行,产生
/// `(logic_B, strategy_A)` 错配对,或 A 的 analyzer shutdown_tx 被 B 误取走 drop,提前杀死
/// 对方刚启动的后台任务。以进程级 `Mutex` 串行化单例写入段,保证分步写入对并发调用方原子可见。
static BUILD_LOCK: parking_lot::Mutex<()> = parking_lot::Mutex::new(());

impl GarrisonManagerBuilder {
    /// 创建空的 builder 实例(所有字段为 None)。
    pub fn new() -> Self {
        Self {
            dao: None,
            config: None,
            interface: None,
            plugin_manager: None,
            #[cfg(feature = "listener")]
            listener_manager: None,
            auth_logic: None,
            permission_checker: None,
            disable_repository: None,
            #[cfg(feature = "firewall")]
            limiter_runtime: None,
            #[cfg(feature = "three-tier-cache")]
            user_cache_service: None,
            factory: None,
        }
    }

    /// 按配置构造限流运行时(`firewall` + `rate-limit-redis` 构建面)。
    ///
    /// `Memory` 保持 `None`(沿用 DAO 自适应路径);`Redis` 建立连接,失败 fail-closed。
    /// 调用点在 [`Self::build`] / [`Self::build_explicit`] 的 `BUILD_LOCK` 之前
    /// (网络 I/O 不得进锁)。
    #[cfg(all(feature = "firewall", feature = "rate-limit-redis"))]
    async fn prepare_limiter_runtime(&mut self) -> GarrisonResult<()> {
        use crate::strategy::rate_limiter_backend::RateLimitBackend;

        let (Some(dao), Some(config)) = (self.dao.clone(), self.config.clone()) else {
            return Ok(());
        };
        match &config.rate_limit_backend {
            // Memory 不在预装配阶段 validate,避免与 build_logic 的 validate 重复输出部署警示。
            RateLimitBackend::Memory => Ok(()),
            RateLimitBackend::Redis { .. } => {
                config.validate()?;
                let runtime = crate::limiteron::LimiterRuntime::from_config(&config, dao).await?;
                self.limiter_runtime = Some(runtime);
                tracing::info!(
                    backend = "redis",
                    "{}",
                    crate::i18n::translate_detail("logs-config-rate-limit-redis-active", &[])
                );
                Ok(())
            },
        }
    }

    /// 注入 DAO 引用(必填)。
    pub fn dao(mut self, dao: Arc<dyn GarrisonDao>) -> Self {
        self.dao = Some(dao);
        self
    }

    /// 注入全局配置(必填)。
    pub fn config(mut self, config: Arc<GarrisonConfig>) -> Self {
        self.config = Some(config);
        self
    }

    /// 注入权限数据回调(必填)。
    pub fn interface(mut self, interface: Arc<dyn GarrisonInterface>) -> Self {
        self.interface = Some(interface);
        self
    }

    /// 注入插件管理器(可选;None 时使用 `GarrisonPluginManager::new()` 默认实现)。
    pub fn with_plugin_manager(mut self, pm: Arc<GarrisonPluginManager>) -> Self {
        self.plugin_manager = Some(pm);
        self
    }

    /// 注入监听器管理器(可选,需 `listener` feature;None 时使用 `GarrisonListenerManager::new()` 默认实现)。
    #[cfg(feature = "listener")]
    pub fn with_listener_manager(mut self, lm: Arc<GarrisonListenerManager>) -> Self {
        self.listener_manager = Some(lm);
        self
    }

    /// 注入认证逻辑(可选;None 时使用 `AuthLogicDefault` 默认实现)。
    pub fn with_auth_logic(mut self, al: Arc<dyn AuthLogic>) -> Self {
        self.auth_logic = Some(al);
        self
    }

    /// 注入权限校验器(可选;None 时使用 `PermissionCheckerDefault` 默认实现)。
    pub fn with_permission_checker(mut self, pc: Arc<dyn PermissionChecker>) -> Self {
        self.permission_checker = Some(pc);
        self
    }

    /// 注入封禁库(可选;None 时使用 `DefaultDisableRepository` 默认实现)。
    pub fn with_disable_repository(mut self, dr: Arc<dyn DisableRepository>) -> Self {
        self.disable_repository = Some(dr);
        self
    }

    /// 注入用户缓存服务(可选,需 `three-tier-cache` feature;None 时若 feature 启用则自动构造)。
    #[cfg(feature = "three-tier-cache")]
    pub fn with_user_cache_service(mut self, ucs: Arc<crate::cache::UserCacheService>) -> Self {
        self.user_cache_service = Some(ucs);
        self
    }

    /// 注入自定义 factory entry(可选扩展点)。
    ///
    /// 注入后 `build` / `build_explicit` 使用 `entry.factory` 构造 `GarrisonLogicDefault`;
    /// 否则使用 `inventory` 中注册的默认 factory,无 entry 时走 builder 链兜底。
    pub fn with_factory(mut self, entry: &'static GarrisonLogicFactoryEntry) -> Self {
        self.factory = Some(entry);
        self
    }

    /// 构造 logic + 注入全局单例 + 启动后台 task。
    ///
    /// task handle 归 `GARRISON_MANAGER` 单例,`GarrisonUtil` 静态 API 可用。单例写入段
    /// (logic / strategy / task handle)由进程级 `BUILD_LOCK` 串行化:并发 `build()`
    /// 按获取锁顺序依次完成各自的"写入 + 换 task",后一次 build 覆盖前一次,不会字段
    /// 交错错配或误杀对方后台任务;允许重复 build(便于测试),单例只保留最后一次
    /// build 的组件。
    ///
    /// 错误:必填字段缺失(dao/config/interface 任一为 None)→ `GarrisonError::Config`;
    /// 配置非法透传 `config.validate()` 错误;factory 构造失败透传 factory 错误。
    #[allow(unused_mut)]
    pub async fn build(mut self) -> GarrisonResult<()> {
        // Redis 限流连接属网络 I/O,必须在 BUILD_LOCK 之外完成(锁内禁止 await);
        // Memory / 未启用 rate-limit-redis 时保持 None,沿既有 DAO 自适应路径。
        #[cfg(all(feature = "firewall", feature = "rate-limit-redis"))]
        self.prepare_limiter_runtime().await?;

        // 串行化对全局单例的写入段(锁内无 await,不跨 .await 持锁)
        let _build_guard = BUILD_LOCK.lock();
        let (logic, task_handles) = self.build_logic()?;

        // 覆盖式更新全局单例(允许重复 build,便于测试)
        let strategy = Arc::new(RwLock::new(Strategy::new(logic.clone())));
        GARRISON_MANAGER.logic.store(Some(logic));
        GARRISON_MANAGER.strategy.store(Some(strategy));

        // 先 abort 旧 cleanup task 再保存新 handle,避免短暂重叠窗口
        if let Some(old) = GARRISON_MANAGER.cleanup_task_handle.write().take() {
            old.abort();
        }
        *GARRISON_MANAGER.cleanup_task_handle.write() = task_handles.cleanup;

        #[cfg(feature = "anomalous-detector-dual")]
        {
            // 先 abort 旧 analyzer task
            if let Some(old) = GARRISON_MANAGER.anomalous_analyzer_handle.write().take() {
                old.abort();
            }
            // 清空旧 shutdown_tx(drop 后 shutdown_rx.changed() 返回 Err,task 退出)
            GARRISON_MANAGER
                .anomalous_analyzer_shutdown_tx
                .write()
                .take();
            *GARRISON_MANAGER.anomalous_analyzer_handle.write() = task_handles.anomalous;
            *GARRISON_MANAGER.anomalous_analyzer_shutdown_tx.write() =
                task_handles.anomalous_shutdown;
        }

        Ok(())
    }

    /// 构造 logic + 包装为 [`Manager`] + 启动后台 task。
    ///
    /// **不写入 `GARRISON_MANAGER` 全局单例**,task handle 归返回的 `Manager` 持有,
    /// Drop 时 abort 所有后台 task,用于多实例 / 测试隔离。与 [`Manager::new`](crate::manager::explicit::Manager::new)
    /// 的区别:`build_explicit` 完整构造 logic + 启动后台 task;`Manager::new` 仅包装
    /// 已构造的 logic,不启动 task。
    ///
    /// GarrisonUtil 限制:本路径不写全局单例,`GarrisonUtil` 静态 API(`login` /
    /// `logout` / `check_login` 等,委托 [`GarrisonManager::logic`])返回
    /// `GarrisonError::Session("manager-not-init")`,调用方应通过返回的 `Manager`
    /// 实例方法操作,而非静态 API。
    ///
    /// 错误:必填字段缺失 → `GarrisonError::Config`;配置非法透传 `config.validate()`
    /// 错误;factory 构造失败透传 factory 错误。
    #[cfg(feature = "manager-explicit")]
    #[allow(unused_mut)]
    pub async fn build_explicit(mut self) -> GarrisonResult<Manager> {
        #[cfg(all(feature = "firewall", feature = "rate-limit-redis"))]
        self.prepare_limiter_runtime().await?;
        let (logic, task_handles) = self.build_logic()?;
        Ok(Manager::with_task_handles(logic, task_handles))
    }

    /// 构造 `GarrisonLogicDefault` + 启动后台 task,返回 logic 与 task handle 集合。
    ///
    /// 校验 config + 构造 session + 装配 5 个内部 manager + 通过 factory 或 builder 链
    /// 构造 logic + 启动 cleanup_task 与 anomalous_analyzer_task。
    /// 此方法不触碰全局单例,由 `build` / `build_explicit` 决定注入目标。
    #[allow(unused_variables)]
    #[cfg_attr(not(feature = "firewall"), allow(unused_mut))]
    fn build_logic(mut self) -> GarrisonResult<(Arc<GarrisonLogicDefault>, TaskHandles)> {
        #[cfg(feature = "firewall")]
        let limiter_runtime = self.limiter_runtime.take();
        // fail-closed:必填字段缺失即返回,不构造任何 manager 或 task
        let dao = self
            .dao
            .ok_or_else(|| GarrisonError::Config("builder-dao-missing".to_string()))?;
        let config = self
            .config
            .ok_or_else(|| GarrisonError::Config("builder-config-missing".to_string()))?;
        let interface = self
            .interface
            .ok_or_else(|| GarrisonError::Config("builder-interface-missing".to_string()))?;

        config.validate()?;

        // 构造 session(active_timeout = -1 表示不启用 activity 超时,用 timeout 兜底)
        let timeout = u64::try_from(config.timeout).map_err(|_| {
            GarrisonError::Config(format!("manager-timeout-overflow::{}", config.timeout))
        })?;
        let active_timeout = if config.active_timeout < 0 {
            timeout
        } else {
            u64::try_from(config.active_timeout).map_err(|_| {
                GarrisonError::Config(format!(
                    "manager-active-timeout-overflow::{}",
                    config.active_timeout
                ))
            })?
        };
        let remember_me_timeout = config.remember_me_timeout.max(0) as u64;
        let session = Arc::new(GarrisonSession::new(
            dao.clone(),
            timeout,
            active_timeout,
            remember_me_timeout,
        ));

        // auto-wire:构造各 manager(builder 字段为 Some 用注入值,None 用默认实现)
        // PermissionChecker:委托 interface 查询权限/角色数据
        let permission_checker: Arc<dyn PermissionChecker> = match self.permission_checker {
            Some(pc) => pc,
            None => Arc::new(PermissionCheckerDefault::new(interface.clone())),
        };
        // PluginManager:通过 inventory 收集编译期注册的插件
        let plugin_manager = match self.plugin_manager {
            Some(pm) => pm,
            None => Arc::new(GarrisonPluginManager::new()),
        };
        // ListenerManager:通过 inventory 收集编译期注册的监听器,需 listener feature
        #[cfg(feature = "listener")]
        let listener_manager = match self.listener_manager {
            Some(lm) => lm,
            None => Arc::new(GarrisonListenerManager::new()),
        };
        // AuthLogic:委托 session + token_handler 实现登录/校验
        let token_handler: Arc<dyn crate::core::token::Token> =
            Arc::from(TokenStyleFactory::new_with_jwt_keys(
                &config.token_style,
                config.jwt_secret.as_str(),
                Some(&config.jwt_algorithm),
                config.jwt_rsa_private_key_pem.as_deref(),
                config.jwt_ec_private_key_pem.as_deref(),
                config.jwt_ed_private_key_pem.as_deref(),
            )?);
        let auth_logic: Arc<dyn AuthLogic> = match self.auth_logic {
            Some(al) => al,
            None => Arc::new(
                AuthLogicDefault::new(session.clone(), token_handler, config.timeout)
                    .with_seed_primary_amr(config.seed_primary_amr),
            ),
        };

        // 构造 firewall,注入 permission_checker + plugin_manager
        let firewall_builder = GarrisonPermissionStrategyDefault::new(interface)
            .with_permission_checker(permission_checker.clone())
            .with_plugin_manager(plugin_manager.clone());

        // firewall-* feature 启用时自动装配防火墙 hook(避免 dead-code):经
        // `GarrisonFirewallCheckHookDefault` 注入共享 DAO 的限流器,使 login 流水线的 5 个 hook(含暴力破解/频率/geo/异常检测)真正生效。
        #[cfg(feature = "firewall")]
        let firewall_builder = {
            use crate::strategy::hooks::GarrisonFirewallCheckHookDefault;
            let hook = GarrisonFirewallCheckHookDefault::new().with_dao(dao.clone());
            #[cfg(feature = "rate-limit-redis")]
            let hook = match limiter_runtime {
                Some(runtime) => hook.with_limiter_backend(runtime.limiter()),
                None => hook,
            };
            firewall_builder.with_firewall_hook(std::sync::Arc::new(hook))
        };

        let firewall: Arc<dyn GarrisonPermissionStrategy> = Arc::new(firewall_builder);

        // 构造 disable_repository(委托同一 DAO 实例持久化封禁条目)
        let disable_repo = match self.disable_repository {
            Some(dr) => dr,
            None => Arc::new(DefaultDisableRepository::new(dao.clone())),
        };

        // three-tier-cache feature 启用时构造 UserCacheService(复用 dao + firewall)
        #[cfg(feature = "three-tier-cache")]
        let user_cache_service = match self.user_cache_service {
            Some(ucs) => ucs,
            None => Arc::new(crate::cache::UserCacheService::new_with_capacity(
                dao.clone(),
                firewall.clone(),
                config.l1_cache_ttl_secs,
                config.l1_cache_capacity,
                config.l2_cache_ttl_secs,
            )?),
        };

        // 构造 factory context(持有各 manager 引用)
        #[cfg(feature = "listener")]
        let factory_ctx = GarrisonLogicFactoryContext {
            plugin_manager: Some(plugin_manager.clone()),
            listener_manager: Some(listener_manager.clone()),
            auth_logic: Some(auth_logic.clone()),
            permission_checker: Some(permission_checker.clone()),
            disable_repository: Some(disable_repo.clone()),
            #[cfg(feature = "three-tier-cache")]
            user_cache_service: Some(user_cache_service.clone()),
        };
        #[cfg(not(feature = "listener"))]
        let factory_ctx = GarrisonLogicFactoryContext {
            plugin_manager: Some(plugin_manager.clone()),
            auth_logic: Some(auth_logic.clone()),
            permission_checker: Some(permission_checker.clone()),
            disable_repository: Some(disable_repo.clone()),
            #[cfg(feature = "three-tier-cache")]
            user_cache_service: Some(user_cache_service.clone()),
        };

        // clone listener_manager 和 dao 给 analyzer,读取 config 值(均在 move 之前)
        #[cfg(feature = "anomalous-detector-dual")]
        let (
            analyzer_listener_manager,
            analyzer_dao,
            analyzer_interval_secs,
            analyzer_burst_threshold,
        ) = (
            listener_manager.clone(),
            dao.clone(),
            config.anomalous_analyzer_interval_secs,
            config.anomalous_analyzer_burst_threshold,
        );

        // 通过 factory 构造 logic(builder 字段优先,否则 inventory 默认,最后 builder 链兜底)
        let factory_entry = self.factory.or_else(default_factory_selector);
        let logic: Arc<GarrisonLogicDefault> = match factory_entry {
            Some(entry) => (entry.factory)(
                session.clone(),
                config.clone(),
                firewall.clone(),
                &factory_ctx,
            )?,
            None => Self::build_logic_via_builder_chain(
                session.clone(),
                config.clone(),
                firewall.clone(),
                plugin_manager,
                auth_logic,
                permission_checker,
                disable_repo,
                #[cfg(feature = "listener")]
                listener_manager,
                #[cfg(feature = "three-tier-cache")]
                user_cache_service,
            ),
        };

        // 启动后台 cleanup task(interval_secs <= 0 时不启动)
        let cleanup_handle =
            spawn_cleanup_task(session, config.token_map_cleanup_interval_secs).map(Arc::new);

        // 启动异常登录分析器 task(anomalous-detector-dual feature)
        #[cfg(feature = "anomalous-detector-dual")]
        let (anomalous_handle, anomalous_shutdown) = {
            let (shutdown_tx, shutdown_rx) = watch::channel(false);

            // 从 GarrisonConfig 构造 analyzer config
            let analyzer_config = AnomalousAnalyzerConfig {
                interval_secs: analyzer_interval_secs,
                burst_threshold: analyzer_burst_threshold,
                ..AnomalousAnalyzerConfig::default()
            };

            let analyzer = AnomalousLoginAnalyzer::new(
                analyzer_dao,
                analyzer_config,
                shutdown_rx,
                Some(analyzer_listener_manager),
            );
            let analyzer_handle = Arc::new(analyzer.start());

            (analyzer_handle, shutdown_tx)
        };

        // 装配 task handle 集合,交由构造方持有
        let task_handles = TaskHandles {
            cleanup: cleanup_handle,
            #[cfg(feature = "anomalous-detector-dual")]
            anomalous: Some(anomalous_handle),
            #[cfg(feature = "anomalous-detector-dual")]
            anomalous_shutdown: Some(anomalous_shutdown),
        };

        Ok((logic, task_handles))
    }

    /// 兜底路径:无 factory entry 时直接通过 builder 链构造 `GarrisonLogicDefault`。
    ///
    /// 提取为独立私有函数,便于单元测试兜底逻辑本身(不依赖 inventory 全局状态)。
    #[allow(clippy::too_many_arguments)]
    #[cfg_attr(
        not(any(feature = "listener", feature = "three-tier-cache")),
        allow(unused_mut)
    )]
    fn build_logic_via_builder_chain(
        session: Arc<GarrisonSession>,
        config: Arc<GarrisonConfig>,
        firewall: Arc<dyn GarrisonPermissionStrategy>,
        plugin_manager: Arc<GarrisonPluginManager>,
        auth_logic: Arc<dyn AuthLogic>,
        permission_checker: Arc<dyn PermissionChecker>,
        disable_repo: Arc<dyn DisableRepository>,
        #[cfg(feature = "listener")] listener_manager: Arc<GarrisonListenerManager>,
        #[cfg(feature = "three-tier-cache")] user_cache_service: Arc<
            crate::cache::UserCacheService,
        >,
    ) -> Arc<GarrisonLogicDefault> {
        // 自动注册 SessionHijackDetector(feature 启用时)
        #[cfg(feature = "session-hijack-detection")]
        let hijack_mode = config.session_hijack_mode;

        let mut builder =
            GarrisonLogicDefault::new(session.clone(), config, firewall, disable_repo)
                .with_plugin_manager(plugin_manager)
                .with_auth_logic(auth_logic)
                .with_permission_checker(permission_checker);
        #[cfg(feature = "listener")]
        {
            builder = builder.with_listener_manager(listener_manager);
        }
        #[cfg(feature = "three-tier-cache")]
        {
            builder = builder.with_user_cache_service(user_cache_service);
        }
        // 自动注册会话劫持检测器(复用 session + config 中的 mode)
        #[cfg(feature = "session-hijack-detection")]
        {
            builder = builder.with_anomaly_detector(Arc::new(
                crate::strategy::alert::SessionHijackDetector::new(session, hijack_mode),
            ));
        }
        Arc::new(builder)
    }
}

impl GarrisonManager {
    /// 获取可组合的初始化 builder。
    ///
    /// 返回所有字段为 None 的新 builder,通过链式 setter 注入依赖后调用
    /// [`build`](GarrisonManagerBuilder::build) 或 `build_explicit` 完成构造。
    pub fn builder() -> GarrisonManagerBuilder {
        GarrisonManagerBuilder::new()
    }
}

/// 默认 factory selector:从 inventory 中找到第一个注册的 `GarrisonLogicFactoryEntry`。
///
/// 若无 entry 注册,返回 `None`,由 `build_logic` 兜底使用 builder 链构造 `GarrisonLogicDefault`。
fn default_factory_selector() -> Option<&'static GarrisonLogicFactoryEntry> {
    use std::iter::Iterator;
    inventory::iter::<GarrisonLogicFactoryEntry>().next()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::GarrisonConfig;
    use crate::dao::tests::MockDao;
    use crate::dao::GarrisonDao;
    use crate::manager::mock::MockInterface;
    use crate::session::GarrisonSession;
    use crate::stp::GarrisonInterface;
    use async_trait::async_trait;
    use serial_test::serial;
    use std::sync::Arc;

    // 测试辅助

    fn make_config() -> GarrisonConfig {
        let mut config = GarrisonConfig::default_config();
        config.timeout = 3600;
        config.active_timeout = -1;
        config.throw_on_not_login = false;
        config
    }

    fn make_dao() -> Arc<dyn GarrisonDao> {
        Arc::new(MockDao::new())
    }

    /// `rate_limit_backend=memory`(默认)不构造 Redis 运行时,沿 DAO 自适应路径。
    #[cfg(all(feature = "firewall", feature = "rate-limit-redis"))]
    #[tokio::test]
    async fn prepare_limiter_runtime_memory_returns_none() {
        let mut builder = GarrisonManagerBuilder::new()
            .dao(make_dao())
            .config(Arc::new(make_config()));
        builder.prepare_limiter_runtime().await.unwrap();
        assert!(
            builder.limiter_runtime.is_none(),
            "Memory 配置不应建立 Redis 限流连接"
        );
    }

    fn make_interface() -> Arc<dyn GarrisonInterface> {
        Arc::new(MockInterface::new())
    }

    fn make_default_builder() -> GarrisonManagerBuilder {
        GarrisonManagerBuilder::new()
    }

    /// 构造带必填字段的 builder(用于 build/build_explicit 测试)。
    fn make_ready_builder() -> GarrisonManagerBuilder {
        GarrisonManagerBuilder::new()
            .dao(make_dao())
            .config(Arc::new(make_config()))
            .interface(make_interface())
    }

    /// 等待 task 被 abort 后 is_finished() 返回 true。
    #[cfg(feature = "manager-explicit")]
    async fn wait_finished(handle: &JoinHandle<()>) {
        for _ in 0..100 {
            if handle.is_finished() {
                return;
            }
            tokio::task::yield_now().await;
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        }
    }

    // 测试用 mock(AuthLogic / PermissionChecker / DisableRepository)

    #[derive(Clone)]
    struct MockAuthLogic;

    #[async_trait]
    impl AuthLogic for MockAuthLogic {
        async fn login(&self, id: &str, _params: Option<&str>) -> GarrisonResult<String> {
            Ok(format!("mock-token-{}", id))
        }
        async fn logout(&self, _token: &str) -> GarrisonResult<()> {
            Ok(())
        }
        async fn is_login(&self, _token: &str) -> GarrisonResult<bool> {
            Ok(true)
        }
        async fn get_login_id(&self, _token: &str) -> GarrisonResult<Option<String>> {
            Ok(Some("mock-user".to_string()))
        }
        async fn verify_token(&self, _token: &str) -> GarrisonResult<String> {
            Ok("mock-user".to_string())
        }
    }

    #[derive(Clone)]
    struct MockPermissionChecker;

    #[async_trait]
    impl PermissionChecker for MockPermissionChecker {
        async fn has_permission(&self, _login_id: &str, _permission: &str) -> GarrisonResult<bool> {
            Ok(true)
        }
        async fn has_role(&self, _login_id: &str, _role: &str) -> GarrisonResult<bool> {
            Ok(true)
        }
        async fn has_any_permission(&self, _login_id: &str, _perms: &[&str]) -> bool {
            true
        }
        async fn has_all_permissions(&self, _login_id: &str, _perms: &[&str]) -> bool {
            true
        }
    }

    #[derive(Clone)]
    struct MockDisableRepository;

    #[async_trait]
    impl DisableRepository for MockDisableRepository {
        async fn disable(
            &self,
            _login_id: &str,
            _service: &str,
            _until: Option<chrono::DateTime<chrono::Utc>>,
            _level: u32,
            _duration_secs: u64,
        ) -> GarrisonResult<()> {
            Ok(())
        }
        async fn untie_disable(&self, _login_id: &str, _service: &str) -> GarrisonResult<()> {
            Ok(())
        }
        async fn is_disable(&self, _login_id: &str, _service: &str) -> GarrisonResult<bool> {
            Ok(false)
        }
        async fn get_disable_time(
            &self,
            _login_id: &str,
            _service: &str,
        ) -> GarrisonResult<Option<chrono::DateTime<chrono::Utc>>> {
            Ok(None)
        }
        async fn get_disable_level(
            &self,
            _login_id: &str,
            _service: &str,
        ) -> GarrisonResult<Option<u32>> {
            Ok(None)
        }
    }

    /// 计数 DAO:get 返回 Err 并计数,用于验证 cleanup task 是否仍在运行。
    #[cfg(feature = "manager-explicit")]
    struct CountingDao {
        counter: Arc<std::sync::atomic::AtomicUsize>,
    }

    #[cfg(feature = "manager-explicit")]
    #[async_trait]
    impl GarrisonDao for CountingDao {
        crate::atomic_test_fallback!();
        async fn get(&self, _key: &str) -> GarrisonResult<Option<String>> {
            self.counter
                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            Err(GarrisonError::Dao("test counting".to_string()))
        }
        async fn set(&self, _key: &str, _value: &str, _ttl_seconds: u64) -> GarrisonResult<()> {
            Ok(())
        }
        async fn update(&self, _key: &str, _value: &str) -> GarrisonResult<()> {
            Ok(())
        }
        async fn expire(&self, _key: &str, _seconds: u64) -> GarrisonResult<()> {
            Ok(())
        }
        async fn delete(&self, _key: &str) -> GarrisonResult<()> {
            Ok(())
        }
    }

    // new() 与 9 个链式 setter

    #[test]
    fn builder_new_all_fields_none() {
        let b = make_default_builder();
        assert!(b.dao.is_none());
        assert!(b.config.is_none());
        assert!(b.interface.is_none());
        assert!(b.plugin_manager.is_none());
        #[cfg(feature = "listener")]
        assert!(b.listener_manager.is_none());
        assert!(b.auth_logic.is_none());
        assert!(b.permission_checker.is_none());
        assert!(b.disable_repository.is_none());
        #[cfg(feature = "three-tier-cache")]
        assert!(b.user_cache_service.is_none());
        assert!(b.factory.is_none());
    }

    #[test]
    fn builder_setters_set_fields() {
        let dao = make_dao();
        let config = Arc::new(make_config());
        let interface = make_interface();
        let pm = Arc::new(crate::plugin::GarrisonPluginManager::new());
        #[cfg(feature = "listener")]
        let lm = Arc::new(crate::listener::GarrisonListenerManager::new());
        let auth: Arc<dyn AuthLogic> = Arc::new(MockAuthLogic);
        let pc: Arc<dyn PermissionChecker> = Arc::new(MockPermissionChecker);
        let dr: Arc<dyn DisableRepository> = Arc::new(MockDisableRepository);

        let mut b = make_default_builder();
        b = b
            .dao(dao)
            .config(config)
            .interface(interface)
            .with_plugin_manager(pm)
            .with_auth_logic(auth)
            .with_permission_checker(pc)
            .with_disable_repository(dr);
        #[cfg(feature = "listener")]
        {
            b = b.with_listener_manager(lm);
        }
        #[cfg(feature = "three-tier-cache")]
        {
            let dao2 = make_dao();
            let fw: Arc<dyn GarrisonPermissionStrategy> =
                Arc::new(GarrisonPermissionStrategyDefault::new(make_interface()));
            let ucs = Arc::new(crate::cache::UserCacheService::new(dao2, fw, 60, 3600).unwrap());
            b = b.with_user_cache_service(ucs);
        }

        assert!(b.dao.is_some());
        assert!(b.config.is_some());
        assert!(b.interface.is_some());
        assert!(b.plugin_manager.is_some());
        #[cfg(feature = "listener")]
        assert!(b.listener_manager.is_some());
        assert!(b.auth_logic.is_some());
        assert!(b.permission_checker.is_some());
        assert!(b.disable_repository.is_some());
        #[cfg(feature = "three-tier-cache")]
        assert!(b.user_cache_service.is_some());
        assert!(b.factory.is_none());
    }

    // with_factory setter

    #[test]
    fn builder_with_factory_sets_field() {
        static TEST_ENTRY: GarrisonLogicFactoryEntry = GarrisonLogicFactoryEntry {
            name: "test-factory-setter",
            factory: crate::manager::factory::garrison_logic_factory_default,
        };
        let b = make_default_builder().with_factory(&TEST_ENTRY);
        assert!(b.factory.is_some());
        assert_eq!(b.factory.unwrap().name, "test-factory-setter");
    }

    // build() 注入全局单例

    #[tokio::test]
    #[serial]
    async fn build_injects_global_singleton() {
        GarrisonManager::reset_for_test();
        let result = make_ready_builder().build().await;
        assert!(result.is_ok(), "build 应成功: {:?}", result.map(|_| ()));
        assert!(GarrisonManager::is_initialized());
        GarrisonManager::reset_for_test();
    }

    // build_explicit() 返回独立 Manager,Drop 后 task 被 abort

    #[cfg(feature = "manager-explicit")]
    #[tokio::test]
    #[serial]
    async fn build_explicit_returns_independent_manager() {
        GarrisonManager::reset_for_test();
        let manager = make_ready_builder().build_explicit().await;
        assert!(
            manager.is_ok(),
            "build_explicit 应成功: {:?}",
            manager.err()
        );
        assert!(
            !GarrisonManager::is_initialized(),
            "build_explicit 不应触碰全局单例"
        );
        drop(manager);
        assert!(!GarrisonManager::is_initialized());
    }

    #[cfg(feature = "manager-explicit")]
    #[tokio::test]
    async fn build_explicit_drop_aborts_tasks() {
        let mut config = make_config();
        config.token_map_cleanup_interval_secs = 1;
        let counter = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let dao: Arc<dyn GarrisonDao> = Arc::new(CountingDao {
            counter: counter.clone(),
        });
        let builder = GarrisonManagerBuilder::new()
            .dao(dao)
            .config(Arc::new(config))
            .interface(make_interface());
        let (logic, task_handles) = builder.build_logic().unwrap();

        let cleanup_handle = task_handles.cleanup.clone().unwrap();
        #[cfg(feature = "anomalous-detector-dual")]
        let anomalous_handle = task_handles.anomalous.clone().unwrap();
        #[cfg(feature = "anomalous-detector-dual")]
        let anomalous_shutdown = task_handles.anomalous_shutdown.clone();

        let manager = Manager::with_task_handles(logic, task_handles);
        assert!(
            !cleanup_handle.is_finished(),
            "build 后 cleanup task 应运行中"
        );

        // 直接向 session 注入 token,使 cleanup 遍历 login_token_map 并调用 dao.get(计数)。
        // 不通过 login:CountingDao.get 返回 Err,login 会失败。
        manager.logic.session.add_login_token("1001", "token1");
        tokio::time::sleep(std::time::Duration::from_millis(1500)).await;
        let count_before = counter.load(std::sync::atomic::Ordering::SeqCst);
        assert!(
            count_before >= 1,
            "drop 前 cleanup task 应已运行(计数>=1)"
        );

        // 保留 shutdown_tx 引用使 manager Drop 后能通过 abort 终止 analyzer
        drop(manager);

        wait_finished(&cleanup_handle).await;
        assert!(
            cleanup_handle.is_finished(),
            "Manager Drop 后 cleanup task 应被 abort"
        );
        #[cfg(feature = "anomalous-detector-dual")]
        {
            wait_finished(&anomalous_handle).await;
            assert!(
                anomalous_handle.is_finished(),
                "Manager Drop 后 anomalous task 应被 abort"
            );
            drop(anomalous_shutdown);
        }

        // 验证 cleanup task 已停止(计数不再增长)
        let count_mid = counter.load(std::sync::atomic::Ordering::SeqCst);
        tokio::time::sleep(std::time::Duration::from_millis(1500)).await;
        let count_after = counter.load(std::sync::atomic::Ordering::SeqCst);
        assert!(
            count_after <= count_mid + 1,
            "abort 后 cleanup task 不应继续运行。mid={}, after={}",
            count_mid,
            count_after
        );
    }

    // 5 个 with_* manager 注入

    #[tokio::test]
    #[serial]
    async fn build_injects_plugin_manager() {
        GarrisonManager::reset_for_test();
        let pm = Arc::new(crate::plugin::GarrisonPluginManager::new());
        make_ready_builder()
            .with_plugin_manager(pm.clone())
            .build()
            .await
            .unwrap();
        let logic = GarrisonManager::logic().unwrap();
        assert!(
            Arc::ptr_eq(logic.plugin_manager.as_ref().unwrap(), &pm),
            "build 后 plugin_manager 应为注入实例"
        );
        GarrisonManager::reset_for_test();
    }

    #[cfg(feature = "listener")]
    #[tokio::test]
    #[serial]
    async fn build_injects_listener_manager() {
        GarrisonManager::reset_for_test();
        let lm = Arc::new(crate::listener::GarrisonListenerManager::new());
        make_ready_builder()
            .with_listener_manager(lm.clone())
            .build()
            .await
            .unwrap();
        let logic = GarrisonManager::logic().unwrap();
        assert!(
            Arc::ptr_eq(logic.listener_manager.as_ref().unwrap(), &lm),
            "build 后 listener_manager 应为注入实例"
        );
        GarrisonManager::reset_for_test();
    }

    #[tokio::test]
    #[serial]
    async fn build_injects_auth_logic() {
        GarrisonManager::reset_for_test();
        let al: Arc<dyn AuthLogic> = Arc::new(MockAuthLogic);
        make_ready_builder()
            .with_auth_logic(al.clone())
            .build()
            .await
            .unwrap();
        let logic = GarrisonManager::logic().unwrap();
        assert!(
            Arc::ptr_eq(&logic.auth_logic.as_ref().unwrap().clone(), &al),
            "build 后 auth_logic 应为注入实例"
        );
        GarrisonManager::reset_for_test();
    }

    #[tokio::test]
    #[serial]
    async fn build_injects_permission_checker() {
        GarrisonManager::reset_for_test();
        let pc: Arc<dyn PermissionChecker> = Arc::new(MockPermissionChecker);
        make_ready_builder()
            .with_permission_checker(pc.clone())
            .build()
            .await
            .unwrap();
        let logic = GarrisonManager::logic().unwrap();
        assert!(
            Arc::ptr_eq(&logic.permission_checker.as_ref().unwrap().clone(), &pc),
            "build 后 permission_checker 应为注入实例"
        );
        GarrisonManager::reset_for_test();
    }

    #[tokio::test]
    #[serial]
    async fn build_injects_disable_repository() {
        GarrisonManager::reset_for_test();
        let dr: Arc<dyn DisableRepository> = Arc::new(MockDisableRepository);
        make_ready_builder()
            .with_disable_repository(dr.clone())
            .build()
            .await
            .unwrap();
        let logic = GarrisonManager::logic().unwrap();
        assert!(
            Arc::ptr_eq(&logic.disable_repository, &dr),
            "build 后 disable_repository 应为注入实例"
        );
        GarrisonManager::reset_for_test();
    }

    // build_explicit() 路径下 GarrisonUtil 契约

    #[cfg(feature = "manager-explicit")]
    #[tokio::test]
    #[serial]
    async fn build_explicit_garrison_util_returns_manager_not_init() {
        GarrisonManager::reset_for_test();
        let _manager = make_ready_builder().build_explicit().await.unwrap();
        let result = crate::stp::GarrisonUtil::login_simple("1001").await;
        assert!(
            matches!(
                result,
                Err(GarrisonError::Session(ref msg)) if msg.contains("manager-not-init")
            ),
            "build_explicit 路径下 GarrisonUtil 应返回 manager-not-init,实际: {:?}",
            result.map(|_| ())
        );
        drop(_manager);
        GarrisonManager::reset_for_test();
    }

    #[tokio::test]
    #[serial]
    async fn build_garrison_util_works_normally() {
        GarrisonManager::reset_for_test();
        make_ready_builder().build().await.unwrap();
        let token = crate::stp::GarrisonUtil::login_simple("1001").await;
        assert!(token.is_ok(), "build 路径下 GarrisonUtil 应正常工作");
        GarrisonManager::reset_for_test();
    }

    // build() 后 cleanup_task_handle 状态

    #[tokio::test]
    #[serial]
    async fn build_sets_cleanup_task_handle() {
        GarrisonManager::reset_for_test();
        let mut config = make_config();
        config.token_map_cleanup_interval_secs = 1;
        let builder = GarrisonManagerBuilder::new()
            .dao(make_dao())
            .config(Arc::new(config))
            .interface(make_interface());
        builder.build().await.unwrap();
        assert!(
            GARRISON_MANAGER.cleanup_task_handle.read().is_some(),
            "interval > 0 时 build 后应持有 cleanup task handle"
        );
        GarrisonManager::reset_for_test();
        assert!(
            GARRISON_MANAGER.cleanup_task_handle.read().is_none(),
            "reset_for_test 后 cleanup task handle 应为 None"
        );
    }

    // 必填字段缺失 fail-closed

    #[tokio::test]
    #[serial]
    async fn build_missing_dao_fails_closed() {
        GarrisonManager::reset_for_test();
        let builder = GarrisonManagerBuilder::new()
            .config(Arc::new(make_config()))
            .interface(make_interface());
        let result = builder.build().await;
        assert!(
            matches!(result, Err(GarrisonError::Config(ref m)) if m == "builder-dao-missing"),
            "dao=None 应返回 builder-dao-missing,实际: {:?}",
            result.map(|_| ())
        );
        assert!(!GarrisonManager::is_initialized(), "失败后单例不应被初始化");
        GarrisonManager::reset_for_test();
    }

    #[tokio::test]
    #[serial]
    async fn build_missing_config_fails_closed() {
        GarrisonManager::reset_for_test();
        let builder = GarrisonManagerBuilder::new()
            .dao(make_dao())
            .interface(make_interface());
        let result = builder.build().await;
        assert!(
            matches!(result, Err(GarrisonError::Config(ref m)) if m == "builder-config-missing"),
            "config=None 应返回 builder-config-missing,实际: {:?}",
            result.map(|_| ())
        );
        assert!(!GarrisonManager::is_initialized());
        GarrisonManager::reset_for_test();
    }

    #[tokio::test]
    #[serial]
    async fn build_missing_interface_fails_closed() {
        GarrisonManager::reset_for_test();
        let builder = GarrisonManagerBuilder::new()
            .dao(make_dao())
            .config(Arc::new(make_config()));
        let result = builder.build().await;
        assert!(
            matches!(result, Err(GarrisonError::Config(ref m)) if m == "builder-interface-missing"),
            "interface=None 应返回 builder-interface-missing,实际: {:?}",
            result.map(|_| ())
        );
        assert!(!GarrisonManager::is_initialized());
        GarrisonManager::reset_for_test();
    }

    // with_factory 自定义 factory 构造 logic

    static TEST_MARKER_ENTRY: GarrisonLogicFactoryEntry = GarrisonLogicFactoryEntry {
        name: "test-marker",
        factory: test_marker_factory,
    };

    fn test_marker_factory(
        session: Arc<GarrisonSession>,
        config: Arc<GarrisonConfig>,
        firewall: Arc<dyn GarrisonPermissionStrategy>,
        ctx: &GarrisonLogicFactoryContext,
    ) -> GarrisonResult<Arc<GarrisonLogicDefault>> {
        let disable_repository = ctx.disable_repository.clone().unwrap_or_else(|| {
            Arc::new(crate::account::disable::DefaultDisableRepository::new(
                session.dao().clone(),
            )) as Arc<dyn crate::account::disable::DisableRepository>
        });
        let mut builder = GarrisonLogicDefault::new(session, config, firewall, disable_repository);
        if let Some(pm) = ctx.plugin_manager.clone() {
            builder = builder.with_plugin_manager(pm);
        }
        #[cfg(feature = "listener")]
        if let Some(lm) = ctx.listener_manager.clone() {
            builder = builder.with_listener_manager(lm);
        }
        if let Some(auth) = ctx.auth_logic.clone() {
            builder = builder.with_auth_logic(auth);
        }
        if let Some(pc) = ctx.permission_checker.clone() {
            builder = builder.with_permission_checker(pc);
        }
        Ok(Arc::new(builder.with_marker("custom-factory")))
    }

    #[tokio::test]
    #[serial]
    async fn build_with_factory_uses_custom_marker() {
        GarrisonManager::reset_for_test();
        make_ready_builder()
            .with_factory(&TEST_MARKER_ENTRY)
            .build()
            .await
            .unwrap();
        let logic = GarrisonManager::logic().unwrap();
        assert_eq!(
            logic.marker,
            Some("custom-factory"),
            "with_factory 应使用自定义 factory 构造 logic"
        );
        GarrisonManager::reset_for_test();
    }

    // three-tier-cache 注入与自动构造

    #[cfg(feature = "three-tier-cache")]
    #[tokio::test]
    #[serial]
    async fn build_injects_user_cache_service() {
        GarrisonManager::reset_for_test();
        let fw: Arc<dyn GarrisonPermissionStrategy> =
            Arc::new(GarrisonPermissionStrategyDefault::new(make_interface()));
        let custom_ucs =
            Arc::new(crate::cache::UserCacheService::new(make_dao(), fw, 60, 3600).unwrap());
        make_ready_builder()
            .with_user_cache_service(custom_ucs.clone())
            .build()
            .await
            .unwrap();
        let logic = GarrisonManager::logic().unwrap();
        assert!(
            Arc::ptr_eq(logic.user_cache_service.as_ref().unwrap(), &custom_ucs),
            "build 后 user_cache_service 应为注入实例"
        );
        GarrisonManager::reset_for_test();
    }

    #[cfg(feature = "three-tier-cache")]
    #[tokio::test]
    #[serial]
    async fn build_auto_constructs_user_cache_service() {
        GarrisonManager::reset_for_test();
        make_ready_builder().build().await.unwrap();
        let logic = GarrisonManager::logic().unwrap();
        assert!(
            logic.user_cache_service.is_some(),
            "three-tier-cache feature 下未注入时 build 应自动构造 user_cache_service"
        );
        GarrisonManager::reset_for_test();
    }

    // build_logic_via_builder_chain 兜底逻辑

    #[tokio::test]
    async fn build_logic_via_builder_chain_constructs_default_managers() {
        let dao = make_dao();
        let config = Arc::new(make_config());
        let interface = make_interface();
        let timeout = u64::try_from(config.timeout).unwrap();
        let session = Arc::new(GarrisonSession::new(dao, timeout, timeout, 0));
        let firewall: Arc<dyn GarrisonPermissionStrategy> =
            Arc::new(GarrisonPermissionStrategyDefault::new(interface));
        let plugin_manager = Arc::new(crate::plugin::GarrisonPluginManager::new());
        #[cfg(feature = "listener")]
        let listener_manager = Arc::new(crate::listener::GarrisonListenerManager::new());
        let auth_logic: Arc<dyn AuthLogic> = Arc::new(MockAuthLogic);
        let permission_checker: Arc<dyn PermissionChecker> = Arc::new(MockPermissionChecker);
        let disable_repo: Arc<dyn DisableRepository> = Arc::new(MockDisableRepository);
        #[cfg(feature = "three-tier-cache")]
        let firewall_for_cache = firewall.clone();

        let logic = GarrisonManagerBuilder::build_logic_via_builder_chain(
            session,
            config,
            firewall,
            plugin_manager,
            auth_logic,
            permission_checker,
            disable_repo,
            #[cfg(feature = "listener")]
            listener_manager,
            #[cfg(feature = "three-tier-cache")]
            Arc::new(
                crate::cache::UserCacheService::new(make_dao(), firewall_for_cache, 60, 3600)
                    .unwrap(),
            ),
        );

        assert!(
            logic.plugin_manager.is_some(),
            "兜底 logic 应注入 plugin_manager"
        );
        #[cfg(feature = "listener")]
        assert!(
            logic.listener_manager.is_some(),
            "兜底 logic 应注入 listener_manager"
        );
        assert!(logic.auth_logic.is_some(), "兜底 logic 应注入 auth_logic");
        assert!(
            logic.permission_checker.is_some(),
            "兜底 logic 应注入 permission_checker"
        );
        // disable_repository 为必需构造参数,字段恒存在(无 Option 断言)
    }

    // 覆盖率补充:TaskHandles::empty() + build_logic 错误路径

    /// `TaskHandles::empty()` 所有字段为 None。
    #[cfg(feature = "manager-explicit")]
    #[test]
    fn task_handles_empty_all_fields_none() {
        let handles = TaskHandles::empty();
        assert!(handles.cleanup.is_none(), "empty() cleanup 应为 None");
        #[cfg(feature = "anomalous-detector-dual")]
        assert!(handles.anomalous.is_none(), "empty() anomalous 应为 None");
        #[cfg(feature = "anomalous-detector-dual")]
        assert!(
            handles.anomalous_shutdown.is_none(),
            "empty() anomalous_shutdown 应为 None"
        );
    }

    /// `build_logic` 缺少 dao 时返回 Config 错误。
    #[tokio::test]
    async fn build_logic_missing_dao_returns_error() {
        let config = Arc::new(make_config());
        let interface = make_interface();
        let timeout = u64::try_from(config.timeout).unwrap();
        let session = Arc::new(crate::session::GarrisonSession::new(
            make_dao(),
            timeout,
            timeout,
            0,
        ));
        let firewall: Arc<dyn crate::strategy::GarrisonPermissionStrategy> = Arc::new(
            crate::strategy::GarrisonPermissionStrategyDefault::new(interface),
        );
        let plugin_manager = Arc::new(crate::plugin::GarrisonPluginManager::new());
        let auth_logic: Arc<dyn crate::core::auth::AuthLogic> = Arc::new(MockAuthLogic);
        let permission_checker: Arc<dyn crate::core::permission::PermissionChecker> =
            Arc::new(MockPermissionChecker);
        let disable_repo: Arc<dyn crate::account::disable::DisableRepository> =
            Arc::new(MockDisableRepository);

        // build_logic_via_builder_chain 本身不检查 dao(dao 在 session 内部),
        // 但应成功构造 logic。验证完整链路无 panic。
        let result = GarrisonManagerBuilder::build_logic_via_builder_chain(
            session,
            config,
            firewall,
            plugin_manager,
            auth_logic,
            permission_checker,
            disable_repo,
            #[cfg(feature = "listener")]
            Arc::new(crate::listener::GarrisonListenerManager::new()),
            #[cfg(feature = "three-tier-cache")]
            {
                let dao2 = make_dao();
                let fw2: Arc<dyn crate::strategy::GarrisonPermissionStrategy> = Arc::new(
                    crate::strategy::GarrisonPermissionStrategyDefault::new(make_interface()),
                );
                Arc::new(crate::cache::UserCacheService::new(dao2, fw2, 60, 3600).unwrap())
            },
        );
        // 成功构造(logic 内部状态正确即可)
        assert!(result.plugin_manager.is_some());
    }

    // 覆盖率补充:mock 方法调用(覆盖 async_trait 生成的 wrapper)

    /// 调用所有 mock 方法以覆盖 async_trait 生成的 async wrapper。
    #[tokio::test]
    async fn mock_methods_coverage_auth_logic_permission_checker_disable_repo() {
        let logic = MockAuthLogic;
        assert!(logic.login("u1", None).await.is_ok());
        assert!(logic.logout("t1").await.is_ok());
        assert!(logic.is_login("t1").await.is_ok());
        assert!(logic.get_login_id("t1").await.is_ok());
        assert!(logic.verify_token("t1").await.is_ok());

        let pc = MockPermissionChecker;
        assert!(pc.has_permission("u1", "p1").await.is_ok());
        assert!(pc.has_role("u1", "r1").await.is_ok());
        assert!(pc.has_any_permission("u1", &["p1", "p2"]).await);
        assert!(pc.has_all_permissions("u1", &["p1", "p2"]).await);

        let dr = MockDisableRepository;
        assert!(dr.disable("u1", "svc", None, 0, 0).await.is_ok());
        assert!(dr.untie_disable("u1", "svc").await.is_ok());
        assert!(dr.is_disable("u1", "svc").await.is_ok());
        assert!(dr.get_disable_time("u1", "svc").await.is_ok());
        assert!(dr.get_disable_level("u1", "svc").await.is_ok());
    }

    /// `GarrisonManagerBuilder::default()` 返回空 builder。
    #[test]
    fn builder_default_returns_empty_builder() {
        let b = GarrisonManagerBuilder::default();
        assert!(b.dao.is_none());
        assert!(b.config.is_none());
        assert!(b.interface.is_none());
    }
}