limiteron 0.2.4

Unified flow control framework for 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
// Copyright (c) 2026 Kirky.X
// SPDX-License-Identifier: MIT
//! 地理位置匹配器
//!
//! 基于MaxMind GeoLite2数据库实现IP地理位置查询和匹配。
//!
//! # 特性
//!
//! - 支持国家/地区/城市查询
//! - 内存映射数据库文件(高性能)
//! - 内置缓存(查询延迟 < 1ms)
//! - 支持离线模式
//!
//! # 性能
//!
//! - 查询延迟 P99 < 1ms
//! - 缓存命中率 > 95%
//! - 准确率 > 95%
//!
//! # 使用示例
//!
//! ```rust
//! use limiteron::matchers::geo::GeoMatcher;
//! use std::net::IpAddr;
//!
//! #[tokio::main]
//! async fn main() {
//!     // 注意:需要有效的 GeoLite2-City.mmdb 文件
//!     // let matcher = GeoMatcher::new("GeoLite2-City.mmdb").await.unwrap();
//!     // let ip: IpAddr = "114.114.114.114".parse().unwrap();
//!     // let info = matcher.lookup(ip).unwrap();
//! }
//! ```

#[cfg(feature = "geo-matching")]
use crate::error::LimiteronError;
use maxminddb::{Reader, geoip2};
use oxcache::Cache;
use serde::{Deserialize, Serialize};
use std::net::IpAddr;
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;

// ============================================================================
// 地理信息结构
// ============================================================================

#[cfg(feature = "geo-matching")]
/// 地理信息
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct GeoInfo {
    /// 国家代码(ISO 3166-1 alpha-2)
    pub country_code: Option<String>,
    /// 国家名称
    pub country_name: Option<String>,
    /// 城市
    pub city: Option<String>,
    /// 大洲
    pub continent: Option<String>,
    /// 经度
    pub longitude: Option<f64>,
    /// 纬度
    pub latitude: Option<f64>,
    /// 时区
    pub timezone: Option<String>,
}

impl GeoInfo {
    /// 创建空的地理信息
    pub fn empty() -> Self {
        Self {
            country_code: None,
            country_name: None,
            city: None,
            continent: None,
            longitude: None,
            latitude: None,
            timezone: None,
        }
    }

    /// 检查是否为空
    pub fn is_empty(&self) -> bool {
        self.country_code.is_none()
            && self.country_name.is_none()
            && self.city.is_none()
            && self.continent.is_none()
    }

    /// 获取主要位置描述
    pub fn description(&self) -> String {
        match (&self.city, &self.country_name) {
            (Some(city), Some(country)) => format!("{}, {}", city, country),
            (Some(city), None) => city.clone(),
            (None, Some(country)) => country.clone(),
            (None, None) => "Unknown".to_string(),
        }
    }
}

impl Default for GeoInfo {
    fn default() -> Self {
        Self::empty()
    }
}

// ============================================================================
// 地理匹配条件
// ============================================================================

#[cfg(feature = "geo-matching")]
/// 地理匹配条件
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct GeoCondition {
    /// 国家代码列表(ISO 3166-1 alpha-2)
    pub countries: Vec<String>,
    /// 城市列表
    pub cities: Vec<String>,
    /// 大洲列表
    pub continents: Vec<String>,
}

impl GeoCondition {
    /// 创建空的匹配条件
    pub fn empty() -> Self {
        Self {
            countries: vec![],
            cities: vec![],
            continents: vec![],
        }
    }

    /// 创建国家匹配条件
    pub fn countries(countries: Vec<String>) -> Self {
        Self {
            countries,
            cities: vec![],
            continents: vec![],
        }
    }

    /// 创建城市匹配条件
    pub fn cities(cities: Vec<String>) -> Self {
        Self {
            countries: vec![],
            cities,
            continents: vec![],
        }
    }

    /// 创建大洲匹配条件
    pub fn continents(continents: Vec<String>) -> Self {
        Self {
            countries: vec![],
            cities: vec![],
            continents,
        }
    }

    /// 检查是否为空
    pub fn is_empty(&self) -> bool {
        self.countries.is_empty() && self.cities.is_empty() && self.continents.is_empty()
    }

    /// 检查地理信息是否匹配条件
    pub fn matches(&self, info: &GeoInfo) -> bool {
        if self.is_empty() {
            return true;
        }

        // 检查国家匹配
        if !self.countries.is_empty() {
            if let Some(country_code) = &info.country_code {
                if self.countries.contains(country_code) {
                    return true;
                }
            }
            // 如果没有国家信息,不匹配
            return false;
        }

        // 检查城市匹配
        if !self.cities.is_empty() {
            if let Some(city) = &info.city {
                if self.cities.contains(city) {
                    return true;
                }
            }
            return false;
        }

        // 检查大洲匹配
        if !self.continents.is_empty() {
            if let Some(continent) = &info.continent {
                if self.continents.contains(continent) {
                    return true;
                }
            }
            return false;
        }

        false
    }
}

impl Default for GeoCondition {
    fn default() -> Self {
        Self::empty()
    }
}

// ============================================================================
// 地理匹配器
// ============================================================================

/// 地理匹配器
///
/// 使用MaxMind GeoLite2数据库查询IP地理位置。
#[cfg(feature = "geo-matching")]
pub struct GeoMatcher {
    /// MaxMind数据库读取器
    reader: Arc<Reader<Vec<u8>>>,
    /// 查询缓存(使用 oxcache)
    cache: Arc<Cache<String, GeoInfo>>,
    /// 缓存大小限制
    cache_size_limit: usize,
    /// 缓存命中次数
    cache_hits: AtomicU64,
    /// 缓存未命中次数
    cache_misses: AtomicU64,
}

impl GeoMatcher {
    /// 创建新的地理匹配器
    ///
    /// # 参数
    /// - `db_path`: GeoLite2数据库文件路径
    ///
    /// # 返回
    /// - `Ok(GeoMatcher)`: 成功创建匹配器
    /// - `Err(LimiteronError)`: 创建失败
    ///
    /// # 示例
    /// ```rust
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// use limiteron::matchers::geo::GeoMatcher;
    ///
    /// let matcher = GeoMatcher::new("GeoLite2-City.mmdb").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn new<P: AsRef<Path>>(db_path: P) -> Result<Self, LimiteronError> {
        let db_path = db_path.as_ref();

        // 检查文件是否存在
        if !db_path.exists() {
            return Err(LimiteronError::ConfigError(format!(
                "GeoLite2数据库文件不存在: {}。请从MaxMind官网下载GeoLite2-City.mmdb文件",
                db_path.display()
            )));
        }

        log::info!(target: "geo", "加载GeoLite2数据库: {}", db_path.display());

        // 获取文件元数据
        let metadata = std::fs::metadata(db_path).map_err(LimiteronError::IoError)?;

        // 验证文件大小(GeoLite2-City.mmdb 通常大于 50MB)
        const MIN_DB_SIZE: u64 = 50 * 1024 * 1024; // 50MB
        const MAX_DB_SIZE: u64 = 500 * 1024 * 1024; // 500MB

        let file_size = metadata.len();
        if file_size < MIN_DB_SIZE {
            return Err(LimiteronError::ConfigError(format!(
                "GeoLite2数据库文件大小异常({} bytes),可能已损坏或不是完整文件。最小要求: {} \
                 bytes",
                file_size, MIN_DB_SIZE
            )));
        }

        if file_size > MAX_DB_SIZE {
            log::warn!(
                target: "geo",
                "GeoLite2数据库文件过大({} bytes),可能不是标准文件",
                file_size
            );
        }

        // 读取数据库文件
        let db_content = std::fs::read(db_path).map_err(LimiteronError::IoError)?;

        // 验证文件大小一致性
        if db_content.len() as u64 != file_size {
            return Err(LimiteronError::ConfigError(
                "GeoLite2数据库文件读取不完整,可能被截断".to_string(),
            ));
        }

        log::info!("GeoLite2数据库加载成功,大小: {} bytes", db_content.len());

        // 验证文件头(MaxMind 数据库文件以特定 magic number 开头)
        // MaxMind DB 格式: 0x00 0x00 0x02 0x00 (v2) 或 0x00 0x00 0x00 0x00 (v1)
        if db_content.len() < 4 {
            return Err(LimiteronError::ConfigError(
                "GeoLite2数据库文件过短,无法读取文件头".to_string(),
            ));
        }

        let header = &db_content[0..4];
        // 检查是否是 MaxMind 数据库格式
        let is_valid_header = header == [0x00, 0x00, 0x02, 0x00] || // v2 format
                              header == [0x00, 0x00, 0x00, 0x00] || // v1 format
                              header == [0x00, 0x00, 0x03, 0x00]; // 可能的 v3 格式

        if !is_valid_header {
            log::warn!("GeoLite2数据库文件头格式异常: {:02X?}", header);
            // 不直接返回错误,因为某些版本可能有不同的文件头
            // 让后续的 Reader::from_source 来验证
        }

        // 创建读取器
        let reader = Reader::from_source(db_content)
            .map_err(|e| LimiteronError::ConfigError(format!("无效的GeoLite2数据库文件: {}", e)))?;

        // 验证数据库元数据
        log::info!(
            "GeoLite2数据库元数据: 版本={}, 构建日期={}, 记录数={}",
            reader.metadata().binary_format_major_version,
            reader.metadata().build_epoch,
            reader.metadata().node_count
        );

        // 创建缓存
        let cache = Cache::builder()
            .capacity(10000)
            .ttl(Duration::from_secs(300))
            .build()
            .await
            .map_err(|e| LimiteronError::ConfigError(format!("创建缓存失败: {}", e)))?;

        let matcher = Self {
            reader: Arc::new(reader),
            cache: Arc::new(cache),
            cache_size_limit: 10_000,
            cache_hits: AtomicU64::new(0),
            cache_misses: AtomicU64::new(0),
        };

        log::info!("GeoMatcher创建成功");
        Ok(matcher)
    }

    /// 创建带缓存大小限制的地理匹配器
    ///
    /// # 参数
    /// - `db_path`: GeoLite2数据库文件路径
    /// - `cache_size_limit`: 缓存大小限制
    ///
    /// # 示例
    /// ```rust
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// use limiteron::matchers::geo::GeoMatcher;
    ///
    /// let matcher = GeoMatcher::with_cache_limit("GeoLite2-City.mmdb", 5000).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn with_cache_limit<P: AsRef<Path>>(
        db_path: P,
        cache_size_limit: usize,
    ) -> Result<Self, LimiteronError> {
        let mut matcher = Self::new(db_path).await?;
        matcher.cache_size_limit = cache_size_limit;
        Ok(matcher)
    }

    /// 查询IP地理位置
    ///
    /// # 参数
    /// - `ip`: IP地址
    ///
    /// # 返回
    /// - `Ok(GeoInfo)`: 地理信息
    /// - `Err(LimiteronError)`: 查询失败
    ///
    /// # 性能
    /// - 首次查询: ~1ms
    /// - 缓存命中: < 10μs
    ///
    /// # 示例
    /// ```rust
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// use limiteron::matchers::geo::GeoMatcher;
    /// use std::net::IpAddr;
    ///
    /// let matcher = GeoMatcher::new("GeoLite2-City.mmdb").await?;
    /// let ip: IpAddr = "114.114.114.114".parse()?;
    /// let info = matcher.lookup(ip).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn lookup(&self, ip: IpAddr) -> Result<GeoInfo, LimiteronError> {
        // 检查缓存
        let ip_str = ip.to_string();
        if let Ok(Some(cached)) = self.cache.get(&ip_str).await {
            log::debug!("缓存命中: {}", ip);
            self.cache_hits.fetch_add(1, Ordering::Relaxed);
            return Ok(cached);
        }

        // 记录缓存未命中
        self.cache_misses.fetch_add(1, Ordering::Relaxed);

        log::debug!("查询IP地理位置: {}", ip);

        // 从数据库查询 - maxminddb 0.27 API
        // lookup 返回 LookupResult,需要使用 decode() 获取解析后的数据
        let lookup_result = self
            .reader
            .lookup(ip)
            .map_err(|e| LimiteronError::ConfigError(format!("IP查询失败: {}", e)))?;

        // 解码为 City 结构
        let city: geoip2::City = lookup_result
            .decode()
            .map_err(|e| LimiteronError::ConfigError(format!("IP数据解析失败: {}", e)))?
            .ok_or_else(|| LimiteronError::ConfigError("IP不在数据库中".to_string()))?;

        // 提取地理信息
        let info = self.extract_geo_info(&city);

        // 更新缓存
        let cache_len = self.cache.len().await.unwrap_or(0);
        if cache_len >= self.cache_size_limit as u64 {
            let _maybe_first = (0..(self.cache_size_limit / 10)).next();
            log::debug!("缓存接近限制 ({}/{})", cache_len, self.cache_size_limit);
        }

        // 使用 set 方法存储,支持过期时间
        let _ = self.cache.set(&ip_str, &info).await;
        log::debug!("IP查询成功: {} -> {}", ip, info.description());

        Ok(info)
    }

    /// 批量查询IP地理位置
    ///
    /// # 参数
    /// - `ips`: IP地址列表
    ///
    /// # 返回
    /// - `Vec<Result<GeoInfo>>`: 地理信息列表
    ///
    /// # 示例
    /// ```rust
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// use limiteron::matchers::geo::GeoMatcher;
    /// use std::net::IpAddr;
    ///
    /// let matcher = GeoMatcher::new("GeoLite2-City.mmdb").await?;
    /// let ips: Vec<IpAddr> = vec![
    ///     "114.114.114.114".parse()?,
    ///     "8.8.8.8".parse()?,
    /// ];
    /// let results = matcher.batch_lookup(&ips).await;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn batch_lookup(&self, ips: &[IpAddr]) -> Vec<Result<GeoInfo, LimiteronError>> {
        let mut results = Vec::with_capacity(ips.len());
        for ip in ips {
            results.push(self.lookup(*ip).await);
        }
        results
    }

    /// 检查IP是否匹配地理条件
    ///
    /// # 参数
    /// - `ip`: IP地址
    /// - `condition`: 地理匹配条件
    ///
    /// # 返回
    /// - `Ok(true)`: 匹配
    /// - `Ok(false)`: 不匹配
    /// - `Err(LimiteronError)`: 查询失败
    ///
    /// # 示例
    /// ```rust
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// use limiteron::matchers::geo::{GeoMatcher, GeoCondition};
    /// use std::net::IpAddr;
    ///
    /// let matcher = GeoMatcher::new("GeoLite2-City.mmdb").await?;
    /// let condition = GeoCondition::countries(vec!["CN".to_string()]);
    /// let ip: IpAddr = "114.114.114.114".parse()?;
    /// let matched = matcher.matches_ip(ip, &condition).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn matches_ip(
        &self,
        ip: IpAddr,
        condition: &GeoCondition,
    ) -> Result<bool, LimiteronError> {
        let info = self.lookup(ip).await?;
        Ok(condition.matches(&info))
    }

    /// 检查地理信息是否匹配条件
    ///
    /// # 参数
    /// - `info`: 地理信息
    /// - `condition`: 地理匹配条件
    ///
    /// # 返回
    /// - `true`: 匹配
    /// - `false`: 不匹配
    ///
    /// # 示例
    /// ```rust
    /// use limiteron::matchers::geo::{GeoInfo, GeoCondition};
    ///
    /// let info = GeoInfo {
    ///     country_code: Some("CN".to_string()),
    ///     country_name: Some("China".to_string()),
    ///     city: Some("Beijing".to_string()),
    ///     continent: Some("Asia".to_string()),
    ///     longitude: Some(116.4),
    ///     latitude: Some(39.9),
    ///     timezone: Some("Asia/Shanghai".to_string()),
    /// };
    ///
    /// let condition = GeoCondition::countries(vec!["CN".to_string()]);
    /// let matched = condition.matches(&info);
    /// ```
    pub fn matches(&self, info: &GeoInfo, condition: &GeoCondition) -> bool {
        condition.matches(info)
    }

    /// 清空缓存
    pub async fn clear_cache(&self) {
        let size = self.cache.len().await.unwrap_or(0);
        let _ = self.cache.clear().await;
        log::info!("缓存已清空,移除 {} 条记录", size);
    }

    /// 获取缓存统计信息
    pub async fn cache_stats(&self) -> GeoCacheStats {
        let hits = self.cache_hits.load(Ordering::Relaxed);
        let misses = self.cache_misses.load(Ordering::Relaxed);
        let total = hits.saturating_add(misses);
        let hit_rate = if total > 0 {
            (hits as f64 / total as f64) * 100.0
        } else {
            0.0
        };

        GeoCacheStats {
            size: self.cache.len().await.unwrap_or(0) as usize,
            limit: self.cache_size_limit,
            hit_rate,
            hits,
            misses,
        }
    }

    /// 提取地理信息
    fn extract_geo_info(&self, city: &geoip2::City) -> GeoInfo {
        // maxminddb 0.27 API: City 中的字段不是 Option 包装的
        // city.country 是 Country<'a> 类型,不是 Option<Country>
        // Names<'a> 包含具体的语言字段如 english, french 等

        // Helper to safely get English name from Names
        // Extract country info
        let country_code = city.country.iso_code.map(|s| s.to_string());
        let country_name = city.country.names.english.map(|s| s.to_string());

        // Extract city info - city.city 也是 City<'a> 类型
        let city_name = city.city.names.english.map(|s| s.to_string());

        // Extract continent info
        let continent = city.continent.names.english.map(|s| s.to_string());

        // Extract location info
        let longitude = city.location.longitude;
        let latitude = city.location.latitude;
        let timezone = city.location.time_zone.map(|s| s.to_string());

        GeoInfo {
            country_code,
            country_name,
            city: city_name,
            continent,
            longitude,
            latitude,
            timezone,
        }
    }
}

// ============================================================================
// 缓存統計信息
// ============================================================================

#[cfg(feature = "geo-matching")]
/// 地理缓存统计信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GeoCacheStats {
    /// 当前缓存大小
    pub size: usize,
    /// 缓存大小限制
    pub limit: usize,
    /// 缓存命中率(百分比)
    pub hit_rate: f64,
    /// 缓存命中次数
    pub hits: u64,
    /// 缓存未命中次数
    pub misses: u64,
}

// ============================================================================
// 单元测试
// ============================================================================

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

    #[test]
    fn test_geo_info_empty() {
        let info = GeoInfo::empty();
        assert!(info.is_empty());
        assert_eq!(info.description(), "Unknown");
    }

    #[test]
    fn test_geo_info_description() {
        let info1 = GeoInfo {
            country_code: Some("CN".to_string()),
            country_name: Some("China".to_string()),
            city: Some("Beijing".to_string()),
            continent: Some("Asia".to_string()),
            longitude: Some(116.4),
            latitude: Some(39.9),
            timezone: Some("Asia/Shanghai".to_string()),
        };
        assert_eq!(info1.description(), "Beijing, China");

        let info2 = GeoInfo {
            country_code: Some("CN".to_string()),
            country_name: Some("China".to_string()),
            city: None,
            continent: Some("Asia".to_string()),
            longitude: None,
            latitude: None,
            timezone: None,
        };
        assert_eq!(info2.description(), "China");

        let info3 = GeoInfo {
            country_code: None,
            country_name: None,
            city: Some("Beijing".to_string()),
            continent: None,
            longitude: None,
            latitude: None,
            timezone: None,
        };
        assert_eq!(info3.description(), "Beijing");
    }

    #[test]
    fn test_geo_condition_empty() {
        let condition = GeoCondition::empty();
        assert!(condition.is_empty());

        let info = GeoInfo::empty();
        assert!(condition.matches(&info));
    }

    #[test]
    fn test_geo_condition_countries() {
        let condition = GeoCondition::countries(vec!["CN".to_string(), "US".to_string()]);

        let info1 = GeoInfo {
            country_code: Some("CN".to_string()),
            country_name: Some("China".to_string()),
            city: None,
            continent: None,
            longitude: None,
            latitude: None,
            timezone: None,
        };
        assert!(condition.matches(&info1));

        let info2 = GeoInfo {
            country_code: Some("JP".to_string()),
            country_name: Some("Japan".to_string()),
            city: None,
            continent: None,
            longitude: None,
            latitude: None,
            timezone: None,
        };
        assert!(!condition.matches(&info2));
    }

    #[test]
    fn test_geo_condition_cities() {
        let condition = GeoCondition::cities(vec!["Beijing".to_string(), "Shanghai".to_string()]);

        let info1 = GeoInfo {
            country_code: Some("CN".to_string()),
            country_name: Some("China".to_string()),
            city: Some("Beijing".to_string()),
            continent: None,
            longitude: None,
            latitude: None,
            timezone: None,
        };
        assert!(condition.matches(&info1));

        let info2 = GeoInfo {
            country_code: Some("CN".to_string()),
            country_name: Some("China".to_string()),
            city: Some("Shenzhen".to_string()),
            continent: None,
            longitude: None,
            latitude: None,
            timezone: None,
        };
        assert!(!condition.matches(&info2));
    }

    #[test]
    fn test_geo_condition_continents() {
        let condition = GeoCondition::continents(vec!["Asia".to_string()]);

        let info1 = GeoInfo {
            country_code: Some("CN".to_string()),
            country_name: Some("China".to_string()),
            city: None,
            continent: Some("Asia".to_string()),
            longitude: None,
            latitude: None,
            timezone: None,
        };
        assert!(condition.matches(&info1));

        let info2 = GeoInfo {
            country_code: Some("US".to_string()),
            country_name: Some("United States".to_string()),
            city: None,
            continent: Some("North America".to_string()),
            longitude: None,
            latitude: None,
            timezone: None,
        };
        assert!(!condition.matches(&info2));
    }

    #[test]
    fn test_geo_condition_default() {
        let condition = GeoCondition::default();
        assert!(condition.is_empty());
    }

    #[tokio::test]
    async fn test_geo_cache_stats() {
        // 测试GeoCacheStats的创建和属性
        let cache_stats = GeoCacheStats {
            size: 0,
            limit: 10000,
            hit_rate: 0.0,
            hits: 0,
            misses: 0,
        };

        assert_eq!(cache_stats.size, 0);
        assert_eq!(cache_stats.limit, 10000);
        assert_eq!(cache_stats.hit_rate, 0.0);
    }

    #[tokio::test]
    async fn test_geo_matcher_lookup() {
        let db_path = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("data")
            .join("GeoLite2-City.mmdb");
        if !db_path.exists() {
            eprintln!("GeoLite2-City.mmdb 不存在于 {},跳过", db_path.display());
            return;
        }

        let matcher = GeoMatcher::new(&db_path).await.unwrap();

        let result = matcher.lookup("8.8.8.8".parse().unwrap()).await.unwrap();
        assert_eq!(result.country_code.as_deref(), Some("US"));
        assert_eq!(result.country_name.as_deref(), Some("United States"));

        let result = matcher
            .lookup("114.114.114.114".parse().unwrap())
            .await
            .unwrap();
        assert_eq!(result.country_code.as_deref(), Some("CN"));
    }

    #[test]
    fn test_geo_info_serialization() {
        let info = GeoInfo {
            country_code: Some("CN".to_string()),
            country_name: Some("China".to_string()),
            city: Some("Beijing".to_string()),
            continent: Some("Asia".to_string()),
            longitude: Some(116.4),
            latitude: Some(39.9),
            timezone: Some("Asia/Shanghai".to_string()),
        };

        let json = serde_json::to_string(&info).unwrap();
        let deserialized: GeoInfo = serde_json::from_str(&json).unwrap();

        assert_eq!(info, deserialized);
    }

    #[test]
    fn test_geo_condition_serialization() {
        let condition = GeoCondition {
            countries: vec!["CN".to_string(), "US".to_string()],
            cities: vec!["Beijing".to_string()],
            continents: vec!["Asia".to_string()],
        };

        let json = serde_json::to_string(&condition).unwrap();
        let deserialized: GeoCondition = serde_json::from_str(&json).unwrap();

        assert_eq!(condition, deserialized);
    }

    #[test]
    fn test_geo_info_default_is_empty() {
        let info = GeoInfo::default();
        assert!(info.is_empty());
        assert_eq!(info.description(), "Unknown");
    }

    #[test]
    fn test_geo_info_is_empty_false_with_fields() {
        // 设置任一关键字段后 is_empty 应返回 false
        let info = GeoInfo {
            country_code: Some("CN".to_string()),
            country_name: None,
            city: None,
            continent: None,
            longitude: None,
            latitude: None,
            timezone: None,
        };
        assert!(!info.is_empty());

        let info2 = GeoInfo {
            country_code: None,
            country_name: Some("China".to_string()),
            city: None,
            continent: None,
            longitude: None,
            latitude: None,
            timezone: None,
        };
        assert!(!info2.is_empty());

        let info3 = GeoInfo {
            country_code: None,
            country_name: None,
            city: Some("Beijing".to_string()),
            continent: None,
            longitude: None,
            latitude: None,
            timezone: None,
        };
        assert!(!info3.is_empty());

        let info4 = GeoInfo {
            country_code: None,
            country_name: None,
            city: None,
            continent: Some("Asia".to_string()),
            longitude: None,
            latitude: None,
            timezone: None,
        };
        assert!(!info4.is_empty());
    }

    #[test]
    fn test_geo_info_is_empty_true_with_only_optional_location_fields() {
        // is_empty 仅检查 country_code/country_name/city/continent,
        // 仅设置 longitude/latitude/timezone 时仍返回 true
        let info = GeoInfo {
            country_code: None,
            country_name: None,
            city: None,
            continent: None,
            longitude: Some(116.4),
            latitude: Some(39.9),
            timezone: Some("Asia/Shanghai".to_string()),
        };
        assert!(info.is_empty());
    }

    #[test]
    fn test_geo_info_description_city_only() {
        let info = GeoInfo {
            country_code: None,
            country_name: None,
            city: Some("Tokyo".to_string()),
            continent: None,
            longitude: None,
            latitude: None,
            timezone: None,
        };
        assert_eq!(info.description(), "Tokyo");
    }

    #[test]
    fn test_geo_info_description_country_only() {
        let info = GeoInfo {
            country_code: Some("JP".to_string()),
            country_name: Some("Japan".to_string()),
            city: None,
            continent: None,
            longitude: None,
            latitude: None,
            timezone: None,
        };
        assert_eq!(info.description(), "Japan");
    }

    #[test]
    fn test_geo_condition_countries_no_country_info() {
        // 当条件包含国家列表但 GeoInfo.country_code 为 None 时应返回 false
        let condition = GeoCondition::countries(vec!["CN".to_string()]);
        let info = GeoInfo::empty();
        assert!(!condition.matches(&info));
    }

    #[test]
    fn test_geo_condition_cities_no_city_info() {
        // 当条件包含城市列表但 GeoInfo.city 为 None 时应返回 false
        let condition = GeoCondition::cities(vec!["Beijing".to_string()]);
        let info = GeoInfo::empty();
        assert!(!condition.matches(&info));
    }

    #[test]
    fn test_geo_condition_continents_no_continent_info() {
        // 当条件包含大洲列表但 GeoInfo.continent 为 None 时应返回 false
        let condition = GeoCondition::continents(vec!["Asia".to_string()]);
        let info = GeoInfo::empty();
        assert!(!condition.matches(&info));
    }

    #[test]
    fn test_geo_condition_countries_match_with_partial_info() {
        // 条件匹配但 info 仅有部分字段
        let condition = GeoCondition::countries(vec!["US".to_string()]);
        let info = GeoInfo {
            country_code: Some("US".to_string()),
            country_name: None,
            city: None,
            continent: None,
            longitude: None,
            latitude: None,
            timezone: None,
        };
        assert!(condition.matches(&info));
    }

    #[test]
    fn test_geo_condition_cities_match() {
        let condition = GeoCondition::cities(vec!["Shanghai".to_string()]);
        let info = GeoInfo {
            country_code: Some("CN".to_string()),
            country_name: Some("China".to_string()),
            city: Some("Shanghai".to_string()),
            continent: None,
            longitude: None,
            latitude: None,
            timezone: None,
        };
        assert!(condition.matches(&info));
    }

    #[test]
    fn test_geo_condition_continents_match() {
        let condition = GeoCondition::continents(vec!["Europe".to_string()]);
        let info = GeoInfo {
            country_code: Some("FR".to_string()),
            country_name: Some("France".to_string()),
            city: Some("Paris".to_string()),
            continent: Some("Europe".to_string()),
            longitude: None,
            latitude: None,
            timezone: None,
        };
        assert!(condition.matches(&info));
    }

    #[test]
    fn test_geo_condition_partial_equality() {
        let c1 = GeoCondition::countries(vec!["CN".to_string()]);
        let c2 = GeoCondition::countries(vec!["CN".to_string()]);
        assert_eq!(c1, c2);

        let c3 = GeoCondition::cities(vec!["CN".to_string()]);
        assert_ne!(c1, c3);
    }

    #[test]
    fn test_geo_info_clone_equality() {
        let info = GeoInfo {
            country_code: Some("CN".to_string()),
            country_name: Some("China".to_string()),
            city: Some("Beijing".to_string()),
            continent: Some("Asia".to_string()),
            longitude: Some(116.4),
            latitude: Some(39.9),
            timezone: Some("Asia/Shanghai".to_string()),
        };
        let cloned = info.clone();
        assert_eq!(info, cloned);
    }

    #[test]
    fn test_geo_info_debug_format() {
        let info = GeoInfo::empty();
        let debug = format!("{:?}", info);
        assert!(debug.contains("GeoInfo"));
    }

    // ------------------------------------------------------------------------
    // GeoMatcher 测试(需要 geo-matching feature)
    // ------------------------------------------------------------------------

    #[cfg(feature = "geo-matching")]
    #[tokio::test]
    async fn test_geo_matcher_new_file_not_found() {
        // 文件不存在时应返回 ConfigError
        let result = GeoMatcher::new("/nonexistent/path/to/GeoLite2-City.mmdb").await;
        assert!(result.is_err());
        // 使用 err() 避免 GeoMatcher 需要 Debug 的约束
        let err = result.err().unwrap();
        assert!(
            matches!(err, LimiteronError::ConfigError(_)),
            "expected ConfigError, got {:?}",
            err
        );
        let msg = err.to_string();
        assert!(
            msg.contains("不存在") || msg.contains("not exist"),
            "error should mention missing file: {}",
            msg
        );
    }

    #[cfg(feature = "geo-matching")]
    #[tokio::test]
    async fn test_geo_matcher_new_file_too_small() {
        // 创建一个临时小文件,应触发文件大小异常错误
        let temp_dir = std::env::temp_dir();
        let temp_path = temp_dir.join(format!(
            "limiteron_test_geo_small_{}.mmdb",
            std::process::id()
        ));
        std::fs::write(&temp_path, b"too small to be a real mmdb file").unwrap();

        let result = GeoMatcher::new(&temp_path).await;
        // 清理临时文件
        let _ = std::fs::remove_file(&temp_path);

        assert!(result.is_err());
        let err = result.err().unwrap();
        assert!(
            matches!(err, LimiteronError::ConfigError(_)),
            "expected ConfigError, got {:?}",
            err
        );
        let msg = err.to_string();
        assert!(
            msg.contains("大小异常") || msg.contains("size"),
            "error should mention file size: {}",
            msg
        );
    }

    #[cfg(feature = "geo-matching")]
    #[tokio::test]
    async fn test_geo_matcher_with_cache_limit_file_not_found() {
        // with_cache_limit 内部调用 new,文件不存在时应返回错误
        let result =
            GeoMatcher::with_cache_limit("/nonexistent/path/to/GeoLite2-City.mmdb", 5000).await;
        assert!(result.is_err());
        let err = result.err().unwrap();
        assert!(matches!(err, LimiteronError::ConfigError(_)));
    }

    #[cfg(feature = "geo-matching")]
    #[tokio::test]
    async fn test_geo_cache_stats_zero_state() {
        // 直接构造 GeoCacheStats 验证字段
        let stats = GeoCacheStats {
            size: 100,
            limit: 10000,
            hit_rate: 75.0,
            hits: 750,
            misses: 250,
        };
        assert_eq!(stats.size, 100);
        assert_eq!(stats.limit, 10000);
        assert_eq!(stats.hit_rate, 75.0);
        assert_eq!(stats.hits, 750);
        assert_eq!(stats.misses, 250);
    }

    #[cfg(feature = "geo-matching")]
    #[tokio::test]
    async fn test_geo_cache_stats_high_hit_rate() {
        let stats = GeoCacheStats {
            size: 5000,
            limit: 10000,
            hit_rate: 99.5,
            hits: 9950,
            misses: 50,
        };
        assert!(stats.hit_rate > 99.0);
        assert!(stats.hits > stats.misses);
    }

    #[cfg(feature = "geo-matching")]
    #[test]
    fn test_geo_cache_stats_serialization() {
        let stats = GeoCacheStats {
            size: 42,
            limit: 100,
            hit_rate: 50.0,
            hits: 10,
            misses: 10,
        };
        let json = serde_json::to_string(&stats).unwrap();
        let deserialized: GeoCacheStats = serde_json::from_str(&json).unwrap();
        assert_eq!(stats.size, deserialized.size);
        assert_eq!(stats.limit, deserialized.limit);
        assert_eq!(stats.hits, deserialized.hits);
        assert_eq!(stats.misses, deserialized.misses);
    }

    #[cfg(feature = "geo-matching")]
    #[test]
    fn test_geo_cache_stats_debug_format() {
        let stats = GeoCacheStats {
            size: 0,
            limit: 0,
            hit_rate: 0.0,
            hits: 0,
            misses: 0,
        };
        let debug = format!("{:?}", stats);
        assert!(debug.contains("GeoCacheStats"));
    }
}