limiteron 0.3.0-rc.7

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
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: MIT
//! 自定义匹配器扩展模块
//!
//! 提供自定义匹配器接口和注册机制,允许用户在运行时动态注册和使用自定义匹配器。
//!
//! # 特性
//!
//! - 定义 CustomMatcher trait 作为匹配器接口
//! - 支持异步匹配操作
//! - 支持配置加载
//! - 提供线程安全的注册表(CustomMatcherRegistry)
//! - 支持运行时动态注册、查询和注销
//!
//! # 示例
//!
//! ```rust
//! use limiteron::matchers::custom::{CustomMatcher, CustomMatcherRegistry};
//! use limiteron::matchers::RequestContext;
//! use limiteron::error::LimiteronError;
//! use async_trait::async_trait;
//!
//! #[derive(Debug)]
//! struct MyCustomMatcher {
//!     threshold: u64,
//! }
//!
//! #[async_trait]
//! impl CustomMatcher for MyCustomMatcher {
//!     fn name(&self) -> &str {
//!         "my_custom"
//!     }
//!
//!     async fn matches(&self, context: &RequestContext) -> Result<bool, LimiteronError> {
//!         // 自定义匹配逻辑
//!         Ok(true)
//!     }
//!
//!     fn load_config(&mut self, config: serde_json::Value) -> Result<(), LimiteronError> {
//!         self.threshold = config["threshold"].as_u64().unwrap_or(100);
//!         Ok(())
//!     }
//! }
//!
//! #[tokio::main]
//! async fn main() {
//!     let registry = CustomMatcherRegistry::new();
//!     let matcher = Box::new(MyCustomMatcher { threshold: 100 });
//!     registry.register("my_custom".to_string(), matcher).await.unwrap();
//! }
//! ```

use crate::error::LimiteronError;
use crate::i18n::t;
use crate::matchers::RequestContext;
use ahash::AHashMap as HashMap;
use async_trait::async_trait;
use chrono::Timelike;
use log::{debug, error, info, warn};
use serde_json::Value;
use std::sync::Arc;
use tokio::sync::RwLock;

// ============================================================================
// 输入验证常量
// ============================================================================

/// 最大匹配器名称长度
const MAX_MATCHER_NAME_LENGTH: usize = 100;

/// 最大 HTTP 头名称长度
const MAX_HEADER_NAME_LENGTH: usize = 256;

/// 最大 HTTP 头值长度
const MAX_HEADER_VALUE_LENGTH: usize = 4096;

/// 最大允许的 HTTP 头值数量
const MAX_ALLOWED_VALUES_COUNT: usize = 100;

// ============================================================================
// 输入验证函数
// ============================================================================

/// 验证匹配器名称
///
/// # 参数
/// - `name`: 匹配器名称
///
/// # 返回
/// - `Ok(())`: 验证通过
/// - `Err(LimiteronError)`: 验证失败
fn validate_matcher_name(name: &str) -> Result<(), LimiteronError> {
    if name.is_empty() {
        return Err(LimiteronError::ConfigError(t("matcher-name-empty", &[])));
    }

    if name.len() > MAX_MATCHER_NAME_LENGTH {
        return Err(LimiteronError::ConfigError(t(
            "matcher-name-too-long",
            &[("max", MAX_MATCHER_NAME_LENGTH.to_string())],
        )));
    }

    // 只允许字母、数字、下划线和连字符
    if !name
        .chars()
        .all(|c| c.is_alphanumeric() || c == '_' || c == '-')
    {
        return Err(LimiteronError::ConfigError(t(
            "matcher-name-invalid-chars",
            &[],
        )));
    }

    Ok(())
}

/// 验证 HTTP 头名称
///
/// # 参数
/// - `name`: HTTP 头名称
///
/// # 返回
/// - `Ok(())`: 验证通过
/// - `Err(LimiteronError)`: 验证失败
fn validate_header_name(name: &str) -> Result<(), LimiteronError> {
    if name.is_empty() {
        return Err(LimiteronError::ConfigError(t("header-name-empty", &[])));
    }

    if name.len() > MAX_HEADER_NAME_LENGTH {
        return Err(LimiteronError::ConfigError(t(
            "header-name-too-long",
            &[("max", MAX_HEADER_NAME_LENGTH.to_string())],
        )));
    }

    // 只允许字母、数字、连字符
    if !name.chars().all(|c| c.is_alphanumeric() || c == '-') {
        return Err(LimiteronError::ConfigError(t(
            "header-name-invalid-chars",
            &[],
        )));
    }

    Ok(())
}

/// 验证 HTTP 头值
///
/// # 参数
/// - `value`: HTTP 头值
///
/// # 返回
/// - `Ok(())`: 验证通过
/// - `Err(LimiteronError)`: 验证失败
fn validate_header_value(value: &str) -> Result<(), LimiteronError> {
    // 空串在 Prefix 模式下语义翻转为通配符(`starts_with("")` 恒真,
    // 匹配所有携带该头的请求),Exact 模式下几乎不可能是有意配置——
    // 两入口(new/load_config)统一显性拒绝
    if value.is_empty() {
        return Err(LimiteronError::ConfigError(t("header-value-empty", &[])));
    }
    if value.len() > MAX_HEADER_VALUE_LENGTH {
        return Err(LimiteronError::ConfigError(t(
            "header-value-too-long",
            &[("max", MAX_HEADER_VALUE_LENGTH.to_string())],
        )));
    }

    Ok(())
}

/// 校验 HTTP 方法名的合法性(非空 + RFC 9110 token 字符集)
///
/// 方法名为 ASCII token:`!#$%&'*+-.^_`|~` 与字母数字;空串与含分隔符
/// (空格、`()/@:;,"` 等)的伪方法名永不命中,显性拒绝防止配置静默失效。
fn validate_method(method: &str) -> Result<(), LimiteronError> {
    if method.is_empty() {
        return Err(LimiteronError::ConfigError(t(
            "matcher-method-invalid",
            &[("value", method.to_string())],
        )));
    }
    if !method.bytes().all(is_token_byte) {
        return Err(LimiteronError::ConfigError(t(
            "matcher-method-invalid",
            &[("value", method.to_string())],
        )));
    }
    Ok(())
}

/// RFC 9110 token 字符集判定
fn is_token_byte(b: u8) -> bool {
    b.is_ascii_alphanumeric()
        || matches!(
            b,
            b'!' | b'#'
                | b'$'
                | b'%'
                | b'&'
                | b'\''
                | b'*'
                | b'+'
                | b'-'
                | b'.'
                | b'^'
                | b'_'
                | b'`'
                | b'|'
                | b'~'
        )
}

// ============================================================================
// CustomMatcher Trait
// ============================================================================

/// 自定义匹配器 trait
///
/// 所有自定义匹配器都需要实现此trait。
#[async_trait]
pub trait CustomMatcher: Send + Sync {
    /// 获取匹配器名称
    ///
    /// # 返回
    /// - 匹配器的唯一标识符
    fn name(&self) -> &str;

    /// 检查请求是否匹配
    ///
    /// # 参数
    /// - `context`: 请求上下文
    ///
    /// # 返回
    /// - `Ok(true)`: 请求匹配
    /// - `Ok(false)`: 请求不匹配
    /// - `Err(_)`: 发生错误
    async fn matches(&self, context: &RequestContext) -> Result<bool, LimiteronError>;

    /// 加载配置
    ///
    /// # 参数
    /// - `config`: 配置值(JSON格式)
    ///
    /// # 返回
    /// - `Ok(())`: 配置加载成功
    /// - `Err(_)`: 配置加载失败
    fn load_config(&mut self, config: Value) -> Result<(), LimiteronError>;
}

// ============================================================================
// CustomMatcherRegistry
// ============================================================================

/// 自定义匹配器注册表
///
/// 提供线程安全的匹配器注册、查询和注销功能。
#[derive(Clone)]
pub struct CustomMatcherRegistry {
    /// 匹配器存储(Arc 包装以便快照到规则条件中,E1/D3 修复:
    /// 旧实现存 `Box` 且 `get()` 受 trait object 不可克隆限制恒返回 None)
    matchers: Arc<RwLock<HashMap<String, std::sync::Arc<dyn CustomMatcher>>>>,
}

impl std::fmt::Debug for CustomMatcherRegistry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CustomMatcherRegistry")
            .field("matchers", &"<custom matchers>")
            .finish()
    }
}

impl CustomMatcherRegistry {
    /// 创建新的注册表(保持向后兼容)
    ///
    /// # 示例
    /// ```rust
    /// use limiteron::matchers::custom::CustomMatcherRegistry;
    ///
    /// let registry = CustomMatcherRegistry::new();
    /// ```
    pub fn new() -> Self {
        Self {
            matchers: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// 创建设置器(Builder模式)
    ///
    /// # 示例
    /// ```rust
    /// use limiteron::matchers::custom::CustomMatcherRegistry;
    ///
    /// let registry = CustomMatcherRegistry::builder().build();
    /// ```
    pub fn builder() -> CustomMatcherRegistryBuilder {
        CustomMatcherRegistryBuilder::new()
    }

    /// 使用依赖注入创建(完整依赖模式)
    ///
    /// 对于CustomMatcherRegistry,无需外部依赖,此方法主要用于API一致性
    pub fn with_dependencies() -> Self {
        Self::new()
    }

    /// 注册自定义匹配器
    ///
    /// # 参数
    /// - `name`: 匹配器名称(唯一标识符)
    /// - `matcher`: 匹配器实例
    ///
    /// # 返回
    /// - `Ok(())`: 注册成功
    /// - `Err(LimiteronError::ConfigError)`: 名称已存在或验证失败
    ///
    /// # 示例
    /// ```rust
    /// use limiteron::matchers::custom::{CustomMatcherRegistry, TimeWindowMatcher};
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let registry = CustomMatcherRegistry::new();
    ///     let matcher = TimeWindowMatcher::new(9, 18);
    ///     registry.register("time_window".to_string(), Box::new(matcher)).await.unwrap();
    /// }
    /// ```
    pub async fn register(
        &self,
        name: String,
        matcher: Box<dyn CustomMatcher>,
    ) -> Result<(), LimiteronError> {
        // 验证匹配器名称
        validate_matcher_name(&name)?;

        let mut matchers = self.matchers.write().await;

        if matchers.contains_key(&name) {
            let error_msg = t("matcher-already-exists", &[("name", name.clone())]);
            warn!("{}", error_msg);
            return Err(LimiteronError::ConfigError(error_msg));
        }

        info!("{}", t("matcher-registered", &[("name", name.clone())]));
        matchers.insert(name.clone(), std::sync::Arc::from(matcher));
        debug!("registered matcher count: {}", matchers.len());

        Ok(())
    }

    /// 获取匹配器
    ///
    /// # 参数
    /// - `name`: 匹配器名称
    ///
    /// # 返回
    /// - `Some(matcher)`: 找到匹配器
    /// - `None`: 未找到匹配器
    ///
    /// # 示例
    /// ```rust
    /// use limiteron::matchers::custom::CustomMatcherRegistry;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let registry = CustomMatcherRegistry::new();
    ///     if let Some(matcher) = registry.get("time_window").await {
    ///         println!("找到匹配器: {}", matcher.name());
    /// }
    /// }
    /// ```
    pub async fn get(&self, name: &str) -> Option<std::sync::Arc<dyn CustomMatcher>> {
        let matchers = self.matchers.read().await;
        let found = matchers.get(name).cloned();
        if found.is_some() {
            debug!("query matcher: {}", name);
        } else {
            debug!("matcher not found: {}", name);
        }
        found
    }

    /// 检查匹配器是否存在
    ///
    /// # 参数
    /// - `name`: 匹配器名称
    ///
    /// # 返回
    /// - `true`: 匹配器存在
    /// - `false`: 匹配器不存在
    pub async fn contains(&self, name: &str) -> bool {
        let matchers = self.matchers.read().await;
        matchers.contains_key(name)
    }

    /// 注销匹配器
    ///
    /// # 参数
    /// - `name`: 匹配器名称
    ///
    /// # 返回
    /// - `Ok(())`: 注销成功
    /// - `Err(LimiteronError::ConfigError)`: 匹配器不存在
    ///
    /// # 示例
    /// ```rust
    /// use limiteron::matchers::custom::CustomMatcherRegistry;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let registry = CustomMatcherRegistry::new();
    ///     // 首先注册一个匹配器
    ///     registry.register("my_matcher".to_string(), Box::new(
    ///         limiteron::matchers::custom::TimeWindowMatcher::new(9, 18)
    ///     )).await.unwrap();
    ///     // 然后注销它
    ///     registry.unregister("my_matcher").await.unwrap();
    /// }
    /// ```
    pub async fn unregister(&self, name: &str) -> Result<(), LimiteronError> {
        let mut matchers = self.matchers.write().await;

        if !matchers.contains_key(name) {
            let error_msg = t("matcher-not-found", &[("name", name.to_string())]);
            warn!("{}", error_msg);
            return Err(LimiteronError::ConfigError(error_msg));
        }

        info!(
            "{}",
            t("matcher-unregistered", &[("name", name.to_string())])
        );
        matchers.remove(name);
        debug!("registered matcher count: {}", matchers.len());

        Ok(())
    }

    /// 获取所有注册的匹配器名称
    ///
    /// # 返回
    /// - 匹配器名称列表
    #[allow(clippy::map_clone)]
    pub async fn list(&self) -> Vec<String> {
        let matchers = self.matchers.read().await;
        matchers.keys().map(|k| k.clone()).collect()
    }

    /// 获取注册的匹配器数量
    ///
    /// # 返回
    /// - 匹配器数量
    pub async fn count(&self) -> usize {
        let matchers = self.matchers.read().await;
        matchers.len()
    }

    /// 清空所有匹配器
    ///
    /// # 示例
    /// ```rust
    /// use limiteron::matchers::custom::CustomMatcherRegistry;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let registry = CustomMatcherRegistry::new();
    ///     registry.clear().await;
    /// }
    /// ```
    pub async fn clear(&self) {
        let mut matchers = self.matchers.write().await;
        info!("{}", t("matcher-registry-cleared", &[]));
        matchers.clear();
    }

    /// 匹配请求
    ///
    /// 使用指定名称的匹配器检查请求是否匹配。
    ///
    /// # 参数
    /// - `name`: 匹配器名称
    /// - `context`: 请求上下文
    ///
    /// # 返回
    /// - `Ok(true)`: 匹配成功
    /// - `Ok(false)`: 匹配失败
    /// - `Err(_)`: 匹配器不存在或发生错误
    pub async fn match_with(
        &self,
        name: &str,
        context: &RequestContext,
    ) -> Result<bool, LimiteronError> {
        let matchers = self.matchers.read().await;

        let matcher = matchers.get(name).ok_or_else(|| {
            let error_msg = t("matcher-not-found", &[("name", name.to_string())]);
            error!("{}", error_msg);
            LimiteronError::ConfigError(error_msg)
        })?;

        debug!("checking request with matcher '{}'", name);
        matcher.matches(context).await
    }
}

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

/// 自定义匹配器注册表设置器
#[derive(Debug, Clone, Default)]
pub struct CustomMatcherRegistryBuilder;

impl CustomMatcherRegistryBuilder {
    /// 创建新的设置器
    pub fn new() -> Self {
        Self
    }

    /// 构建CustomMatcherRegistry
    pub fn build(self) -> CustomMatcherRegistry {
        CustomMatcherRegistry::new()
    }
}

// ============================================================================
// TimeWindowMatcher 示例实现
// ============================================================================

/// 时间窗口匹配器
///
/// 根据当前时间是否在指定的时间窗口内来匹配请求。
///
/// # 示例
/// ```rust
/// use limiteron::matchers::custom::TimeWindowMatcher;
///
/// let matcher = TimeWindowMatcher::new(9, 18); // 9:00 - 18:00
/// ```
#[derive(Debug, Clone)]
pub struct TimeWindowMatcher {
    /// 开始小时(0-23)
    start_hour: u8,
    /// 结束小时(0-23)
    end_hour: u8,
}

impl TimeWindowMatcher {
    /// 创建新的时间窗口匹配器(保持向后兼容)
    ///
    /// # 参数
    /// - `start_hour`: 开始小时(0-23)
    /// - `end_hour`: 结束小时(0-23)
    ///
    /// # 示例
    /// ```rust
    /// use limiteron::matchers::custom::TimeWindowMatcher;
    ///
    /// let matcher = TimeWindowMatcher::new(9, 18);
    /// ```
    pub fn new(start_hour: u8, end_hour: u8) -> Self {
        assert!(start_hour <= 23, "start_hour must be in range 0-23");
        assert!(end_hour <= 23, "end_hour must be in range 0-23");

        Self {
            start_hour,
            end_hour,
        }
    }

    /// 获取开始小时
    pub fn start_hour(&self) -> u8 {
        self.start_hour
    }

    /// 获取结束小时
    pub fn end_hour(&self) -> u8 {
        self.end_hour
    }

    /// 创建设置器(Builder模式)
    ///
    /// # 示例
    /// ```rust
    /// use limiteron::matchers::custom::TimeWindowMatcher;
    ///
    /// let matcher = TimeWindowMatcher::builder()
    ///     .start_hour(9)
    ///     .end_hour(18)
    ///     .build();
    /// ```
    pub fn builder() -> TimeWindowMatcherBuilder {
        TimeWindowMatcherBuilder::new()
    }

    /// 使用依赖注入创建(完整依赖模式)
    ///
    /// 对于TimeWindowMatcher,无需外部依赖,此方法主要用于API一致性
    ///
    /// # 参数
    /// - `start_hour`: 开始小时(0-23)
    /// - `end_hour`: 结束小时(0-23)
    pub fn with_dependencies(start_hour: u8, end_hour: u8) -> Self {
        Self::new(start_hour, end_hour)
    }
}

#[async_trait]
impl CustomMatcher for TimeWindowMatcher {
    fn name(&self) -> &str {
        "time_window"
    }

    async fn matches(&self, _context: &RequestContext) -> Result<bool, LimiteronError> {
        let now = chrono::Utc::now();
        let hour = now.hour() as u8;

        // 检查当前小时是否在时间窗口内
        let matches = if self.start_hour <= self.end_hour {
            // 正常时间窗口(如 9-18)
            hour >= self.start_hour && hour <= self.end_hour
        } else {
            // 跨午夜时间窗口(如 22-6)
            hour >= self.start_hour || hour <= self.end_hour
        };

        debug!(
            "time window match: current hour {}, window {}-{}, result: {}",
            hour, self.start_hour, self.end_hour, matches
        );

        Ok(matches)
    }

    fn load_config(&mut self, config: Value) -> Result<(), LimiteronError> {
        // 先获取 start_hour 并验证
        let start_hour_u64 = config["start_hour"].as_u64().ok_or_else(|| {
            LimiteronError::ConfigError(t(
                "matcher-config-missing",
                &[("field", "start_hour".to_string())],
            ))
        })?;
        // 先校验范围再转换,避免 `as u8` 截断绕过校验(如 256 截断为 0)
        if start_hour_u64 > 23 {
            return Err(LimiteronError::ConfigError(t(
                "matcher-hour-out-of-range",
                &[("field", "start_hour".to_string())],
            )));
        }
        let start_hour = start_hour_u64 as u8;

        // 然后获取 end_hour 并验证
        let end_hour_u64 = config["end_hour"].as_u64().ok_or_else(|| {
            LimiteronError::ConfigError(t(
                "matcher-config-missing",
                &[("field", "end_hour".to_string())],
            ))
        })?;
        if end_hour_u64 > 23 {
            return Err(LimiteronError::ConfigError(t(
                "matcher-hour-out-of-range",
                &[("field", "end_hour".to_string())],
            )));
        }
        let end_hour = end_hour_u64 as u8;

        self.start_hour = start_hour;
        self.end_hour = end_hour;

        info!(
            "{}",
            t(
                "matcher-time-window-config-loaded",
                &[
                    ("start", self.start_hour.to_string()),
                    ("end", self.end_hour.to_string()),
                ]
            )
        );

        Ok(())
    }
}

/// 时间窗口匹配器设置器
#[derive(Debug, Clone, Default)]
pub struct TimeWindowMatcherBuilder {
    start_hour: u8,
    end_hour: u8,
}

impl TimeWindowMatcherBuilder {
    /// 创建新的设置器
    pub fn new() -> Self {
        Self::default()
    }

    /// 设置开始小时
    pub fn start_hour(mut self, start_hour: u8) -> Self {
        self.start_hour = start_hour;
        self
    }

    /// 设置结束小时
    pub fn end_hour(mut self, end_hour: u8) -> Self {
        self.end_hour = end_hour;
        self
    }

    /// 构建TimeWindowMatcher
    pub fn build(self) -> TimeWindowMatcher {
        TimeWindowMatcher::new(self.start_hour, self.end_hour)
    }
}

// ============================================================================
// HeaderMatcher 示例实现
// ============================================================================

/// HTTP头匹配器
///
/// 根据HTTP头的值来匹配请求:值列表**相等**或**前缀**两种模式
/// ([`HeaderMatchMode`],默认精确相等)。
///
/// # 示例
/// ```rust
/// use limiteron::matchers::custom::HeaderMatcher;
///
/// let matcher = HeaderMatcher::new("X-API-Key", vec!["secret123".to_string()]).unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct HeaderMatcher {
    /// HTTP头名称
    header_name: String,
    /// 允许的值列表(原始值,供观测/访问器)
    allowed_values: Vec<String>,
    /// 允许的值列表的小写副本(构造期归一化,热路径零逐项分配)
    allowed_values_normalized: Vec<String>,
    /// 逐值 ASCII 标志(与 allowed_values/allowed_values_normalized 对齐):
    /// ASCII 值可用零分配 ASCII 折叠比较(纯 ASCII 输入的 Unicode 折叠与
    /// ASCII 折叠一致,语义严格等价);非 ASCII 值的 Unicode 折叠产物无法
    /// 用 ASCII 折叠覆盖(如带点大写 I 'İ' 经 to_lowercase 产生 "i̇" 双
    /// 字节序列)仅对该值回退 to_lowercase 原路径——按值粒度门控,混合
    /// 字符集列表的 ASCII 值不受牵连降级
    values_ascii: Vec<bool>,
    /// 是否区分大小写
    case_sensitive: bool,
    /// 匹配模式(相等/前缀,默认相等)
    match_mode: HeaderMatchMode,
}

/// HTTP头值匹配模式
///
/// - [`HeaderMatchMode::Exact`]:头值与允许值列表中的某项完全相等(默认,
///   向后兼容既有语义)
/// - [`HeaderMatchMode::Prefix`]:头值以允许值列表中的某项为前缀
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum HeaderMatchMode {
    /// 相等匹配(默认)
    #[default]
    Exact,
    /// 前缀匹配
    Prefix,
}

impl HeaderMatcher {
    /// 创建新的HTTP头匹配器
    ///
    /// # 参数
    /// - `header_name`: HTTP头名称
    /// - `allowed_values`: 允许的值列表
    ///
    /// # 返回
    /// - 新的 HeaderMatcher 实例
    ///
    /// # 错误
    /// - 如果 header_name 或 allowed_values 验证失败
    ///
    /// # 示例
    /// ```rust
    /// use limiteron::matchers::custom::HeaderMatcher;
    ///
    /// let matcher = HeaderMatcher::new("X-API-Key", vec!["secret123".to_string()]).unwrap();
    /// ```
    pub fn new(header_name: &str, allowed_values: Vec<String>) -> Result<Self, LimiteronError> {
        // 验证 HTTP 头名称
        validate_header_name(header_name)?;

        // 空 allowlist 的匹配器静默永不命中,与 MethodMatcher 的空列表
        // 拒绝政策对齐,显性报错防配置失效不可知
        if allowed_values.is_empty() {
            return Err(LimiteronError::ConfigError(t(
                "matcher-header-values-empty",
                &[],
            )));
        }
        if allowed_values.len() > MAX_ALLOWED_VALUES_COUNT {
            return Err(LimiteronError::ValidationError(t(
                "matcher-allowed-values-too-many",
                &[("max", MAX_ALLOWED_VALUES_COUNT.to_string())],
            )));
        }

        // 验证每个值
        for value in &allowed_values {
            validate_header_value(value)?;
        }

        let allowed_values_normalized = allowed_values.iter().map(|v| v.to_lowercase()).collect();
        let values_ascii = allowed_values.iter().map(|v| v.is_ascii()).collect();
        Ok(Self {
            header_name: header_name.to_lowercase(),
            allowed_values,
            allowed_values_normalized,
            values_ascii,
            case_sensitive: false,
            match_mode: HeaderMatchMode::Exact,
        })
    }

    /// 设置匹配模式(相等/前缀,默认相等)
    ///
    /// # 参数
    /// - `match_mode`: 匹配模式
    pub fn with_match_mode(mut self, match_mode: HeaderMatchMode) -> Self {
        self.match_mode = match_mode;
        self
    }

    /// 获取匹配模式
    pub fn match_mode(&self) -> HeaderMatchMode {
        self.match_mode
    }

    /// 设置是否区分大小写
    ///
    /// # 参数
    /// - `case_sensitive`: 是否区分大小写
    pub fn with_case_sensitive(mut self, case_sensitive: bool) -> Self {
        self.case_sensitive = case_sensitive;
        self
    }

    /// 获取HTTP头名称
    pub fn header_name(&self) -> &str {
        &self.header_name
    }

    /// 获取允许的值列表
    pub fn allowed_values(&self) -> &[String] {
        &self.allowed_values
    }

    /// 创建设置器(Builder模式)
    ///
    /// # 示例
    /// ```rust
    /// use limiteron::matchers::custom::HeaderMatcher;
    ///
    /// let matcher = HeaderMatcher::builder()
    ///     .header_name("X-API-Key")
    ///     .allowed_values(vec!["secret123".to_string()])
    ///     .case_sensitive(false)
    ///     .build();
    /// ```
    pub fn builder() -> HeaderMatcherBuilder {
        HeaderMatcherBuilder::new()
    }

    /// 使用依赖注入创建(完整依赖模式)
    ///
    /// 对于HeaderMatcher,无需外部依赖,此方法主要用于API一致性
    ///
    /// # 参数
    /// - `header_name`: HTTP头名称
    /// - `allowed_values`: 允许的值列表
    /// - `case_sensitive`: 是否区分大小写
    pub fn with_dependencies(
        header_name: &str,
        allowed_values: Vec<String>,
        case_sensitive: bool,
    ) -> Result<Self, LimiteronError> {
        Self::new(header_name, allowed_values).map(|mut m| {
            m.case_sensitive = case_sensitive;
            m
        })
    }
}

#[async_trait]
impl CustomMatcher for HeaderMatcher {
    fn name(&self) -> &str {
        "header"
    }

    async fn matches(&self, context: &RequestContext) -> Result<bool, LimiteronError> {
        let header_value = match context.get_header(&self.header_name) {
            Some(value) => value,
            None => {
                debug!("HTTP header '{}' not present", self.header_name);
                return Ok(false);
            }
        };

        // 大小写敏感路径零分配(直接与原始值比较)。不敏感路径分两级:
        // 允许值与头值均为 ASCII 时走零分配 ASCII 折叠快路径(纯 ASCII
        // 输入的 Unicode 折叠与 ASCII 折叠一致,语义严格等价);否则
        // to_lowercase 一次后与构造期归一化副本比较(allowed_values 是
        // 构造期静态配置,逐项 to_lowercase 的每请求分配在 matches 热
        // 路径上不可接受)
        // 不敏感路径逐值门控:ASCII 值走零分配 ASCII 折叠(头值含非 ASCII
        // 时 ASCII 折叠必不命中,等价跳过);非 ASCII 值对 header_value 做
        // 一次 to_lowercase 后折叠比较(惰性分配:仅在存在非 ASCII 值且
        // ASCII 扫描未命中时才发生)
        let lower_value = || header_value.to_lowercase();
        let matches = match self.match_mode {
            HeaderMatchMode::Exact => {
                if self.case_sensitive {
                    self.allowed_values.contains(header_value)
                } else {
                    let mut lower: Option<String> = None;
                    self.allowed_values_normalized
                        .iter()
                        .zip(self.values_ascii.iter())
                        .any(|(v, ascii)| {
                            if *ascii {
                                v.eq_ignore_ascii_case(header_value)
                            } else {
                                lower.get_or_insert_with(lower_value);
                                *v == lower.as_deref().unwrap()
                            }
                        })
                }
            }
            HeaderMatchMode::Prefix => {
                if self.case_sensitive {
                    self.allowed_values
                        .iter()
                        .any(|v| header_value.starts_with(v))
                } else {
                    let header_bytes = header_value.as_bytes();
                    let mut lower: Option<String> = None;
                    self.allowed_values_normalized
                        .iter()
                        .zip(self.values_ascii.iter())
                        .any(|(v, ascii)| {
                            let v_bytes = v.as_bytes();
                            if header_bytes.len() < v_bytes.len() {
                                return false;
                            }
                            if *ascii {
                                header_bytes[..v_bytes.len()].eq_ignore_ascii_case(v_bytes)
                            } else {
                                let lower_str = lower.get_or_insert_with(lower_value);
                                lower_str.starts_with(v.as_str())
                            }
                        })
                }
            }
        };

        debug!(
            "HTTP header match: header='{}', value='{}', result: {}",
            self.header_name, header_value, matches
        );

        Ok(matches)
    }

    fn load_config(&mut self, config: Value) -> Result<(), LimiteronError> {
        if let Some(header_name) = config["header_name"].as_str() {
            validate_header_name(header_name)?;
            self.header_name = header_name.to_lowercase();
        }

        if let Some(values) = config["allowed_values"].as_array() {
            if values.len() > MAX_ALLOWED_VALUES_COUNT {
                return Err(LimiteronError::ConfigError(t(
                    "matcher-allowed-values-too-many",
                    &[("max", MAX_ALLOWED_VALUES_COUNT.to_string())],
                )));
            }

            // 显性遍历:非字符串项报错而非 filter_map 静默丢弃(与
            // MethodMatcher::load_config 政策一致——跳过会让匹配范围
            // 静默缩小且不可观测)
            self.allowed_values = values
                .iter()
                .map(|v| {
                    let s = v.as_str().ok_or_else(|| {
                        LimiteronError::ConfigError(t(
                            "matcher-value-invalid",
                            &[("value", v.to_string())],
                        ))
                    })?;
                    validate_header_value(s).map(|_| s.to_string())
                })
                .collect::<Result<Vec<_>, LimiteronError>>()?;
            self.allowed_values_normalized = self
                .allowed_values
                .iter()
                .map(|v| v.to_lowercase())
                .collect();
            self.values_ascii = self.allowed_values.iter().map(|v| v.is_ascii()).collect();
        }

        if let Some(case_sensitive) = config["case_sensitive"].as_bool() {
            self.case_sensitive = case_sensitive;
        }

        if let Some(mode) = config["match_mode"].as_str() {
            self.match_mode =
                serde_json::from_value(Value::String(mode.to_string())).map_err(|e| {
                    LimiteronError::ConfigError(t(
                        "matcher-header-match-mode-invalid",
                        &[("mode", mode.to_string()), ("error", e.to_string())],
                    ))
                })?;
        }

        info!(
            "{}",
            t(
                "matcher-header-config-loaded",
                &[
                    ("header", self.header_name.clone()),
                    ("values", format!("{:?}", self.allowed_values)),
                    ("case_sensitive", self.case_sensitive.to_string()),
                ]
            )
        );

        Ok(())
    }
}

/// HTTP头匹配器设置器
#[derive(Debug, Clone, Default)]
pub struct HeaderMatcherBuilder {
    header_name: Option<String>,
    allowed_values: Vec<String>,
    case_sensitive: bool,
    match_mode: HeaderMatchMode,
}

impl HeaderMatcherBuilder {
    /// 创建新的设置器
    pub fn new() -> Self {
        Self::default()
    }

    /// 设置HTTP头名称
    pub fn header_name(mut self, header_name: &str) -> Self {
        self.header_name = Some(header_name.to_string());
        self
    }

    /// 设置允许的值列表
    pub fn allowed_values(mut self, allowed_values: Vec<String>) -> Self {
        self.allowed_values = allowed_values;
        self
    }

    /// 添加允许的值
    pub fn add_allowed_value(mut self, value: &str) -> Self {
        self.allowed_values.push(value.to_string());
        self
    }

    /// 设置是否区分大小写
    pub fn case_sensitive(mut self, case_sensitive: bool) -> Self {
        self.case_sensitive = case_sensitive;
        self
    }

    /// 设置匹配模式(相等/前缀,默认相等)
    pub fn match_mode(mut self, match_mode: HeaderMatchMode) -> Self {
        self.match_mode = match_mode;
        self
    }

    /// 构建HeaderMatcher
    pub fn build(self) -> Result<HeaderMatcher, LimiteronError> {
        HeaderMatcher::new(
            self.header_name.as_deref().unwrap_or(""),
            self.allowed_values,
        )
        .map(|mut m| {
            m.case_sensitive = self.case_sensitive;
            m.match_mode = self.match_mode;
            m
        })
    }
}

// ============================================================================
// MethodMatcher(请求方法匹配)
// ============================================================================

/// 请求方法匹配器
///
/// 按 HTTP 方法匹配请求(GET/POST/...);方法名在构造与匹配时统一
/// 大写规范化,对调用方传入大小写不敏感。
#[derive(Debug, Clone)]
pub struct MethodMatcher {
    /// 允许的请求方法(大写规范化)
    methods: Vec<String>,
}

impl MethodMatcher {
    /// 创建请求方法匹配器
    ///
    /// # 参数
    /// - `methods`: 允许的请求方法列表(如 `["GET", "POST"]`,大小写不敏感)
    ///
    /// # 错误
    /// - 列表为空或超过 `MAX_ALLOWED_VALUES_COUNT`
    pub fn new(methods: Vec<String>) -> Result<Self, LimiteronError> {
        if methods.is_empty() {
            return Err(LimiteronError::ConfigError(t("matcher-methods-empty", &[])));
        }
        if methods.len() > MAX_ALLOWED_VALUES_COUNT {
            return Err(LimiteronError::ValidationError(t(
                "matcher-allowed-values-too-many",
                &[("max", MAX_ALLOWED_VALUES_COUNT.to_string())],
            )));
        }
        // 逐项校验(非空 + RFC 9110 token 字符集):空串与含分隔符的
        // 伪方法名永不命中,静默接受会让配置失效不可知;ASCII 大写
        // 归一化(非 ASCII 方法串不命中,防御纵深)
        let methods = methods
            .iter()
            .map(|m| validate_method(m).map(|_| m.to_ascii_uppercase()))
            .collect::<Result<Vec<_>, LimiteronError>>()?;
        Ok(Self { methods })
    }

    /// 获取允许的请求方法(大写规范化后)
    pub fn methods(&self) -> &[String] {
        &self.methods
    }

    /// 创建设置器
    pub fn builder() -> MethodMatcherBuilder {
        MethodMatcherBuilder::new()
    }
}

#[async_trait]
impl CustomMatcher for MethodMatcher {
    fn name(&self) -> &str {
        "method"
    }

    async fn matches(&self, context: &RequestContext) -> Result<bool, LimiteronError> {
        // 方法名大写规范化后比对(与构造期一致,大小写不敏感)
        // ASCII 大小写折叠比较:零分配热路径;非 ASCII 方法串不命中
        //(RFC 9110 方法为 ASCII token,与构造期 to_ascii_uppercase 对齐)
        let matches = self
            .methods
            .iter()
            .any(|m| m.eq_ignore_ascii_case(&context.method));
        debug!(
            "HTTP method match: method='{}', result: {}",
            context.method, matches
        );
        Ok(matches)
    }

    fn load_config(&mut self, config: Value) -> Result<(), LimiteronError> {
        if let Some(methods) = config["methods"].as_array() {
            if methods.len() > MAX_ALLOWED_VALUES_COUNT {
                return Err(LimiteronError::ConfigError(t(
                    "matcher-allowed-values-too-many",
                    &[("max", MAX_ALLOWED_VALUES_COUNT.to_string())],
                )));
            }
            // 显性遍历:非字符串项报错而非 filter_map 静默丢弃(跳过会让
            // 匹配范围静默变化且不可观测)
            let parsed: Vec<String> = methods
                .iter()
                .map(|v| {
                    let str_value = v.as_str().ok_or_else(|| {
                        LimiteronError::ConfigError(t(
                            "matcher-method-invalid",
                            &[("value", v.to_string())],
                        ))
                    })?;
                    validate_method(str_value).map(|_| str_value.to_ascii_uppercase())
                })
                .collect::<Result<Vec<_>, LimiteronError>>()?;
            if parsed.is_empty() {
                return Err(LimiteronError::ConfigError(t("matcher-methods-empty", &[])));
            }
            self.methods = parsed;
        }

        info!(
            "{}",
            t(
                "matcher-method-config-loaded",
                &[("methods", format!("{:?}", self.methods))]
            )
        );
        Ok(())
    }
}

/// 请求方法匹配器设置器
#[derive(Debug, Clone, Default)]
pub struct MethodMatcherBuilder {
    methods: Vec<String>,
}

impl MethodMatcherBuilder {
    /// 创建新的设置器
    pub fn new() -> Self {
        Self::default()
    }

    /// 设置允许的方法列表
    pub fn methods(mut self, methods: Vec<String>) -> Self {
        self.methods = methods;
        self
    }

    /// 添加允许的方法
    pub fn add_method(mut self, method: &str) -> Self {
        self.methods.push(method.to_string());
        self
    }

    /// 构建MethodMatcher
    pub fn build(self) -> Result<MethodMatcher, LimiteronError> {
        MethodMatcher::new(self.methods)
    }
}

// ============================================================================
// RegexPathMatcher(路径正则匹配,feature `regex-matching`)
// ============================================================================

/// 路径正则匹配器(feature `regex-matching`)
///
/// 以正则表达式匹配请求路径(`RequestContext::path`)。模式在构造与
/// `load_config` 时编译,非法模式显性报错;匹配语义与 `regex` crate
/// 一致(`is_match`:模式命中路径任意子串即匹配,锚定用 `^`/`$`)。
#[cfg(feature = "regex-matching")]
#[derive(Debug, Clone)]
pub struct RegexPathMatcher {
    /// 编译后的路径模式
    pattern: regex::Regex,
    /// 原始模式串(load_config 与观测用)
    source: String,
    /// 是否大小写不敏感(构造时以 `(?i)` 语义编译)
    case_insensitive: bool,
}

#[cfg(feature = "regex-matching")]
impl RegexPathMatcher {
    /// 创建路径正则匹配器
    ///
    /// # 参数
    /// - `pattern`: 正则表达式(非锚定 `is_match` 语义)
    /// - `case_insensitive`: 是否大小写不敏感
    ///
    /// # 错误
    /// - 模式非法(编译失败)
    pub fn new(pattern: &str, case_insensitive: bool) -> Result<Self, LimiteronError> {
        if pattern.is_empty() {
            return Err(LimiteronError::ConfigError(t(
                "matcher-regex-pattern-empty",
                &[],
            )));
        }
        let source = if case_insensitive {
            format!("(?i){pattern}")
        } else {
            pattern.to_string()
        };
        let pattern = regex::Regex::new(&source).map_err(|e| {
            LimiteronError::ConfigError(t(
                "matcher-regex-pattern-invalid",
                &[("error", e.to_string())],
            ))
        })?;
        Ok(Self {
            pattern,
            source,
            case_insensitive,
        })
    }

    /// 原始模式串(含大小写内联旗标)
    pub fn pattern(&self) -> &str {
        &self.source
    }

    /// 是否大小写不敏感
    pub fn case_insensitive(&self) -> bool {
        self.case_insensitive
    }
}

#[cfg(feature = "regex-matching")]
#[async_trait]
impl CustomMatcher for RegexPathMatcher {
    fn name(&self) -> &str {
        "regex_path"
    }

    async fn matches(&self, context: &RequestContext) -> Result<bool, LimiteronError> {
        let matches = self.pattern.is_match(&context.path);
        debug!(
            "regex path match: path='{}', result: {}",
            context.path, matches
        );
        Ok(matches)
    }

    fn load_config(&mut self, config: Value) -> Result<(), LimiteronError> {
        // case_insensitive 独立读取(与 HeaderMatcher::load_config 的
        // case_sensitive 对齐):仅传旗标不传 pattern 时切换语义并按现有
        // 模式串重编译,而非静默忽略
        if let Some(case_insensitive) = config["case_insensitive"].as_bool()
            && case_insensitive != self.case_insensitive
        {
            self.case_insensitive = case_insensitive;
            let base = self.source.strip_prefix("(?i)").unwrap_or(&self.source);
            self.source = if case_insensitive {
                format!("(?i){base}")
            } else {
                base.to_string()
            };
            self.pattern = regex::Regex::new(&self.source).map_err(|e| {
                LimiteronError::ConfigError(t(
                    "matcher-regex-pattern-invalid",
                    &[("error", e.to_string())],
                ))
            })?;
        }

        if let Some(pattern) = config["pattern"].as_str() {
            if pattern.is_empty() {
                return Err(LimiteronError::ConfigError(t(
                    "matcher-regex-pattern-empty",
                    &[],
                )));
            }
            self.source = if self.case_insensitive {
                format!("(?i){pattern}")
            } else {
                pattern.to_string()
            };
            self.pattern = regex::Regex::new(&self.source).map_err(|e| {
                LimiteronError::ConfigError(t(
                    "matcher-regex-pattern-invalid",
                    &[("error", e.to_string())],
                ))
            })?;
        }

        info!(
            "{}",
            t(
                "matcher-regex-config-loaded",
                &[("pattern", self.source.clone())]
            )
        );
        Ok(())
    }
}

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

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

    // ==================== CustomMatcherRegistry 测试 ====================

    #[tokio::test]
    async fn test_registry_new() {
        let registry = CustomMatcherRegistry::new();
        assert_eq!(registry.count().await, 0);
    }

    #[tokio::test]
    async fn test_registry_register() {
        let registry = CustomMatcherRegistry::new();
        let matcher = TimeWindowMatcher::new(9, 18);

        assert!(
            registry
                .register("time_window".to_string(), Box::new(matcher))
                .await
                .is_ok()
        );
        assert_eq!(registry.count().await, 1);
        assert!(registry.contains("time_window").await);
    }

    #[tokio::test]
    async fn test_registry_register_duplicate() {
        let registry = CustomMatcherRegistry::new();
        let matcher = TimeWindowMatcher::new(9, 18);

        assert!(
            registry
                .register("time_window".to_string(), Box::new(matcher))
                .await
                .is_ok()
        );

        let result = registry
            .register(
                "time_window".to_string(),
                Box::new(TimeWindowMatcher::new(10, 20)),
            )
            .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_registry_unregister() {
        let registry = CustomMatcherRegistry::new();
        let matcher = TimeWindowMatcher::new(9, 18);

        registry
            .register("time_window".to_string(), Box::new(matcher))
            .await
            .unwrap();

        assert!(registry.unregister("time_window").await.is_ok());
        assert_eq!(registry.count().await, 0);
        assert!(!registry.contains("time_window").await);
    }

    #[tokio::test]
    async fn test_registry_unregister_nonexistent() {
        let registry = CustomMatcherRegistry::new();
        let result = registry.unregister("nonexistent").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_registry_list() {
        let registry = CustomMatcherRegistry::new();

        registry
            .register(
                "matcher1".to_string(),
                Box::new(TimeWindowMatcher::new(9, 18)),
            )
            .await
            .unwrap();
        registry
            .register(
                "matcher2".to_string(),
                Box::new(HeaderMatcher::new("X-API-Key", vec!["secret".to_string()]).unwrap()),
            )
            .await
            .unwrap();

        let list = registry.list().await;
        assert_eq!(list.len(), 2);
        assert!(list.contains(&"matcher1".to_string()));
        assert!(list.contains(&"matcher2".to_string()));
    }

    #[tokio::test]
    async fn test_registry_clear() {
        let registry = CustomMatcherRegistry::new();

        registry
            .register(
                "matcher1".to_string(),
                Box::new(TimeWindowMatcher::new(9, 18)),
            )
            .await
            .unwrap();

        registry.clear().await;
        assert_eq!(registry.count().await, 0);
    }

    #[tokio::test]
    async fn test_registry_match_with() {
        let registry = CustomMatcherRegistry::new();
        let matcher = TimeWindowMatcher::new(0, 23); // 全天匹配

        registry
            .register("time_window".to_string(), Box::new(matcher))
            .await
            .unwrap();

        let context = RequestContext::new();
        let result = registry.match_with("time_window", &context).await;
        assert!(result.is_ok());
        assert!(result.unwrap());
    }

    #[tokio::test]
    async fn test_registry_match_with_nonexistent() {
        let registry = CustomMatcherRegistry::new();
        let context = RequestContext::new();

        let result = registry.match_with("nonexistent", &context).await;
        assert!(result.is_err());
    }

    // ==================== TimeWindowMatcher 测试 ====================

    #[tokio::test]
    async fn test_time_window_matcher_new() {
        let matcher = TimeWindowMatcher::new(9, 18);
        assert_eq!(matcher.name(), "time_window");
        assert_eq!(matcher.start_hour(), 9);
        assert_eq!(matcher.end_hour(), 18);
    }

    #[tokio::test]
    async fn test_time_window_matcher_matches() {
        let matcher = TimeWindowMatcher::new(0, 23); // 全天匹配
        let context = RequestContext::new();

        let result = matcher.matches(&context).await.unwrap();
        assert!(result);
    }

    #[tokio::test]
    async fn test_time_window_matcher_load_config() {
        let mut matcher = TimeWindowMatcher::new(9, 18);
        let config = serde_json::json!({
            "start_hour": 10,
            "end_hour": 20
        });

        assert!(matcher.load_config(config).is_ok());
        assert_eq!(matcher.start_hour(), 10);
        assert_eq!(matcher.end_hour(), 20);
    }

    #[tokio::test]
    async fn test_time_window_matcher_load_config_invalid() {
        let mut matcher = TimeWindowMatcher::new(9, 18);
        let config = serde_json::json!({
            "start_hour": 25
        });

        let result = matcher.load_config(config);
        assert!(result.is_err());
    }

    #[test]
    #[should_panic(expected = "start_hour must be in range 0-23")]
    fn test_time_window_matcher_invalid_start_hour() {
        TimeWindowMatcher::new(25, 18);
    }

    #[test]
    #[should_panic(expected = "end_hour must be in range 0-23")]
    fn test_time_window_matcher_invalid_end_hour() {
        TimeWindowMatcher::new(9, 25);
    }

    // ==================== HeaderMatcher 测试 ====================

    #[tokio::test]
    async fn test_header_matcher_new() {
        let matcher = HeaderMatcher::new("X-API-Key", vec!["secret123".to_string()]).unwrap();
        assert_eq!(matcher.name(), "header");
        assert_eq!(matcher.header_name(), "x-api-key");
        assert_eq!(matcher.allowed_values().len(), 1);
    }

    #[tokio::test]
    async fn test_header_matcher_matches() {
        let matcher = HeaderMatcher::new("X-API-Key", vec!["secret123".to_string()]).unwrap();
        let context = RequestContext::new().with_header("X-API-Key", "secret123");

        let result = matcher.matches(&context).await.unwrap();
        assert!(result);
    }

    #[tokio::test]
    async fn test_header_matcher_not_matches() {
        let matcher = HeaderMatcher::new("X-API-Key", vec!["secret123".to_string()]).unwrap();
        let context = RequestContext::new().with_header("X-API-Key", "wrong");

        let result = matcher.matches(&context).await.unwrap();
        assert!(!result);
    }

    #[tokio::test]
    async fn test_header_matcher_missing_header() {
        let matcher = HeaderMatcher::new("X-API-Key", vec!["secret123".to_string()]).unwrap();
        let context = RequestContext::new();

        let result = matcher.matches(&context).await.unwrap();
        assert!(!result);
    }

    #[tokio::test]
    async fn test_header_matcher_case_insensitive() {
        let matcher = HeaderMatcher::new("X-API-Key", vec!["SECRET123".to_string()]).unwrap();
        let context = RequestContext::new().with_header("X-API-Key", "secret123");

        let result = matcher.matches(&context).await.unwrap();
        assert!(result);
    }

    #[tokio::test]
    async fn test_header_header_matcher_case_sensitive() {
        let matcher = HeaderMatcher::new("X-API-Key", vec!["SECRET123".to_string()])
            .unwrap()
            .with_case_sensitive(true);
        let context = RequestContext::new().with_header("X-API-Key", "secret123");

        let result = matcher.matches(&context).await.unwrap();
        assert!(!result);
    }

    #[tokio::test]
    async fn test_header_matcher_multiple_values() {
        let matcher = HeaderMatcher::new(
            "X-API-Key",
            vec!["secret123".to_string(), "secret456".to_string()],
        )
        .unwrap();
        let context1 = RequestContext::new().with_header("X-API-Key", "secret123");
        let context2 = RequestContext::new().with_header("X-API-Key", "secret456");

        assert!(matcher.matches(&context1).await.unwrap());
        assert!(matcher.matches(&context2).await.unwrap());
    }

    #[tokio::test]
    async fn test_header_matcher_load_config() {
        let mut matcher = HeaderMatcher::new("X-API-Key", vec!["secret123".to_string()]).unwrap();
        let config = serde_json::json!({
            "header_name": "Authorization",
            "allowed_values": ["Bearer token123"],
            "case_sensitive": true
        });

        assert!(matcher.load_config(config).is_ok());
        assert_eq!(matcher.header_name(), "authorization");
        assert_eq!(matcher.allowed_values().len(), 1);
    }

    // ==================== 并发测试 ====================

    #[tokio::test]
    async fn test_registry_concurrent_register() {
        let registry = Arc::new(CustomMatcherRegistry::new());
        let mut handles = vec![];

        for i in 0..10 {
            let registry_clone = Arc::clone(&registry);
            handles.push(tokio::spawn(async move {
                let matcher = TimeWindowMatcher::new(i as u8, (i + 10) as u8);
                registry_clone
                    .register(format!("matcher_{}", i), Box::new(matcher))
                    .await
            }));
        }

        let mut success_count = 0;
        for handle in handles {
            if handle.await.unwrap().is_ok() {
                success_count += 1;
            }
        }

        assert_eq!(success_count, 10);
        assert_eq!(registry.count().await, 10);
    }

    #[tokio::test]
    async fn test_registry_concurrent_match() {
        let registry = Arc::new(CustomMatcherRegistry::new());
        let matcher = TimeWindowMatcher::new(0, 23);

        registry
            .register("time_window".to_string(), Box::new(matcher))
            .await
            .unwrap();

        let mut handles = vec![];
        for _ in 0..100 {
            let registry_clone = Arc::clone(&registry);
            handles.push(tokio::spawn(async move {
                let context = RequestContext::new();
                registry_clone.match_with("time_window", &context).await
            }));
        }

        let mut success_count = 0;
        for handle in handles {
            if let Ok(Ok(true)) = handle.await {
                success_count += 1;
            }
        }

        assert_eq!(success_count, 100);
    }

    // ==================== 输入验证函数测试 ====================

    #[test]
    fn test_validate_matcher_name_empty() {
        let result = validate_matcher_name("");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_matcher_name_too_long() {
        let long_name = "a".repeat(MAX_MATCHER_NAME_LENGTH + 1);
        let result = validate_matcher_name(&long_name);
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_matcher_name_invalid_chars() {
        let result = validate_matcher_name("invalid@name!");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_header_name_empty() {
        let result = validate_header_name("");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_header_name_too_long() {
        let long_name = "a".repeat(MAX_HEADER_NAME_LENGTH + 1);
        let result = validate_header_name(&long_name);
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_header_name_invalid_chars() {
        let result = validate_header_name("X-Header@Name");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_header_value_too_long() {
        let long_value = "a".repeat(MAX_HEADER_VALUE_LENGTH + 1);
        let result = validate_header_value(&long_value);
        assert!(result.is_err());

        assert!(
            validate_header_value("").is_err(),
            "an empty value semantically flipping to a wildcard in Prefix mode must be rejected"
        );
        assert!(validate_header_value("valid-value").is_ok());
    }

    // ==================== CustomMatcherRegistry 补充测试 ====================

    #[tokio::test]
    async fn test_registry_default() {
        let registry = CustomMatcherRegistry::default();
        assert_eq!(registry.count().await, 0);
    }

    #[test]
    fn test_registry_debug() {
        let registry = CustomMatcherRegistry::new();
        let debug_str = format!("{:?}", registry);
        assert!(debug_str.contains("CustomMatcherRegistry"));
        assert!(debug_str.contains("<custom matchers>"));
    }

    #[tokio::test]
    async fn test_registry_builder() {
        let registry = CustomMatcherRegistry::builder().build();
        assert_eq!(registry.count().await, 0);
    }

    #[tokio::test]
    async fn test_registry_with_dependencies() {
        let registry = CustomMatcherRegistry::with_dependencies();
        assert_eq!(registry.count().await, 0);
    }

    #[tokio::test]
    async fn test_registry_register_with_invalid_name() {
        let registry = CustomMatcherRegistry::new();
        let matcher = TimeWindowMatcher::new(9, 18);

        let result = registry.register("".to_string(), Box::new(matcher)).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_registry_get_found() {
        // D3/matchers-2 修复回归:get() 返回已注册匹配器的 Arc 快照
        // (旧实现受 trait object 不可克隆限制恒返回 None)
        let registry = CustomMatcherRegistry::new();
        registry
            .register("test".to_string(), Box::new(TimeWindowMatcher::new(9, 18)))
            .await
            .unwrap();
        let result = registry.get("test").await;
        assert!(
            result.is_some(),
            "a registered matcher must be retrievable by get"
        );
        assert_eq!(result.unwrap().name(), "time_window");
    }

    #[tokio::test]
    async fn test_registry_get_not_found() {
        let registry = CustomMatcherRegistry::new();
        let result = registry.get("nonexistent").await;
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn test_registry_list_empty() {
        let registry = CustomMatcherRegistry::new();
        let list = registry.list().await;
        assert!(list.is_empty());
    }

    // ==================== TimeWindowMatcher 补充测试 ====================

    #[test]
    fn test_time_window_matcher_builder() {
        let matcher = TimeWindowMatcher::builder()
            .start_hour(8)
            .end_hour(20)
            .build();
        assert_eq!(matcher.start_hour(), 8);
        assert_eq!(matcher.end_hour(), 20);
    }

    #[test]
    fn test_time_window_matcher_with_dependencies() {
        let matcher = TimeWindowMatcher::with_dependencies(7, 19);
        assert_eq!(matcher.start_hour(), 7);
        assert_eq!(matcher.end_hour(), 19);
    }

    #[tokio::test]
    async fn test_time_window_matcher_cross_midnight() {
        let matcher = TimeWindowMatcher::new(12, 11);
        let context = RequestContext::new();
        let result = matcher.matches(&context).await.unwrap();
        assert!(result);
    }

    #[test]
    fn test_time_window_matcher_load_config_missing_start_hour() {
        let mut matcher = TimeWindowMatcher::new(9, 18);
        let config = serde_json::json!({ "end_hour": 20 });
        let result = matcher.load_config(config);
        assert!(result.is_err());
    }

    #[test]
    fn test_time_window_matcher_load_config_missing_end_hour() {
        let mut matcher = TimeWindowMatcher::new(9, 18);
        let config = serde_json::json!({ "start_hour": 10 });
        let result = matcher.load_config(config);
        assert!(result.is_err());
    }

    #[test]
    fn test_time_window_matcher_load_config_start_out_of_range() {
        let mut matcher = TimeWindowMatcher::new(9, 18);
        let config = serde_json::json!({
            "start_hour": 25,
            "end_hour": 20,
        });
        let result = matcher.load_config(config);
        assert!(result.is_err());
    }

    #[test]
    fn test_time_window_matcher_load_config_end_out_of_range() {
        let mut matcher = TimeWindowMatcher::new(9, 18);
        let config = serde_json::json!({
            "start_hour": 10,
            "end_hour": 25,
        });
        let result = matcher.load_config(config);
        assert!(result.is_err());
    }

    // ==================== HeaderMatcher 补充测试 ====================

    #[test]
    fn test_header_matcher_new_empty_name() {
        let result = HeaderMatcher::new("", vec!["value".to_string()]);
        assert!(result.is_err());
    }

    #[test]
    fn test_header_matcher_new_invalid_name_chars() {
        let result = HeaderMatcher::new("X-Header@Name", vec!["value".to_string()]);
        assert!(result.is_err());
    }

    #[test]
    fn test_header_matcher_new_too_many_values() {
        let values: Vec<String> = (0..=MAX_ALLOWED_VALUES_COUNT)
            .map(|i| format!("val_{}", i))
            .collect();
        let result = HeaderMatcher::new("X-Test", values);
        assert!(result.is_err());
    }

    #[test]
    fn test_header_matcher_new_value_too_long() {
        let long_value = "a".repeat(MAX_HEADER_VALUE_LENGTH + 1);
        let result = HeaderMatcher::new("X-Test", vec![long_value]);
        assert!(result.is_err());
    }

    #[test]
    fn test_header_matcher_builder() {
        let matcher = HeaderMatcher::builder()
            .header_name("X-Custom")
            .add_allowed_value("val1")
            .add_allowed_value("val2")
            .case_sensitive(true)
            .build()
            .unwrap();
        assert_eq!(matcher.header_name(), "x-custom");
        assert_eq!(matcher.allowed_values().len(), 2);
    }

    #[test]
    fn test_header_matcher_with_dependencies() {
        let matcher =
            HeaderMatcher::with_dependencies("X-Custom", vec!["value1".to_string()], true).unwrap();
        assert_eq!(matcher.header_name(), "x-custom");
        assert_eq!(matcher.allowed_values().len(), 1);
    }

    #[tokio::test]
    async fn test_header_matcher_case_sensitive_match() {
        let matcher = HeaderMatcher::new("X-Key", vec!["ExactMatch".to_string()])
            .unwrap()
            .with_case_sensitive(true);
        let context = RequestContext::new().with_header("x-key", "ExactMatch");
        let result = matcher.matches(&context).await.unwrap();
        assert!(result);
    }

    #[test]
    fn test_header_matcher_load_config_partial_header_name() {
        let mut matcher = HeaderMatcher::new("X-Original", vec!["value".to_string()]).unwrap();
        let config = serde_json::json!({ "header_name": "Authorization" });
        assert!(matcher.load_config(config).is_ok());
        assert_eq!(matcher.header_name(), "authorization");
        assert_eq!(matcher.allowed_values().len(), 1);
    }

    #[test]
    fn test_header_matcher_load_config_partial_values() {
        let mut matcher = HeaderMatcher::new("X-Original", vec!["old_value".to_string()]).unwrap();
        let config = serde_json::json!({ "allowed_values": ["new_value"] });
        assert!(matcher.load_config(config).is_ok());
        assert_eq!(matcher.header_name(), "x-original");
        assert_eq!(matcher.allowed_values().len(), 1);
        assert_eq!(matcher.allowed_values()[0], "new_value");
    }

    #[test]
    fn test_header_matcher_load_config_partial_case_sensitive() {
        let mut matcher = HeaderMatcher::new("X-Test", vec!["value".to_string()]).unwrap();
        let config = serde_json::json!({ "case_sensitive": true });
        assert!(matcher.load_config(config).is_ok());
        assert!(matcher.case_sensitive);
    }

    #[test]
    fn test_header_matcher_load_config_too_many_values() {
        let mut matcher = HeaderMatcher::new("X-Test", vec!["value".to_string()]).unwrap();
        let values: Vec<String> = (0..=MAX_ALLOWED_VALUES_COUNT)
            .map(|i| format!("value_{}", i))
            .collect();
        let config = serde_json::json!({ "allowed_values": values });
        let result = matcher.load_config(config);
        assert!(result.is_err());
    }

    #[test]
    fn test_header_matcher_load_config_non_string_value_rejected() {
        // 非字符串项显性报错而非 filter_map 静默丢弃(与 MethodMatcher
        // 政策一致:跳过会让匹配范围静默缩小且不可观测)
        let mut matcher = HeaderMatcher::new("X-Test", vec!["valid".to_string()]).unwrap();
        let config = serde_json::json!({
            "allowed_values": ["valid1", 123, "valid2"],
        });
        assert!(matcher.load_config(config).is_err());
        // 报错时旧配置原样保留(rollback 语义)
        assert_eq!(matcher.allowed_values().len(), 1);
        assert_eq!(matcher.allowed_values()[0], "valid");
    }

    #[test]
    fn test_header_matcher_builder_allowed_values() {
        // 覆盖 HeaderMatcherBuilder::allowed_values 方法(设置整个值列表)
        let values = vec!["v1".to_string(), "v2".to_string(), "v3".to_string()];
        let matcher = HeaderMatcher::builder()
            .header_name("X-Test")
            .allowed_values(values)
            .build()
            .unwrap();
        assert_eq!(matcher.allowed_values().len(), 3);
        assert_eq!(matcher.allowed_values()[0], "v1");
        assert_eq!(matcher.allowed_values()[2], "v3");
    }

    // ==================== HeaderMatcher 前缀/相等模式 ====================

    fn ctx_with_header(name: &str, value: &str) -> RequestContext {
        RequestContext::new().with_header(name, value)
    }

    #[tokio::test]
    async fn test_header_matcher_prefix_mode() {
        let matcher =
            HeaderMatcher::new("X-Tenant", vec!["team-a".to_string(), "team-b".to_string()])
                .unwrap()
                .with_match_mode(HeaderMatchMode::Prefix);

        // 前缀命中(team-a-prod 以 team-a 开头)
        assert!(
            matcher
                .matches(&ctx_with_header("X-Tenant", "team-a-prod"))
                .await
                .unwrap()
        );
        // 非前缀拒绝(前缀不对)
        assert!(
            !matcher
                .matches(&ctx_with_header("X-Tenant", "team-c-prod"))
                .await
                .unwrap()
        );
        // 头缺失拒绝
        assert!(!matcher.matches(&RequestContext::new()).await.unwrap());
    }

    #[tokio::test]
    async fn test_header_matcher_exact_mode_rejects_superstring() {
        // 相等模式(默认)不接受超串:team-a-prod != team-a
        let matcher = HeaderMatcher::new("X-Tenant", vec!["team-a".to_string()]).unwrap();
        assert!(
            !matcher
                .matches(&ctx_with_header("X-Tenant", "team-a-prod"))
                .await
                .unwrap(),
            "the default exact mode must not allow a superstring via a prefix hit"
        );
        assert!(
            matcher
                .matches(&ctx_with_header("X-Tenant", "team-a"))
                .await
                .unwrap()
        );
    }

    #[tokio::test]
    async fn test_header_matcher_prefix_mode_case_insensitive() {
        let matcher = HeaderMatcher::new("X-Tenant", vec!["Team-A".to_string()])
            .unwrap()
            .with_match_mode(HeaderMatchMode::Prefix);
        assert!(
            matcher
                .matches(&ctx_with_header("X-Tenant", "TEAM-A-prod"))
                .await
                .unwrap(),
            "case-insensitive by default: prefix comparison must ignore case"
        );
    }

    #[tokio::test]
    async fn test_header_matcher_prefix_mode_case_sensitive() {
        let matcher = HeaderMatcher::new("X-Tenant", vec!["Team-A".to_string()])
            .unwrap()
            .with_case_sensitive(true)
            .with_match_mode(HeaderMatchMode::Prefix);
        assert!(
            !matcher
                .matches(&ctx_with_header("X-Tenant", "team-a-prod"))
                .await
                .unwrap(),
            "in case-sensitive mode the prefix must match character by character"
        );
    }

    #[tokio::test]
    async fn test_header_matcher_ascii_fast_path_semantics_equivalence() {
        // ASCII 快路径与 Unicode 折叠原路径语义等价:纯 ASCII 输入的
        // Unicode 折叠与 ASCII 折叠一致(大写头值、混合大小写、miss 均验证)
        let matcher = HeaderMatcher::new("X-Tenant", vec!["team-a".to_string()])
            .unwrap()
            .with_match_mode(HeaderMatchMode::Prefix);
        assert!(
            matcher
                .matches(&ctx_with_header("X-Tenant", "TEAM-A-prod"))
                .await
                .unwrap(),
            "an ASCII uppercase header value must hit via the zero-allocation fast path"
        );
        assert!(
            !matcher
                .matches(&ctx_with_header("X-Tenant", "zzz-miss"))
                .await
                .unwrap()
        );
        let exact = HeaderMatcher::new("X-Tenant", vec!["team-a".to_string()]).unwrap();
        assert!(
            exact
                .matches(&ctx_with_header("X-Tenant", "TEAM-A"))
                .await
                .unwrap(),
            "an Exact ASCII uppercase header value must hit via the fast path"
        );
        assert!(
            !exact
                .matches(&ctx_with_header("X-Tenant", "team-a-prod"))
                .await
                .unwrap(),
            "the Exact fast path must not allow a superstring via a prefix hit"
        );
    }

    #[tokio::test]
    async fn test_header_matcher_non_ascii_values_fall_back_to_unicode_fold() {
        // 逐值门控:非 ASCII 值走 to_lowercase 原路径('İ' 经 to_lowercase
        // 产生 "i̇" 双字节序列,ASCII 折叠无法覆盖),同列表的 ASCII 值
        // 不受牵连仍走零分配折叠;匹配行为与列表级门控时逐位一致
        let matcher = HeaderMatcher::new(
            "X-Tenant",
            vec!["ſpecial".to_string(), "team-a".to_string()],
        )
        .unwrap()
        .with_match_mode(HeaderMatchMode::Prefix);
        assert_eq!(
            matcher.values_ascii,
            [false, true],
            "the ASCII flag must align per value"
        );
        // 非 ASCII 值走原路径:'ſpecial' 经 to_lowercase 原样保留('ſ' 已是
        // 小写),前缀精确匹配命中
        assert!(
            matcher
                .matches(&ctx_with_header("X-Tenant", "ſpecial-offer"))
                .await
                .unwrap()
        );
        // ASCII 值零分配快路径不受非 ASCII 邻值影响
        assert!(
            matcher
                .matches(&ctx_with_header("X-Tenant", "TEAM-A-prod"))
                .await
                .unwrap()
        );
        // 头值含非 ASCII(允许值同含非 ASCII):走原路径 Unicode 折叠,
        // 大写非 ASCII 前缀照常命中;且 "team-ä" 不因形似 "team-a" 误命中
        let unicode_values = HeaderMatcher::new("X-Tenant", vec!["mä-team".to_string()])
            .unwrap()
            .with_match_mode(HeaderMatchMode::Prefix);
        assert!(
            unicode_values
                .matches(&ctx_with_header("X-Tenant", "MÄ-TEAM-prod"))
                .await
                .unwrap(),
            "a non-ASCII header value must fold via to_lowercase on the original path"
        );
        let lookalike = HeaderMatcher::new("X-Tenant", vec!["team-a".to_string()])
            .unwrap()
            .with_match_mode(HeaderMatchMode::Prefix);
        assert!(
            !lookalike
                .matches(&ctx_with_header("X-Tenant", "team-ä-prod"))
                .await
                .unwrap(),
            "a-umlaut != a: after Unicode folding it must still not match, no false pass"
        );
    }

    #[test]
    fn test_header_matcher_empty_values_rejected() {
        // 空 allowlist 的匹配器静默永不命中,与 MethodMatcher 空列表
        // 拒绝政策对齐,显性报错防配置失效不可知
        assert!(HeaderMatcher::new("X-Tenant", vec![]).is_err());
        assert!(
            HeaderMatcher::builder()
                .header_name("X-Tenant")
                .build()
                .is_err()
        );
    }

    #[test]
    fn test_header_matcher_default_mode_is_exact() {
        let matcher = HeaderMatcher::new("X-Tenant", vec!["a".to_string()]).unwrap();
        assert_eq!(matcher.match_mode(), HeaderMatchMode::Exact);
    }

    #[tokio::test]
    async fn test_header_matcher_load_config_match_mode() {
        let mut matcher = HeaderMatcher::new("X-Tenant", vec!["team".to_string()]).unwrap();
        matcher
            .load_config(serde_json::json!({"match_mode": "prefix"}))
            .unwrap();
        assert_eq!(matcher.match_mode(), HeaderMatchMode::Prefix);
        assert!(
            matcher
                .matches(&ctx_with_header("X-Tenant", "team-42"))
                .await
                .unwrap(),
            "load_config swapping in the prefix mode should take effect"
        );
    }

    #[test]
    fn test_header_matcher_load_config_invalid_match_mode() {
        let mut matcher = HeaderMatcher::new("X-Tenant", vec!["a".to_string()]).unwrap();
        let result = matcher.load_config(serde_json::json!({"match_mode": "fuzzy"}));
        assert!(
            result.is_err(),
            "an illegal match_mode must error explicitly"
        );
    }

    #[test]
    fn test_header_matcher_builder_match_mode() {
        let matcher = HeaderMatcher::builder()
            .header_name("X-Tenant")
            .add_allowed_value("team")
            .match_mode(HeaderMatchMode::Prefix)
            .build()
            .unwrap();
        assert_eq!(matcher.match_mode(), HeaderMatchMode::Prefix);
    }

    // ==================== MethodMatcher ====================

    #[test]
    fn test_method_matcher_new_normalizes_case() {
        let matcher = MethodMatcher::new(vec!["get".to_string(), "Post".to_string()]).unwrap();
        assert_eq!(matcher.methods(), ["GET", "POST"]);
    }

    #[test]
    fn test_method_matcher_empty_rejected() {
        assert!(
            MethodMatcher::new(vec![]).is_err(),
            "an empty method list must be rejected"
        );
    }

    #[test]
    fn test_method_matcher_too_many_rejected() {
        let methods: Vec<String> = (0..=MAX_ALLOWED_VALUES_COUNT)
            .map(|i| format!("M{i}"))
            .collect();
        assert!(
            MethodMatcher::new(methods).is_err(),
            "over-limit must be rejected"
        );
    }

    #[tokio::test]
    async fn test_method_matcher_matches() {
        let matcher = MethodMatcher::new(vec!["GET".to_string(), "POST".to_string()]).unwrap();
        assert!(
            matcher
                .matches(&RequestContext::new().with_method("GET"))
                .await
                .unwrap()
        );
        // 大小写规范化:context 传小写同样命中
        assert!(
            matcher
                .matches(&RequestContext::new().with_method("post"))
                .await
                .unwrap()
        );
        assert!(
            !matcher
                .matches(&RequestContext::new().with_method("DELETE"))
                .await
                .unwrap()
        );
        // 方法缺失(空串)不命中
        assert!(!matcher.matches(&RequestContext::new()).await.unwrap());
    }

    #[tokio::test]
    async fn test_method_matcher_load_config() {
        let mut matcher = MethodMatcher::new(vec!["GET".to_string()]).unwrap();
        matcher
            .load_config(serde_json::json!({"methods": ["PUT", "delete"]}))
            .unwrap();
        assert_eq!(matcher.methods(), ["PUT", "DELETE"]);
        assert!(
            matcher
                .matches(&RequestContext::new().with_method("DELETE"))
                .await
                .unwrap()
        );
        assert!(
            !matcher
                .matches(&RequestContext::new().with_method("GET"))
                .await
                .unwrap(),
            "load_config must replace the method list wholesale"
        );
    }

    #[tokio::test]
    async fn test_method_matcher_registry_roundtrip() {
        let registry = CustomMatcherRegistry::new();
        registry
            .register(
                "method".to_string(),
                Box::new(MethodMatcher::new(vec!["GET".to_string()]).unwrap()),
            )
            .await
            .unwrap();
        assert!(registry.contains("method").await);

        let ctx = RequestContext::new().with_method("GET");
        assert!(registry.match_with("method", &ctx).await.unwrap());

        registry.unregister("method").await.unwrap();
        assert!(!registry.contains("method").await);
        let result = registry.match_with("method", &ctx).await;
        assert!(result.is_err(), "unregistering must error explicitly");
    }

    // ==================== RegexPathMatcher(regex-matching feature) ====================

    #[cfg(feature = "regex-matching")]
    #[tokio::test]
    async fn test_regex_path_matcher_matches() {
        let matcher = RegexPathMatcher::new("^/api/v[0-9]+/users", false).unwrap();
        assert!(
            matcher
                .matches(&RequestContext::new().with_path("/api/v2/users/42"))
                .await
                .unwrap()
        );
        assert!(
            !matcher
                .matches(&RequestContext::new().with_path("/web/users"))
                .await
                .unwrap()
        );
    }

    #[cfg(feature = "regex-matching")]
    #[tokio::test]
    async fn test_regex_path_matcher_case_insensitive() {
        let sensitive = RegexPathMatcher::new("^/Admin", false).unwrap();
        let insensitive = RegexPathMatcher::new("^/Admin", true).unwrap();
        let ctx = RequestContext::new().with_path("/admin/dashboard");
        assert!(!sensitive.matches(&ctx).await.unwrap());
        assert!(insensitive.matches(&ctx).await.unwrap());
        assert_eq!(insensitive.pattern(), "(?i)^/Admin");
    }

    #[cfg(feature = "regex-matching")]
    #[test]
    fn test_regex_path_matcher_invalid_pattern_rejected() {
        assert!(RegexPathMatcher::new("(unclosed", false).is_err());
        assert!(
            RegexPathMatcher::new("", false).is_err(),
            "an empty pattern must be rejected"
        );
    }

    #[cfg(feature = "regex-matching")]
    #[tokio::test]
    async fn test_regex_path_matcher_load_config() {
        let mut matcher = RegexPathMatcher::new("^/old", false).unwrap();
        matcher
            .load_config(serde_json::json!({"pattern": "^/new", "case_insensitive": true}))
            .unwrap();
        assert_eq!(matcher.pattern(), "(?i)^/new");
        assert!(
            matcher
                .matches(&RequestContext::new().with_path("/NEW/path"))
                .await
                .unwrap()
        );
    }

    #[cfg(feature = "regex-matching")]
    #[tokio::test]
    async fn test_regex_path_matcher_registry_roundtrip() {
        let registry = CustomMatcherRegistry::new();
        registry
            .register(
                "api_paths".to_string(),
                Box::new(RegexPathMatcher::new("^/api/", false).unwrap()),
            )
            .await
            .unwrap();
        let ctx = RequestContext::new().with_path("/api/health");
        assert!(registry.match_with("api_paths", &ctx).await.unwrap());
        registry.unregister("api_paths").await.unwrap();
        assert!(registry.match_with("api_paths", &ctx).await.is_err());
    }

    // ==================== 三 matcher 注册表注册/注销集成 ====================

    #[tokio::test]
    async fn test_registry_register_duplicate_rejected() {
        let registry = CustomMatcherRegistry::new();
        registry
            .register(
                "dup".to_string(),
                Box::new(MethodMatcher::new(vec!["GET".to_string()]).unwrap()),
            )
            .await
            .unwrap();
        let second = registry
            .register(
                "dup".to_string(),
                Box::new(MethodMatcher::new(vec!["POST".to_string()]).unwrap()),
            )
            .await;
        assert!(
            second.is_err(),
            "duplicate-name registration must be rejected"
        );
        // 原注册不受影响
        assert!(
            registry
                .match_with("dup", &RequestContext::new().with_method("GET"))
                .await
                .unwrap()
        );
    }

    #[tokio::test]
    async fn test_registry_unregister_missing_rejected() {
        let registry = CustomMatcherRegistry::new();
        let result = registry.unregister("nonexistent").await;
        assert!(
            result.is_err(),
            "unregistering a non-existent matcher must error explicitly"
        );
    }

    #[test]
    fn test_header_matcher_empty_value_rejected() {
        // 空值在 Prefix 模式下语义翻转为通配符(starts_with("") 恒真),
        // Exact 模式下也无意义,构造与 load_config 均显性拒绝
        assert!(HeaderMatcher::new("X-Tenant", vec![String::new()]).is_err());
        let mut matcher = HeaderMatcher::new("X-Tenant", vec!["a".to_string()]).unwrap();
        assert!(
            matcher
                .load_config(serde_json::json!({"allowed_values": [""]}))
                .is_err()
        );
    }

    #[test]
    fn test_method_matcher_invalid_entries_rejected() {
        // 逐项校验:空串、含分隔符、非 ASCII 均显性报错
        assert!(MethodMatcher::new(vec![String::new()]).is_err());
        assert!(MethodMatcher::new(vec!["GET POST".to_string()]).is_err());
        assert!(MethodMatcher::new(vec!["GËT".to_string()]).is_err());
        // 合法 token 字符集(RFC 9110)放行
        assert!(MethodMatcher::new(vec!["CUSTOM-METHOD_1".to_string()]).is_ok());
        // load_config 非字符串项显性报错而非静默丢弃
        let mut matcher = MethodMatcher::new(vec!["GET".to_string()]).unwrap();
        assert!(
            matcher
                .load_config(serde_json::json!({"methods": ["GET", 42]}))
                .is_err()
        );
        // load_config 逐项校验同样生效
        assert!(
            matcher
                .load_config(serde_json::json!({"methods": [""]}))
                .is_err()
        );
    }

    #[tokio::test]
    async fn test_method_matcher_non_ascii_never_matches() {
        let matcher = MethodMatcher::new(vec!["GET".to_string()]).unwrap();
        // 'ſ'(U+017F) 经 Unicode 大写折叠会变 'S'——ASCII token 语义下
        // 非 ASCII 输入必须不命中
        assert!(
            !matcher
                .matches(&RequestContext::new().with_method("ſet"))
                .await
                .unwrap()
        );
    }

    #[cfg(feature = "regex-matching")]
    #[tokio::test]
    async fn test_regex_path_matcher_ci_flag_independent_update() {
        // 仅传 case_insensitive 不传 pattern:切换语义并按现有模式重编译,
        // 而非静默忽略
        let mut matcher = RegexPathMatcher::new("^/Admin", false).unwrap();
        matcher
            .load_config(serde_json::json!({"case_insensitive": true}))
            .unwrap();
        assert!(matcher.case_insensitive());
        assert_eq!(matcher.pattern(), "(?i)^/Admin");
        assert!(
            matcher
                .matches(&RequestContext::new().with_path("/admin/x"))
                .await
                .unwrap()
        );
        // 切回敏感
        matcher
            .load_config(serde_json::json!({"case_insensitive": false}))
            .unwrap();
        assert_eq!(matcher.pattern(), "^/Admin");
        assert!(
            !matcher
                .matches(&RequestContext::new().with_path("/admin/x"))
                .await
                .unwrap()
        );
    }
}