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
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! 异常登录定时分析引擎(双引擎的定时部分):`AnomalousLoginAnalyzer` 与实时引擎 `AnomalousLoginStrategy` 互补——
//! 实时引擎(`anomalous.rs`)登录时即时检测异地跳变(haversine 距离),定时引擎(本模块)定期扫描历史登录记录识别模式。
//!
//! 流程:`record_login` 将每次登录写入 DAO(key `anomalous:login:{login_id}:{nanos}`,TTL 24h);`analyze_once` 扫描时间窗口(1h)内记录
//! 按 login_id 分组,检测 3 种异常:`burst_login`(登录次数 > `burst_threshold`,默认 5)、`geo_jump`(不同 geo > 2,None 不计入)、
//! `device_mutation`(不同 device > 3,None 不计入)。

use crate::dao::GarrisonDao;
use crate::error::{GarrisonError, GarrisonResult};
use crate::listener::{GarrisonEvent, GarrisonListenerManager};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::watch;

/// 最大扫描 key 数量(DoS 防护)。
const MAX_SCAN: usize = 10_000;
/// login_id 最大长度(DoS 防护):超长 login_id 会构造极端长的 Redis key(`anomalous:login:{login_id}:{nanos}`),造成 key 膨胀/内存压力。
const MAX_LOGIN_ID_LEN: usize = 128;
/// 登录记录 TTL(秒,24h)。
const RECORD_TTL_SECS: u64 = 86_400;
/// 扫描时间窗口(秒,1h)。
const SCAN_WINDOW_SECS: i64 = 3_600;
/// 扫描耗时告警阈值(秒)。
const SCAN_SLOW_THRESHOLD: Duration = Duration::from_secs(1);
/// 默认关闭超时(秒)。
const DEFAULT_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);

/// 登录结果枚举。
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LoginResult {
    /// 登录成功。
    Success,
    /// 登录失败。
    Failed,
}

/// 异常登录记录。
///
/// 每次登录(成功/失败)均写入 DAO,供定时分析引擎扫描。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnomalousLoginRecord {
    /// 登录主体标识。
    pub login_id: String,
    /// 登录 IP 地址。
    pub ip: String,
    /// 地理位置标识(如 "CN-Beijing"),无法定位时为 None。
    pub geo: Option<String>,
    /// 设备指纹标识,无法识别时为 None。
    pub device: Option<String>,
    /// 登录时间戳(Unix 秒)。
    pub timestamp: i64,
    /// 登录结果。
    pub result: LoginResult,
}

/// 异常登录分析器配置。
#[derive(Debug, Clone)]
pub struct AnomalousAnalyzerConfig {
    /// 定时扫描间隔(秒,默认 3600)。
    pub interval_secs: u64,
    /// burst 登录阈值(次数 > 此值则告警,默认 5)。
    pub burst_threshold: u32,
    /// 最大扫描 key 数量(DoS 防护,默认 10_000)。
    pub max_scan: usize,
}

impl Default for AnomalousAnalyzerConfig {
    fn default() -> Self {
        Self {
            interval_secs: 3600,
            burst_threshold: 5,
            max_scan: MAX_SCAN,
        }
    }
}

impl AnomalousAnalyzerConfig {
    /// 校验配置合法性:`interval_secs` / `burst_threshold` / `max_scan` 任一为 0 返回 `Config` 错误。
    pub fn validate(&self) -> GarrisonResult<()> {
        if self.interval_secs == 0 {
            return Err(GarrisonError::Config(
                "strategy-interval-secs-zero::".to_string(),
            ));
        }
        if self.burst_threshold == 0 {
            return Err(GarrisonError::Config(
                "strategy-burst-threshold-zero::".to_string(),
            ));
        }
        if self.max_scan == 0 {
            return Err(GarrisonError::Config(
                "strategy-max-scan-zero::".to_string(),
            ));
        }
        Ok(())
    }
}

/// 异常登录检测事件。
///
/// 在定时分析引擎检测到异常模式时生成,可转换为 `GarrisonEvent` 广播。
#[derive(Debug, Clone)]
pub struct AnomalousLoginDetected {
    /// 登录主体标识。
    pub login_id: String,
    /// 异常原因(`"burst_login"` / `"geo_jump"` / `"device_mutation"`)。
    pub reason: String,
    /// 检测详情(JSON 值)。
    pub detail: serde_json::Value,
    /// 检测时间戳(Unix 秒)。
    pub timestamp: i64,
}

impl From<AnomalousLoginDetected> for GarrisonEvent {
    fn from(e: AnomalousLoginDetected) -> Self {
        GarrisonEvent::AnomalousLoginDetected {
            login_id: e.login_id,
            reason: e.reason,
            detail: e.detail,
            timestamp: e.timestamp,
            request_context: None,
        }
    }
}

/// 异常登录定时分析引擎:`start(self)` 消费自身并 spawn 定时任务,调用方持有 `shutdown_tx` 以优雅停止。
pub struct AnomalousLoginAnalyzer {
    /// DAO 抽象层(用于登录记录持久化与扫描)。
    dao: Arc<dyn GarrisonDao>,
    /// 分析器配置。
    config: AnomalousAnalyzerConfig,
    /// 监听器管理器(可选,Some 时广播事件)。
    listener_manager: Option<Arc<GarrisonListenerManager>>,
    /// shutdown 信号接收端(调用方持有发送端)。
    shutdown_rx: watch::Receiver<bool>,
}

impl AnomalousLoginAnalyzer {
    /// 创建分析器实例:`dao` 为 DAO 抽象层,`config` 为分析器配置,`shutdown_rx` 为 shutdown 接收端(调用方持有发送端),
    /// `listener_manager` 为监听器管理器(None 时不广播事件)。
    pub fn new(
        dao: Arc<dyn GarrisonDao>,
        config: AnomalousAnalyzerConfig,
        shutdown_rx: watch::Receiver<bool>,
        listener_manager: Option<Arc<GarrisonListenerManager>>,
    ) -> Self {
        Self {
            dao,
            config,
            listener_manager,
            shutdown_rx,
        }
    }

    /// 记录一次登录事件:序列化为 JSON 存入 DAO,key 格式 `anomalous:login:{login_id}:{nanos}`,TTL 24h。
    ///
    /// # 纳秒精度
    /// key 用纳秒精度时间戳(而非 record.timestamp 的秒级),避免同一秒内同一 login_id 的多次登录互相覆盖;
    /// `record.timestamp` 仍为秒级(用于时间窗口过滤),key 的纳秒仅用于唯一性。
    ///
    /// # 错误
    /// `login_id` 为空 / 含 `:`(破坏 key 解析)/ 超 128 字节(防超长 key DoS)→ `InvalidParam`;序列化失败 → `Internal`。
    pub async fn record_login(&self, record: &AnomalousLoginRecord) -> GarrisonResult<()> {
        if record.login_id.is_empty() {
            return Err(GarrisonError::InvalidParam(
                "strategy-login-id-empty::".to_string(),
            ));
        }
        if record.login_id.contains(':') {
            return Err(GarrisonError::InvalidParam(
                "strategy-login-id-no-colon".to_string(),
            ));
        }
        if record.login_id.len() > MAX_LOGIN_ID_LEN {
            return Err(GarrisonError::InvalidParam(format!(
                "strategy-login-id-too-long::{}::{}",
                record.login_id.len(),
                MAX_LOGIN_ID_LEN
            )));
        }
        let key = Self::make_storage_key(&record.login_id, record.timestamp);
        let value = serde_json::to_string(record)
            .map_err(|e| GarrisonError::Internal(format!("strategy-anomalous-serialize::{}", e)))?;
        self.dao.set(&key, &value, RECORD_TTL_SECS).await
    }

    /// 生成存储 key(纳秒精度避免同秒覆盖),格式 `anomalous:login:{login_id}:{nanos}`;`nanos` 取自 `SystemTime::now()`,保证同秒内多次调用产生不同 key。
    fn make_storage_key(login_id: &str, timestamp_secs: i64) -> String {
        use std::time::{SystemTime, UNIX_EPOCH};
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(timestamp_secs as u128);
        if nanos == timestamp_secs as u128 {
            // fallback 命中说明系统时钟异常(before UNIX_EPOCH),纳秒唯一性保证失效,同秒同 login_id 的并发写入可能互相覆盖——显式 warn 提示(不中断记录)
            tracing::warn!(
                login_id,
                fallback_ts = timestamp_secs,
                "anomalous_analyzer: system clock error, storage key falls back to second-precision timestamp (uniqueness not guaranteed)"
            );
        }
        format!("anomalous:login:{}:{}", login_id, nanos)
    }

    /// 执行一次分析扫描(使用当前时间戳),返回检测到的异常事件列表。
    pub async fn analyze(&self) -> GarrisonResult<Vec<AnomalousLoginDetected>> {
        let now = chrono::Utc::now().timestamp();
        Self::analyze_once(&self.dao, &self.config, now).await
    }

    /// 核心分析逻辑(关联函数,接收固定 `now` 参数便于测试):`dao.keys("anomalous:login:*")`(受 `max_scan` 限制)→ 反序列化
    /// (失败 `tracing::warn!` 跳过)→ 过滤时间窗口(`timestamp >= now - 3600 && timestamp <= now`)→ 按 login_id 分组 → 检测
    /// burst / geo_jump / device_mutation 3 种异常。
    ///
    /// # 性能监控
    /// 记录扫描总耗时,超过 1s 时 `tracing::warn!`(Redis 后端 N+1 查询需优化为批量 mget;oxcache 内存后端 get_sync <100ns,10000 次 get ~1ms,无需优化)。
    async fn analyze_once(
        dao: &Arc<dyn GarrisonDao>,
        config: &AnomalousAnalyzerConfig,
        now: i64,
    ) -> GarrisonResult<Vec<AnomalousLoginDetected>> {
        let scan_start = std::time::Instant::now();

        let keys = dao.keys("anomalous:login:*").await?;
        let keys: Vec<String> = keys.into_iter().take(config.max_scan).collect();

        // 已知性能问题:keys 后逐 key dao.get 构成 N+1 查询,Redis 后端在 keys 数接近 max_scan(默认 10000)时产生等量网络往返。
        // 保持原因:`GarrisonDao` trait 无 mget/get_many 批量接口(扩 trait 属 breaking change),缓解为 max_scan 上限(本行 take)+ 扫描耗时 > 1s 的 warn 监控。
        // 修复路径:DAO 层提供批量读取接口后改为分批 mget/SCAN 迭代。
        let mut grouped: HashMap<String, Vec<AnomalousLoginRecord>> = HashMap::new();

        for key in &keys {
            match dao.get(key).await {
                Ok(Some(value)) => match serde_json::from_str::<AnomalousLoginRecord>(&value) {
                    Ok(record) => {
                        if record.timestamp >= now - SCAN_WINDOW_SECS && record.timestamp <= now {
                            grouped
                                .entry(record.login_id.clone())
                                .or_default()
                                .push(record);
                        }
                    },
                    Err(e) => {
                        tracing::warn!("failed to deserialize login record (key={}): {}", key, e);
                    },
                },
                Ok(None) => {},
                Err(e) => {
                    tracing::warn!("failed to read login record (key={}): {}", key, e);
                },
            }
        }

        let mut events = Vec::new();

        for (login_id, records) in grouped {
            // burst_login: 登录次数 > burst_threshold
            if records.len() > config.burst_threshold as usize {
                events.push(AnomalousLoginDetected {
                    login_id: login_id.clone(),
                    reason: "burst_login".to_string(),
                    detail: serde_json::json!({
                        "count": records.len(),
                        "threshold": config.burst_threshold,
                    }),
                    timestamp: now,
                });
            }

            // geo_jump: 不同 geo > 2(None 不计入)
            let distinct_geo: HashSet<&str> =
                records.iter().filter_map(|r| r.geo.as_deref()).collect();
            if distinct_geo.len() > 2 {
                events.push(AnomalousLoginDetected {
                    login_id: login_id.clone(),
                    reason: "geo_jump".to_string(),
                    detail: serde_json::json!({
                        "distinct_geo": distinct_geo.len(),
                        "geo": distinct_geo.iter().collect::<Vec<_>>(),
                    }),
                    timestamp: now,
                });
            }

            // device_mutation: 不同 device > 3(None 不计入)
            let distinct_device: HashSet<&str> =
                records.iter().filter_map(|r| r.device.as_deref()).collect();
            if distinct_device.len() > 3 {
                events.push(AnomalousLoginDetected {
                    login_id: login_id.clone(),
                    reason: "device_mutation".to_string(),
                    detail: serde_json::json!({
                        "distinct_device": distinct_device.len(),
                        "device": distinct_device.iter().collect::<Vec<_>>(),
                    }),
                    timestamp: now,
                });
            }
        }

        // 扫描时间监控(Redis 后端 N+1 查询需优化为批量 mget)
        let scan_elapsed = scan_start.elapsed();
        if scan_elapsed > SCAN_SLOW_THRESHOLD {
            tracing::warn!(
                elapsed_ms = scan_elapsed.as_millis(),
                key_count = keys.len(),
                "anomaly login analysis scan exceeded 1s, Redis backend needs optimization to batch mget"
            );
        } else {
            tracing::debug!(
                elapsed_ms = scan_elapsed.as_millis(),
                key_count = keys.len(),
                "anomaly login analysis scan completed"
            );
        }

        Ok(events)
    }

    /// 启动定时分析任务:消费 `self`,spawn 一个 tokio 任务——按 `interval_secs` 间隔执行 `analyze_once`;检测到异常时经
    /// `listener_manager` 广播事件(若 Some);分析失败仅 `tracing::warn!` 不中断循环;收到 shutdown 信号时优雅停止。
    ///
    /// 返回 `JoinHandle<()>`,调用方可 `.await` 等待任务结束,或通过 [`shutdown`](Self::shutdown) 优雅停止。
    pub fn start(self) -> tokio::task::JoinHandle<()> {
        let dao = self.dao;
        let config = self.config;
        let listener_manager = self.listener_manager;
        let mut shutdown_rx = self.shutdown_rx;

        tokio::spawn(async move {
            let mut interval = tokio::time::interval(Duration::from_secs(config.interval_secs));
            loop {
                tokio::select! {
                    _ = interval.tick() => {
                        let now = chrono::Utc::now().timestamp();
                        match Self::analyze_once(&dao, &config, now).await {
                            Ok(events) => {
                                for event in events {
                                    if let Some(ref lm) = listener_manager {
                                        let garrison_event: GarrisonEvent = event.into();
                                        lm.broadcast(&garrison_event).await;
                                    }
                                }
                            },
                            Err(e) => {
                                tracing::warn!("anomaly login analysis failed: {}", e);
                            },
                        }
                    },
                    _ = shutdown_rx.changed() => {
                        tracing::info!(
                            "anomaly login analysis engine received shutdown signal, stopping"
                        );
                        break;
                    },
                }
            }
        })
    }

    /// 优雅停止分析器任务(默认 5 秒超时):发送 shutdown 信号后等待任务结束,超时则强制 abort;适用于异步上下文
    /// (GarrisonManager 的同步 Drop 仍用 `handle.abort()`)。`handle` 为 [`start`](Self::start) 返回的 `JoinHandle<()>`,
    /// `shutdown_tx` 为 `watch::Sender<bool>`;任务正常结束(或已被 cancelled)返回 `Ok(())`,panic 或超时被 abort 返回 `Err(Internal)`。
    pub async fn shutdown(
        handle: tokio::task::JoinHandle<()>,
        shutdown_tx: watch::Sender<bool>,
    ) -> GarrisonResult<()> {
        Self::shutdown_with_timeout(handle, shutdown_tx, DEFAULT_SHUTDOWN_TIMEOUT).await
    }

    /// 优雅停止分析器任务(自定义超时):发送 shutdown 信号(`shutdown_tx.send(true)`)→ 用 `tokio::time::timeout` 包裹
    /// `handle.await` → 超时后 `abort_handle.abort()` 强制终止。返回语义同 [`shutdown`](Self::shutdown)。
    pub async fn shutdown_with_timeout(
        handle: tokio::task::JoinHandle<()>,
        shutdown_tx: watch::Sender<bool>,
        timeout: Duration,
    ) -> GarrisonResult<()> {
        let _ = shutdown_tx.send(true);
        let abort_handle = handle.abort_handle();
        match tokio::time::timeout(timeout, handle).await {
            Ok(Ok(())) => Ok(()),
            Ok(Err(e)) if e.is_cancelled() => Ok(()),
            Ok(Err(e)) => Err(GarrisonError::Internal(format!(
                "strategy-analyzer-panic::{}",
                e
            ))),
            Err(_) => {
                abort_handle.abort();
                Err(GarrisonError::Internal(format!(
                    "strategy-analyzer-shutdown-timeout::{}",
                    timeout.as_millis()
                )))
            },
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dao::tests::MockDao;

    // LoginResult 序列化测试

    #[test]
    fn login_result_serde_roundtrip() {
        let success = LoginResult::Success;
        let failed = LoginResult::Failed;
        let success_json = serde_json::to_string(&success).unwrap();
        let failed_json = serde_json::to_string(&failed).unwrap();
        assert_eq!(success_json, "\"success\"");
        assert_eq!(failed_json, "\"failed\"");
        let success_de: LoginResult = serde_json::from_str(&success_json).unwrap();
        let failed_de: LoginResult = serde_json::from_str(&failed_json).unwrap();
        assert_eq!(success_de, LoginResult::Success);
        assert_eq!(failed_de, LoginResult::Failed);
    }

    // AnomalousLoginRecord 序列化与字段测试

    #[test]
    fn anomalous_login_record_serde_roundtrip() {
        let record = AnomalousLoginRecord {
            login_id: "1001".to_string(),
            ip: "1.2.3.4".to_string(),
            geo: Some("CN-Beijing".to_string()),
            device: Some("web-chrome".to_string()),
            timestamp: 1700000000,
            result: LoginResult::Success,
        };
        let json = serde_json::to_string(&record).unwrap();
        let de: AnomalousLoginRecord = serde_json::from_str(&json).unwrap();
        assert_eq!(de.login_id, "1001");
        assert_eq!(de.ip, "1.2.3.4");
        assert_eq!(de.geo, Some("CN-Beijing".to_string()));
        assert_eq!(de.device, Some("web-chrome".to_string()));
        assert_eq!(de.timestamp, 1700000000);
        assert_eq!(de.result, LoginResult::Success);
    }

    #[test]
    fn anomalous_login_record_optional_fields_none() {
        let record = AnomalousLoginRecord {
            login_id: "1001".to_string(),
            ip: "1.2.3.4".to_string(),
            geo: None,
            device: None,
            timestamp: 1700000000,
            result: LoginResult::Failed,
        };
        let json = serde_json::to_string(&record).unwrap();
        let de: AnomalousLoginRecord = serde_json::from_str(&json).unwrap();
        assert!(de.geo.is_none());
        assert!(de.device.is_none());
        assert_eq!(de.result, LoginResult::Failed);
    }

    // AnomalousAnalyzerConfig 测试

    #[test]
    fn analyzer_config_default() {
        let config = AnomalousAnalyzerConfig::default();
        assert_eq!(config.interval_secs, 3600);
        assert_eq!(config.burst_threshold, 5);
        assert_eq!(config.max_scan, 10_000);
    }

    #[test]
    fn analyzer_config_validate_ok() {
        let config = AnomalousAnalyzerConfig::default();
        assert!(config.validate().is_ok());
    }

    #[test]
    fn analyzer_config_validate_zero_interval() {
        let config = AnomalousAnalyzerConfig {
            interval_secs: 0,
            burst_threshold: 5,
            max_scan: 100,
        };
        assert!(config.validate().is_err());
    }

    #[test]
    fn analyzer_config_validate_zero_burst() {
        let config = AnomalousAnalyzerConfig {
            interval_secs: 3600,
            burst_threshold: 0,
            max_scan: 100,
        };
        assert!(config.validate().is_err());
    }

    #[test]
    fn analyzer_config_validate_zero_max_scan() {
        let config = AnomalousAnalyzerConfig {
            interval_secs: 3600,
            burst_threshold: 5,
            max_scan: 0,
        };
        assert!(config.validate().is_err());
    }

    // record_login 测试

    #[tokio::test]
    async fn record_login_persists_record() {
        let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
        let (tx, rx) = watch::channel(false);
        let analyzer =
            AnomalousLoginAnalyzer::new(dao.clone(), AnomalousAnalyzerConfig::default(), rx, None);
        let record = AnomalousLoginRecord {
            login_id: "1001".to_string(),
            ip: "1.2.3.4".to_string(),
            geo: Some("CN-Beijing".to_string()),
            device: Some("web".to_string()),
            timestamp: 1700000000,
            result: LoginResult::Success,
        };
        analyzer.record_login(&record).await.unwrap();

        // record_login 用纳秒精度 key,用 keys() 查找
        let keys = dao.keys("anomalous:login:1001:*").await.unwrap();
        assert_eq!(keys.len(), 1, "record_login 后应有 1 个 key");
        let stored = dao.get(&keys[0]).await.unwrap();
        assert!(stored.is_some());
        let de: AnomalousLoginRecord = serde_json::from_str(&stored.unwrap()).unwrap();
        assert_eq!(de.login_id, "1001");
        assert_eq!(de.ip, "1.2.3.4");
        let _ = tx;
    }

    #[tokio::test]
    async fn record_login_empty_login_id_errors() {
        let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
        let (_tx, rx) = watch::channel(false);
        let analyzer =
            AnomalousLoginAnalyzer::new(dao, AnomalousAnalyzerConfig::default(), rx, None);
        let record = AnomalousLoginRecord {
            login_id: "".to_string(),
            ip: "1.2.3.4".to_string(),
            geo: None,
            device: None,
            timestamp: 1700000000,
            result: LoginResult::Success,
        };
        let result = analyzer.record_login(&record).await;
        assert!(
            matches!(result, Err(GarrisonError::InvalidParam(_))),
            "空 login_id 应返回 InvalidParam"
        );
    }

    #[tokio::test]
    async fn record_login_colon_in_login_id_errors() {
        let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
        let (_tx, rx) = watch::channel(false);
        let analyzer =
            AnomalousLoginAnalyzer::new(dao, AnomalousAnalyzerConfig::default(), rx, None);
        let record = AnomalousLoginRecord {
            login_id: "user:1001".to_string(),
            ip: "1.2.3.4".to_string(),
            geo: None,
            device: None,
            timestamp: 1700000000,
            result: LoginResult::Success,
        };
        let result = analyzer.record_login(&record).await;
        assert!(
            matches!(result, Err(GarrisonError::InvalidParam(_))),
            "包含 ':' 的 login_id 应返回 InvalidParam"
        );
    }

    /// 超长 login_id 返回 InvalidParam(防超长 key DoS)。
    #[tokio::test]
    async fn record_login_overlong_login_id_errors() {
        let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
        let (_tx, rx) = watch::channel(false);
        let analyzer =
            AnomalousLoginAnalyzer::new(dao, AnomalousAnalyzerConfig::default(), rx, None);
        let record = AnomalousLoginRecord {
            login_id: "a".repeat(129),
            ip: "1.2.3.4".to_string(),
            geo: None,
            device: None,
            timestamp: 1700000000,
            result: LoginResult::Success,
        };
        let result = analyzer.record_login(&record).await;
        assert!(
            matches!(&result, Err(GarrisonError::InvalidParam(msg)) if msg.contains("too-long")),
            "超过 128 字节的 login_id 应返回 InvalidParam,实际: {:?}",
            result
        );

        // 边界:恰好 128 字节应通过
        let record_ok = AnomalousLoginRecord {
            login_id: "b".repeat(128),
            ..record
        };
        assert!(
            analyzer.record_login(&record_ok).await.is_ok(),
            "恰好 128 字节的 login_id 应通过"
        );
    }

    /// 同秒内多次 record_login 不覆盖:同一 login_id 同一秒内调用 3 次,keys() 应返回 3 个不同的 key(纳秒精度避免覆盖)。
    #[tokio::test]
    async fn record_login_same_second_no_overwrite() {
        let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
        let (_tx, rx) = watch::channel(false);
        let analyzer =
            AnomalousLoginAnalyzer::new(dao.clone(), AnomalousAnalyzerConfig::default(), rx, None);
        let now = 1700000000i64;
        // 同一 login_id 同一秒内 3 次登录
        for i in 0..3 {
            let record = AnomalousLoginRecord {
                login_id: "1001".to_string(),
                ip: format!("1.2.3.{}", i),
                geo: None,
                device: None,
                timestamp: now,
                result: LoginResult::Success,
            };
            analyzer.record_login(&record).await.unwrap();
        }
        // keys() 应返回 3 个不同的 key(纳秒精度避免覆盖)
        let keys = dao.keys("anomalous:login:1001:*").await.unwrap();
        assert_eq!(
            keys.len(),
            3,
            "同秒内 3 次 record_login 应产生 3 个不同的 key(HIGH-002 修复)"
        );
        // 验证 3 个 key 互不相同
        let unique: HashSet<&str> = keys.iter().map(|s| s.as_str()).collect();
        assert_eq!(unique.len(), 3, "3 个 key 应互不相同");
    }

    // analyze_once 测试(核心检测逻辑)

    /// 辅助函数:创建并插入登录记录到 DAO。
    async fn insert_records(dao: &Arc<dyn GarrisonDao>, records: &[AnomalousLoginRecord]) {
        for record in records {
            let key = format!("anomalous:login:{}:{}", record.login_id, record.timestamp);
            let value = serde_json::to_string(record).unwrap();
            dao.set(&key, &value, RECORD_TTL_SECS).await.unwrap();
        }
    }

    #[tokio::test]
    async fn analyze_empty_returns_empty() {
        let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
        let config = AnomalousAnalyzerConfig::default();
        let events = AnomalousLoginAnalyzer::analyze_once(&dao, &config, 1700000000)
            .await
            .unwrap();
        assert!(events.is_empty());
    }

    #[tokio::test]
    async fn analyze_burst_below_threshold() {
        let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
        let now = 1700000000i64;
        let records: Vec<AnomalousLoginRecord> = (0..5)
            .map(|i| AnomalousLoginRecord {
                login_id: "1001".to_string(),
                ip: format!("1.2.3.{}", i),
                geo: None,
                device: None,
                timestamp: now - 100 - i as i64,
                result: LoginResult::Success,
            })
            .collect();
        insert_records(&dao, &records).await;
        let config = AnomalousAnalyzerConfig::default();
        let events = AnomalousLoginAnalyzer::analyze_once(&dao, &config, now)
            .await
            .unwrap();
        let burst_events: Vec<_> = events
            .iter()
            .filter(|e| e.reason == "burst_login")
            .collect();
        assert!(
            burst_events.is_empty(),
            "5 条记录(== 阈值 5)不应触发 burst"
        );
    }

    #[tokio::test]
    async fn analyze_burst_above_threshold() {
        let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
        let now = 1700000000i64;
        let records: Vec<AnomalousLoginRecord> = (0..6)
            .map(|i| AnomalousLoginRecord {
                login_id: "1001".to_string(),
                ip: format!("1.2.3.{}", i),
                geo: None,
                device: None,
                timestamp: now - 100 - i as i64,
                result: LoginResult::Success,
            })
            .collect();
        insert_records(&dao, &records).await;
        let config = AnomalousAnalyzerConfig::default();
        let events = AnomalousLoginAnalyzer::analyze_once(&dao, &config, now)
            .await
            .unwrap();
        let burst_events: Vec<_> = events
            .iter()
            .filter(|e| e.reason == "burst_login")
            .collect();
        assert_eq!(
            burst_events.len(),
            1,
            "6 条记录(> 阈值 5)应触发 1 次 burst"
        );
        assert_eq!(burst_events[0].login_id, "1001");
    }

    #[tokio::test]
    async fn analyze_burst_event_fields() {
        let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
        let now = 1700000000i64;
        let records: Vec<AnomalousLoginRecord> = (0..10)
            .map(|i| AnomalousLoginRecord {
                login_id: "1001".to_string(),
                ip: format!("1.2.3.{}", i),
                geo: None,
                device: None,
                timestamp: now - 50 - i as i64,
                result: LoginResult::Success,
            })
            .collect();
        insert_records(&dao, &records).await;
        let config = AnomalousAnalyzerConfig::default();
        let events = AnomalousLoginAnalyzer::analyze_once(&dao, &config, now)
            .await
            .unwrap();
        let burst = events.iter().find(|e| e.reason == "burst_login").unwrap();
        assert_eq!(burst.login_id, "1001");
        assert_eq!(burst.timestamp, now);
        assert_eq!(burst.detail["count"], 10);
        assert_eq!(burst.detail["threshold"], 5);
    }

    #[tokio::test]
    async fn analyze_geo_jump_below_threshold() {
        let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
        let now = 1700000000i64;
        let records = vec![
            AnomalousLoginRecord {
                login_id: "1001".to_string(),
                ip: "1.1.1.1".to_string(),
                geo: Some("CN-Beijing".to_string()),
                device: None,
                timestamp: now - 100,
                result: LoginResult::Success,
            },
            AnomalousLoginRecord {
                login_id: "1001".to_string(),
                ip: "2.2.2.2".to_string(),
                geo: Some("CN-Shanghai".to_string()),
                device: None,
                timestamp: now - 50,
                result: LoginResult::Success,
            },
        ];
        insert_records(&dao, &records).await;
        let config = AnomalousAnalyzerConfig::default();
        let events = AnomalousLoginAnalyzer::analyze_once(&dao, &config, now)
            .await
            .unwrap();
        let geo_events: Vec<_> = events.iter().filter(|e| e.reason == "geo_jump").collect();
        assert!(
            geo_events.is_empty(),
            "2 个不同 geo(== 阈值 2)不应触发 geo_jump"
        );
    }

    #[tokio::test]
    async fn analyze_geo_jump_above_threshold() {
        let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
        let now = 1700000000i64;
        let records = vec![
            AnomalousLoginRecord {
                login_id: "1001".to_string(),
                ip: "1.1.1.1".to_string(),
                geo: Some("CN-Beijing".to_string()),
                device: None,
                timestamp: now - 100,
                result: LoginResult::Success,
            },
            AnomalousLoginRecord {
                login_id: "1001".to_string(),
                ip: "2.2.2.2".to_string(),
                geo: Some("CN-Shanghai".to_string()),
                device: None,
                timestamp: now - 80,
                result: LoginResult::Success,
            },
            AnomalousLoginRecord {
                login_id: "1001".to_string(),
                ip: "3.3.3.3".to_string(),
                geo: Some("US-NewYork".to_string()),
                device: None,
                timestamp: now - 50,
                result: LoginResult::Success,
            },
        ];
        insert_records(&dao, &records).await;
        let config = AnomalousAnalyzerConfig::default();
        let events = AnomalousLoginAnalyzer::analyze_once(&dao, &config, now)
            .await
            .unwrap();
        let geo_events: Vec<_> = events.iter().filter(|e| e.reason == "geo_jump").collect();
        assert_eq!(
            geo_events.len(),
            1,
            "3 个不同 geo(> 阈值 2)应触发 1 次 geo_jump"
        );
        assert_eq!(geo_events[0].detail["distinct_geo"], 3);
    }

    #[tokio::test]
    async fn analyze_geo_jump_none_excluded() {
        let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
        let now = 1700000000i64;
        // 2 个有 geo + 10 个 None → distinct_geo = 2(== 阈值,不触发)
        let mut records = vec![
            AnomalousLoginRecord {
                login_id: "1001".to_string(),
                ip: "1.1.1.1".to_string(),
                geo: Some("CN-Beijing".to_string()),
                device: None,
                timestamp: now - 100,
                result: LoginResult::Success,
            },
            AnomalousLoginRecord {
                login_id: "1001".to_string(),
                ip: "2.2.2.2".to_string(),
                geo: Some("CN-Shanghai".to_string()),
                device: None,
                timestamp: now - 50,
                result: LoginResult::Success,
            },
        ];
        for i in 0..10 {
            records.push(AnomalousLoginRecord {
                login_id: "1001".to_string(),
                ip: format!("10.0.0.{}", i),
                geo: None,
                device: None,
                timestamp: now - 10 - i as i64,
                result: LoginResult::Success,
            });
        }
        insert_records(&dao, &records).await;
        let config = AnomalousAnalyzerConfig::default();
        let events = AnomalousLoginAnalyzer::analyze_once(&dao, &config, now)
            .await
            .unwrap();
        let geo_events: Vec<_> = events.iter().filter(|e| e.reason == "geo_jump").collect();
        assert!(
            geo_events.is_empty(),
            "None geo 不计入,2 个有 geo 不应触发 geo_jump"
        );
    }

    #[tokio::test]
    async fn analyze_device_mutation_below_threshold() {
        let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
        let now = 1700000000i64;
        let records = vec![
            AnomalousLoginRecord {
                login_id: "1001".to_string(),
                ip: "1.1.1.1".to_string(),
                geo: None,
                device: Some("web".to_string()),
                timestamp: now - 100,
                result: LoginResult::Success,
            },
            AnomalousLoginRecord {
                login_id: "1001".to_string(),
                ip: "2.2.2.2".to_string(),
                geo: None,
                device: Some("ios".to_string()),
                timestamp: now - 50,
                result: LoginResult::Success,
            },
            AnomalousLoginRecord {
                login_id: "1001".to_string(),
                ip: "3.3.3.3".to_string(),
                geo: None,
                device: Some("android".to_string()),
                timestamp: now - 30,
                result: LoginResult::Success,
            },
        ];
        insert_records(&dao, &records).await;
        let config = AnomalousAnalyzerConfig::default();
        let events = AnomalousLoginAnalyzer::analyze_once(&dao, &config, now)
            .await
            .unwrap();
        let device_events: Vec<_> = events
            .iter()
            .filter(|e| e.reason == "device_mutation")
            .collect();
        assert!(
            device_events.is_empty(),
            "3 个不同 device(== 阈值 3)不应触发 device_mutation"
        );
    }

    #[tokio::test]
    async fn analyze_device_mutation_above_threshold() {
        let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
        let now = 1700000000i64;
        let records = vec![
            AnomalousLoginRecord {
                login_id: "1001".to_string(),
                ip: "1.1.1.1".to_string(),
                geo: None,
                device: Some("web".to_string()),
                timestamp: now - 100,
                result: LoginResult::Success,
            },
            AnomalousLoginRecord {
                login_id: "1001".to_string(),
                ip: "2.2.2.2".to_string(),
                geo: None,
                device: Some("ios".to_string()),
                timestamp: now - 80,
                result: LoginResult::Success,
            },
            AnomalousLoginRecord {
                login_id: "1001".to_string(),
                ip: "3.3.3.3".to_string(),
                geo: None,
                device: Some("android".to_string()),
                timestamp: now - 60,
                result: LoginResult::Success,
            },
            AnomalousLoginRecord {
                login_id: "1001".to_string(),
                ip: "4.4.4.4".to_string(),
                geo: None,
                device: Some("tablet".to_string()),
                timestamp: now - 40,
                result: LoginResult::Success,
            },
        ];
        insert_records(&dao, &records).await;
        let config = AnomalousAnalyzerConfig::default();
        let events = AnomalousLoginAnalyzer::analyze_once(&dao, &config, now)
            .await
            .unwrap();
        let device_events: Vec<_> = events
            .iter()
            .filter(|e| e.reason == "device_mutation")
            .collect();
        assert_eq!(
            device_events.len(),
            1,
            "4 个不同 device(> 阈值 3)应触发 1 次 device_mutation"
        );
        assert_eq!(device_events[0].detail["distinct_device"], 4);
    }

    #[tokio::test]
    async fn analyze_device_mutation_none_excluded() {
        let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
        let now = 1700000000i64;
        // 3 个有 device + 10 个 None → distinct_device = 3(== 阈值,不触发)
        let mut records = vec![
            AnomalousLoginRecord {
                login_id: "1001".to_string(),
                ip: "1.1.1.1".to_string(),
                geo: None,
                device: Some("web".to_string()),
                timestamp: now - 100,
                result: LoginResult::Success,
            },
            AnomalousLoginRecord {
                login_id: "1001".to_string(),
                ip: "2.2.2.2".to_string(),
                geo: None,
                device: Some("ios".to_string()),
                timestamp: now - 80,
                result: LoginResult::Success,
            },
            AnomalousLoginRecord {
                login_id: "1001".to_string(),
                ip: "3.3.3.3".to_string(),
                geo: None,
                device: Some("android".to_string()),
                timestamp: now - 60,
                result: LoginResult::Success,
            },
        ];
        for i in 0..10 {
            records.push(AnomalousLoginRecord {
                login_id: "1001".to_string(),
                ip: format!("10.0.0.{}", i),
                geo: None,
                device: None,
                timestamp: now - 10 - i as i64,
                result: LoginResult::Success,
            });
        }
        insert_records(&dao, &records).await;
        let config = AnomalousAnalyzerConfig::default();
        let events = AnomalousLoginAnalyzer::analyze_once(&dao, &config, now)
            .await
            .unwrap();
        let device_events: Vec<_> = events
            .iter()
            .filter(|e| e.reason == "device_mutation")
            .collect();
        assert!(
            device_events.is_empty(),
            "None device 不计入,3 个有 device 不应触发 device_mutation"
        );
    }

    // 时间窗口与 max_scan 测试

    #[tokio::test]
    async fn analyze_time_window_filter() {
        let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
        let now = 1700000000i64;
        // 窗口内的记录(6 条,触发 burst)
        let in_window: Vec<AnomalousLoginRecord> = (0..6)
            .map(|i| AnomalousLoginRecord {
                login_id: "1001".to_string(),
                ip: format!("1.2.3.{}", i),
                geo: None,
                device: None,
                timestamp: now - 100 - i as i64,
                result: LoginResult::Success,
            })
            .collect();
        insert_records(&dao, &in_window).await;
        // 窗口外的记录(6 条,不应计入)
        let out_window: Vec<AnomalousLoginRecord> = (0..6)
            .map(|i| AnomalousLoginRecord {
                login_id: "1001".to_string(),
                ip: format!("5.6.7.{}", i),
                geo: None,
                device: None,
                timestamp: now - SCAN_WINDOW_SECS - 100 - i as i64,
                result: LoginResult::Success,
            })
            .collect();
        insert_records(&dao, &out_window).await;

        let config = AnomalousAnalyzerConfig::default();
        let events = AnomalousLoginAnalyzer::analyze_once(&dao, &config, now)
            .await
            .unwrap();
        let burst = events.iter().find(|e| e.reason == "burst_login").unwrap();
        // 只计入窗口内 6 条
        assert_eq!(burst.detail["count"], 6);
    }

    #[tokio::test]
    async fn analyze_max_scan_limit() {
        let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
        let now = 1700000000i64;
        let records: Vec<AnomalousLoginRecord> = (0..20)
            .map(|i| AnomalousLoginRecord {
                login_id: "1001".to_string(),
                ip: format!("1.2.3.{}", i),
                geo: None,
                device: None,
                timestamp: now - 100 - i as i64,
                result: LoginResult::Success,
            })
            .collect();
        insert_records(&dao, &records).await;
        // max_scan = 5,只扫描前 5 条(<= 阈值 5,不触发 burst)
        let config = AnomalousAnalyzerConfig {
            interval_secs: 3600,
            burst_threshold: 5,
            max_scan: 5,
        };
        let events = AnomalousLoginAnalyzer::analyze_once(&dao, &config, now)
            .await
            .unwrap();
        let burst_events: Vec<_> = events
            .iter()
            .filter(|e| e.reason == "burst_login")
            .collect();
        assert!(
            burst_events.is_empty(),
            "max_scan=5 只扫描 5 条,不触发 burst"
        );
    }

    // 反序列化容错测试

    #[tokio::test]
    async fn analyze_deserialization_failure_skips() {
        let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
        let now = 1700000000i64;
        // 插入 6 条有效记录(触发 burst)
        let records: Vec<AnomalousLoginRecord> = (0..6)
            .map(|i| AnomalousLoginRecord {
                login_id: "1001".to_string(),
                ip: format!("1.2.3.{}", i),
                geo: None,
                device: None,
                timestamp: now - 100 - i as i64,
                result: LoginResult::Success,
            })
            .collect();
        insert_records(&dao, &records).await;
        dao.set("anomalous:login:1001:bad1", "not-json", RECORD_TTL_SECS)
            .await
            .unwrap();
        dao.set("anomalous:login:1001:bad2", "{invalid}", RECORD_TTL_SECS)
            .await
            .unwrap();

        let config = AnomalousAnalyzerConfig::default();
        let events = AnomalousLoginAnalyzer::analyze_once(&dao, &config, now)
            .await
            .unwrap();
        // 损坏记录应被跳过,不影响有效记录的 burst 检测
        let burst = events.iter().find(|e| e.reason == "burst_login");
        assert!(burst.is_some(), "损坏记录应跳过,6 条有效记录仍触发 burst");
        assert_eq!(burst.unwrap().detail["count"], 6);
    }

    // 多用户场景测试

    #[tokio::test]
    async fn analyze_multiple_users() {
        let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
        let now = 1700000000i64;
        // 用户 1001:6 条记录(触发 burst)
        let user_a: Vec<AnomalousLoginRecord> = (0..6)
            .map(|i| AnomalousLoginRecord {
                login_id: "1001".to_string(),
                ip: format!("1.2.3.{}", i),
                geo: None,
                device: None,
                timestamp: now - 100 - i as i64,
                result: LoginResult::Success,
            })
            .collect();
        insert_records(&dao, &user_a).await;
        // 用户 1002:6 条记录(触发 burst)
        let user_b: Vec<AnomalousLoginRecord> = (0..6)
            .map(|i| AnomalousLoginRecord {
                login_id: "1002".to_string(),
                ip: format!("5.6.7.{}", i),
                geo: None,
                device: None,
                timestamp: now - 100 - i as i64,
                result: LoginResult::Success,
            })
            .collect();
        insert_records(&dao, &user_b).await;

        let config = AnomalousAnalyzerConfig::default();
        let events = AnomalousLoginAnalyzer::analyze_once(&dao, &config, now)
            .await
            .unwrap();
        let burst_events: Vec<_> = events
            .iter()
            .filter(|e| e.reason == "burst_login")
            .collect();
        assert_eq!(burst_events.len(), 2, "两个用户各触发 1 次 burst");
        let login_ids: HashSet<&str> = burst_events.iter().map(|e| e.login_id.as_str()).collect();
        assert!(login_ids.contains("1001"));
        assert!(login_ids.contains("1002"));
    }

    // start + shutdown 集成测试

    #[tokio::test]
    async fn start_shutdown_stops_task() {
        let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
        let (tx, rx) = watch::channel(false);
        let config = AnomalousAnalyzerConfig {
            interval_secs: 3600,
            burst_threshold: 5,
            max_scan: 100,
        };
        let analyzer = AnomalousLoginAnalyzer::new(dao, config, rx, None);
        let handle = analyzer.start();
        let _ = tx.send(true);
        // 等待任务结束(给 1 秒超时)
        tokio::time::timeout(Duration::from_secs(1), handle)
            .await
            .expect("任务应在 shutdown 信号后 1 秒内结束")
            .expect("任务不应 panic");
    }

    // From<AnomalousLoginDetected> for GarrisonEvent 测试

    #[test]
    fn from_anomalous_login_detected_to_garrison_event() {
        let detected = AnomalousLoginDetected {
            login_id: "1001".to_string(),
            reason: "burst_login".to_string(),
            detail: serde_json::json!({"count": 10}),
            timestamp: 1700000000,
        };
        let event: GarrisonEvent = detected.into();
        match event {
            GarrisonEvent::AnomalousLoginDetected {
                login_id,
                reason,
                detail,
                timestamp,
                ..
            } => {
                assert_eq!(login_id, "1001");
                assert_eq!(reason, "burst_login");
                assert_eq!(detail["count"], 10);
                assert_eq!(timestamp, 1700000000);
            },
            _ => panic!("期望 AnomalousLoginDetected 事件"),
        }
    }

    // shutdown + shutdown_with_timeout 测试

    /// shutdown_with_timeout 对慢任务(不响应 shutdown 信号)超时后强制 abort:创建一个永远 pending 的任务,100ms 超时后应返回 Err。
    #[tokio::test]
    async fn shutdown_with_timeout_aborts_slow_task() {
        let _en = crate::i18n::set_locale(crate::i18n::GarrisonLocale::En);
        let handle = tokio::spawn(async {
            std::future::pending::<()>().await;
        });
        let (tx, _rx) = watch::channel(false);

        let result =
            AnomalousLoginAnalyzer::shutdown_with_timeout(handle, tx, Duration::from_millis(100))
                .await;

        assert!(result.is_err(), "慢任务应超时返回 Err");
        let err_msg = format!("{}", result.unwrap_err());
        assert!(
            err_msg.contains("anomalous analyzer shutdown timeout"),
            "错误信息应包含关闭超时标识(嵌套错误不经过翻译链,断言取 locale 无关片段),实际: {}",
            err_msg
        );
    }

    /// shutdown_with_timeout 对正常结束的任务返回 Ok。
    #[tokio::test]
    async fn shutdown_with_timeout_normal_completion() {
        let handle = tokio::spawn(async {
            tokio::time::sleep(Duration::from_millis(10)).await;
        });
        let (tx, _rx) = watch::channel(false);

        let result =
            AnomalousLoginAnalyzer::shutdown_with_timeout(handle, tx, Duration::from_secs(1)).await;

        assert!(result.is_ok(), "正常结束的任务应返回 Ok");
    }

    /// shutdown_with_timeout 对响应 shutdown 信号的任务返回 Ok:任务通过 `rx.has_changed()` 检测信号并退出。
    #[tokio::test]
    async fn shutdown_with_timeout_responds_to_signal() {
        let (tx, rx) = watch::channel(false);
        let rx = rx;
        let handle = tokio::spawn(async move {
            loop {
                if rx.has_changed().unwrap_or(false) {
                    break;
                }
                tokio::time::sleep(Duration::from_millis(5)).await;
            }
        });

        let result =
            AnomalousLoginAnalyzer::shutdown_with_timeout(handle, tx, Duration::from_secs(1)).await;

        assert!(result.is_ok(), "响应 shutdown 信号的任务应返回 Ok");
    }

    /// shutdown_with_timeout 对已 cancelled 的任务返回 Ok(幂等)。
    #[tokio::test]
    async fn shutdown_with_timeout_already_cancelled() {
        let handle = tokio::spawn(async {
            tokio::time::sleep(Duration::from_millis(10)).await;
        });
        let (tx, _rx) = watch::channel(false);
        handle.abort();

        let result =
            AnomalousLoginAnalyzer::shutdown_with_timeout(handle, tx, Duration::from_secs(1)).await;

        assert!(result.is_ok(), "已 cancelled 的任务应返回 Ok(幂等)");
    }

    /// shutdown_with_timeout 对 panic 的任务返回 Err(包含 panic 信息)。
    #[tokio::test]
    async fn shutdown_with_timeout_panic_task() {
        let handle = tokio::spawn(async {
            panic!("任务 panic 测试");
        });
        let (tx, _rx) = watch::channel(false);

        // 等待任务 panic 完成
        tokio::time::sleep(Duration::from_millis(50)).await;

        let result =
            AnomalousLoginAnalyzer::shutdown_with_timeout(handle, tx, Duration::from_secs(1)).await;

        assert!(result.is_err(), "panic 任务应返回 Err");
        let err_msg = format!("{}", result.unwrap_err());
        assert!(
            err_msg.contains("panic"),
            "错误信息应包含 'panic',实际: {}",
            err_msg
        );
    }

    /// start + shutdown 集成测试:创建真实 analyzer,start 后用 shutdown_with_timeout 停止,验证任务在 1 秒内响应 shutdown 信号退出。
    #[tokio::test]
    async fn start_then_shutdown_normal_stop() {
        let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
        let (tx, rx) = watch::channel(false);
        let config = AnomalousAnalyzerConfig {
            interval_secs: 3600,
            burst_threshold: 5,
            max_scan: 100,
        };
        let analyzer = AnomalousLoginAnalyzer::new(dao, config, rx, None);
        let handle = analyzer.start();

        let result =
            AnomalousLoginAnalyzer::shutdown_with_timeout(handle, tx, Duration::from_secs(1)).await;

        assert!(result.is_ok(), "正常 shutdown 应返回 Ok");
    }
}