volga 0.9.1

Easy & Fast Web 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
//! Tools and utilities for Rate Limiting

use crate::{
    App, ClientIp, HttpRequest, HttpResult,
    error::Error,
    headers::{FORWARDED, X_FORWARDED_FOR},
    http::{StatusCode, request_scope::HttpRequestScope},
    middleware::{HttpContext, Middleware, NextFn},
    routing::{Route, RouteGroup},
    status,
};
use smallvec::SmallVec;
use std::fmt::Debug;
use std::{
    collections::HashSet,
    hash::{Hash, Hasher},
    net::{IpAddr, SocketAddr},
};
use twox_hash::XxHash64;

pub use by::RateLimitKeySource;
pub use fixed_window::FixedWindow;
pub use gcra::Gcra;
pub use key::{PolicyName, RateLimitBinding, RateLimitKey, RateLimitKeyExt};
pub use sliding_window::SlidingWindow;
pub use token_bucket::TokenBucket;

pub use volga_rate_limiter::{
    FixedWindowParams, FixedWindowRateLimiter, FixedWindowStore, GcraParams, GcraRateLimiter,
    GcraStore, RateLimiter, SlidingWindowParams, SlidingWindowRateLimiter, SlidingWindowStore,
    TokenBucketParams, TokenBucketRateLimiter, TokenBucketStore,
};

pub mod by;
mod fixed_window;
mod gcra;
mod key;
mod sliding_window;
mod token_bucket;

const MAX_FORWARDED_IPS: usize = 16;
const MAX_FORWARDED_HEADER_LEN: usize = 2 * 1024;
const DEFAULT_POLICIES_COUNT: usize = 4;
const DEFAULT_IPS_COUNT: usize = 4;
const RATE_LIMIT_ERROR_MSG: &str = "Rate limit exceeded. Try again later.";

/// A tuple representing a named policy entry: `(policy_name, limiter)`.
///
/// Used internally in `GlobalRateLimiter` to store named rate-limiting policies.
type PolicyEntry<T> = (String, T);

/// Represents the global rate limiting configuration for the application.
///
/// This structure holds both **fixed window** and **sliding window** limiters,
/// each of which can have a **default** limiter (applied when no policy name is specified)
/// and **named policies** (applied when a specific policy name is used).
///
/// Typically, this structure is managed internally by the `App` and should not be
/// accessed directly from middleware; instead, helper methods provide access to
/// the appropriate limiter by policy name.
#[derive(Debug, Default)]
pub(crate) struct GlobalRateLimiter {
    /// Default fixed window rate limiter (used when no policy name is specified)
    default_fixed_window: Option<FixedWindowRateLimiter>,
    /// Named fixed window rate limiters
    named_fixed_window: SmallVec<[PolicyEntry<FixedWindowRateLimiter>; DEFAULT_POLICIES_COUNT]>,

    /// Default sliding window rate limiter (used when no policy name is specified)
    default_sliding_window: Option<SlidingWindowRateLimiter>,
    /// Named sliding window rate limiters
    named_sliding_window: SmallVec<[PolicyEntry<SlidingWindowRateLimiter>; DEFAULT_POLICIES_COUNT]>,

    /// Default token bucket rate limiter (used when no policy name is specified)
    default_token_bucket: Option<TokenBucketRateLimiter>,
    /// Named token bucket rate limiters
    named_token_bucket: SmallVec<[PolicyEntry<TokenBucketRateLimiter>; DEFAULT_POLICIES_COUNT]>,

    /// Default GCRA rate limiter (used when no policy name is specified)
    default_gcra: Option<GcraRateLimiter>,
    /// Named GCRA rate limiters
    named_gcra: SmallVec<[PolicyEntry<GcraRateLimiter>; DEFAULT_POLICIES_COUNT]>,
}

impl GlobalRateLimiter {
    /// Adds a fixed window rate limiting policy to the global configuration.
    ///
    /// - If the policy has a `name`, it will be stored in `named_fixed_window`.
    /// - If the policy has no `name`, it will become the `default_fixed_window`.
    #[inline]
    fn add_fixed_window(&mut self, policy: FixedWindow) {
        let limiter = policy.build();
        let name = policy.name;
        match name {
            None => self.default_fixed_window = Some(limiter),
            Some(name) => self.named_fixed_window.push((name, limiter)),
        }
    }

    /// Adds a sliding window rate limiting policy to the global configuration.
    ///
    /// - If the policy has a `name`, it will be stored in `named_sliding_window`.
    /// - If the policy has no `name`, it will become the `default_sliding_window`.
    #[inline]
    fn add_sliding_window(&mut self, policy: SlidingWindow) {
        let limiter = policy.build();
        let name = policy.name;
        match name {
            None => self.default_sliding_window = Some(limiter),
            Some(name) => self.named_sliding_window.push((name, limiter)),
        }
    }

    /// Adds a token bucket rate limiting policy to the global configuration.
    ///
    /// - If the policy has a `name`, it will be stored in `named_token_bucket`.
    /// - If the policy has no `name`, it will become the `default_token_bucket`.
    #[inline]
    fn add_token_bucket(&mut self, policy: TokenBucket) {
        let limiter = policy.build();
        let name = policy.name;
        match name {
            None => self.default_token_bucket = Some(limiter),
            Some(name) => self.named_token_bucket.push((name, limiter)),
        }
    }

    /// Adds GCRA rate limiting policy to the global configuration.
    ///
    /// - If the policy has a `name`, it will be stored in `default_gcra`.
    /// - If the policy has no `name`, it will become the `named_gcra`.
    #[inline]
    fn add_gcra(&mut self, policy: Gcra) {
        let limiter = policy.build();
        let name = policy.name;
        match name {
            None => self.default_gcra = Some(limiter),
            Some(name) => self.named_gcra.push((name, limiter)),
        }
    }

    /// Returns a reference to a fixed window rate limiter by policy name.
    ///
    /// - `policy_name = None` -> returns the default fixed window limiter.
    /// - `policy_name = Some(name)` -> returns the named fixed window limiter if it exists.
    #[inline]
    pub(crate) fn fixed_window(
        &self,
        policy_name: Option<&str>,
    ) -> Option<&FixedWindowRateLimiter> {
        match policy_name {
            None => self.default_fixed_window.as_ref(),
            Some(name) => self
                .named_fixed_window
                .iter()
                .find(|(n, _)| n == name)
                .map(|(_, v)| v),
        }
    }

    /// Returns a reference to a sliding window rate limiter by policy name.
    ///
    /// - `policy_name = None` -> returns the default sliding window limiter.
    /// - `policy_name = Some(name)` -> returns the named sliding window limiter if it exists.
    #[inline]
    pub(crate) fn sliding_window(
        &self,
        policy_name: Option<&str>,
    ) -> Option<&SlidingWindowRateLimiter> {
        match policy_name {
            None => self.default_sliding_window.as_ref(),
            Some(name) => self
                .named_sliding_window
                .iter()
                .find(|(n, _)| n == name)
                .map(|(_, v)| v),
        }
    }

    /// Returns a reference to a token bucket rate limiter by policy name.
    ///
    /// - `policy_name = None` -> returns the default token bucket limiter.
    /// - `policy_name = Some(name)` -> returns the named token bucket limiter if it exists.
    #[inline]
    pub(crate) fn token_bucket(
        &self,
        policy_name: Option<&str>,
    ) -> Option<&TokenBucketRateLimiter> {
        match policy_name {
            None => self.default_token_bucket.as_ref(),
            Some(name) => self
                .named_token_bucket
                .iter()
                .find(|(n, _)| n == name)
                .map(|(_, v)| v),
        }
    }

    /// Returns a reference to GCRA rate limiter by policy name.
    ///
    /// - `policy_name = None` -> returns the default GCRA limiter.
    /// - `policy_name = Some(name)` -> returns the named GCRA limiter if it exists.
    #[inline]
    pub(crate) fn gcra(&self, policy_name: Option<&str>) -> Option<&GcraRateLimiter> {
        match policy_name {
            None => self.default_gcra.as_ref(),
            Some(name) => self
                .named_gcra
                .iter()
                .find(|(n, _)| n == name)
                .map(|(_, v)| v),
        }
    }
}

impl App {
    /// Registers a fixed-window rate limiting policy.
    ///
    /// This method defines **how** rate limiting should work (limits, window size,
    /// eviction behavior), but does **not** enable rate limiting by itself.
    /// To actually apply the policy to incoming requests, it must be referenced
    /// from rate-limiting middleware (see [`App::use_fixed_window`] or [`Route::fixed_window`]).
    ///
    /// ## Named vs. default policy
    ///
    /// - If the policy has a name (`FixedWindow::with_name`), it is registered
    ///   as a **named policy** and can be referenced explicitly by name.
    /// - If no name is provided, the policy becomes the **default fixed-window
    ///   policy**, used when no policy name is specified in middleware.
    ///
    /// Registering a policy with the same name multiple times will override
    /// the previously registered policy.
    ///
    /// ## Example
    ///
    /// ```no_run
    /// use std::time::Duration;
    /// use volga::{
    ///     App,
    ///     rate_limiting::{by, FixedWindow, RateLimitKeyExt},
    /// };
    ///
    /// # fn main() {
    /// // Define a fixed window rate-limiting policy
    /// let fixed_window = FixedWindow::new(100, Duration::from_secs(30))
    ///     .with_name("burst");
    ///
    /// // Register the policy in the application
    /// let mut app = App::new()
    ///     .with_fixed_window(fixed_window);
    ///
    /// // Enable fixed-window rate limiting using the "burst" policy,
    /// // partitioned by the client IP address
    /// app.use_fixed_window(by::ip().using("burst"));
    ///
    /// # app.run_blocking();
    /// # }
    /// ```
    ///
    /// ## See also
    ///
    /// - [`FixedWindow`] - fixed window policy definition
    /// - [`App::use_fixed_window`] - enabling fixed-window rate limiting middleware
    /// - [`Route::fixed_window`] - enabling fixed-window rate limiting middleware for a particular route
    /// - [`RouteGroup::fixed_window`] - enabling fixed-window rate limiting middleware for a route group
    pub fn with_fixed_window(mut self, policy: FixedWindow) -> Self {
        self.rate_limiter
            .get_or_insert_default()
            .add_fixed_window(policy);
        self
    }

    /// Registers a sliding-window rate limiting policy.
    ///
    /// This method defines **how** rate limiting should work (limits, window size,
    /// eviction behavior), but does **not** enable rate limiting by itself.
    /// To actually apply the policy to incoming requests, it must be referenced
    /// from rate-limiting middleware (see [`App::use_sliding_window`] or [`Route::sliding_window`]).
    ///
    /// ## Named vs. default policy
    ///
    /// - If the policy has a name (`SlidingWindow::with_name`), it is registered
    ///   as a **named policy** and can be referenced explicitly by name.
    /// - If no name is provided, the policy becomes the **default sliding-window
    ///   policy**, used when no policy name is specified in middleware.
    ///
    /// Registering a policy with the same name multiple times will override
    /// the previously registered policy.
    ///
    /// ## Example
    ///
    /// ```no_run
    /// use std::time::Duration;
    /// use volga::{
    ///     App,
    ///     rate_limiting::{by, SlidingWindow, RateLimitKeyExt},
    /// };
    ///
    /// # fn main() {
    /// // Define a sliding window rate-limiting policy
    /// let sliding_window = SlidingWindow::new(100, Duration::from_secs(30))
    ///     .with_name("burst");
    ///
    /// // Register the policy in the application
    /// let mut app = App::new()
    ///     .with_sliding_window(sliding_window);
    ///
    /// // Enable sliding-window rate limiting using the "burst" policy,
    /// // partitioned by the client IP address
    /// app.use_sliding_window(by::ip().using("burst"));
    ///
    /// # app.run_blocking();
    /// # }
    /// ```
    ///
    /// ## See also
    ///
    /// - [`SlidingWindow`] - fixed window policy definition
    /// - [`App::use_sliding_window`] - enabling sliding-window rate limiting middleware
    /// - [`Route::sliding_window`] - enabling sliding-window rate limiting middleware for a particular route
    /// - [`RouteGroup::sliding_window`] - enabling sliding-window rate limiting middleware for a route group
    pub fn with_sliding_window(mut self, policy: SlidingWindow) -> Self {
        self.rate_limiter
            .get_or_insert_default()
            .add_sliding_window(policy);
        self
    }

    /// Registers a token bucket rate limiting policy.
    ///
    /// This method defines **how** rate limiting should work (limits, capacity,
    /// eviction behavior), but does **not** enable rate limiting by itself.
    /// To actually apply the policy to incoming requests, it must be referenced
    /// from rate-limiting middleware (see [`App::use_token_bucket`] or [`Route::token_bucket`]).
    ///
    /// ## Named vs. default policy
    ///
    /// - If the policy has a name (`TokenBucket::with_name`), it is registered
    ///   as a **named policy** and can be referenced explicitly by name.
    /// - If no name is provided, the policy becomes the **default token bucket
    ///   policy**, used when no policy name is specified in middleware.
    ///
    /// Registering a policy with the same name multiple times will override
    /// the previously registered policy.
    ///
    /// ## Example
    ///
    /// ```no_run
    /// use std::time::Duration;
    /// use volga::{
    ///     App,
    ///     rate_limiting::{by, TokenBucket, RateLimitKeyExt},
    /// };
    ///
    /// # fn main() {
    /// // Define a token bucket rate-limiting policy
    /// let token_bucket = TokenBucket::new(100, 1.0)
    ///     .with_name("burst");
    ///
    /// // Register the policy in the application
    /// let mut app = App::new()
    ///     .with_token_bucket(token_bucket);
    ///
    /// // Enable token bucket rate limiting using the "burst" policy,
    /// // partitioned by the client IP address
    /// app.use_token_bucket(by::ip().using("burst"));
    ///
    /// # app.run_blocking();
    /// # }
    /// ```
    ///
    /// ## See also
    ///
    /// - [`TokenBucket`] - token_bucket policy definition
    /// - [`App::use_token_bucket`] - enabling token_bucket rate limiting middleware
    /// - [`Route::token_bucket`] - enabling token_bucket rate limiting middleware for a particular route
    /// - [`RouteGroup::token_bucket`] - enabling token_bucket rate limiting middleware for a route group
    pub fn with_token_bucket(mut self, policy: TokenBucket) -> Self {
        self.rate_limiter
            .get_or_insert_default()
            .add_token_bucket(policy);
        self
    }

    /// Registers GCRA rate limiting policy.
    ///
    /// This method defines **how** rate limiting should work (limits, rate, burst,
    /// eviction behavior), but does **not** enable rate limiting by itself.
    /// To actually apply the policy to incoming requests, it must be referenced
    /// from rate-limiting middleware (see [`App::use_gcra`] or [`Route::gcra`]).
    ///
    /// ## Named vs. default policy
    ///
    /// - If the policy has a name (`Gcra::with_name`), it is registered
    ///   as a **named policy** and can be referenced explicitly by name.
    /// - If no name is provided, the policy becomes the **default GCRA
    ///   policy**, used when no policy name is specified in middleware.
    ///
    /// Registering a policy with the same name multiple times will override
    /// the previously registered policy.
    ///
    /// ## Example
    ///
    /// ```no_run
    /// use std::time::Duration;
    /// use volga::{
    ///     App,
    ///     rate_limiting::{by, Gcra, RateLimitKeyExt},
    /// };
    ///
    /// # fn main() {
    /// // Define a GCRA rate-limiting policy
    /// let gcra = Gcra::new(10.0, 3)
    ///     .with_name("burst");
    ///
    /// // Register the policy in the application
    /// let mut app = App::new()
    ///     .with_gcra(gcra);
    ///
    /// // Enable GCRA rate limiting using the "burst" policy,
    /// // partitioned by the client IP address
    /// app.use_gcra(by::ip().using("burst"));
    ///
    /// # app.run_blocking();
    /// # }
    /// ```
    ///
    /// ## See also
    ///
    /// - [`Gcra`] - GCRA policy definition
    /// - [`App::use_gcra`] - enabling GCRA rate limiting middleware
    /// - [`Route::gcra`] - enabling GCRA rate limiting middleware for a particular route
    /// - [`RouteGroup::gcra`] - enabling GCRA rate limiting middleware for a route group
    pub fn with_gcra(mut self, policy: Gcra) -> Self {
        self.rate_limiter.get_or_insert_default().add_gcra(policy);
        self
    }

    /// Configures the list of trusted reverse proxies for client-IP resolution.
    ///
    /// # Security
    ///
    /// This setting is **required** for [`by::ip()`] and [`ClientIp`] to honor
    /// `Forwarded` (RFC 7239) or `X-Forwarded-For` headers. Without it, volga
    /// uses the direct TCP peer address and ignores forwarded headers entirely —
    /// this prevents IP-spoofing attacks where an attacker could bypass IP-based
    /// rate limiting by setting `X-Forwarded-For: <arbitrary>`.
    ///
    /// When configured, volga walks the forwarded chain **right-to-left** and
    /// returns the first hop whose address is **not** in this list. Headers are
    /// only consulted if the direct peer is itself a trusted proxy — forwarded
    /// values from untrusted peers are discarded.
    ///
    /// # When to set
    ///
    /// - Behind a reverse proxy (nginx, Caddy, Cloudflare, ALB) — configure
    ///   the proxy's internal/egress IPs here.
    /// - Direct-to-internet deployment — leave unset.
    ///
    /// Passing an empty iterator is equivalent to leaving it unset.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use std::net::{IpAddr, Ipv4Addr};
    /// use volga::App;
    ///
    /// let app = App::new()
    ///     .with_trusted_proxies([
    ///         IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1)),
    ///         IpAddr::V4(Ipv4Addr::new(10, 0, 0, 2)),
    ///     ]);
    /// ```
    ///
    /// ## See also
    ///
    /// - [`by::ip`] — rate-limiting partition by client IP
    /// - [`ClientIp`] — extractor that uses the same resolution logic
    pub fn with_trusted_proxies<I, T>(mut self, proxies: I) -> Self
    where
        I: IntoIterator<Item = T>,
        T: Into<IpAddr>,
    {
        let proxies: HashSet<IpAddr> = proxies.into_iter().map(Into::into).collect();
        self.trusted_proxies = if proxies.is_empty() {
            None
        } else {
            Some(proxies)
        };
        self
    }

    /// Enables fixed-window rate limiting for incoming requests.
    ///
    /// This method installs a **global middleware** that applies a fixed-window
    /// rate limiter to all requests passing through the application.
    ///
    /// The provided `source` defines:
    /// - **How requests are partitioned** (e.g. by IP, user, header, path)
    /// - **Which rate-limiting policy is used** (default or named)
    ///
    /// The middleware will look up a previously registered [`FixedWindow`]
    /// policy and apply it to each request. If no matching policy is found,
    /// the middleware is a no-op.
    ///
    /// ## Partition keys
    ///
    /// The partition key determines how requests are grouped for rate limiting.
    /// Common examples include:
    /// - Client IP address
    /// - Authenticated user ID
    /// - API key or header value
    /// - Route or tenant identifier
    ///
    /// ## Policy selection
    ///
    /// - If the key is bound **without** a policy name, the **default fixed-window
    ///   policy** is used.
    /// - If the key is bound **with** `.using(name)`, the named policy with the
    ///   corresponding name is applied.
    ///
    /// ## Example
    ///
    /// ```no_run
    /// use std::time::Duration;
    /// use volga::{
    ///     App,
    ///     rate_limiting::{by, FixedWindow, RateLimitKeyExt},
    /// };
    ///
    /// # fn main() {
    /// let mut app = App::new()
    ///     // Register a default fixed-window policy
    ///     .with_fixed_window(
    ///         FixedWindow::new(60, Duration::from_secs(60))
    ///     )
    ///     // Register a named policy for burst traffic
    ///     .with_fixed_window(
    ///         FixedWindow::new(100, Duration::from_secs(30))
    ///             .with_name("burst")
    ///     );
    ///
    /// // Apply rate limiting by client IP using the default policy
    /// app.use_fixed_window(by::ip());
    ///
    /// // Apply rate limiting by user ID using the "burst" policy
    /// app.use_fixed_window(by::header("x-tenant-id").using("burst"));
    ///
    /// # app.run_blocking()
    /// # }
    /// ```
    ///
    /// ## Notes
    ///
    /// - This middleware is **global** and affects all routes registered
    ///   after it is applied.
    /// - Multiple rate-limiting middlewares may be installed, each with
    ///   its own partition key and policy.
    /// - Rate limiting failures result in an HTTP `429 Too Many Requests` response.
    ///
    /// ## See also
    ///
    /// - [`FixedWindow`] — fixed window policy definition
    /// - [`App::with_fixed_window`] — registering fixed-window policies
    /// - [`RateLimitKeyExt`] — binding partition keys to policies
    pub fn use_fixed_window<K: RateLimitKeyExt>(&mut self, source: K) -> &mut Self {
        self.attach(RateLimiting::<FixedWindow>::new(source))
    }

    /// Enables sliding-window rate limiting for incoming requests.
    ///
    /// This method installs a **global middleware** that applies a sliding-window
    /// rate limiter to all requests passing through the application.
    ///
    /// The provided `source` defines:
    /// - **How requests are partitioned** (e.g. by IP, user, header, path)
    /// - **Which rate-limiting policy is used** (default or named)
    ///
    /// The middleware will look up a previously registered [`SlidingWindow`]
    /// policy and apply it to each request. If no matching policy is found,
    /// the middleware is a no-op.
    ///
    /// ## Partition keys
    ///
    /// The partition key determines how requests are grouped for rate limiting.
    /// Common examples include:
    /// - Client IP address
    /// - Authenticated user ID
    /// - API key or header value
    /// - Route or tenant identifier
    ///
    /// ## Policy selection
    ///
    /// - If the key is bound **without** a policy name, the **default sliding-window
    ///   policy** is used.
    /// - If the key is bound **with** `.using(name)`, the named policy with the
    ///   corresponding name is applied.
    ///
    /// ## Example
    ///
    /// ```no_run
    /// use std::time::Duration;
    /// use volga::{
    ///     App,
    ///     rate_limiting::{by, SlidingWindow, RateLimitKeyExt},
    /// };
    ///
    /// # fn main() {
    /// let mut app = App::new()
    ///     // Register a default sliding-window policy
    ///     .with_sliding_window(
    ///         SlidingWindow::new(60, Duration::from_secs(60))
    ///     )
    ///     // Register a named policy for burst traffic
    ///     .with_sliding_window(
    ///         SlidingWindow::new(100, Duration::from_secs(30))
    ///             .with_name("burst")
    ///     );
    ///
    /// // Apply rate limiting by client IP using the default policy
    /// app.use_sliding_window(by::ip());
    ///
    /// // Apply rate limiting by user ID using the "burst" policy
    /// app.use_sliding_window(by::header("x-tenant-id").using("burst"));
    ///
    /// # app.run_blocking()
    /// # }
    /// ```
    ///
    /// ## Notes
    ///
    /// - This middleware is **global** and affects all routes registered
    ///   after it is applied.
    /// - Multiple rate-limiting middlewares may be installed, each with
    ///   its own partition key and policy.
    /// - Rate limiting failures result in an HTTP `429 Too Many Requests` response.
    ///
    /// ## See also
    ///
    /// - [`SlidingWindow`] — sliding window policy definition
    /// - [`App::with_sliding_window`] — registering sliding-window policies
    /// - [`RateLimitKeyExt`] — binding partition keys to policies
    pub fn use_sliding_window<K: RateLimitKeyExt>(&mut self, source: K) -> &mut Self {
        self.attach(RateLimiting::<SlidingWindow>::new(source))
    }

    /// Enables token bucket rate limiting for incoming requests.
    ///
    /// This method installs a **global middleware** that applies a token bucket
    /// rate limiter to all requests passing through the application.
    ///
    /// The provided `source` defines:
    /// - **How requests are partitioned** (e.g. by IP, user, header, path)
    /// - **Which rate-limiting policy is used** (default or named)
    ///
    /// The middleware will look up a previously registered [`TokenBucket`]
    /// policy and apply it to each request. If no matching policy is found,
    /// the middleware is a no-op.
    ///
    /// ## Partition keys
    ///
    /// The partition key determines how requests are grouped for rate limiting.
    /// Common examples include:
    /// - Client IP address
    /// - Authenticated user ID
    /// - API key or header value
    /// - Route or tenant identifier
    ///
    /// ## Policy selection
    ///
    /// - If the key is bound **without** a policy name, the **default token bucket
    ///   policy** is used.
    /// - If the key is bound **with** `.using(name)`, the named policy with the
    ///   corresponding name is applied.
    ///
    /// ## Example
    ///
    /// ```no_run
    /// use std::time::Duration;
    /// use volga::{
    ///     App,
    ///     rate_limiting::{by, TokenBucket, RateLimitKeyExt},
    /// };
    ///
    /// # fn main() {
    /// let mut app = App::new()
    ///     // Register a default token bucket policy
    ///     .with_token_bucket(
    ///         TokenBucket::new(100, 1.0)
    ///     )
    ///     // Register a named policy for burst traffic
    ///     .with_token_bucket(
    ///         TokenBucket::new(200, 2.0)
    ///             .with_name("burst")
    ///     );
    ///
    /// // Apply rate limiting by client IP using the default policy
    /// app.use_token_bucket(by::ip());
    ///
    /// // Apply rate limiting by user ID using the "burst" policy
    /// app.use_token_bucket(by::header("x-tenant-id").using("burst"));
    ///
    /// # app.run_blocking()
    /// # }
    /// ```
    ///
    /// ## Notes
    ///
    /// - This middleware is **global** and affects all routes registered
    ///   after it is applied.
    /// - Multiple rate-limiting middlewares may be installed, each with
    ///   its own partition key and policy.
    /// - Rate limiting failures result in an HTTP `429 Too Many Requests` response.
    ///
    /// ## See also
    ///
    /// - [`TokenBucket`] — token bucket policy definition
    /// - [`App::with_token_bucket`] — registering token bucket policies
    /// - [`RateLimitKeyExt`] — binding partition keys to policies
    pub fn use_token_bucket<K: RateLimitKeyExt>(&mut self, source: K) -> &mut Self {
        self.attach(RateLimiting::<TokenBucket>::new(source))
    }

    /// Enables GCRA rate limiting for incoming requests.
    ///
    /// This method installs a **global middleware** that applies GCRA
    /// rate limiter to all requests passing through the application.
    ///
    /// The provided `source` defines:
    /// - **How requests are partitioned** (e.g. by IP, user, header, path)
    /// - **Which rate-limiting policy is used** (default or named)
    ///
    /// The middleware will look up a previously registered [`Gcra`]
    /// policy and apply it to each request. If no matching policy is found,
    /// the middleware is a no-op.
    ///
    /// ## Partition keys
    ///
    /// The partition key determines how requests are grouped for rate limiting.
    /// Common examples include:
    /// - Client IP address
    /// - Authenticated user ID
    /// - API key or header value
    /// - Route or tenant identifier
    ///
    /// ## Policy selection
    ///
    /// - If the key is bound **without** a policy name, the **default GCRA
    ///   policy** is used.
    /// - If the key is bound **with** `.using(name)`, the named policy with the
    ///   corresponding name is applied.
    ///
    /// ## Example
    ///
    /// ```no_run
    /// use std::time::Duration;
    /// use volga::{
    ///     App,
    ///     rate_limiting::{by, Gcra, RateLimitKeyExt},
    /// };
    ///
    /// # fn main() {
    /// let mut app = App::new()
    ///     // Register a default GCRA policy
    ///     .with_gcra(
    ///         Gcra::new(5.0, 3)
    ///     )
    ///     // Register a named policy for burst traffic
    ///     .with_gcra(
    ///         Gcra::new(10.0, 10)
    ///             .with_name("burst")
    ///     );
    ///
    /// // Apply rate limiting by client IP using the default policy
    /// app.use_gcra(by::ip());
    ///
    /// // Apply rate limiting by user ID using the "burst" policy
    /// app.use_gcra(by::header("x-tenant-id").using("burst"));
    ///
    /// # app.run_blocking()
    /// # }
    /// ```
    ///
    /// ## Notes
    ///
    /// - This middleware is **global** and affects all routes registered
    ///   after it is applied.
    /// - Multiple rate-limiting middlewares may be installed, each with
    ///   its own partition key and policy.
    /// - Rate limiting failures result in an HTTP `429 Too Many Requests` response.
    ///
    /// ## See also
    ///
    /// - [`Gcra`] — GCRA policy definition
    /// - [`App::with_gcra`] — registering GCRA policies
    /// - [`RateLimitKeyExt`] — binding partition keys to policies
    pub fn use_gcra<K: RateLimitKeyExt>(&mut self, source: K) -> &mut Self {
        self.attach(RateLimiting::<Gcra>::new(source))
    }
}

impl<'a> Route<'a> {
    /// Enables fixed-window rate limiting for this route.
    ///
    /// This method installs a **route-scoped middleware** that applies a
    /// fixed-window rate limiter **only** to requests handled by this route.
    ///
    /// The provided `source` defines:
    /// - How requests are partitioned (e.g. by IP, user, header, path)
    /// - Which fixed-window policy is used (default or named)
    ///
    /// ## Policy resolution
    ///
    /// - If the partition key is bound **without** a policy name, the
    ///   default fixed-window policy is used.
    /// - If `using(name)` is specified, the named policy with the
    ///   corresponding name is applied.
    ///
    /// ## Middleware order
    ///
    /// Route-level rate limiting is executed:
    /// - **after global middleware**
    /// - **after route group middleware**
    /// - **before the route handler**
    ///
    /// This allows route-specific limits to refine or override
    /// broader rate-limiting rules.
    ///
    /// ## Example
    ///
    /// ```no_run
    /// use volga::rate_limiting::{by, RateLimitKeyExt};
    ///
    /// # let mut app = volga::App::new();
    /// app.map_get("/api/private", || async { /*...*/ })
    ///     .fixed_window(by::ip().using("burst"));
    /// ```
    ///
    /// ## Notes
    ///
    /// - Multiple rate-limiting middlewares may be attached to the same route.
    /// - A rate limit violation results in an HTTP `429 Too Many Requests` response.
    pub fn fixed_window<K: RateLimitKeyExt>(self, source: K) -> Self {
        self.attach(RateLimiting::<FixedWindow>::new(source))
    }

    /// Enables sliding-window rate limiting for this route.
    ///
    /// This method installs a **route-scoped middleware** that applies a
    /// sliding-window rate limiter **only** to requests handled by this route.
    ///
    /// The provided `source` defines:
    /// - How requests are partitioned (e.g. by IP, user, header, path)
    /// - Which sliding-window policy is used (default or named)
    ///
    /// ## Policy resolution
    ///
    /// - If the partition key is bound **without** a policy name, the
    ///   default sliding-window policy is used.
    /// - If `using(name)` is specified, the named policy with the
    ///   corresponding name is applied.
    ///
    /// ## Middleware order
    ///
    /// Route-level rate limiting is executed:
    /// - **after global middleware**
    /// - **after route group middleware**
    /// - **before the route handler**
    ///
    /// This allows route-specific limits to refine or override
    /// broader rate-limiting rules.
    ///
    /// ## Example
    ///
    /// ```no_run
    /// use volga::rate_limiting::{by, RateLimitKeyExt};
    ///
    /// # let mut app = volga::App::new();
    /// app.map_get("/api/private", || async { /*...*/ })
    ///     .sliding_window(by::ip().using("burst"));
    /// ```
    ///
    /// ## Notes
    ///
    /// - Multiple rate-limiting middlewares may be attached to the same route.
    /// - A rate limit violation results in an HTTP `429 Too Many Requests` response.
    pub fn sliding_window<K: RateLimitKeyExt>(self, source: K) -> Self {
        self.attach(RateLimiting::<SlidingWindow>::new(source))
    }

    /// Enables token bucket rate limiting for this route.
    ///
    /// This method installs a **route-scoped middleware** that applies a
    /// token bucket rate limiter **only** to requests handled by this route.
    ///
    /// The provided `source` defines:
    /// - How requests are partitioned (e.g. by IP, user, header, path)
    /// - Which token bucket policy is used (default or named)
    ///
    /// ## Policy resolution
    ///
    /// - If the partition key is bound **without** a policy name, the
    ///   default token bucket policy is used.
    /// - If `using(name)` is specified, the named policy with the
    ///   corresponding name is applied.
    ///
    /// ## Middleware order
    ///
    /// Route-level rate limiting is executed:
    /// - **after global middleware**
    /// - **after route group middleware**
    /// - **before the route handler**
    ///
    /// This allows route-specific limits to refine or override
    /// broader rate-limiting rules.
    ///
    /// ## Example
    ///
    /// ```no_run
    /// use volga::rate_limiting::{by, RateLimitKeyExt};
    ///
    /// # let mut app = volga::App::new();
    /// app.map_get("/api/private", || async { /*...*/ })
    ///     .token_bucket(by::ip().using("burst"));
    /// ```
    ///
    /// ## Notes
    ///
    /// - Multiple rate-limiting middlewares may be attached to the same route.
    /// - A rate limit violation results in an HTTP `429 Too Many Requests` response.
    pub fn token_bucket<K: RateLimitKeyExt>(self, source: K) -> Self {
        self.attach(RateLimiting::<TokenBucket>::new(source))
    }

    /// Enables GCRA rate limiting for this route.
    ///
    /// This method installs a **route-scoped middleware** that applies a
    /// GCRA rate limiter **only** to requests handled by this route.
    ///
    /// The provided `source` defines:
    /// - How requests are partitioned (e.g. by IP, user, header, path)
    /// - Which GCRA policy is used (default or named)
    ///
    /// ## Policy resolution
    ///
    /// - If the partition key is bound **without** a policy name, the
    ///   default GCRA policy is used.
    /// - If `using(name)` is specified, the named policy with the
    ///   corresponding name is applied.
    ///
    /// ## Middleware order
    ///
    /// Route-level rate limiting is executed:
    /// - **after global middleware**
    /// - **after route group middleware**
    /// - **before the route handler**
    ///
    /// This allows route-specific limits to refine or override
    /// broader rate-limiting rules.
    ///
    /// ## Example
    ///
    /// ```no_run
    /// use volga::rate_limiting::{by, RateLimitKeyExt};
    ///
    /// # let mut app = volga::App::new();
    /// app.map_get("/api/private", || async { /*...*/ })
    ///     .gcra(by::ip().using("burst"));
    /// ```
    ///
    /// ## Notes
    ///
    /// - Multiple rate-limiting middlewares may be attached to the same route.
    /// - A rate limit violation results in an HTTP `429 Too Many Requests` response.
    pub fn gcra<K: RateLimitKeyExt>(self, source: K) -> Self {
        self.attach(RateLimiting::<Gcra>::new(source))
    }
}

impl<'a> RouteGroup<'a> {
    /// Enables fixed-window rate limiting for all routes in this group.
    ///
    /// This method installs a **group-scoped middleware** that applies a
    /// fixed-window rate limiter to every route contained within the group.
    ///
    /// Group-level rate limiting allows sharing a common rate-limiting
    /// strategy across multiple related routes.
    ///
    /// ## Policy resolution
    ///
    /// - Uses the default fixed-window policy unless overridden with `using(name)`.
    /// - Named policies must be registered via [`App::with_fixed_window`].
    ///
    /// ## Middleware order
    ///
    /// Group-level rate limiting is executed:
    /// - **after global middleware**
    /// - **before route-level middleware**
    ///
    /// ## Example
    ///
    /// ```no_run
    /// use volga::rate_limiting::{by, RateLimitKeyExt};
    ///
    /// # let mut app = volga::App::new();
    /// app.group("/api", |api| {
    ///     api.fixed_window(by::ip());
    ///
    ///     api.map_get("/status", || async { /*...*/ });
    ///     api.map_post("/upload", || async { /*...*/ })
    ///         .fixed_window(by::header("x-tenant-id").using("burst"));
    /// });
    /// ```
    pub fn fixed_window<K: RateLimitKeyExt>(&mut self, source: K) -> &mut Self {
        self.attach(RateLimiting::<FixedWindow>::new(source))
    }

    /// Enables sliding-window rate limiting for all routes in this group.
    ///
    /// This method installs a **group-scoped middleware** that applies a
    /// sliding-window rate limiter to every route contained within the group.
    ///
    /// Group-level rate limiting allows sharing a common rate-limiting
    /// strategy across multiple related routes.
    ///
    /// ## Policy resolution
    ///
    /// - Uses the default sliding-window policy unless overridden with `using(name)`.
    /// - Named policies must be registered via [`App::with_sliding_window`].
    ///
    /// ## Middleware order
    ///
    /// Group-level rate limiting is executed:
    /// - **after global middleware**
    /// - **before route-level middleware**
    ///
    /// ## Example
    ///
    /// ```no_run
    /// use volga::rate_limiting::{by, RateLimitKeyExt};
    ///
    /// # let mut app = volga::App::new();
    /// app.group("/api", |api| {
    ///     api.sliding_window(by::ip());
    ///
    ///     api.map_get("/status", || async { /*...*/ });
    ///     api.map_post("/upload", || async { /*...*/ })
    ///         .sliding_window(by::header("x-tenant-id").using("burst"));
    /// });
    /// ```
    pub fn sliding_window<K: RateLimitKeyExt>(&mut self, source: K) -> &mut Self {
        self.attach(RateLimiting::<SlidingWindow>::new(source))
    }

    /// Enables token bucket rate limiting for all routes in this group.
    ///
    /// This method installs a **group-scoped middleware** that applies a
    /// token bucket rate limiter to every route contained within the group.
    ///
    /// Group-level rate limiting allows sharing a common rate-limiting
    /// strategy across multiple related routes.
    ///
    /// ## Policy resolution
    ///
    /// - Uses the default token bucket policy unless overridden with `using(name)`.
    /// - Named policies must be registered via [`App::with_token_bucket`].
    ///
    /// ## Middleware order
    ///
    /// Group-level rate limiting is executed:
    /// - **after global middleware**
    /// - **before route-level middleware**
    ///
    /// ## Example
    ///
    /// ```no_run
    /// use volga::rate_limiting::{by, RateLimitKeyExt};
    ///
    /// # let mut app = volga::App::new();
    /// app.group("/api", |api| {
    ///     api.token_bucket(by::ip());
    ///
    ///     api.map_get("/status", || async { /*...*/ });
    ///     api.map_post("/upload", || async { /*...*/ })
    ///         .sliding_window(by::header("x-tenant-id").using("burst"));
    /// });
    /// ```
    pub fn token_bucket<K: RateLimitKeyExt>(&mut self, source: K) -> &mut Self {
        self.attach(RateLimiting::<TokenBucket>::new(source))
    }

    /// Enables GCRA rate limiting for all routes in this group.
    ///
    /// This method installs a **group-scoped middleware** that applies
    /// GCRA rate limiter to every route contained within the group.
    ///
    /// Group-level rate limiting allows sharing a common rate-limiting
    /// strategy across multiple related routes.
    ///
    /// ## Policy resolution
    ///
    /// - Uses the default GCRA policy unless overridden with `using(name)`.
    /// - Named policies must be registered via [`App::with_gcra`].
    ///
    /// ## Middleware order
    ///
    /// Group-level rate limiting is executed:
    /// - **after global middleware**
    /// - **before route-level middleware**
    ///
    /// ## Example
    ///
    /// ```no_run
    /// use volga::rate_limiting::{by, RateLimitKeyExt};
    ///
    /// # let mut app = volga::App::new();
    /// app.group("/api", |api| {
    ///     api.gcra(by::ip());
    ///
    ///     api.map_get("/status", || async { /*...*/ });
    ///     api.map_post("/upload", || async { /*...*/ })
    ///         .gcra(by::header("x-tenant-id").using("burst"));
    /// });
    /// ```
    pub fn gcra<K: RateLimitKeyExt>(&mut self, source: K) -> &mut Self {
        self.attach(RateLimiting::<Gcra>::new(source))
    }
}

struct RateLimiting<T> {
    binding: RateLimitBinding,
    _marker: std::marker::PhantomData<T>,
}

impl<T> RateLimiting<T> {
    #[inline]
    fn new<K: RateLimitKeyExt>(source: K) -> Self {
        Self {
            binding: source.bind(),
            _marker: std::marker::PhantomData,
        }
    }
}

impl Middleware for RateLimiting<FixedWindow> {
    #[inline]
    fn call(
        &self,
        ctx: HttpContext,
        next: NextFn,
    ) -> impl Future<Output = HttpResult> + Send + 'static {
        check_fixed_window(ctx, self.binding.clone(), next)
    }
}

impl Middleware for RateLimiting<SlidingWindow> {
    #[inline]
    fn call(
        &self,
        ctx: HttpContext,
        next: NextFn,
    ) -> impl Future<Output = HttpResult> + Send + 'static {
        check_sliding_window(ctx, self.binding.clone(), next)
    }
}

impl Middleware for RateLimiting<TokenBucket> {
    #[inline]
    fn call(
        &self,
        ctx: HttpContext,
        next: NextFn,
    ) -> impl Future<Output = HttpResult> + Send + 'static {
        check_token_bucket(ctx, self.binding.clone(), next)
    }
}

impl Middleware for RateLimiting<Gcra> {
    #[inline]
    fn call(
        &self,
        ctx: HttpContext,
        next: NextFn,
    ) -> impl Future<Output = HttpResult> + Send + 'static {
        check_gcra(ctx, self.binding.clone(), next)
    }
}

#[inline]
async fn check_fixed_window(
    ctx: HttpContext,
    binding: RateLimitBinding,
    next: NextFn,
) -> HttpResult {
    if let Some(limiter) = ctx.fixed_window_rate_limiter(binding.policy.as_deref()) {
        let key = binding.key.extract(ctx.request())?;
        if !limiter.check(key) {
            status!(
                StatusCode::TOO_MANY_REQUESTS.as_u16(),
                text: RATE_LIMIT_ERROR_MSG
            )
        } else {
            next(ctx).await
        }
    } else {
        next(ctx).await
    }
}

#[inline]
async fn check_sliding_window(
    ctx: HttpContext,
    binding: RateLimitBinding,
    next: NextFn,
) -> HttpResult {
    if let Some(limiter) = ctx.sliding_window_rate_limiter(binding.policy.as_deref()) {
        let key = binding.key.extract(ctx.request())?;
        if !limiter.check(key) {
            status!(
                StatusCode::TOO_MANY_REQUESTS.as_u16(),
                text: RATE_LIMIT_ERROR_MSG
            )
        } else {
            next(ctx).await
        }
    } else {
        next(ctx).await
    }
}

#[inline]
async fn check_token_bucket(
    ctx: HttpContext,
    binding: RateLimitBinding,
    next: NextFn,
) -> HttpResult {
    if let Some(limiter) = ctx.token_bucket_rate_limiter(binding.policy.as_deref()) {
        let key = binding.key.extract(ctx.request())?;
        if !limiter.check(key) {
            status!(
                StatusCode::TOO_MANY_REQUESTS.as_u16(),
                text: RATE_LIMIT_ERROR_MSG
            )
        } else {
            next(ctx).await
        }
    } else {
        next(ctx).await
    }
}

#[inline]
async fn check_gcra(ctx: HttpContext, binding: RateLimitBinding, next: NextFn) -> HttpResult {
    if let Some(limiter) = ctx.gcra_rate_limiter(binding.policy.as_deref()) {
        let key = binding.key.extract(ctx.request())?;
        if !limiter.check(key) {
            status!(
                StatusCode::TOO_MANY_REQUESTS.as_u16(),
                text: RATE_LIMIT_ERROR_MSG
            )
        } else {
            next(ctx).await
        }
    } else {
        next(ctx).await
    }
}

#[inline]
fn extract_partition_key_from_ip(req: &HttpRequest) -> Result<u64, Error> {
    let ip = req.extract::<ClientIp>()?;
    let client_ip = extract_client_ip(req, ip.into_inner());
    Ok(stable_hash(&client_ip))
}

#[inline]
fn stable_hash<T: Hash + ?Sized>(value: &T) -> u64 {
    let mut hasher = XxHash64::with_seed(0);
    value.hash(&mut hasher);
    hasher.finish()
}

fn extract_client_ip(req: &HttpRequest, remote_addr: SocketAddr) -> IpAddr {
    let peer = remote_addr.ip();

    let Some(trusted) = req
        .extensions()
        .get::<HttpRequestScope>()
        .and_then(|s| s.trusted_proxies.as_ref())
    else {
        return peer;
    };

    // Don't trust headers unless the direct peer is trusted
    if !trusted.contains(&peer) {
        return peer;
    }

    let chain = forwarded_chain(req).or_else(|| x_forwarded_for_chain(req));

    let Some(mut chain) = chain else {
        return peer;
    };

    if chain.last().copied() != Some(peer) {
        chain.push(peer);
    }

    for ip in chain.iter() {
        if !trusted.contains(ip) {
            return *ip;
        }
    }

    // all hops trusted - best guess: left-most (original) or peer
    chain.last().copied().unwrap_or(peer)
}

#[inline]
fn forwarded_chain(req: &HttpRequest) -> Option<SmallVec<[IpAddr; DEFAULT_IPS_COUNT]>> {
    let header = req.headers().get(FORWARDED)?.to_str().ok()?;
    if header.len() > MAX_FORWARDED_HEADER_LEN {
        return None;
    }

    let mut out = SmallVec::new();

    for entry in header.rsplit(',').take(MAX_FORWARDED_IPS) {
        // entry: for=...;proto=...;by=...
        for part in entry.split(';') {
            let part = part.trim();
            let Some(v) = part.strip_prefix("for=") else {
                continue;
            };

            let v = v.trim().trim_matches('"'); // remove quotes

            // RFC allows: for=unknown or obfuscated identifiers; ignore those
            if v.eq_ignore_ascii_case("unknown") || v.starts_with('_') {
                continue;
            }

            // Handle bracketed IPv6, optionally with port: [v6] or [v6]:port
            if let Some(rest) = v.strip_prefix('[') {
                if let Some((inside, _port)) = rest.split_once(']') {
                    // after is "" or ":port" (or garbage). We ignore port.
                    if let Ok(ip) = inside.parse::<IpAddr>() {
                        out.push(ip);
                    }
                }
                continue;
            }

            // Remove port if present:
            // - IPv4: 1.2.3.4:123
            // - IPv6 might come as 2001:db8::1 (no port) OR [2001:db8::1]:123
            // (brackets already handled above, so the port form should have been bracketed; but be defensive)
            let ip_str = if let Some((host, _port)) = v.rsplit_once(':') {
                // Heuristic: only treat as host:port if host parses as IpAddr
                if host.parse::<IpAddr>().is_ok() {
                    host
                } else {
                    v
                }
            } else {
                v
            };

            if let Ok(ip) = ip_str.parse::<IpAddr>() {
                out.push(ip);
            }
        }
    }

    (!out.is_empty()).then_some(out)
}

#[inline]
fn x_forwarded_for_chain(req: &HttpRequest) -> Option<SmallVec<[IpAddr; DEFAULT_IPS_COUNT]>> {
    let header = req.headers().get(X_FORWARDED_FOR)?.to_str().ok()?;
    if header.len() > MAX_FORWARDED_HEADER_LEN {
        return None;
    }

    let mut out = SmallVec::new();

    for part in header.rsplit(',').take(MAX_FORWARDED_IPS) {
        let s = part.trim();
        if s.is_empty() {
            continue;
        }

        if let Ok(ip) = s.parse::<IpAddr>() {
            out.push(ip);
        }
    }

    (!out.is_empty()).then_some(out)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::HttpBody;
    use hyper::Request;
    use hyper::http::HeaderName;
    use std::net::Ipv4Addr;
    use std::sync::Arc;
    use std::time::Duration;

    fn create_request() -> HttpRequest {
        use crate::http::request_scope::HttpRequestScope;

        let (mut parts, body) = Request::get("/")
            .body(HttpBody::empty())
            .unwrap()
            .into_parts();

        parts.extensions.insert(HttpRequestScope {
            client_ip: ClientIp(SocketAddr::new(IpAddr::V4(127_u32.into()), 8080)),
            ..HttpRequestScope::default()
        });

        HttpRequest::from_parts(parts, body)
    }

    fn create_request_with_trusted_proxy() -> HttpRequest {
        create_request_with_specific_trusted_proxy_chain(
            IpAddr::V4(127_u32.into()),
            [IpAddr::V4(127_u32.into())],
        )
    }

    fn create_request_with_specific_trusted_proxy_chain(
        peer: IpAddr,
        trusted_proxies: impl IntoIterator<Item = IpAddr>,
    ) -> HttpRequest {
        use crate::http::request_scope::HttpRequestScope;

        let (mut parts, body) = Request::get("/")
            .body(HttpBody::empty())
            .unwrap()
            .into_parts();

        let trusted: HashSet<IpAddr> = trusted_proxies.into_iter().collect();
        parts.extensions.insert(HttpRequestScope {
            client_ip: ClientIp(SocketAddr::new(peer, 8080)),
            trusted_proxies: Some(Arc::new(trusted)),
            ..HttpRequestScope::default()
        });

        HttpRequest::from_parts(parts, body)
    }

    #[test]
    fn it_extracts_partition_key_from_ip() {
        let req = create_request();

        let key = extract_partition_key_from_ip(&req).unwrap();

        assert_eq!(key, stable_hash(&IpAddr::V4(127_u32.into())));
    }

    #[test]
    fn it_extracts_forwarded_ip() {
        let mut req = create_request_with_trusted_proxy();
        req.headers_mut().insert(
            HeaderName::from_static("forwarded"),
            "for=192.168.1.1".parse().unwrap(),
        );

        let key = extract_partition_key_from_ip(&req).unwrap();

        assert_eq!(key, stable_hash(&IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1))));
    }

    #[test]
    fn it_extracts_x_forwarded_for_ip() {
        let mut req = create_request_with_trusted_proxy();
        req.headers_mut().insert(
            HeaderName::from_static("x-forwarded-for"),
            "192.168.1.1".parse().unwrap(),
        );

        let key = extract_partition_key_from_ip(&req).unwrap();

        assert_eq!(key, stable_hash(&IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1))));
    }

    #[test]
    fn it_extracts_prioritized_forwarded_ip() {
        let mut req = create_request_with_trusted_proxy();
        req.headers_mut().insert(
            HeaderName::from_static("forwarded"),
            "for=10.24.1.101".parse().unwrap(),
        );
        req.headers_mut().insert(
            HeaderName::from_static("x-forwarded-for"),
            "192.168.1.1".parse().unwrap(),
        );

        let key = extract_partition_key_from_ip(&req).unwrap();

        assert_eq!(key, stable_hash(&IpAddr::V4(Ipv4Addr::new(10, 24, 1, 101))));
    }

    #[test]
    fn it_ignores_forwarded_when_proxy_is_untrusted() {
        let mut req = create_request();
        req.headers_mut().insert(
            HeaderName::from_static("forwarded"),
            "for=192.168.1.1".parse().unwrap(),
        );

        let key = extract_partition_key_from_ip(&req).unwrap();

        assert_eq!(key, stable_hash(&IpAddr::V4(127_u32.into())));
    }

    #[test]
    fn it_extracts_forwarded_ip_with_quotes() {
        let mut req = create_request_with_trusted_proxy();
        req.headers_mut().insert(
            HeaderName::from_static("forwarded"),
            r#"for="192.168.1.1""#.parse().unwrap(),
        );

        let key = extract_partition_key_from_ip(&req).unwrap();
        assert_eq!(key, stable_hash(&IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1))));
    }

    #[test]
    fn it_extracts_forwarded_ipv6_in_brackets() {
        let mut req = create_request_with_trusted_proxy();
        req.headers_mut().insert(
            HeaderName::from_static("forwarded"),
            r#"for="[2001:db8::1]""#.parse().unwrap(),
        );

        let key = extract_partition_key_from_ip(&req).unwrap();
        assert_eq!(key, stable_hash(&"2001:db8::1".parse::<IpAddr>().unwrap()));
    }

    #[test]
    fn it_extracts_forwarded_ip_ignoring_port() {
        let mut req = create_request_with_trusted_proxy();
        req.headers_mut().insert(
            HeaderName::from_static("forwarded"),
            "for=192.168.1.1:1234".parse().unwrap(),
        );

        let key = extract_partition_key_from_ip(&req).unwrap();
        assert_eq!(key, stable_hash(&IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1))));
    }

    #[test]
    fn it_extracts_forwarded_ipv6_with_port() {
        let mut req = create_request_with_trusted_proxy();
        req.headers_mut().insert(
            HeaderName::from_static("forwarded"),
            r#"for="[2001:db8::1]:8443""#.parse().unwrap(),
        );

        let key = extract_partition_key_from_ip(&req).unwrap();
        assert_eq!(key, stable_hash(&"2001:db8::1".parse::<IpAddr>().unwrap()));
    }

    #[test]
    fn it_extracts_forwarded_from_multiple_entries_preferring_nearest_tail() {
        let mut req = create_request_with_trusted_proxy();
        req.headers_mut().insert(
            HeaderName::from_static("forwarded"),
            "for=10.0.0.1, for=192.168.1.1".parse().unwrap(),
        );

        let key = extract_partition_key_from_ip(&req).unwrap();
        assert_eq!(key, stable_hash(&IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1))));
    }

    #[test]
    fn it_extracts_xff_from_list() {
        let mut req = create_request_with_trusted_proxy();
        req.headers_mut().insert(
            HeaderName::from_static("x-forwarded-for"),
            "10.0.0.1, 192.168.1.1".parse().unwrap(),
        );

        let key = extract_partition_key_from_ip(&req).unwrap();
        assert_eq!(key, stable_hash(&IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1))));
    }

    #[test]
    fn it_ignores_xff_unknown_and_parses_next() {
        let mut req = create_request_with_trusted_proxy();
        req.headers_mut().insert(
            HeaderName::from_static("x-forwarded-for"),
            "unknown, 192.168.1.1".parse().unwrap(),
        );

        let key = extract_partition_key_from_ip(&req).unwrap();
        assert_eq!(key, stable_hash(&IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1))));
    }

    #[test]
    fn it_ignores_xff_when_proxy_is_untrusted() {
        let mut req = create_request();
        req.headers_mut().insert(
            HeaderName::from_static("x-forwarded-for"),
            "192.168.1.1".parse().unwrap(),
        );

        let key = extract_partition_key_from_ip(&req).unwrap();
        assert_eq!(key, stable_hash(&IpAddr::V4(127_u32.into())));
    }

    #[test]
    fn it_selects_first_untrusted_before_trusted_proxies_from_xff_chain() {
        let mut req = create_request_with_specific_trusted_proxy_chain(
            /* peer */ "10.0.0.3".parse().unwrap(),
            /* trusted */ ["10.0.0.2".parse().unwrap(), "10.0.0.3".parse().unwrap()],
        );

        req.headers_mut().insert(
            HeaderName::from_static("x-forwarded-for"),
            "192.168.1.1, 10.0.0.2".parse().unwrap(),
        );

        let key = extract_partition_key_from_ip(&req).unwrap();
        assert_eq!(key, stable_hash(&IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1))));
    }

    #[test]
    fn it_falls_back_when_forwarded_header_is_too_long() {
        let mut req = create_request_with_trusted_proxy();
        let huge = "for=192.168.1.1;proto=https,".repeat(10_000);
        req.headers_mut()
            .insert(HeaderName::from_static("forwarded"), huge.parse().unwrap());

        let key = extract_partition_key_from_ip(&req).unwrap();
        assert_eq!(key, stable_hash(&IpAddr::V4(127_u32.into())));
    }

    #[test]
    fn it_caps_xff_chain_to_max_ips_using_right_tail() {
        let mut req = create_request_with_trusted_proxy();
        let mut parts = vec![];
        for i in 0..50 {
            parts.push(format!("10.0.0.{i}"));
        }
        parts.push("192.168.1.1".into());
        let header = parts.join(", ");

        req.headers_mut().insert(
            HeaderName::from_static("x-forwarded-for"),
            header.parse().unwrap(),
        );

        let key = extract_partition_key_from_ip(&req).unwrap();
        assert_eq!(key, stable_hash(&IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1))));
    }

    #[test]
    fn it_tests_stable_hash() {
        let key = stable_hash(&IpAddr::V4(127_u32.into()));
        assert_eq!(key, stable_hash(&IpAddr::V4(127_u32.into())));
    }

    #[test]
    fn it_adds_default_fixed_window_policy() {
        let mut global_limiter = GlobalRateLimiter {
            ..Default::default()
        };

        global_limiter.add_fixed_window(FixedWindow::new(10, Duration::from_secs(10)));

        let default = global_limiter.fixed_window(None).unwrap();

        assert_eq!(default.max_requests(), 10);
        assert_eq!(default.window_size_secs(), 10);
    }

    #[test]
    fn it_adds_default_sliding_window_policy() {
        let mut global_limiter = GlobalRateLimiter {
            ..Default::default()
        };

        global_limiter.add_sliding_window(SlidingWindow::new(10, Duration::from_secs(10)));

        let default = global_limiter.sliding_window(None).unwrap();

        assert_eq!(default.max_requests(), 10);
        assert_eq!(default.window_size_secs(), 10);
    }

    #[test]
    fn it_adds_default_token_bucket_policy() {
        let mut global_limiter = GlobalRateLimiter {
            ..Default::default()
        };

        global_limiter.add_token_bucket(TokenBucket::new(10, 1.0));

        let default = global_limiter.token_bucket(None).unwrap();

        assert_eq!(default.capacity(), 10);
        assert_eq!(default.refill_rate(), 1.0);
    }

    #[test]
    fn it_adds_default_gcra_policy() {
        let mut global_limiter = GlobalRateLimiter {
            ..Default::default()
        };

        global_limiter.add_gcra(Gcra::new(10.0, 1));

        let default = global_limiter.gcra(None).unwrap();

        assert_eq!(default.rate_per_second(), 10.0);
        assert_eq!(default.burst(), 1);
    }

    #[test]
    fn it_adds_named_fixed_window_policy() {
        let mut global_limiter = GlobalRateLimiter {
            ..Default::default()
        };

        global_limiter
            .add_fixed_window(FixedWindow::new(10, Duration::from_secs(10)).with_name("burst"));

        assert!(global_limiter.default_fixed_window.is_none());

        let default = global_limiter.fixed_window(Some("burst")).unwrap();

        assert_eq!(default.max_requests(), 10);
        assert_eq!(default.window_size_secs(), 10);
    }

    #[test]
    fn it_adds_named_sliding_window_policy() {
        let mut global_limiter = GlobalRateLimiter {
            ..Default::default()
        };

        global_limiter
            .add_sliding_window(SlidingWindow::new(10, Duration::from_secs(10)).with_name("burst"));

        assert!(global_limiter.default_sliding_window.is_none());

        let default = global_limiter.sliding_window(Some("burst")).unwrap();

        assert_eq!(default.max_requests(), 10);
        assert_eq!(default.window_size_secs(), 10);
    }

    #[test]
    fn it_adds_named_token_bucket_policy() {
        let mut global_limiter = GlobalRateLimiter {
            ..Default::default()
        };

        global_limiter.add_token_bucket(TokenBucket::new(10, 1.0).with_name("burst"));

        assert!(global_limiter.default_token_bucket.is_none());

        let default = global_limiter.token_bucket(Some("burst")).unwrap();

        assert_eq!(default.capacity(), 10);
        assert_eq!(default.refill_rate(), 1.);
    }

    #[test]
    fn it_adds_named_gcra_policy() {
        let mut global_limiter = GlobalRateLimiter {
            ..Default::default()
        };

        global_limiter.add_gcra(Gcra::new(10.0, 1).with_name("burst"));

        assert!(global_limiter.default_gcra.is_none());

        let default = global_limiter.gcra(Some("burst")).unwrap();

        assert_eq!(default.rate_per_second(), 10.0);
        assert_eq!(default.burst(), 1);
    }

    #[test]
    fn it_add_fixed_window_policy() {
        let app = App::new().with_fixed_window(FixedWindow::new(10, Duration::from_secs(10)));

        let limiter = app.rate_limiter.unwrap().default_fixed_window.unwrap();

        assert_eq!(limiter.max_requests(), 10);
        assert_eq!(limiter.window_size_secs(), 10);
    }

    #[test]
    fn it_add_named_fixed_window_policy() {
        let app = App::new()
            .with_fixed_window(FixedWindow::new(10, Duration::from_secs(10)).with_name("burst"));

        let global_limiter = app.rate_limiter.unwrap();
        let limiter = global_limiter.fixed_window(Some("burst")).unwrap();

        assert_eq!(limiter.max_requests(), 10);
        assert_eq!(limiter.window_size_secs(), 10);
    }

    #[test]
    fn it_add_sliding_window_policy() {
        let app = App::new().with_sliding_window(SlidingWindow::new(10, Duration::from_secs(10)));

        let limiter = app.rate_limiter.unwrap().default_sliding_window.unwrap();

        assert_eq!(limiter.max_requests(), 10);
        assert_eq!(limiter.window_size_secs(), 10);
    }

    #[test]
    fn it_add_named_sliding_window_policy() {
        let app = App::new().with_sliding_window(
            SlidingWindow::new(10, Duration::from_secs(10)).with_name("burst"),
        );

        let global_limiter = app.rate_limiter.unwrap();
        let limiter = global_limiter.sliding_window(Some("burst")).unwrap();

        assert_eq!(limiter.max_requests(), 10);
        assert_eq!(limiter.window_size_secs(), 10);
    }

    #[test]
    fn it_add_token_bucket_policy() {
        let app = App::new().with_token_bucket(TokenBucket::new(10, 1.0));

        let limiter = app.rate_limiter.unwrap().default_token_bucket.unwrap();

        assert_eq!(limiter.capacity(), 10);
        assert_eq!(limiter.refill_rate(), 1.0);
    }

    #[test]
    fn it_add_named_token_bucket_policy() {
        let app = App::new().with_token_bucket(TokenBucket::new(10, 1.0).with_name("burst"));

        let global_limiter = app.rate_limiter.unwrap();
        let limiter = global_limiter.token_bucket(Some("burst")).unwrap();

        assert_eq!(limiter.capacity(), 10);
        assert_eq!(limiter.refill_rate(), 1.0);
    }

    #[test]
    fn it_add_gcra_policy() {
        let app = App::new().with_gcra(Gcra::new(10.0, 3));

        let limiter = app.rate_limiter.unwrap().default_gcra.unwrap();

        assert_eq!(limiter.rate_per_second(), 10.);
        assert_eq!(limiter.burst(), 3);
    }

    #[test]
    fn it_add_named_gcra_policy() {
        let app = App::new().with_gcra(Gcra::new(10., 3).with_name("burst"));

        let global_limiter = app.rate_limiter.unwrap();
        let limiter = global_limiter.gcra(Some("burst")).unwrap();

        assert_eq!(limiter.rate_per_second(), 10.);
        assert_eq!(limiter.burst(), 3);
    }
}