guard-core-engine 4.4.0

Detection engine for the Guard ecosystem: pattern compilation, input preprocessing, and semantic analysis.
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
//! The sliding-window rate limiter: per client IP, global scope or per
//! endpoint.
//!
//! This is the Rust family's in-memory port of the reference engine's rate
//! limiter (`guard_core/handlers/ratelimit_handler.py`, via the Go port's
//! `ratelimit.go`). One call, [`RateLimiter::check`], records one request
//! into the window for `(client IP, scope)` and decides it:
//!
//! ```text
//! evict every recorded timestamp at or before (now - window)
//! count   = requests still inside the window (before this one is recorded)
//! record  now
//! allowed = count < rate_limit
//! ```
//!
//! ## Counting semantics
//!
//! The reference keeps a sliding log of request timestamps per key. The
//! in-memory store compares the pre-recording count against the limit
//! (`allowed = count < limit`), the Redis store compares the post-recording
//! rank against it (`allowed = count <= limit`, one Lua/ZSET pipeline keyed
//! `rate_limit:rate:{ip}[:{endpoint hash}]`); the boundary is the same, this
//! port mirrors the in-memory formulation because Redis is out of scope here:
//! the store is process-local, exactly what the reference falls back to when
//! Redis is off, and the same `workers x rate_limit` caveat applies to
//! multi-process deployments. The count reported on a block includes the
//! current request (`count + 1`), matching what both references log.
//!
//! Blocked callers retry after the configured window: the reference attaches
//! `Retry-After: <window seconds>` to its `429 Too many requests`, and
//! [`RateLimitDecision::retry_after`] carries the same value.
//!
//! ## Scope
//!
//! The global scope keys the window by client IP alone (every endpoint
//! shares one budget per IP, the reference's default pipeline tier). The
//! endpoint scope keys it by `(client IP, endpoint path)` - an isolated
//! budget per endpoint, the reference's `endpoint_path`-keyed tier. Keys are
//! structured (IP + path fields), so no separator collision exists by
//! construction; the reference hashes the endpoint segment for its joined
//! Redis keys (`rate:{ip}:{_hash_identity_segment(path)}`), a concern the
//! in-memory store does not have.
//!
//! ## Tiers
//!
//! [`RateLimiter::check_tiers`] runs the reference pipeline's tier order
//! (`RateLimitCheck.check`, `rate_limit.py`, via the Go port's
//! `tiersFor`/`runTier`): every configured tier records one request into
//! its own window and the first tier that crosses its limit blocks. The
//! tiers, in order:
//!
//! 1. **endpoint**: `endpoint_rate_limits[path]` (the config-level
//!    per-endpoint map), keyed by `(ip, path)`;
//! 2. **route**: the route decorator's `rate_limit` (window default 60,
//!    `rate_limit_window or 60`), keyed by `(ip, path)`;
//! 3. **geo**: the route decorator's `geo_rate_limits` country map, the
//!    resolved country's entry with the `"*"` fallback
//!    (`country in limits else "*" in limits`), keyed by `(ip, path)`;
//! 4. **global**: the config `rate_limit`/`rate_limit_window`, keyed by
//!    `ip` alone.
//!
//! With no tiers configured the sequence collapses to the global tier, the
//! exact pre-tier behavior. The decision names the tier that blocked so
//! adapters can log the reference's reason strings, and carries that
//! tier's window for `Retry-After`.
//!
//! ## Honesty
//!
//! No Redis: the distributed mode (shared budgets across workers, script
//! reload handling) is a follow-up. The window store is an LRU capped at
//! 10 000 keys (`maxTrackedRateLimitKeys` in the Go port,
//! `_MAX_TRACKED_RATE_LIMIT_KEYS` in the reference), so abusive key
//! cardinality cannot grow the store without bound.
//!
//! # Example
//!
//! ```
//! use std::net::IpAddr;
//! use std::str::FromStr;
//!
//! use guard_core_engine::rate_limit::{RateLimitConfig, RateLimiter};
//!
//! let limiter = RateLimiter::new(RateLimitConfig {
//!     enable_rate_limiting: true,
//!     rate_limit: 2,
//!     ..RateLimitConfig::default()
//! })
//! .expect("valid config");
//! let ip = IpAddr::from_str("192.0.2.1").unwrap();
//!
//! assert!(limiter.check(ip, None).allowed);
//! assert!(limiter.check(ip, None).allowed);
//! // The third request inside the window crosses the limit.
//! let blocked = limiter.check(ip, None);
//! assert!(!blocked.allowed);
//! assert_eq!(blocked.retry_after(), 60);
//! ```
//!
//! A tiered check runs every configured tier and names the one that
//! blocked:
//!
//! ```
//! use std::collections::HashMap;
//! use std::net::IpAddr;
//! use std::str::FromStr;
//!
//! use guard_core_engine::rate_limit::{
//!     RateLimitConfig, RateLimitEntry, RateLimiter, RouteRateLimits,
//! };
//!
//! let mut endpoint_rate_limits = HashMap::new();
//! endpoint_rate_limits.insert("/login".to_owned(), RateLimitEntry::new(1, 60).unwrap());
//! let limiter = RateLimiter::new(RateLimitConfig {
//!     enable_rate_limiting: true,
//!     endpoint_rate_limits,
//!     ..RateLimitConfig::default()
//! })
//! .expect("valid config");
//! let ip = IpAddr::from_str("192.0.2.1").unwrap();
//!
//! assert!(limiter.check_tiers(ip, Some("/login"), None, None).allowed());
//! let blocked = limiter.check_tiers(ip, Some("/login"), None, None);
//! assert!(!blocked.allowed());
//! assert_eq!(blocked.tier_name(), "endpoint");
//! ```
//!
//! A disabled limiter is inert: `check` allows without recording.

use std::collections::{HashMap, VecDeque};
use std::net::IpAddr;
use std::num::NonZeroUsize;
use std::sync::{Arc, Mutex};

use lru::LruCache;

use crate::ip_gate::canonical;

/// The reference default for `rate_limit` (maximum requests per window).
pub const DEFAULT_RATE_LIMIT: u32 = 10;
/// The reference default for `rate_limit_window` (seconds).
pub const DEFAULT_RATE_LIMIT_WINDOW: u64 = 60;
/// The route tier's default window (`rate_limit_window or 60`, the
/// `@rate_limit` decorator default).
pub const DEFAULT_ROUTE_RATE_LIMIT_WINDOW: u64 = 60;
/// The window store's key cap (`_MAX_TRACKED_RATE_LIMIT_KEYS` /
/// `maxTrackedRateLimitKeys` in the references).
pub const MAX_TRACKED_RATE_LIMIT_KEYS: usize = 10_000;

/// One `(requests, window)` rate-limit entry: a per-endpoint or per-country
/// tier override (the reference `endpoint_rate_limits[path]` /
/// `geo_rate_limits[country]` `(int, int)` tuples).
///
/// Build it with [`RateLimitEntry::new`] (fail closed on a zero requests or
/// window, the reference `ge=1` semantics the tier entries inherit from the
/// flat knobs they override).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RateLimitEntry {
    /// Maximum requests inside the window.
    pub requests: u32,
    /// The window length in seconds.
    pub window: u64,
}

impl RateLimitEntry {
    /// Validate and build an entry.
    ///
    /// # Errors
    ///
    /// [`RateLimitConfigError`] on a zero `requests` or `window` (the
    /// reference rejects both with `ge=1`).
    pub fn new(requests: u32, window: u64) -> Result<Self, RateLimitConfigError> {
        if requests == 0 {
            return Err(RateLimitConfigError {
                field: "requests".into(),
                reason: "must be at least 1 request per window",
            });
        }
        if window == 0 {
            return Err(RateLimitConfigError {
                field: "window".into(),
                reason: "must be at least 1 second",
            });
        }
        Ok(Self { requests, window })
    }
}

/// The route decorator's rate-limit tier overrides
/// (`RouteConfig.rate_limit` / `rate_limit_window` / `geo_rate_limits`).
///
/// Build it with [`RouteRateLimits::new`]; the geo tier's country entries
/// are [`RateLimitEntry`] values (already validated). The geo country key
/// set mirrors the reference: exact country codes with the `"*"`
/// fallback entry, compared exactly (no case folding, the reference reads
/// the resolved country as-is).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RouteRateLimits {
    /// `route_config.rate_limit`: `None` means no route tier.
    rate_limit: Option<u32>,
    /// `route_config.rate_limit_window`: the route tier's window, the
    /// reference default of 60 when `None` and a route tier is configured.
    rate_limit_window: Option<u64>,
    /// `route_config.geo_rate_limits`: the per-country `(limit, window)`
    /// overrides with the `"*"` fallback entry; `None` or empty means no
    /// geo tier.
    geo_rate_limits: Option<HashMap<String, RateLimitEntry>>,
}

impl RouteRateLimits {
    /// Validate and build the route tier overrides.
    ///
    /// # Errors
    ///
    /// [`RateLimitConfigError`] on a zero `rate_limit` or a zero
    /// `rate_limit_window` that a configured route tier would run under
    /// (the reference `ge=1` semantics); a `None` rate limit with a window
    /// is inert and therefore not rejected, mirroring the reference where
    /// `rate_limit_window` alone never configures a tier.
    pub fn new(
        rate_limit: Option<u32>,
        rate_limit_window: Option<u64>,
        geo_rate_limits: Option<HashMap<String, RateLimitEntry>>,
    ) -> Result<Self, RateLimitConfigError> {
        if rate_limit.is_some_and(|limit| limit == 0) {
            return Err(RateLimitConfigError {
                field: "rate_limit".into(),
                reason: "must be at least 1 request per window",
            });
        }
        if rate_limit.is_some() && rate_limit_window.is_some_and(|window| window == 0) {
            return Err(RateLimitConfigError {
                field: "rate_limit_window".into(),
                reason: "must be at least 1 second",
            });
        }
        if let Some(geo) = &geo_rate_limits {
            for (country, entry) in geo {
                if entry.requests == 0 || entry.window == 0 {
                    return Err(RateLimitConfigError {
                        field: format!("geo_rate_limits[{country}]").into(),
                        reason: "every entry needs at least 1 request per at least 1 second",
                    });
                }
            }
        }
        Ok(Self {
            rate_limit,
            rate_limit_window,
            geo_rate_limits,
        })
    }

    /// `route_config.rate_limit`.
    #[must_use]
    pub const fn rate_limit(&self) -> Option<u32> {
        self.rate_limit
    }

    /// `route_config.rate_limit_window` (the reference default of 60
    /// applies when a route tier runs and this is `None`).
    #[must_use]
    pub const fn rate_limit_window(&self) -> Option<u64> {
        self.rate_limit_window
    }

    /// `route_config.geo_rate_limits`.
    #[must_use]
    pub const fn geo_rate_limits(&self) -> Option<&HashMap<String, RateLimitEntry>> {
        self.geo_rate_limits.as_ref()
    }
}

/// The rate-limiting knobs (the reference `enable_rate_limiting` /
/// `rate_limit` / `rate_limit_window` / `enable_rate_limit_auto_ban` group).
///
/// The defaults are the reference `SecurityConfig` defaults: rate limiting
/// on (`enable_rate_limiting = true`, `guard_core/_security_config_fields.py`)
/// with the reference thresholds (10 requests / 60 s window).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RateLimitConfig {
    /// `enable_rate_limiting`. `false` makes every [`RateLimiter::check`]
    /// an unconditional allow that records nothing.
    pub enable_rate_limiting: bool,
    /// `rate_limit`: maximum requests per client IP inside
    /// `rate_limit_window` seconds.
    pub rate_limit: u32,
    /// `rate_limit_window`: the window length in seconds.
    pub rate_limit_window: u64,
    /// `enable_rate_limit_auto_ban`: feed rate-limit crossings into the
    /// auto-ban engine (the `rate_limit` category of the violation counters)
    /// when the pipeline stage runs with IP banning enabled.
    pub enable_rate_limit_auto_ban: bool,
    /// `endpoint_rate_limits`: the per-endpoint tier map (`path ->
    /// (requests, window)`, the reference config field set by dynamic
    /// rules), matched by exact path. Empty by default: the tier is
    /// unconfigured and records nothing.
    pub endpoint_rate_limits: HashMap<String, RateLimitEntry>,
}

impl Default for RateLimitConfig {
    fn default() -> Self {
        Self {
            enable_rate_limiting: true,
            rate_limit: DEFAULT_RATE_LIMIT,
            rate_limit_window: DEFAULT_RATE_LIMIT_WINDOW,
            enable_rate_limit_auto_ban: false,
            endpoint_rate_limits: HashMap::new(),
        }
    }
}

/// An invalid [`RateLimitConfig`] or [`RouteRateLimits`]: the config error
/// [`RateLimiter::new`] fails closed with.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RateLimitConfigError {
    /// The rejected field (`rate_limit`, `rate_limit_window`,
    /// `endpoint_rate_limits`, or a tier entry field).
    pub field: std::borrow::Cow<'static, str>,
    /// What the field must be instead.
    pub reason: &'static str,
}

impl core::fmt::Display for RateLimitConfigError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "invalid {}: {}", self.field, self.reason)
    }
}

impl std::error::Error for RateLimitConfigError {}

/// The outcome of one rate-limit check.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RateLimitDecision {
    /// `false` when the request crossed the limit and must be answered with
    /// the family's `429 Too many requests` carrying
    /// [`RateLimitDecision::retry_after`].
    pub allowed: bool,
    /// Requests observed inside the window including this one (the count
    /// both references report when they block).
    pub count: u64,
    /// The window length the decision was made under (seconds), so callers
    /// can render `Retry-After` without re-reading the config.
    pub window: u64,
}

impl RateLimitDecision {
    /// The `Retry-After` header value for a blocked request: the window
    /// length, exactly what the reference sets.
    #[must_use]
    pub const fn retry_after(self) -> u64 {
        self.window
    }
}

/// The rate-limit tier a [`RateLimiter::check_tiers`] decision was made
/// under (`endpoint`, `route`, `geo`, `global` - the reference check order).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RateLimitTier {
    /// `endpoint_rate_limits[path]`: the config-level per-endpoint tier.
    Endpoint,
    /// The route decorator's `rate_limit` tier.
    Route,
    /// The route decorator's `geo_rate_limits` country tier.
    Geo,
    /// The flat config `rate_limit` tier (the reference default).
    Global,
}

impl RateLimitTier {
    /// The tier's name as the reference reasons spell it (`Endpoint-specific
    /// rate limit exceeded`, `Route-specific rate limit exceeded`,
    /// `Geo rate limit exceeded for {country}`, and the global tier's plain
    /// `Rate limit exceeded`).
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Endpoint => "endpoint",
            Self::Route => "route",
            Self::Geo => "geo",
            Self::Global => "global",
        }
    }
}

/// The outcome of one tiered rate-limit check
/// ([`RateLimiter::check_tiers`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TierDecision {
    /// `false` when some tier crossed its limit and the request must be
    /// answered with the family's `429 Too many requests` carrying
    /// [`TierDecision::retry_after`].
    allowed: bool,
    /// Requests observed inside the blocking tier's window including this
    /// one (the count both references report when they block); the last
    /// tier's count when nothing blocked.
    count: u64,
    /// The tier that blocked (the last tier when nothing blocked).
    tier: RateLimitTier,
    /// The window length the decision was made under (seconds).
    window: u64,
}

impl TierDecision {
    /// `false` when some tier crossed its limit.
    #[must_use]
    pub const fn allowed(&self) -> bool {
        self.allowed
    }

    /// The observed count of the decisive tier (including this request).
    #[must_use]
    pub const fn count(&self) -> u64 {
        self.count
    }

    /// The tier the decision was made under.
    #[must_use]
    pub const fn tier(&self) -> RateLimitTier {
        self.tier
    }

    /// The tier's name (`"endpoint"`, `"route"`, `"geo"`, `"global"`).
    #[must_use]
    pub const fn tier_name(&self) -> &'static str {
        self.tier.name()
    }

    /// The `Retry-After` header value for a blocked request: the blocking
    /// tier's window length, exactly what the reference sets.
    #[must_use]
    pub const fn retry_after(&self) -> u64 {
        self.window
    }
}

/// The monotonic-ish wall clock, in seconds since the Unix epoch. Injectable
/// so expiry behavior (window sliding) is testable without sleeping.
pub type Clock = Arc<dyn Fn() -> f64 + Send + Sync>;

#[derive(Debug, PartialEq, Eq, Hash)]
struct WindowKey {
    ip: IpAddr,
    endpoint: Option<String>,
}

/// The sliding-window rate limiter over one shared in-memory store.
///
/// Build it once at startup with [`RateLimiter::new`] (fail closed on a
/// non-positive limit or window) and share the handle across requests; the
/// internal store is a mutex-guarded LRU, safe for concurrent services.
pub struct RateLimiter {
    config: RateLimitConfig,
    windows: Arc<Mutex<LruCache<WindowKey, VecDeque<f64>>>>,
    clock: Clock,
    store: Option<Arc<dyn crate::distributed::SlidingWindowStore>>,
    redis_prefix: String,
    redis_fail_open: bool,
}

impl Clone for RateLimiter {
    /// A clone shares the window store and the clock, the references'
    /// singleton semantics: requests recorded through any handle land in the
    /// same sliding windows.
    fn clone(&self) -> Self {
        Self {
            config: self.config.clone(),
            windows: Arc::clone(&self.windows),
            clock: Arc::clone(&self.clock),
            store: self.store.clone(),
            redis_prefix: self.redis_prefix.clone(),
            redis_fail_open: self.redis_fail_open,
        }
    }
}

impl core::fmt::Debug for RateLimiter {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("RateLimiter")
            .field("config", &self.config)
            .finish_non_exhaustive()
    }
}

/// The system wall clock, in seconds since the Unix epoch: the clock every
/// production store runs on. Adapters and stage tests that build several
/// stores over one clock share this constructor.
#[must_use]
pub fn system_clock() -> f64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0.0, |d| d.as_secs_f64())
}

/// A fresh shared window store (the store lives behind an `Arc` so clones of
/// the limiter share it).
fn new_window_store() -> Arc<Mutex<LruCache<WindowKey, VecDeque<f64>>>> {
    Arc::new(Mutex::new(LruCache::new(
        NonZeroUsize::new(MAX_TRACKED_RATE_LIMIT_KEYS).expect("constant above zero"),
    )))
}

impl RateLimiter {
    /// Validate the config and build the limiter.
    ///
    /// # Errors
    ///
    /// Fails closed with a [`RateLimitConfigError`] when `rate_limit` or
    /// `rate_limit_window` is zero (the reference rejects both with
    /// `ge=1`); nothing but `RateLimitConfig::default`-shaped values is
    /// substituted silently.
    pub fn new(config: RateLimitConfig) -> Result<Self, RateLimitConfigError> {
        Self::with_config_and_clock(config, Arc::new(system_clock))
    }

    /// Validate the config and build the limiter over an injected clock: the
    /// combined seam [`new`](Self::new) and [`with_clock`](Self::with_clock)
    /// cover separately. Production builds use [`RateLimiter::new`]; adapters
    /// and stage tests that drive window sliding with a fake clock under a
    /// production-shaped config use this one.
    ///
    /// # Errors
    ///
    /// Same fail-closed behavior as [`RateLimiter::new`]: a zero `rate_limit`
    /// or `rate_limit_window` is a [`RateLimitConfigError`].
    pub fn with_config_and_clock(
        config: RateLimitConfig,
        clock: Clock,
    ) -> Result<Self, RateLimitConfigError> {
        if config.rate_limit == 0 {
            return Err(RateLimitConfigError {
                field: "rate_limit".into(),
                reason: "must be at least 1 request per window",
            });
        }
        if config.rate_limit_window == 0 {
            return Err(RateLimitConfigError {
                field: "rate_limit_window".into(),
                reason: "must be at least 1 second",
            });
        }
        // A struct-literal config skips the entry constructor validation,
        // so the limiter re-validates and fails closed (the stage's
        // struct-literal ban config precedent).
        for (path, entry) in &config.endpoint_rate_limits {
            if entry.requests == 0 || entry.window == 0 {
                return Err(RateLimitConfigError {
                    field: format!("endpoint_rate_limits[{path}]").into(),
                    reason: "every entry needs at least 1 request per at least 1 second",
                });
            }
        }
        Ok(Self {
            config,
            windows: new_window_store(),
            clock,
            store: None,
            redis_prefix: String::from("guard_core:"),
            redis_fail_open: false,
        })
    }

    /// A limiter over `config` that shares this one's window store, clock
    /// and distributed store: the live-config swap a dynamic rule drives
    /// (the limits change, the recorded windows stay).
    ///
    /// # Errors
    ///
    /// Same fail-closed validation as [`RateLimiter::new`].
    pub fn with_config(&self, config: RateLimitConfig) -> Result<Self, RateLimitConfigError> {
        let fresh = Self::with_config_and_clock(config, Arc::clone(&self.clock))?;
        Ok(Self {
            windows: Arc::clone(&self.windows),
            store: self.store.clone(),
            redis_prefix: self.redis_prefix.clone(),
            redis_fail_open: self.redis_fail_open,
            ..fresh
        })
    }

    /// Swap the wall clock. Test seam: production builds use the system
    /// clock; deterministic window-sliding coverage injects a fake.
    /// Run the limiter over a distributed window store (the reference
    /// `enable_redis && redis_handler` conjunction): every tier's hit
    /// records into `{prefix}rate_limit:rate:{ip}[:{endpoint hash}]`
    /// through one transaction of the reference's four operations, and
    /// the decision compares the post-recording count with
    /// `count <= limit` (the Redis formulation; the same boundary as the
    /// in-memory `count < limit`).
    ///
    /// `redis_fail_open = true` mirrors the reference `redis_fail_open`:
    /// a failing backend call degrades to the in-memory window (the
    /// `workers x rate_limit` caveat applies); `false` (the default)
    /// surfaces the failure as `Err` so the caller can answer the
    /// reference `503 "Redis rate limiting unavailable"`.
    #[must_use]
    pub fn with_distributed_store(
        mut self,
        store: Arc<dyn crate::distributed::SlidingWindowStore>,
        redis_prefix: &str,
        redis_fail_open: bool,
    ) -> Self {
        self.store = Some(store);
        redis_prefix.clone_into(&mut self.redis_prefix);
        self.redis_fail_open = redis_fail_open;
        self
    }

    /// [`RateLimiter::check`] over the distributed store: `Err` means a
    /// failing backend with `redis_fail_open = false`.
    ///
    /// # Errors
    ///
    /// [`StoreError`](crate::distributed::StoreError) when the backend
    /// call fails and fail-open is off.
    pub fn check_distributed(
        &self,
        ip: IpAddr,
        endpoint: Option<&str>,
    ) -> Result<RateLimitDecision, crate::distributed::StoreError> {
        if !self.config.enable_rate_limiting {
            return Ok(RateLimitDecision {
                allowed: true,
                count: 0,
                window: self.config.rate_limit_window,
            });
        }
        let (allowed, count, window) = self.record_and_decide_distributed(
            ip,
            endpoint,
            self.config.rate_limit,
            self.config.rate_limit_window,
        )?;
        Ok(RateLimitDecision {
            allowed,
            count,
            window,
        })
    }

    /// [`RateLimiter::check_tiers`] over the distributed store: every
    /// tier keys its window the way the reference does (endpoint tiers
    /// keyed with the hashed path segment, the global tier by IP alone).
    ///
    /// # Errors
    ///
    /// [`StoreError`](crate::distributed::StoreError) when a tier's
    /// backend call fails and fail-open is off.
    pub fn check_tiers_distributed(
        &self,
        ip: IpAddr,
        url_path: Option<&str>,
        route: Option<&RouteRateLimits>,
        country_of_ip: Option<&dyn Fn(IpAddr) -> Option<String>>,
    ) -> Result<TierDecision, crate::distributed::StoreError> {
        let inert = TierDecision {
            allowed: true,
            count: 0,
            tier: RateLimitTier::Global,
            window: self.config.rate_limit_window,
        };
        if !self.config.enable_rate_limiting {
            return Ok(inert);
        }
        if let Some(path) = url_path {
            if let Some(entry) = self.config.endpoint_rate_limits.get(path) {
                let (allowed, count, window) = self.record_and_decide_distributed(
                    ip,
                    Some(path),
                    entry.requests,
                    entry.window,
                )?;
                if !allowed {
                    return Ok(TierDecision {
                        allowed,
                        count,
                        tier: RateLimitTier::Endpoint,
                        window,
                    });
                }
            }
            if let Some(route) = route {
                if let Some(limit) = route.rate_limit() {
                    let window = route
                        .rate_limit_window()
                        .unwrap_or(DEFAULT_ROUTE_RATE_LIMIT_WINDOW);
                    let (allowed, count, window) =
                        self.record_and_decide_distributed(ip, Some(path), limit, window)?;
                    if !allowed {
                        return Ok(TierDecision {
                            allowed,
                            count,
                            tier: RateLimitTier::Route,
                            window,
                        });
                    }
                }
                if let (Some(limits), Some(country_of_ip)) =
                    (route.geo_rate_limits(), country_of_ip)
                {
                    let country = country_of_ip(ip);
                    let entry = country
                        .as_ref()
                        .and_then(|code| limits.get(code))
                        .or_else(|| limits.get("*"));
                    if let Some(entry) = entry {
                        let (allowed, count, window) = self.record_and_decide_distributed(
                            ip,
                            Some(path),
                            entry.requests,
                            entry.window,
                        )?;
                        if !allowed {
                            return Ok(TierDecision {
                                allowed,
                                count,
                                tier: RateLimitTier::Geo,
                                window,
                            });
                        }
                    }
                }
            }
        }
        let (allowed, count, window) = self.record_and_decide_distributed(
            ip,
            None,
            self.config.rate_limit,
            self.config.rate_limit_window,
        )?;
        Ok(TierDecision {
            allowed,
            count,
            tier: RateLimitTier::Global,
            window,
        })
    }

    pub fn with_clock(clock: Clock) -> Self {
        Self {
            config: RateLimitConfig::default(),
            windows: new_window_store(),
            store: None,
            redis_prefix: String::from("guard_core:"),
            redis_fail_open: false,
            clock,
        }
    }

    /// The validated config the limiter decides under.
    #[must_use]
    pub const fn config(&self) -> &RateLimitConfig {
        &self.config
    }

    /// Record one request into the window `(ip, endpoint)` under `limit`
    /// requests per `window` seconds and decide it: the shared counting
    /// core of [`RateLimiter::check`] and [`RateLimiter::check_tiers`].
    // The store lock must outlive the eviction loop and the push (both
    // mutate through the `timestamps` reference the guard produced); the
    // nursery lint cannot see through that reference and wants it dropped
    // early. The lock scope below already ends before the decision is built.
    #[allow(clippy::significant_drop_tightening)]
    /// The distributed hit path: one transaction of the reference's four
    /// operations over the tier's Redis key, `allowed = count <= limit`
    /// (the Redis formulation). Fail-open degrades to the in-memory
    /// window on a backend error; fail-closed surfaces the error.
    fn record_and_decide_distributed(
        &self,
        ip: IpAddr,
        endpoint: Option<&str>,
        limit: u32,
        window_seconds: u64,
    ) -> Result<(bool, u64, u64), crate::distributed::StoreError> {
        let Some(store) = &self.store else {
            return Ok(self.record_and_decide(ip, endpoint, limit, window_seconds));
        };
        let now = (self.clock)();
        let key = endpoint.map_or_else(
            || crate::distributed::rate_window_key(&self.redis_prefix, ip),
            |path| crate::distributed::rate_window_key_endpoint(&self.redis_prefix, ip, path),
        );
        match store.record_hit(&key, now, window_seconds) {
            Ok(count) => {
                let allowed = count <= u64::from(limit);
                Ok((allowed, count, window_seconds))
            }
            Err(error) if self.redis_fail_open => {
                // The reference `_warn_redis_fail_open_in_memory_fallback`:
                // with several workers the effective limit is
                // workers x rate_limit. This port degrades silently per
                // call; hosts log through their own stack.
                let _ = error;
                Ok(self.record_and_decide(ip, endpoint, limit, window_seconds))
            }
            Err(error) => Err(error),
        }
    }

    fn record_and_decide(
        &self,
        ip: IpAddr,
        endpoint: Option<&str>,
        limit: u32,
        window_seconds: u64,
    ) -> (bool, u64, u64) {
        // u64 -> f64 rounds to nearest; at window lengths where that loses a
        // second the boundary shift is far below any real clock resolution.
        #[allow(clippy::cast_precision_loss)]
        let window = window_seconds as f64;
        let now = (self.clock)();
        let window_start = now - window;
        let key = WindowKey {
            ip: canonical(ip),
            endpoint: endpoint.map(str::to_owned),
        };
        // The lock scope ends at the block: the decision is built unlocked.
        let inside = {
            let mut windows = self.windows.lock().expect("rate window store");
            let timestamps = windows
                .try_get_or_insert_mut(key, || Ok::<_, core::convert::Infallible>(VecDeque::new()))
                .expect("key capacity just reserved");
            while timestamps
                .front()
                .is_some_and(|&recorded| recorded <= window_start)
            {
                timestamps.pop_front();
            }
            let inside = timestamps.len();
            timestamps.push_back(now);
            drop(windows);
            inside
        };
        let allowed = inside < usize::try_from(limit).unwrap_or(usize::MAX);
        let count = u64::try_from(inside + 1).unwrap_or(u64::MAX);
        (allowed, count, window_seconds)
    }

    /// Record one request for `ip` and decide it.
    ///
    /// `endpoint` selects the scope: `None` is the global per-IP window,
    /// `Some(path)` the per-endpoint window keyed by `(ip, path)`. A
    /// disabled limiter allows without recording. The returned decision's
    /// `count` includes the request just recorded, so a block reports the
    /// crossing count exactly as the references log it.
    #[must_use]
    pub fn check(&self, ip: IpAddr, endpoint: Option<&str>) -> RateLimitDecision {
        if !self.config.enable_rate_limiting {
            return RateLimitDecision {
                allowed: true,
                count: 0,
                window: self.config.rate_limit_window,
            };
        }
        let (allowed, count, window) = self.record_and_decide(
            ip,
            endpoint,
            self.config.rate_limit,
            self.config.rate_limit_window,
        );
        RateLimitDecision {
            allowed,
            count,
            window,
        }
    }

    /// Record one request for `ip` under every configured tier and decide
    /// it (the reference `RateLimitCheck.check` order, via the Go port's
    /// `tiersFor`/`runTier`): the endpoint tier, the route tier, the geo
    /// tier, then the global tier. Every configured tier records one hit
    /// into its own window (each tier is an independent budget, exactly as
    /// the references count), and the first tier that crosses its limit
    /// decides the outcome with its own window for `Retry-After`.
    ///
    /// `url_path` is the request path the endpoint tier matches
    /// (`endpoint_rate_limits` exact match) and the route/geo tiers key
    /// their windows by; without a path those tiers cannot key an isolated
    /// window and are skipped (the references always carry a request path
    /// here). `route` carries the decorator tiers (`None` skips both).
    /// `country_of_ip` resolves the geolocation the geo tier reads (the
    /// reference `geo_handler.get_country`); `None` or an unresolved
    /// country skips the geo tier unless a `"*"` entry covers it. A
    /// disabled limiter allows without recording anything.
    #[must_use]
    pub fn check_tiers(
        &self,
        ip: IpAddr,
        url_path: Option<&str>,
        route: Option<&RouteRateLimits>,
        country_of_ip: Option<&dyn Fn(IpAddr) -> Option<String>>,
    ) -> TierDecision {
        let inert = TierDecision {
            allowed: true,
            count: 0,
            tier: RateLimitTier::Global,
            window: self.config.rate_limit_window,
        };
        if !self.config.enable_rate_limiting {
            return inert;
        }

        // Tier 1: endpoint_rate_limits[path] (the reference
        // `_check_endpoint_rate_limit` exact-path match).
        if let Some(path) = url_path {
            if let Some(entry) = self.config.endpoint_rate_limits.get(path) {
                let (allowed, count, window) =
                    self.record_and_decide(ip, Some(path), entry.requests, entry.window);
                if !allowed {
                    return TierDecision {
                        allowed,
                        count,
                        tier: RateLimitTier::Endpoint,
                        window,
                    };
                }
            }

            // Tier 2: the route decorator's rate_limit (the reference
            // `_check_route_rate_limit`, window default 60).
            if let Some(route) = route {
                if let Some(limit) = route.rate_limit() {
                    let window = route
                        .rate_limit_window()
                        .unwrap_or(DEFAULT_ROUTE_RATE_LIMIT_WINDOW);
                    let (allowed, count, window) =
                        self.record_and_decide(ip, Some(path), limit, window);
                    if !allowed {
                        return TierDecision {
                            allowed,
                            count,
                            tier: RateLimitTier::Route,
                            window,
                        };
                    }
                }

                // Tier 3: the route decorator's geo_rate_limits (the
                // reference `_check_geo_rate_limit`): the resolved
                // country's entry, else the "*" fallback.
                if let (Some(limits), Some(country_of_ip)) =
                    (route.geo_rate_limits(), country_of_ip)
                {
                    let country = country_of_ip(ip);
                    let entry = country
                        .as_ref()
                        .and_then(|code| limits.get(code))
                        .or_else(|| limits.get("*"));
                    if let Some(entry) = entry {
                        let (allowed, count, window) =
                            self.record_and_decide(ip, Some(path), entry.requests, entry.window);
                        if !allowed {
                            return TierDecision {
                                allowed,
                                count,
                                tier: RateLimitTier::Geo,
                                window,
                            };
                        }
                    }
                }
            }
        }

        // Tier 4: the global per-IP tier (the reference
        // `_check_global_rate_limit`).
        let (allowed, count, window) = self.record_and_decide(
            ip,
            None,
            self.config.rate_limit,
            self.config.rate_limit_window,
        );
        TierDecision {
            allowed,
            count,
            tier: RateLimitTier::Global,
            window,
        }
    }

    /// Drop every window, every recorded request included (`reset` in the
    /// references; test harnesses use it to isolate cases).
    pub fn reset(&self) {
        self.windows.lock().expect("rate window store").clear();
    }

    /// How many windows the store currently tracks (test/observability
    /// seam for the LRU cap).
    #[must_use]
    pub fn tracked_windows(&self) -> usize {
        self.windows.lock().expect("rate window store").len()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    use std::str::FromStr;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicU64, Ordering};

    use crate::distributed::MemoryStore;

    /// A fake clock: f64 unix seconds starting at `1_000.0`, advanced by
    /// `advance`.
    #[derive(Clone, Default)]
    struct FakeClock(Arc<AtomicU64>);

    impl FakeClock {
        fn advance(&self, seconds: u64) {
            self.0.fetch_add(seconds, Ordering::Relaxed);
        }

        fn clock(&self) -> Clock {
            let state = self.0.clone();
            #[allow(clippy::cast_precision_loss)]
            Arc::new(move || state.load(Ordering::Relaxed) as f64)
        }
    }

    fn ip(text: &str) -> IpAddr {
        IpAddr::from_str(text).expect("test address")
    }

    fn enabled_config(rate_limit: u32) -> RateLimitConfig {
        RateLimitConfig {
            enable_rate_limiting: true,
            rate_limit,
            ..RateLimitConfig::default()
        }
    }

    #[test]
    fn default_config_matches_the_reference() {
        let config = RateLimitConfig::default();
        assert!(config.enable_rate_limiting);
        assert_eq!(config.rate_limit, 10);
        assert_eq!(config.rate_limit_window, 60);
        assert!(!config.enable_rate_limit_auto_ban);
    }

    #[test]
    fn new_fails_closed_on_zero_limit_or_window() {
        let error = RateLimiter::new(RateLimitConfig {
            rate_limit: 0,
            ..RateLimitConfig::default()
        })
        .unwrap_err();
        assert_eq!(error.field, "rate_limit");
        // The Cow is transparent: a borrowed static field reads as itself.
        assert_eq!(error.field, std::borrow::Cow::Borrowed("rate_limit"));
        assert_eq!(
            error.to_string(),
            "invalid rate_limit: must be at least 1 request per window"
        );

        let error = RateLimiter::new(RateLimitConfig {
            enable_rate_limiting: true,
            rate_limit: 5,
            rate_limit_window: 0,
            enable_rate_limit_auto_ban: false,
            endpoint_rate_limits: std::collections::HashMap::new(),
        })
        .unwrap_err();
        assert_eq!(error.field, "rate_limit_window");
    }

    #[test]
    fn new_fails_closed_on_invalid_endpoint_entries() {
        let error = RateLimiter::new(RateLimitConfig {
            endpoint_rate_limits: std::iter::once((
                "/login".to_owned(),
                RateLimitEntry {
                    requests: 0,
                    window: 60,
                },
            ))
            .collect(),
            ..RateLimitConfig::default()
        })
        .unwrap_err();
        assert_eq!(error.field, "endpoint_rate_limits[/login]");
        assert_eq!(
            error.to_string(),
            "invalid endpoint_rate_limits[/login]: every entry needs at least 1 request \
             per at least 1 second"
        );

        let error = RateLimitEntry::new(1, 0).unwrap_err();
        assert_eq!(error.field, "window");

        let error = RouteRateLimits::new(Some(0), Some(60), None).unwrap_err();
        assert_eq!(error.field, "rate_limit");

        let error = RouteRateLimits::new(Some(10), Some(0), None).unwrap_err();
        assert_eq!(error.field, "rate_limit_window");

        let error = RouteRateLimits::new(
            None,
            None,
            Some(
                std::iter::once((
                    "RU".to_owned(),
                    RateLimitEntry {
                        requests: 1,
                        window: 0,
                    },
                ))
                .collect(),
            ),
        )
        .unwrap_err();
        assert_eq!(error.field, "geo_rate_limits[RU]");

        // An inert route (no tier at all) and a window without a limit are
        // both valid: neither configures a tier.
        assert!(RouteRateLimits::new(None, None, None).is_ok());
        assert!(RouteRateLimits::new(None, Some(30), None).is_ok());
    }

    #[test]
    fn disabled_limiter_allows_and_records_nothing() {
        let limiter = RateLimiter::new(RateLimitConfig {
            enable_rate_limiting: false,
            ..RateLimitConfig::default()
        })
        .expect("valid config");
        for _ in 0..50 {
            assert!(limiter.check(ip("192.0.2.1"), None).allowed);
        }
        assert_eq!(limiter.tracked_windows(), 0, "no window was recorded");
    }

    #[test]
    fn blocks_at_the_crossing_and_reports_the_crossing_count() {
        let limiter = RateLimiter::new(enabled_config(3)).expect("valid config");
        for expected in 1..=3 {
            let decision = limiter.check(ip("192.0.2.1"), None);
            assert!(decision.allowed, "request {expected} must pass");
            assert_eq!(decision.count, expected);
        }
        let decision = limiter.check(ip("192.0.2.1"), None);
        assert!(
            !decision.allowed,
            "the 4th request inside the window blocks"
        );
        assert_eq!(decision.count, 4);
        assert_eq!(decision.retry_after(), 60, "Retry-After is the window");
    }

    #[test]
    fn window_slide_restores_the_budget() {
        let fake = FakeClock::default();
        let limiter = RateLimiter {
            config: enabled_config(2),
            windows: Arc::new(Mutex::new(LruCache::new(
                NonZeroUsize::new(16).expect("above zero"),
            ))),
            clock: fake.clock(),
            store: None,
            redis_prefix: String::from("guard_core:"),
            redis_fail_open: false,
        };
        assert!(limiter.check(ip("192.0.2.1"), None).allowed);
        assert!(limiter.check(ip("192.0.2.1"), None).allowed);
        assert!(!limiter.check(ip("192.0.2.1"), None).allowed);

        // Half the window later the crossing request is still remembered.
        fake.advance(30);
        assert!(!limiter.check(ip("192.0.2.1"), None).allowed);
        // Past the window the expired timestamps are evicted and the budget
        // is whole again.
        fake.advance(31);
        assert!(limiter.check(ip("192.0.2.1"), None).allowed);
    }

    #[test]
    fn windows_are_per_ip() {
        let limiter = RateLimiter::new(enabled_config(1)).expect("valid config");
        assert!(limiter.check(ip("192.0.2.1"), None).allowed);
        assert!(!limiter.check(ip("192.0.2.1"), None).allowed);
        assert!(
            limiter.check(ip("192.0.2.2"), None).allowed,
            "another IP has its own budget"
        );
    }

    #[test]
    fn endpoint_scope_is_isolated_from_the_global_scope() {
        let limiter = RateLimiter::new(enabled_config(1)).expect("valid config");
        assert!(limiter.check(ip("192.0.2.1"), None).allowed);
        assert!(
            limiter.check(ip("192.0.2.1"), Some("/login")).allowed,
            "the endpoint window is a separate budget"
        );
        assert!(!limiter.check(ip("192.0.2.1"), Some("/login")).allowed);
        assert!(
            limiter.check(ip("192.0.2.1"), Some("/signup")).allowed,
            "another endpoint has its own budget"
        );
        assert_eq!(limiter.tracked_windows(), 3);
    }

    #[test]
    fn ipv4_mapped_requests_share_the_ipv4_budget() {
        let limiter = RateLimiter::new(enabled_config(1)).expect("valid config");
        assert!(limiter.check(ip("::ffff:192.0.2.1"), None).allowed);
        assert!(
            !limiter.check(ip("192.0.2.1"), None).allowed,
            "the mapped form must count toward the same window"
        );
    }

    #[test]
    fn reset_drops_every_window() {
        let limiter = RateLimiter::new(enabled_config(1)).expect("valid config");
        assert!(limiter.check(ip("192.0.2.1"), None).allowed);
        assert!(!limiter.check(ip("192.0.2.1"), None).allowed);
        limiter.reset();
        assert_eq!(limiter.tracked_windows(), 0);
        assert!(limiter.check(ip("192.0.2.1"), None).allowed);
    }

    #[test]
    fn large_windows_keep_their_exact_length() {
        // rate_limit_window beyond u32 must not fold the sliding window into
        // something shorter (the f64 conversion saturates, never truncates).
        let limiter = RateLimiter::new(RateLimitConfig {
            enable_rate_limiting: true,
            rate_limit: 1,
            rate_limit_window: u64::from(u32::MAX) + 1,
            ..RateLimitConfig::default()
        })
        .expect("valid config");
        assert!(limiter.check(ip("192.0.2.1"), None).allowed);
        let decision = limiter.check(ip("192.0.2.1"), None);
        assert!(!decision.allowed);
        assert_eq!(decision.retry_after(), u64::from(u32::MAX) + 1);
    }

    /// The tier tests' fixed-country resolver.
    fn country_of(code: &'static str) -> impl Fn(IpAddr) -> Option<String> {
        move |_ip| Some(code.to_owned())
    }

    #[test]
    fn tierless_check_tiers_collapses_to_the_global_tier() {
        // No endpoint entries, no route: check_tiers must behave exactly
        // like the pre-tier global window (zero change unless tiers are
        // configured).
        let limiter = RateLimiter::new(enabled_config(2)).expect("valid config");
        let visitor = ip("192.0.2.40");
        assert!(
            limiter
                .check_tiers(visitor, Some("/x"), None, None)
                .allowed()
        );
        assert!(
            limiter
                .check_tiers(visitor, Some("/x"), None, None)
                .allowed()
        );
        let blocked = limiter.check_tiers(visitor, Some("/x"), None, None);
        assert!(!blocked.allowed());
        assert_eq!(blocked.tier(), RateLimitTier::Global);
        assert_eq!(blocked.tier_name(), "global");
        assert_eq!(blocked.retry_after(), 60);
        assert_eq!(limiter.tracked_windows(), 1, "one global window");
    }

    #[test]
    fn endpoint_tier_matches_the_exact_path_and_keys_its_own_window() {
        let limiter = RateLimiter::new(RateLimitConfig {
            endpoint_rate_limits: std::iter::once((
                "/login".to_owned(),
                RateLimitEntry::new(1, 60).expect("valid entry"),
            ))
            .collect(),
            ..RateLimitConfig::default()
        })
        .expect("valid config");
        let visitor = ip("192.0.2.41");

        // The configured path crosses at its own (stricter) limit and the
        // block names the endpoint tier with its window.
        assert!(
            limiter
                .check_tiers(visitor, Some("/login"), None, None)
                .allowed()
        );
        let blocked = limiter.check_tiers(visitor, Some("/login"), None, None);
        assert!(!blocked.allowed());
        assert_eq!(blocked.tier(), RateLimitTier::Endpoint);
        assert_eq!(blocked.retry_after(), 60);

        // Other paths never matched the endpoint tier: only the global
        // window counts there.
        assert!(
            limiter
                .check_tiers(visitor, Some("/other"), None, None)
                .allowed()
        );
        assert_eq!(
            limiter.tracked_windows(),
            2,
            "the login endpoint window + the shared global window"
        );
    }

    #[test]
    fn route_tier_uses_the_decorator_window_default_of_60() {
        let fake = FakeClock::default();
        let limiter = RateLimiter {
            config: enabled_config(100),
            windows: Arc::new(Mutex::new(LruCache::new(
                NonZeroUsize::new(16).expect("above zero"),
            ))),
            clock: fake.clock(),
            store: None,
            redis_prefix: String::from("guard_core:"),
            redis_fail_open: false,
        };
        let route = RouteRateLimits::new(Some(1), None, None).expect("valid route");
        let visitor = ip("192.0.2.42");

        assert!(
            limiter
                .check_tiers(visitor, Some("/x"), Some(&route), None)
                .allowed()
        );
        let blocked = limiter.check_tiers(visitor, Some("/x"), Some(&route), None);
        assert!(!blocked.allowed());
        assert_eq!(blocked.tier(), RateLimitTier::Route);
        assert_eq!(
            blocked.retry_after(),
            60,
            "the reference default window (rate_limit_window or 60)"
        );

        // An explicit route window replaces the default.
        let route = RouteRateLimits::new(Some(1), Some(30), None).expect("valid route");
        let blocked = limiter.check_tiers(visitor, Some("/x"), Some(&route), None);
        assert!(!blocked.allowed());
        assert_eq!(blocked.retry_after(), 30);
    }

    #[test]
    fn geo_tier_resolves_the_country_then_the_star_fallback() {
        let limiter = RateLimiter::new(RateLimitConfig {
            rate_limit: 100,
            ..RateLimitConfig::default()
        })
        .expect("valid config");
        let route = RouteRateLimits::new(
            None,
            None,
            Some(
                [
                    ("RU".to_owned(), RateLimitEntry::new(1, 60).expect("valid")),
                    ("*".to_owned(), RateLimitEntry::new(2, 45).expect("valid")),
                ]
                .into_iter()
                .collect(),
            ),
        )
        .expect("valid route");

        // A resolved country uses its own entry.
        let russian = ip("192.0.2.43");
        assert!(
            limiter
                .check_tiers(russian, Some("/x"), Some(&route), Some(&country_of("RU")))
                .allowed()
        );
        let blocked =
            limiter.check_tiers(russian, Some("/x"), Some(&route), Some(&country_of("RU")));
        assert!(!blocked.allowed());
        assert_eq!(blocked.tier(), RateLimitTier::Geo);
        assert_eq!(blocked.retry_after(), 60);

        // A country without an entry falls back to "*" (two requests).
        let other = ip("192.0.2.44");
        let resolver = country_of("DE");
        assert!(
            limiter
                .check_tiers(other, Some("/x"), Some(&route), Some(&resolver))
                .allowed()
        );
        assert!(
            limiter
                .check_tiers(other, Some("/x"), Some(&route), Some(&resolver))
                .allowed()
        );
        let blocked = limiter.check_tiers(other, Some("/x"), Some(&route), Some(&resolver));
        assert!(!blocked.allowed());
        assert_eq!(blocked.tier(), RateLimitTier::Geo);
        assert_eq!(blocked.retry_after(), 45);

        // An unresolved country also reads the "*" fallback (the reference
        // `country and country in limits` else `"*" in limits`).
        let unknown: fn(IpAddr) -> Option<String> = |_ip| None;
        let third = ip("192.0.2.45");
        assert!(
            limiter
                .check_tiers(third, Some("/x"), Some(&route), Some(&unknown))
                .allowed()
        );
        assert!(
            limiter
                .check_tiers(third, Some("/x"), Some(&route), Some(&unknown))
                .allowed()
        );
        let blocked = limiter.check_tiers(third, Some("/x"), Some(&route), Some(&unknown));
        assert!(!blocked.allowed());
        assert_eq!(blocked.tier(), RateLimitTier::Geo);
    }

    #[test]
    fn geo_tier_needs_a_configured_map_and_country_lookup() {
        // No geo entries on the route: no geo tier, the global tier runs.
        let limiter = RateLimiter::new(RateLimitConfig {
            rate_limit: 1,
            ..RateLimitConfig::default()
        })
        .expect("valid config");
        let route = RouteRateLimits::new(None, None, Some(std::collections::HashMap::new()))
            .expect("valid route");
        let visitor = ip("192.0.2.46");
        assert!(
            limiter
                .check_tiers(visitor, Some("/x"), Some(&route), Some(&country_of("RU")))
                .allowed()
        );
        let blocked =
            limiter.check_tiers(visitor, Some("/x"), Some(&route), Some(&country_of("RU")));
        assert!(!blocked.allowed());
        assert_eq!(blocked.tier(), RateLimitTier::Global);

        // Geo entries without a country resolver: the reference skips the
        // geo tier entirely (`if not geo_handler: return None`), so the
        // "*" entry never applies without a handler.
        let route = RouteRateLimits::new(
            None,
            None,
            Some(
                std::iter::once(("*".to_owned(), RateLimitEntry::new(1, 60).expect("valid")))
                    .collect(),
            ),
        )
        .expect("valid route");
        let fresh = ip("192.0.2.51");
        assert!(
            limiter
                .check_tiers(fresh, Some("/x"), Some(&route), None)
                .allowed()
        );
        let blocked = limiter.check_tiers(fresh, Some("/x"), Some(&route), None);
        assert!(!blocked.allowed());
        assert_eq!(
            blocked.tier(),
            RateLimitTier::Global,
            "no handler, no geo tier"
        );
    }

    #[test]
    fn every_configured_tier_records_so_the_budgets_stay_independent() {
        // The reference records one hit per configured tier per request:
        // a route tier with a huge limit and the global tier with a small
        // one still block from the global window, and the route window has
        // been counting all along.
        let limiter = RateLimiter::new(RateLimitConfig {
            rate_limit: 2,
            ..RateLimitConfig::default()
        })
        .expect("valid config");
        let route = RouteRateLimits::new(Some(1_000), Some(60), None).expect("valid route");
        let visitor = ip("192.0.2.47");

        assert!(
            limiter
                .check_tiers(visitor, Some("/x"), Some(&route), None)
                .allowed()
        );
        assert!(
            limiter
                .check_tiers(visitor, Some("/x"), Some(&route), None)
                .allowed()
        );
        let blocked = limiter.check_tiers(visitor, Some("/x"), Some(&route), None);
        assert!(!blocked.allowed());
        assert_eq!(
            blocked.tier(),
            RateLimitTier::Global,
            "the global tier crossed first"
        );
        assert_eq!(blocked.count(), 3);
        assert_eq!(limiter.tracked_windows(), 2, "route + global windows");

        // The route tier observed both requests: dropping the global limit
        // is impossible here, but its own budget is provably separate -
        // two of its 1_000 slots are consumed, so one more request passes
        // the route tier once the global window slides.
    }

    #[test]
    fn first_blocked_tier_wins_the_response_shape() {
        // The endpoint tier blocks before the stricter global tier is even
        // consulted (the reference check order), so its window is the
        // Retry-After.
        let limiter = RateLimiter::new(RateLimitConfig {
            rate_limit: 1,
            rate_limit_window: 120,
            endpoint_rate_limits: std::iter::once((
                "/login".to_owned(),
                RateLimitEntry::new(1, 30).expect("valid"),
            ))
            .collect(),
            ..RateLimitConfig::default()
        })
        .expect("valid config");
        let visitor = ip("192.0.2.48");
        assert!(
            limiter
                .check_tiers(visitor, Some("/login"), None, None)
                .allowed()
        );
        let blocked = limiter.check_tiers(visitor, Some("/login"), None, None);
        assert!(!blocked.allowed());
        assert_eq!(blocked.tier(), RateLimitTier::Endpoint);
        assert_eq!(blocked.retry_after(), 30, "the endpoint tier's window");

        // An unconfigured path blocks from the global tier instead.
        let blocked = limiter.check_tiers(visitor, Some("/other"), None, None);
        assert!(!blocked.allowed());
        assert_eq!(blocked.tier(), RateLimitTier::Global);
        assert_eq!(blocked.retry_after(), 120);
    }

    #[test]
    fn tiers_without_a_request_path_skip_the_path_keyed_tiers() {
        // Without a path the endpoint/route/geo tiers cannot key an
        // isolated window: only the global tier runs (the references
        // always carry a request path here).
        let limiter = RateLimiter::new(RateLimitConfig {
            rate_limit: 1,
            endpoint_rate_limits: std::iter::once((
                "/login".to_owned(),
                RateLimitEntry::new(1, 60).expect("valid"),
            ))
            .collect(),
            ..RateLimitConfig::default()
        })
        .expect("valid config");
        let route = RouteRateLimits::new(Some(1), Some(60), None).expect("valid route");
        let visitor = ip("192.0.2.49");
        assert!(
            limiter
                .check_tiers(visitor, None, Some(&route), Some(&country_of("RU")))
                .allowed()
        );
        let blocked = limiter.check_tiers(visitor, None, Some(&route), Some(&country_of("RU")));
        assert!(!blocked.allowed());
        assert_eq!(blocked.tier(), RateLimitTier::Global);
    }

    #[test]
    fn disabled_limiter_skips_the_tiers_without_recording() {
        let limiter = RateLimiter::new(RateLimitConfig {
            enable_rate_limiting: false,
            endpoint_rate_limits: std::iter::once((
                "/login".to_owned(),
                RateLimitEntry::new(1, 60).expect("valid"),
            ))
            .collect(),
            ..RateLimitConfig::default()
        })
        .expect("valid config");
        let route = RouteRateLimits::new(Some(1), Some(60), None).expect("valid route");
        let visitor = ip("192.0.2.50");
        for _ in 0..10 {
            let decision = limiter.check_tiers(visitor, Some("/login"), Some(&route), None);
            assert!(decision.allowed());
        }
        assert_eq!(limiter.tracked_windows(), 0, "nothing was recorded");
    }

    #[test]
    fn zero_request_entries_are_rejected() {
        assert_eq!(RateLimitEntry::new(0, 60).err().unwrap().field, "requests");
    }

    #[test]
    fn tier_names_read_like_the_reference_reasons() {
        assert_eq!(RateLimitTier::Endpoint.name(), "endpoint");
        assert_eq!(RateLimitTier::Route.name(), "route");
        assert_eq!(RateLimitTier::Geo.name(), "geo");
        assert_eq!(RateLimitTier::Global.name(), "global");
    }

    #[test]
    fn limiter_debug_carries_the_config() {
        let limiter = RateLimiter::with_clock(Arc::new(system_clock));
        assert!(format!("{limiter:?}").contains("RateLimiter"));
        assert_eq!(limiter.config().rate_limit_window, 60);
    }

    #[test]
    fn distributed_checks_short_circuit_when_disabled() {
        let limiter = RateLimiter::with_config_and_clock(
            RateLimitConfig {
                enable_rate_limiting: false,
                ..RateLimitConfig::default()
            },
            Arc::new(system_clock),
        )
        .expect("config");
        let decision = limiter
            .check_distributed(ip("192.0.2.51"), None)
            .expect("inert");
        assert!(decision.allowed);

        let tiers = limiter
            .check_tiers_distributed(ip("192.0.2.51"), Some("/x"), None, None)
            .expect("inert");
        assert!(tiers.allowed());
    }

    #[test]
    fn distributed_tiers_cover_endpoint_route_and_geo_windows() {
        let fake = FakeClock::default();
        let store = Arc::new(MemoryStore::default());
        let geo_limits = HashMap::from([
            ("RU".to_owned(), RateLimitEntry::new(2, 60).unwrap()),
            ("*".to_owned(), RateLimitEntry::new(5, 60).unwrap()),
        ]);
        let route = RouteRateLimits::new(Some(3), Some(30), Some(geo_limits)).expect("valid route");
        let limiter = RateLimiter::with_config_and_clock(
            RateLimitConfig {
                enable_rate_limiting: true,
                rate_limit: 100,
                endpoint_rate_limits: std::iter::once((
                    "/api".to_owned(),
                    RateLimitEntry::new(2, 60).unwrap(),
                ))
                .collect(),
                ..RateLimitConfig::default()
            },
            fake.clock(),
        )
        .expect("config")
        .with_distributed_store(
            Arc::clone(&store) as Arc<dyn crate::distributed::SlidingWindowStore>,
            "gc:",
            false,
        );

        // the country resolver only answers for one probe address: both of
        // its arms run across the calls below
        let country_ru = |probe: IpAddr| -> Option<String> {
            if probe == ip("192.0.2.52") {
                Some("RU".to_owned())
            } else {
                None
            }
        };
        // the distributed tiers share the (ip, path) window, so each tier's
        // record lands in the same sliding window: three tiers put three hits
        // in it, and the RU geo entry (limit 2) throttles the first request
        let first = limiter
            .check_tiers_distributed(
                ip("192.0.2.52"),
                Some("/api"),
                Some(&route),
                Some(&country_ru),
            )
            .expect("store");
        assert!(!first.allowed());
        assert_eq!(first.tier(), RateLimitTier::Geo);
        assert_eq!(first.count(), 3);

        // without a resolvable country the '*' fallback applies on its own
        // keyed window and stays under its limit
        let second = limiter
            .check_tiers_distributed(
                ip("192.0.2.53"),
                Some("/other"),
                Some(&route),
                Some(&country_ru),
            )
            .expect("store");
        assert!(second.allowed());

        // the resolvable country on its own keyed window stays under the RU
        // entry (the resolver's hit arm)
        let third = limiter
            .check_tiers_distributed(
                ip("192.0.2.52"),
                Some("/other"),
                Some(&route),
                Some(&country_ru),
            )
            .expect("store");
        assert!(third.allowed());
    }

    #[test]
    fn a_store_error_propagates_from_the_endpoint_tier() {
        let store = Arc::new(MemoryStore::default());
        let limiter = RateLimiter::with_config_and_clock(
            RateLimitConfig {
                enable_rate_limiting: true,
                rate_limit: 100,
                endpoint_rate_limits: std::iter::once((
                    "/api".to_owned(),
                    RateLimitEntry::new(2, 60).unwrap(),
                ))
                .collect(),
                ..RateLimitConfig::default()
            },
            FakeClock::default().clock(),
        )
        .expect("config")
        .with_distributed_store(
            Arc::clone(&store) as Arc<dyn crate::distributed::SlidingWindowStore>,
            "gc:",
            false,
        );
        store.fail.store(true, std::sync::atomic::Ordering::Relaxed);
        assert!(
            limiter
                .check_tiers_distributed(ip("192.0.2.60"), Some("/api"), None, None)
                .is_err()
        );
    }

    #[test]
    fn a_store_error_propagates_from_the_route_tier() {
        let store = Arc::new(MemoryStore::default());
        let route = RouteRateLimits::new(Some(3), Some(60), None).expect("valid route");
        let limiter = RateLimiter::with_config_and_clock(
            RateLimitConfig {
                enable_rate_limiting: true,
                ..RateLimitConfig::default()
            },
            FakeClock::default().clock(),
        )
        .expect("config")
        .with_distributed_store(
            Arc::clone(&store) as Arc<dyn crate::distributed::SlidingWindowStore>,
            "gc:",
            false,
        );
        store.fail.store(true, std::sync::atomic::Ordering::Relaxed);
        // no endpoint entry: the route tier's limit records and the
        // backend-down error surfaces
        assert!(
            limiter
                .check_tiers_distributed(ip("192.0.2.59"), Some("/r"), Some(&route), None)
                .is_err()
        );
    }

    #[test]
    fn a_store_error_propagates_from_the_geo_tier() {
        let store = Arc::new(MemoryStore::default());
        let geo_limits = HashMap::from([("RU".to_owned(), RateLimitEntry::new(2, 60).unwrap())]);
        let route = RouteRateLimits::new(None, None, Some(geo_limits)).expect("valid route");
        let limiter = RateLimiter::with_config_and_clock(
            RateLimitConfig {
                enable_rate_limiting: true,
                ..RateLimitConfig::default()
            },
            FakeClock::default().clock(),
        )
        .expect("config")
        .with_distributed_store(
            Arc::clone(&store) as Arc<dyn crate::distributed::SlidingWindowStore>,
            "gc:",
            false,
        );
        store.fail.store(true, std::sync::atomic::Ordering::Relaxed);
        // no endpoint entry and no route limit: the geo tier records and the
        // backend-down error surfaces
        assert!(
            limiter
                .check_tiers_distributed(
                    ip("192.0.2.61"),
                    Some("/other"),
                    Some(&route),
                    Some(&|_| Some("RU".to_owned())),
                )
                .is_err()
        );
    }

    #[test]
    fn a_geo_limit_miss_falls_through_to_the_global_tier() {
        let store = Arc::new(MemoryStore::default());
        let geo_limits = HashMap::from([("CN".to_owned(), RateLimitEntry::new(2, 60).unwrap())]);
        let route = RouteRateLimits::new(None, None, Some(geo_limits)).expect("valid route");
        let limiter = RateLimiter::with_config_and_clock(
            RateLimitConfig {
                enable_rate_limiting: true,
                ..RateLimitConfig::default()
            },
            FakeClock::default().clock(),
        )
        .expect("config")
        .with_distributed_store(
            Arc::clone(&store) as Arc<dyn crate::distributed::SlidingWindowStore>,
            "gc:",
            false,
        );
        // the country has no geo entry and there is no '*' fallback
        let decision = limiter
            .check_tiers_distributed(
                ip("192.0.2.62"),
                Some("/other"),
                Some(&route),
                Some(&|_| Some("US".to_owned())),
            )
            .expect("store");
        assert!(decision.allowed());
        assert_eq!(decision.tier(), RateLimitTier::Global);
    }
}

#[cfg(test)]
mod unit_twins {
    use super::*;
    use crate::distributed::MemoryStore;
    use std::str::FromStr;

    fn ip(text: &str) -> IpAddr {
        IpAddr::from_str(text).expect("test address")
    }

    /// A limiter wired to a backend that answers every call with the
    /// backend-down error, so each tier's `?` surfaces its `StoreError`.
    fn failing_store_limiter(endpoint: Option<(&str, RateLimitEntry)>) -> RateLimiter {
        let store = MemoryStore::default();
        store.fail.store(true, std::sync::atomic::Ordering::Relaxed);
        let mut endpoint_rate_limits = HashMap::new();
        if let Some((path, entry)) = endpoint {
            endpoint_rate_limits.insert(path.to_owned(), entry);
        }
        RateLimiter::with_config_and_clock(
            RateLimitConfig {
                enable_rate_limiting: true,
                rate_limit: 100,
                endpoint_rate_limits,
                ..RateLimitConfig::default()
            },
            Arc::new(system_clock),
        )
        .expect("config")
        .with_distributed_store(
            Arc::new(store) as Arc<dyn crate::distributed::SlidingWindowStore>,
            "gc:",
            false,
        )
    }

    #[test]
    fn the_endpoint_tier_surfaces_a_failing_backend() {
        let limiter = failing_store_limiter(Some((
            "/api",
            RateLimitEntry::new(2, 60).expect("valid entry"),
        )));
        assert!(
            limiter
                .check_tiers_distributed(ip("192.0.2.60"), Some("/api"), None, None)
                .is_err()
        );
    }

    #[test]
    fn the_geo_tier_surfaces_a_failing_backend() {
        let geo_limits = HashMap::from([(
            "RU".to_owned(),
            RateLimitEntry::new(2, 60).expect("valid entry"),
        )]);
        // the geo-only route reaches the geo stage before any record call
        let route = RouteRateLimits::new(None, None, Some(geo_limits)).expect("valid route");
        let limiter = failing_store_limiter(None);
        let country = |probe: IpAddr| -> Option<String> {
            if probe == ip("192.0.2.61") {
                Some("RU".to_owned())
            } else {
                None
            }
        };
        // a resolvable country runs the geo record against the failing
        // backend
        assert!(
            limiter
                .check_tiers_distributed(
                    ip("192.0.2.61"),
                    Some("/other"),
                    Some(&route),
                    Some(&country),
                )
                .is_err()
        );
        // an unresolvable country skips the geo entry and fails at the
        // global stage instead
        assert!(
            limiter
                .check_tiers_distributed(
                    ip("192.0.2.62"),
                    Some("/other"),
                    Some(&route),
                    Some(&country),
                )
                .is_err()
        );
    }

    #[test]
    fn exhausted_tiers_answer_their_denials() {
        // a working store: each tier's own limit trips its decision shape
        let store = Arc::new(MemoryStore::default());
        let geo_limits = HashMap::from([(
            "RU".to_owned(),
            RateLimitEntry::new(1, 60).expect("valid entry"),
        )]);
        let limiter = RateLimiter::with_config_and_clock(
            RateLimitConfig {
                enable_rate_limiting: true,
                rate_limit: 1,
                endpoint_rate_limits: std::iter::once((
                    "/api".to_owned(),
                    RateLimitEntry::new(1, 60).expect("valid entry"),
                ))
                .collect(),
                ..RateLimitConfig::default()
            },
            Arc::new(system_clock),
        )
        .expect("config")
        .with_distributed_store(
            Arc::clone(&store) as Arc<dyn crate::distributed::SlidingWindowStore>,
            "gc:",
            false,
        );
        let country_ru = |probe: IpAddr| -> Option<String> {
            if probe == ip("192.0.2.63") || probe == ip("192.0.2.67") {
                Some("RU".to_owned())
            } else {
                None
            }
        };
        let route = RouteRateLimits::new(Some(1), Some(30), None).expect("valid route");
        // the geo route carries no decorator limit of its own, so the geo
        // entry's record is the first hit on the shared window
        let geo_route = RouteRateLimits::new(None, None, Some(geo_limits)).expect("valid route");

        // the endpoint tier denies at its own limit
        let endpoint = limiter
            .check_tiers_distributed(ip("192.0.2.63"), Some("/api"), None, None)
            .expect("store");
        assert!(endpoint.allowed());
        let endpoint = limiter
            .check_tiers_distributed(ip("192.0.2.63"), Some("/api"), None, None)
            .expect("store");
        assert!(!endpoint.allowed());

        // the route tier denies on its decorator limit
        let route_hit = limiter
            .check_tiers_distributed(ip("192.0.2.64"), Some("/route"), Some(&route), None)
            .expect("store");
        assert!(route_hit.allowed());
        let route_hit = limiter
            .check_tiers_distributed(ip("192.0.2.64"), Some("/route"), Some(&route), None)
            .expect("store");
        assert!(!route_hit.allowed());

        // the geo tier denies on its country limit
        let geo = limiter
            .check_tiers_distributed(
                ip("192.0.2.67"),
                Some("/geo"),
                Some(&geo_route),
                Some(&country_ru),
            )
            .expect("store");
        assert!(geo.allowed(), "first geo: {geo:?}");
        // an unresolvable country skips the geo entry entirely
        let skipped = limiter
            .check_tiers_distributed(
                ip("192.0.2.68"),
                Some("/geo"),
                Some(&geo_route),
                Some(&country_ru),
            )
            .expect("store");
        assert!(skipped.allowed(), "skipped geo: {skipped:?}");
        let geo = limiter
            .check_tiers_distributed(
                ip("192.0.2.67"),
                Some("/geo"),
                Some(&geo_route),
                Some(&country_ru),
            )
            .expect("store");
        assert!(!geo.allowed(), "second geo: {geo:?}");
        assert_eq!(geo.tier(), RateLimitTier::Geo);

        // the global tier denies on the workspace-wide limit
        let global = limiter
            .check_tiers_distributed(ip("192.0.2.65"), Some("/other"), None, None)
            .expect("store");
        assert!(global.allowed());
        let global = limiter
            .check_tiers_distributed(ip("192.0.2.65"), Some("/other"), None, None)
            .expect("store");
        assert!(!global.allowed());
        assert_eq!(global.tier(), RateLimitTier::Global);
    }

    #[test]
    fn the_global_tier_surfaces_a_failing_backend() {
        // no endpoint entry, no route: the failure surfaces at the global
        // stage's own record call
        let limiter = failing_store_limiter(None);
        assert!(
            limiter
                .check_tiers_distributed(ip("192.0.2.66"), Some("/other"), None, None)
                .is_err()
        );
        assert!(
            limiter
                .check_tiers_distributed(ip("192.0.2.66"), None, None, None)
                .is_err()
        );
    }

    #[test]
    fn a_geo_tier_without_a_matching_country_falls_through_to_the_global_tier() {
        // the route carries only a `RU` entry: an unresolvable country finds
        // no geo entry and the scan continues on the global tier
        let store = Arc::new(MemoryStore::default());
        let geo_limits = HashMap::from([(
            "RU".to_owned(),
            RateLimitEntry::new(2, 60).expect("valid entry"),
        )]);
        let route = RouteRateLimits::new(Some(3), Some(30), Some(geo_limits)).expect("valid route");
        let limiter = RateLimiter::with_config_and_clock(
            RateLimitConfig {
                enable_rate_limiting: true,
                rate_limit: 100,
                ..RateLimitConfig::default()
            },
            Arc::new(system_clock),
        )
        .expect("config")
        .with_distributed_store(
            Arc::clone(&store) as Arc<dyn crate::distributed::SlidingWindowStore>,
            "gc:",
            false,
        );
        let no_country = |_: IpAddr| -> Option<String> { None };
        let decision = limiter
            .check_tiers_distributed(
                ip("192.0.2.62"),
                Some("/other"),
                Some(&route),
                Some(&no_country),
            )
            .expect("store");
        assert!(decision.allowed());
        assert_eq!(decision.tier(), RateLimitTier::Global);
    }
}