hyperlane-plugin-rate-limit 23.1.0

A 64-way sharded lock-free atomic GCRA and fixed-window rate limiter plugin for the Hyperlane framework with extensible KeyExtractor and RateLimitStore traits and RFC RateLimit headers.
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
use super::*;

/// Implements [`Hasher`] for [`FxHasher`] with zero heap allocations and 8-byte word mixing.
impl Hasher for FxHasher {
    /// Finalizes the 64-bit hash state.
    ///
    /// # Returns
    ///
    /// - `u64` - Finalized 64-bit hash.
    #[inline(always)]
    fn finish(&self) -> u64 {
        let Self { state } = *self;
        state
    }

    /// Mixes `bytes` into the hash state 8 bytes at a time without heap allocation.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Input byte slice.
    #[inline(always)]
    fn write(&mut self, bytes: &[u8]) {
        let Self { state } = self;
        let mut h: u64 = *state;
        let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
        for chunk in chunks {
            h = (h.rotate_left(5) ^ u64::from_ne_bytes(*chunk)).wrapping_mul(FX_HASH_K);
        }
        let mut tail: &[u8] = rem;
        if tail.len() >= 4 {
            let word: u32 = u32::from_ne_bytes([tail[0], tail[1], tail[2], tail[3]]);
            h = (h.rotate_left(5) ^ u64::from(word)).wrapping_mul(FX_HASH_K);
            tail = &tail[4..];
        }
        if tail.len() >= 2 {
            let half: u16 = u16::from_ne_bytes([tail[0], tail[1]]);
            h = (h.rotate_left(5) ^ u64::from(half)).wrapping_mul(FX_HASH_K);
            tail = &tail[2..];
        }
        if let Some(&b) = tail.first() {
            h = (h.rotate_left(5) ^ u64::from(b)).wrapping_mul(FX_HASH_K);
        }
        *state = h;
    }

    /// Mixes a single `u8` byte directly into the hash state.
    ///
    /// # Arguments
    ///
    /// - `u8` - Input byte.
    #[inline(always)]
    fn write_u8(&mut self, i: u8) {
        let Self { state } = self;
        *state = (state.rotate_left(5) ^ u64::from(i)).wrapping_mul(FX_HASH_K);
    }
}

/// Exact precomputed unsigned 64-bit division helpers for [`FastDiv64`].
impl FastDiv64 {
    /// Precomputes Granlund-Montgomery reciprocal parameters for `divisor >= 1`.
    ///
    /// # Arguments
    ///
    /// - `u64` - Positive divisor.
    ///
    /// # Returns
    ///
    /// - `Self` - Precomputed fast divider.
    pub(crate) fn new(divisor: u64) -> Self {
        let d: u64 = divisor.max(1);
        if d.is_power_of_two() {
            return Self {
                divisor: d,
                mult: 0,
                shift: d.trailing_zeros(),
                is_pow2: true,
            };
        }
        let l: u32 = 64 - (d - 1).leading_zeros();
        if l >= 64 {
            return Self {
                divisor: d,
                mult: 0,
                shift: 64,
                is_pow2: false,
            };
        }
        let pow: u128 = 1u128 << (64 + l);
        let m_full: u128 = (pow + u128::from(d) - 1) / u128::from(d);
        let mult: u64 = (m_full - (1u128 << 64)) as u64;
        Self {
            divisor: d,
            mult,
            shift: l - 1,
            is_pow2: false,
        }
    }

    /// Computes exact `n / self.divisor` without executing a hardware `udiv` instruction.
    ///
    /// # Arguments
    ///
    /// - `u64` - Dividend.
    ///
    /// # Returns
    ///
    /// - `u64` - Exact unsigned integer quotient.
    #[inline(always)]
    pub(crate) fn div(self, n: u64) -> u64 {
        let Self {
            divisor,
            mult,
            shift,
            is_pow2,
        } = self;
        if is_pow2 {
            return n >> shift;
        }
        if shift >= 64 {
            return u64::from(n >= divisor);
        }
        let t: u64 = ((u128::from(n) * u128::from(mult)) >> 64) as u64;
        (((n - t) >> 1) + t) >> shift
    }

    /// Computes exact `(n / self.divisor, n % self.divisor)` in one reciprocal multiply.
    ///
    /// # Arguments
    ///
    /// - `u64` - Dividend.
    ///
    /// # Returns
    ///
    /// - `(u64, u64)` - Exact `(quotient, remainder)`.
    #[inline(always)]
    pub(crate) fn div_rem(self, n: u64) -> (u64, u64) {
        let q: u64 = self.div(n);
        let Self { divisor, .. } = self;
        (q, n - q.wrapping_mul(divisor))
    }
}

/// Implements `fmt::Write` for [`StackFmtWriter`].
impl Write for StackFmtWriter<'_> {
    /// Copies `s` into the underlying stack byte slice if capacity permits.
    ///
    /// # Arguments
    ///
    /// - `&str` - UTF-8 chunk to append.
    ///
    /// # Returns
    ///
    /// - `fmt::Result` - `Ok(())` on success or `Err(fmt::Error)` on overflow.
    #[inline]
    fn write_str(&mut self, s: &str) -> fmt::Result {
        let Self { buf, len } = self;
        let bytes: &[u8] = s.as_bytes();
        let next: usize = *len + bytes.len();
        if next > buf.len() {
            return Err(fmt::Error);
        }
        buf[*len..next].copy_from_slice(bytes);
        *len = next;
        Ok(())
    }
}

/// Default construction for [`RateLimitPolicy`].
impl Default for RateLimitPolicy {
    /// Constructs a default [`RateLimitPolicy`] (100 req / 60 s, GCRA, 65 536 max keys).
    fn default() -> Self {
        Self {
            requests_per_window: DEFAULT_RATE_LIMIT_REQUESTS,
            window_ms: DEFAULT_RATE_LIMIT_WINDOW_MS,
            burst: DEFAULT_RATE_LIMIT_BURST,
            algorithm: RateLimitAlgorithm::Gcra,
            max_keys: DEFAULT_RATE_LIMIT_MAX_KEYS,
            include_headers: true,
            exempt_paths: Vec::new(),
        }
    }
}

/// Inherent fluent builders for [`RateLimitPolicy`].
impl RateLimitPolicy {
    /// Constructs a policy with `requests_per_window` allowed over `window_ms`.
    ///
    /// # Arguments
    ///
    /// - `u64` - Sustained requests per window.
    /// - `u64` - Window duration in milliseconds.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed rate-limit policy.
    pub fn new(requests_per_window: u64, window_ms: u64) -> Self {
        let count: u64 = requests_per_window.max(1);
        Self {
            requests_per_window: count,
            window_ms: window_ms.max(1),
            burst: count,
            algorithm: RateLimitAlgorithm::Gcra,
            max_keys: DEFAULT_RATE_LIMIT_MAX_KEYS,
            include_headers: true,
            exempt_paths: Vec::new(),
        }
    }

    /// Sets the burst allowance for GCRA enforcement.
    ///
    /// # Arguments
    ///
    /// - `u64` - Maximum instantaneous burst capacity.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated policy.
    pub fn with_burst(mut self, burst: u64) -> Self {
        self.set_burst(burst.max(1));
        self
    }

    /// Sets the rate-limiting algorithm (`Gcra` or `FixedWindow`).
    ///
    /// # Arguments
    ///
    /// - `RateLimitAlgorithm` - Desired enforcement algorithm.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated policy.
    pub fn with_algorithm(mut self, algorithm: RateLimitAlgorithm) -> Self {
        self.set_algorithm(algorithm);
        self
    }

    /// Sets the maximum tracked key capacity across all 64 shards.
    ///
    /// # Arguments
    ///
    /// - `usize` - Maximum number of concurrent tracked keys.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated policy.
    pub fn with_max_keys(mut self, max_keys: usize) -> Self {
        self.set_max_keys(max_keys.max(1));
        self
    }

    /// Enables or disables `RateLimit-*` response headers.
    ///
    /// # Arguments
    ///
    /// - `bool` - Whether to attach headers.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated policy.
    pub fn with_include_headers(mut self, include_headers: bool) -> Self {
        self.set_include_headers(include_headers);
        self
    }

    /// Sets exact request paths exempted from rate limiting.
    ///
    /// # Arguments
    ///
    /// - `I` - Iterator of exact exempt paths.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated policy.
    pub fn with_exempt_paths<I, S>(mut self, paths: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.set_exempt_paths(paths.into_iter().map(Into::into).collect());
        self
    }
}

/// Inherent implementation of [`BucketEntry`].
impl BucketEntry {
    /// Creates a fresh zero-initialized atomic bucket entry.
    ///
    /// # Arguments
    ///
    /// - `u64` - Current timestamp in nanoseconds since limiter epoch.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized atomic bucket.
    pub(crate) fn new(now_ns: u64) -> Self {
        Self {
            primary: AtomicU64::new(0),
            counter: AtomicU64::new(0),
            last_seen_ns: AtomicU64::new(now_ns),
        }
    }

    /// Refreshes `last_seen_ns` only when elapsed time exceeds `step_ns` to avoid dirtying hot cache lines.
    ///
    /// # Arguments
    ///
    /// - `u64` - Current monotonic timestamp in nanoseconds.
    /// - `u64` - Refresh interval step in nanoseconds.
    #[inline(always)]
    fn touch_last_seen(&self, now_ns: u64, step_ns: u64) {
        let Self { last_seen_ns, .. } = self;
        let prev: u64 = last_seen_ns.load(Ordering::Relaxed);
        if now_ns.saturating_sub(prev) >= step_ns {
            last_seen_ns.store(now_ns, Ordering::Relaxed);
        }
    }

    /// Evaluates one GCRA request atomically using a lock-free CAS loop and reciprocal division.
    ///
    /// # Arguments
    ///
    /// - `u64` - Current elapsed nanoseconds since limiter epoch.
    /// - `u64` - Emission interval in nanoseconds per token.
    /// - `FastDiv64` - Precomputed reciprocal divider for `emission_interval_ns`.
    /// - `u64` - Burst tolerance in nanoseconds (`emission_interval_ns * burst`).
    /// - `u64` - Effective burst limit.
    /// - `u64` - Lazy `last_seen_ns` refresh step in nanoseconds.
    ///
    /// # Returns
    ///
    /// - `RateLimitDecision` - Admission decision and remaining tokens.
    #[inline]
    pub(crate) fn check_gcra(
        &self,
        now_ns: u64,
        emission_interval_ns: u64,
        emission_div: FastDiv64,
        burst_tolerance_ns: u64,
        limit: u64,
        last_seen_step_ns: u64,
    ) -> RateLimitDecision {
        let Self { primary, .. } = self;
        self.touch_last_seen(now_ns, last_seen_step_ns);
        let max_tat: u64 = now_ns.saturating_add(burst_tolerance_ns);
        let mut observed: u64 = primary.load(Ordering::Relaxed);
        loop {
            let base: u64 = observed.max(now_ns);
            let next_tat: u64 = base.saturating_add(emission_interval_ns);
            if next_tat > max_tat {
                let wait_ns: u64 = next_tat.saturating_sub(max_tat);
                let reset_ns: u64 = observed.saturating_sub(now_ns);
                return RateLimitDecision {
                    allowed: false,
                    limit,
                    remaining: 0,
                    reset_after_secs: ceil_nanos_to_secs(reset_ns),
                    retry_after_secs: ceil_nanos_to_secs(wait_ns).max(1),
                };
            }
            match primary.compare_exchange_weak(
                observed,
                next_tat,
                Ordering::AcqRel,
                Ordering::Relaxed,
            ) {
                Ok(_) => {
                    let headroom_ns: u64 = max_tat.saturating_sub(next_tat);
                    let remaining: u64 = emission_div.div(headroom_ns);
                    let reset_ns: u64 = next_tat.saturating_sub(now_ns);
                    return RateLimitDecision {
                        allowed: true,
                        limit,
                        remaining,
                        reset_after_secs: ceil_nanos_to_secs(reset_ns),
                        retry_after_secs: 0,
                    };
                }
                Err(actual) => observed = actual,
            }
        }
    }

    /// Evaluates one fixed-window request atomically via a single packed `(window_id, count)` CAS when representable.
    ///
    /// # Arguments
    ///
    /// - `u64` - Current elapsed nanoseconds since limiter epoch.
    /// - `u64` - Window size in nanoseconds.
    /// - `FastDiv64` - Precomputed reciprocal divider for `window_ns`.
    /// - `u64` - Maximum requests permitted in one window.
    /// - `u64` - Lazy `last_seen_ns` refresh step in nanoseconds.
    ///
    /// # Returns
    ///
    /// - `RateLimitDecision` - Admission decision and remaining quota.
    #[inline]
    pub(crate) fn check_fixed_window(
        &self,
        now_ns: u64,
        window_ns: u64,
        window_div: FastDiv64,
        limit: u64,
        last_seen_step_ns: u64,
    ) -> RateLimitDecision {
        let Self {
            primary, counter, ..
        } = self;
        self.touch_last_seen(now_ns, last_seen_step_ns);
        let (win_quot, elapsed_in_win): (u64, u64) = window_div.div_rem(now_ns);
        let current_win: u64 = win_quot.saturating_add(1);
        let reset_ns: u64 = window_ns.saturating_sub(elapsed_in_win);
        let reset_secs: u64 = ceil_nanos_to_secs(reset_ns).max(1);
        if limit <= FIXED_WIN_COUNT_MASK && current_win <= FIXED_WIN_COUNT_MASK {
            let win_prefix: u64 = current_win << FIXED_WIN_PACK_SHIFT;
            let mut packed: u64 = primary.load(Ordering::Relaxed);
            loop {
                let cur_count: u64 = if (packed >> FIXED_WIN_PACK_SHIFT) == current_win {
                    packed & FIXED_WIN_COUNT_MASK
                } else {
                    0
                };
                if cur_count >= limit {
                    return RateLimitDecision {
                        allowed: false,
                        limit,
                        remaining: 0,
                        reset_after_secs: reset_secs,
                        retry_after_secs: reset_secs,
                    };
                }
                let next_count: u64 = cur_count + 1;
                let next_packed: u64 = win_prefix | next_count;
                match primary.compare_exchange_weak(
                    packed,
                    next_packed,
                    Ordering::AcqRel,
                    Ordering::Relaxed,
                ) {
                    Ok(_) => {
                        return RateLimitDecision {
                            allowed: true,
                            limit,
                            remaining: limit.saturating_sub(next_count),
                            reset_after_secs: reset_secs,
                            retry_after_secs: 0,
                        };
                    }
                    Err(actual) => packed = actual,
                }
            }
        }
        let observed_win: u64 = primary.load(Ordering::Acquire);
        if observed_win != current_win
            && primary
                .compare_exchange(
                    observed_win,
                    current_win,
                    Ordering::AcqRel,
                    Ordering::Acquire,
                )
                .is_ok()
        {
            counter.store(1, Ordering::Release);
            return RateLimitDecision {
                allowed: true,
                limit,
                remaining: limit.saturating_sub(1),
                reset_after_secs: reset_secs,
                retry_after_secs: 0,
            };
        }
        let mut cur: u64 = counter.load(Ordering::Relaxed);
        loop {
            if cur >= limit {
                return RateLimitDecision {
                    allowed: false,
                    limit,
                    remaining: 0,
                    reset_after_secs: reset_secs,
                    retry_after_secs: reset_secs,
                };
            }
            match counter.compare_exchange_weak(cur, cur + 1, Ordering::AcqRel, Ordering::Relaxed) {
                Ok(_) => {
                    return RateLimitDecision {
                        allowed: true,
                        limit,
                        remaining: limit.saturating_sub(cur + 1),
                        reset_after_secs: reset_secs,
                        retry_after_secs: 0,
                    };
                }
                Err(actual) => cur = actual,
            }
        }
    }
}

/// Inherent implementation of [`ShardedRateLimiter`].
impl ShardedRateLimiter {
    /// Builds a 64-way cache-aligned sharded lock-free [`ShardedRateLimiter`] governed by `policy`.
    ///
    /// # Arguments
    ///
    /// - `RateLimitPolicy` - Quota, window, burst, algorithm, and memory cap settings.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready rate limiter.
    pub fn new(policy: RateLimitPolicy) -> Self {
        let window_ns: u64 = policy.get_window_ms().max(1).saturating_mul(NANOS_PER_MS);
        let rpw: u64 = policy.get_requests_per_window().max(1);
        let burst: u64 = policy.get_burst().max(1);
        let emission_interval_ns: u64 = (window_ns / rpw).max(1);
        let burst_tolerance_ns: u64 = emission_interval_ns.saturating_mul(burst);
        let emission_div: FastDiv64 = FastDiv64::new(emission_interval_ns);
        let window_div: FastDiv64 = FastDiv64::new(window_ns);
        let last_seen_step_ns: u64 = (window_ns >> 3).min(NANOS_PER_SEC);
        let shards: Box<[RateLimitShard; RATE_LIMIT_SHARD_COUNT]> =
            Box::new(from_fn(|_: usize| RateLimitShard {
                map: RwLock::new(HashMap::default()),
            }));
        Self {
            inner: Arc::new(ShardedRateLimiterInner {
                policy,
                epoch: Instant::now(),
                emission_interval_ns,
                emission_div,
                burst_tolerance_ns,
                window_ns,
                window_div,
                last_seen_step_ns,
                key_count: AtomicUsize::new(0),
                shards,
            }),
        }
    }

    /// Returns the number of currently tracked distinct keys in `O(1)` time without locking.
    ///
    /// # Returns
    ///
    /// - `usize` - Active tracked key count.
    pub fn tracked_keys(&self) -> usize {
        let Self { inner } = self;
        inner.key_count.load(Ordering::Relaxed)
    }

    /// Evaluates one decision against `entry` using the configured lock-free algorithm.
    ///
    /// # Arguments
    ///
    /// - `&BucketEntry` - Target atomic bucket entry.
    /// - `u64` - Current timestamp in nanoseconds since limiter epoch.
    ///
    /// # Returns
    ///
    /// - `RateLimitDecision` - Admission decision and remaining quota.
    #[inline(always)]
    fn eval_entry(&self, entry: &BucketEntry, now_ns: u64) -> RateLimitDecision {
        let Self { inner } = self;
        match inner.policy.get_algorithm() {
            RateLimitAlgorithm::Gcra => entry.check_gcra(
                now_ns,
                inner.emission_interval_ns,
                inner.emission_div,
                inner.burst_tolerance_ns,
                inner.policy.get_burst().max(1),
                inner.last_seen_step_ns,
            ),
            RateLimitAlgorithm::FixedWindow => entry.check_fixed_window(
                now_ns,
                inner.window_ns,
                inner.window_div,
                inner.policy.get_requests_per_window().max(1),
                inner.last_seen_step_ns,
            ),
        }
    }

    /// Computes the eviction staleness cutoff accounting for `window_ns`, `burst_tolerance_ns`, and `last_seen_step_ns` lag.
    ///
    /// # Arguments
    ///
    /// - `u64` - Current timestamp in nanoseconds since limiter epoch.
    ///
    /// # Returns
    ///
    /// - `u64` - Cutoff timestamp below or equal to which idle buckets may be evicted.
    #[inline(always)]
    fn stale_cutoff_ns(&self, now_ns: u64) -> u64 {
        let Self { inner } = self;
        let retention_ns: u64 = inner
            .window_ns
            .max(inner.burst_tolerance_ns)
            .saturating_add(inner.last_seen_step_ns);
        now_ns.saturating_sub(retention_ns)
    }

    /// Reports whether `entry` must be retained because it is within the retention window or carries live quota state.
    ///
    /// # Arguments
    ///
    /// - `&BucketEntry` - Candidate bucket entry.
    /// - `u64` - Current timestamp in nanoseconds since limiter epoch.
    /// - `u64` - Precomputed staleness cutoff timestamp.
    /// - `u64` - Current fixed-window identifier (`0` for GCRA).
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the bucket must not be evicted.
    #[inline(always)]
    fn is_entry_live(
        &self,
        entry: &BucketEntry,
        now_ns: u64,
        stale_cutoff: u64,
        current_win: u64,
    ) -> bool {
        if entry.last_seen_ns.load(Ordering::Relaxed) > stale_cutoff {
            return true;
        }
        let Self { inner } = self;
        match inner.policy.get_algorithm() {
            RateLimitAlgorithm::Gcra => entry.primary.load(Ordering::Relaxed) > now_ns,
            RateLimitAlgorithm::FixedWindow => {
                let limit: u64 = inner.policy.get_requests_per_window().max(1);
                let primary_val: u64 = entry.primary.load(Ordering::Relaxed);
                let entry_win: u64 =
                    if limit <= FIXED_WIN_COUNT_MASK && current_win <= FIXED_WIN_COUNT_MASK {
                        primary_val >> FIXED_WIN_PACK_SHIFT
                    } else {
                        primary_val
                    };
                entry_win == current_win
            }
        }
    }

    /// Evaluates one request against `key` under a write lock when the key is absent from the read fast path.
    ///
    /// # Arguments
    ///
    /// - `&str` - Bucket partition key.
    /// - `usize` - Precomputed shard index.
    /// - `u64` - Current timestamp in nanoseconds since limiter epoch.
    ///
    /// # Returns
    ///
    /// - `Option<RateLimitDecision>` - Decision once inserted or found, or `None` when capacity is full.
    #[cold]
    fn check_or_insert_slow(
        &self,
        key: &str,
        idx: usize,
        now_ns: u64,
    ) -> Option<RateLimitDecision> {
        let Self { inner } = self;
        let max_keys: usize = inner.policy.get_max_keys();
        if inner.key_count.load(Ordering::Relaxed) >= max_keys {
            let _: usize = self.purge_expired();
        }
        let mut write_map: RwLockWriteGuard<'_, RateLimitShardMap> =
            inner.shards[idx].map.write().ok()?;
        if let Some(existing) = write_map.get(key) {
            return Some(self.eval_entry(existing, now_ns));
        }
        if inner.key_count.load(Ordering::Relaxed) >= max_keys {
            let stale_cutoff: u64 = self.stale_cutoff_ns(now_ns);
            let current_win: u64 = inner.window_div.div(now_ns).saturating_add(1);
            let before: usize = write_map.len();
            write_map.retain(|_: &String, entry: &mut BucketEntry| {
                self.is_entry_live(entry, now_ns, stale_cutoff, current_win)
            });
            let removed: usize = before.saturating_sub(write_map.len());
            if removed > 0 {
                inner.key_count.fetch_sub(removed, Ordering::Relaxed);
            }
            if inner.key_count.load(Ordering::Relaxed) >= max_keys {
                return None;
            }
        }
        let entry: BucketEntry = BucketEntry::new(now_ns);
        let decision: RateLimitDecision = self.eval_entry(&entry, now_ns);
        write_map.insert(key.to_owned(), entry);
        inner.key_count.fetch_add(1, Ordering::Relaxed);
        Some(decision)
    }

    /// Direct non-virtual quota evaluation fast path called by [`RateLimitPlugin`].
    ///
    /// # Arguments
    ///
    /// - `&str` - Bucket partition key.
    ///
    /// # Returns
    ///
    /// - `RateLimitDecision` - Admission decision and remaining quota.
    #[inline]
    pub(crate) fn check_direct(&self, key: &str) -> RateLimitDecision {
        let Self { inner } = self;
        let now_ns: u64 = inner.epoch.elapsed().as_nanos().min(u64::MAX as u128) as u64;
        let idx: usize = rate_limit_shard_index(key);
        if let Ok(read_map) = inner.shards[idx].map.read()
            && let Some(existing) = read_map.get(key)
        {
            return self.eval_entry(existing, now_ns);
        }
        if let Some(decision) = self.check_or_insert_slow(key, idx, now_ns) {
            return decision;
        }
        let limit: u64 = inner.policy.get_requests_per_window();
        let reset_secs: u64 = ceil_nanos_to_secs(inner.window_ns).max(1);
        RateLimitDecision {
            allowed: false,
            limit,
            remaining: 0,
            reset_after_secs: reset_secs,
            retry_after_secs: reset_secs,
        }
    }
}

/// Implements [`RateLimitStore`] for [`ShardedRateLimiter`].
impl RateLimitStore for ShardedRateLimiter {
    /// Evaluates one request against `key` using the configured lock-free algorithm.
    ///
    /// # Arguments
    ///
    /// - `&str` - Bucket partition key.
    ///
    /// # Returns
    ///
    /// - `RateLimitDecision` - Admission decision and remaining quota.
    #[inline]
    fn check(&self, key: &str) -> RateLimitDecision {
        self.check_direct(key)
    }

    /// Evicts entries whose idle age exceeds the configured window duration across all 64 shards.
    ///
    /// # Returns
    ///
    /// - `usize` - Total number of stale keys evicted.
    fn purge_expired(&self) -> usize {
        let Self { inner } = self;
        let now_ns: u64 = inner.epoch.elapsed().as_nanos().min(u64::MAX as u128) as u64;
        let stale_cutoff: u64 = self.stale_cutoff_ns(now_ns);
        let current_win: u64 = inner.window_div.div(now_ns).saturating_add(1);
        let mut evicted: usize = 0;
        for shard in inner.shards.iter() {
            let needs_evict: bool = shard
                .map
                .read()
                .map(|map: RwLockReadGuard<'_, RateLimitShardMap>| !map.is_empty())
                .unwrap_or(false);
            if !needs_evict {
                continue;
            }
            if let Ok(mut map) = shard.map.write() {
                let before: usize = map.len();
                map.retain(|_: &String, entry: &mut BucketEntry| {
                    self.is_entry_live(entry, now_ns, stale_cutoff, current_win)
                });
                evicted += before.saturating_sub(map.len());
            }
        }
        if evicted > 0 {
            inner.key_count.fetch_sub(evicted, Ordering::Relaxed);
        }
        evicted
    }
}

/// Inherent constructors for built-in key extractors.
impl ClientIpKeyExtractor {
    /// Creates a [`ClientIpKeyExtractor`] choosing whether to trust `X-Forwarded-For` / `X-Real-Ip`.
    ///
    /// # Arguments
    ///
    /// - `bool` - `true` when behind a trusted reverse proxy.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed key extractor.
    pub fn new(trust_proxy_headers: bool) -> Self {
        Self {
            trust_proxy_headers,
        }
    }
}

/// Implements [`KeyExtractor`] for [`ClientIpKeyExtractor`].
impl KeyExtractor for ClientIpKeyExtractor {
    /// Extracts the client IP address as the bucket key.
    ///
    /// # Arguments
    ///
    /// - `&Stream` - Transport stream.
    /// - `&Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `String` - Client IP partition key.
    fn extract(&self, stream: &Stream, ctx: &Context) -> String {
        resolve_client_ip(stream, ctx, self.get_trust_proxy_headers())
    }
}

/// Inherent constructors for [`HeaderKeyExtractor`].
impl HeaderKeyExtractor {
    /// Creates a [`HeaderKeyExtractor`] reading `header_name` with optional client-IP fallback.
    ///
    /// # Arguments
    ///
    /// - `H` - Header name convertible into `String`.
    /// - `bool` - Whether to fall back to client IP when the header is absent.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed key extractor.
    pub fn new<H>(header_name: H, fallback_to_ip: bool) -> Self
    where
        H: Into<String>,
    {
        Self {
            header_name: header_name.into(),
            fallback_to_ip,
        }
    }
}

/// Implements [`KeyExtractor`] for [`HeaderKeyExtractor`].
impl KeyExtractor for HeaderKeyExtractor {
    /// Extracts the configured request header value (or client IP fallback) as the bucket key.
    ///
    /// # Arguments
    ///
    /// - `&Stream` - Transport stream.
    /// - `&Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `String` - Header-derived partition key.
    fn extract(&self, stream: &Stream, ctx: &Context) -> String {
        if let Some(val) = get_request_header_back_ref(ctx.get_request(), self.get_header_name()) {
            let trimmed: &str = val.trim();
            if !trimmed.is_empty() {
                return trimmed.to_owned();
            }
        }
        if self.get_fallback_to_ip() {
            resolve_client_ip(stream, ctx, false)
        } else {
            FALLBACK_CLIENT_KEY.to_owned()
        }
    }
}

/// Inherent constructors for [`PathAndIpKeyExtractor`].
impl PathAndIpKeyExtractor {
    /// Creates a [`PathAndIpKeyExtractor`] combining request path and client IP.
    ///
    /// # Arguments
    ///
    /// - `bool` - `true` when forwarding proxy headers are trusted.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed key extractor.
    pub fn new(trust_proxy_headers: bool) -> Self {
        Self {
            trust_proxy_headers,
        }
    }
}

/// Implements [`KeyExtractor`] for [`PathAndIpKeyExtractor`].
impl KeyExtractor for PathAndIpKeyExtractor {
    /// Extracts `"<path>|<client_ip>"` as the partition key.
    ///
    /// # Arguments
    ///
    /// - `&Stream` - Transport stream.
    /// - `&Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `String` - Composite path-and-IP partition key.
    fn extract(&self, stream: &Stream, ctx: &Context) -> String {
        let path: &str = ctx.get_request().get_path();
        let mut ip_buf: [u8; IP_STACK_BUF_LEN] = [0u8; IP_STACK_BUF_LEN];
        let ip: &str =
            resolve_client_ip_ref(stream, ctx, self.get_trust_proxy_headers(), &mut ip_buf);
        let mut out: String = String::with_capacity(path.len() + ip.len() + 1);
        out.push_str(path);
        out.push(KEY_PATH_IP_SEPARATOR);
        out.push_str(ip);
        out
    }
}

/// Inherent implementation of [`RateLimitPlugin`].
impl RateLimitPlugin {
    /// Initializes the global [`RateLimitPlugin`] with the default 64-shard limiter and client-IP extractor.
    ///
    /// # Arguments
    ///
    /// - `RateLimitPolicy` - Quota and algorithm policy.
    ///
    /// # Returns
    ///
    /// - `&'static Self` - Reference to the initialized global plugin.
    pub fn init(policy: RateLimitPolicy) -> &'static Self {
        let limiter: ShardedRateLimiter = ShardedRateLimiter::new(policy.clone());
        let store: Arc<dyn RateLimitStore> = Arc::new(limiter.clone());
        let expected_limit: u64 = match policy.get_algorithm() {
            RateLimitAlgorithm::Gcra => policy.get_burst().max(1),
            RateLimitAlgorithm::FixedWindow => policy.get_requests_per_window().max(1),
        };
        let preformatted_limit: String = expected_limit.to_string();
        let key_extractor: Arc<dyn KeyExtractor> = Arc::new(ClientIpKeyExtractor::new(false));
        RATE_LIMIT_PLUGIN.get_or_init(|| Self {
            policy,
            store,
            fast_store: Some(limiter),
            preformatted_limit,
            expected_limit,
            key_extractor,
            use_default_ip_fast_path: true,
        })
    }

    /// Initializes the global [`RateLimitPlugin`] with custom [`RateLimitStore`] and [`KeyExtractor`].
    ///
    /// # Arguments
    ///
    /// - `RateLimitPolicy` - Quota header and exempt-path policy.
    /// - `Arc<dyn RateLimitStore>` - Custom or distributed backend store.
    /// - `Arc<dyn KeyExtractor>` - Custom partition key extractor.
    ///
    /// # Returns
    ///
    /// - `&'static Self` - Reference to the initialized global plugin.
    pub fn init_custom(
        policy: RateLimitPolicy,
        store: Arc<dyn RateLimitStore>,
        key_extractor: Arc<dyn KeyExtractor>,
    ) -> &'static Self {
        let expected_limit: u64 = match policy.get_algorithm() {
            RateLimitAlgorithm::Gcra => policy.get_burst().max(1),
            RateLimitAlgorithm::FixedWindow => policy.get_requests_per_window().max(1),
        };
        let preformatted_limit: String = expected_limit.to_string();
        RATE_LIMIT_PLUGIN.get_or_init(|| Self {
            policy,
            store,
            fast_store: None,
            preformatted_limit,
            expected_limit,
            key_extractor,
            use_default_ip_fast_path: false,
        })
    }

    /// Returns the initialized global [`RateLimitPlugin`], if initialized.
    ///
    /// # Returns
    ///
    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
    pub fn get() -> Option<&'static Self> {
        RATE_LIMIT_PLUGIN.get()
    }

    /// Returns the active [`RateLimitPolicy`].
    ///
    /// # Returns
    ///
    /// - `&RateLimitPolicy` - Active policy.
    pub fn get_policy(&self) -> &RateLimitPolicy {
        let Self { policy, .. } = self;
        policy
    }

    /// Returns the active [`Arc<dyn RateLimitStore>`].
    ///
    /// # Returns
    ///
    /// - `&Arc<dyn RateLimitStore>` - Active backend store.
    pub fn get_store(&self) -> &Arc<dyn RateLimitStore> {
        let Self { store, .. } = self;
        store
    }

    /// Returns the active [`Arc<dyn KeyExtractor>`].
    ///
    /// # Returns
    ///
    /// - `&Arc<dyn KeyExtractor>` - Active key extractor.
    pub fn get_key_extractor(&self) -> &Arc<dyn KeyExtractor> {
        let Self { key_extractor, .. } = self;
        key_extractor
    }

    /// Reports whether the zero-allocation default peer-IP fast path is enabled.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when initialized with the default [`ClientIpKeyExtractor`].
    #[inline]
    pub(crate) fn is_default_ip_fast_path(&self) -> bool {
        let Self {
            use_default_ip_fast_path,
            ..
        } = self;
        *use_default_ip_fast_path
    }

    /// Evaluates one request against `key` and attaches standard `RateLimit-*` response headers.
    ///
    /// # Arguments
    ///
    /// - `&str` - Partition key.
    /// - `&mut Context` - Request and response context.
    ///
    /// # Returns
    ///
    /// - `RateLimitDecision` - Quota decision for this request.
    #[inline]
    pub fn evaluate_key(&self, key: &str, ctx: &mut Context) -> RateLimitDecision {
        let Self {
            policy,
            store,
            fast_store,
            preformatted_limit,
            expected_limit,
            ..
        } = self;
        let decision: RateLimitDecision = match fast_store {
            Some(limiter) => limiter.check_direct(key),
            None => store.check(key),
        };
        let response: &mut Response = ctx.get_mut_response();
        if policy.get_include_headers() {
            let mut limit_buf: [u8; U64_STACK_BUF_LEN] = [0u8; U64_STACK_BUF_LEN];
            let mut rem_buf: [u8; U64_STACK_BUF_LEN] = [0u8; U64_STACK_BUF_LEN];
            let mut reset_buf: [u8; U64_STACK_BUF_LEN] = [0u8; U64_STACK_BUF_LEN];
            let limit_str: &str = if decision.get_limit() == *expected_limit {
                preformatted_limit.as_str()
            } else {
                format_u64_stack(decision.get_limit(), &mut limit_buf)
            };
            let rem_str: &str = format_u64_stack(decision.get_remaining(), &mut rem_buf);
            let reset_str: &str = format_u64_stack(decision.get_reset_after_secs(), &mut reset_buf);
            response
                .set_header(HEADER_RATE_LIMIT_LIMIT, limit_str)
                .set_header(HEADER_RATE_LIMIT_REMAINING, rem_str)
                .set_header(HEADER_RATE_LIMIT_RESET, reset_str);
        }
        if !decision.get_allowed() {
            let mut retry_buf: [u8; U64_STACK_BUF_LEN] = [0u8; U64_STACK_BUF_LEN];
            let retry_str: &str = format_u64_stack(decision.get_retry_after_secs(), &mut retry_buf);
            response
                .set_status_code(HttpStatus::TooManyRequests.code())
                .set_header(RETRY_AFTER, retry_str)
                .set_body(EMPTY_STR);
        }
        decision
    }
}

/// Implements [`ServerHook`] for [`RateLimitHook`].
impl ServerHook for RateLimitHook {
    /// Constructs a per-request [`RateLimitHook`].
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Self` - Hook instance.
    async fn new(_: &mut Stream, _: &mut Context) -> Self {
        Self
    }

    /// Enforces the configured rate limit and rejects excess traffic with `429 Too Many Requests`.
    ///
    /// # Arguments
    ///
    /// - `Self` - Hook instance.
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Status` - `Status::Continue` when unconfigured, exempt, or admitted; `Status::Reject` when throttled.
    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
        let Some(plugin) = RateLimitPlugin::get() else {
            return Status::Continue;
        };
        let exempt_paths: &Vec<String> = plugin.get_policy().get_exempt_paths();
        if !exempt_paths.is_empty() {
            let path: &str = ctx.get_request().get_path();
            if exempt_paths.iter().any(|exempt: &String| exempt == path) {
                return Status::Continue;
            }
        }
        let decision: RateLimitDecision = if plugin.is_default_ip_fast_path() {
            let mut ip_buf: [u8; IP_STACK_BUF_LEN] = [0u8; IP_STACK_BUF_LEN];
            let peer_key: &str = if let Ok(addr) = stream.get_peer_addr() {
                format_ip_stack(addr.ip(), &mut ip_buf)
            } else {
                FALLBACK_CLIENT_KEY
            };
            plugin.evaluate_key(peer_key, ctx)
        } else {
            let key: String = plugin.get_key_extractor().extract(stream, ctx);
            plugin.evaluate_key(&key, ctx)
        };
        if decision.get_allowed() {
            return Status::Continue;
        }
        let wire: Vec<u8> = ctx.get_mut_response().build();
        let _: Result<(), ResponseError> = stream.try_send(&wire).await;
        Status::Reject
    }
}