Skip to main content

hyperlane_plugin_rate_limit/
impl.rs

1use super::*;
2
3/// Implements [`Hasher`] for [`FxHasher`] with zero heap allocations and 8-byte word mixing.
4impl Hasher for FxHasher {
5    /// Finalizes the 64-bit hash state.
6    ///
7    /// # Returns
8    ///
9    /// - `u64` - Finalized 64-bit hash.
10    #[inline(always)]
11    fn finish(&self) -> u64 {
12        let Self { state } = *self;
13        state
14    }
15
16    /// Mixes `bytes` into the hash state 8 bytes at a time without heap allocation.
17    ///
18    /// # Arguments
19    ///
20    /// - `&[u8]` - Input byte slice.
21    #[inline(always)]
22    fn write(&mut self, bytes: &[u8]) {
23        let Self { state } = self;
24        let mut h: u64 = *state;
25        let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
26        for chunk in chunks {
27            h = (h.rotate_left(5) ^ u64::from_ne_bytes(*chunk)).wrapping_mul(FX_HASH_K);
28        }
29        let mut tail: &[u8] = rem;
30        if tail.len() >= 4 {
31            let word: u32 = u32::from_ne_bytes([tail[0], tail[1], tail[2], tail[3]]);
32            h = (h.rotate_left(5) ^ u64::from(word)).wrapping_mul(FX_HASH_K);
33            tail = &tail[4..];
34        }
35        if tail.len() >= 2 {
36            let half: u16 = u16::from_ne_bytes([tail[0], tail[1]]);
37            h = (h.rotate_left(5) ^ u64::from(half)).wrapping_mul(FX_HASH_K);
38            tail = &tail[2..];
39        }
40        if let Some(&b) = tail.first() {
41            h = (h.rotate_left(5) ^ u64::from(b)).wrapping_mul(FX_HASH_K);
42        }
43        *state = h;
44    }
45
46    /// Mixes a single `u8` byte directly into the hash state.
47    ///
48    /// # Arguments
49    ///
50    /// - `u8` - Input byte.
51    #[inline(always)]
52    fn write_u8(&mut self, i: u8) {
53        let Self { state } = self;
54        *state = (state.rotate_left(5) ^ u64::from(i)).wrapping_mul(FX_HASH_K);
55    }
56}
57
58/// Exact precomputed unsigned 64-bit division helpers for [`FastDiv64`].
59impl FastDiv64 {
60    /// Precomputes Granlund-Montgomery reciprocal parameters for `divisor >= 1`.
61    ///
62    /// # Arguments
63    ///
64    /// - `u64` - Positive divisor.
65    ///
66    /// # Returns
67    ///
68    /// - `Self` - Precomputed fast divider.
69    pub(crate) fn new(divisor: u64) -> Self {
70        let d: u64 = divisor.max(1);
71        if d.is_power_of_two() {
72            return Self {
73                divisor: d,
74                mult: 0,
75                shift: d.trailing_zeros(),
76                is_pow2: true,
77            };
78        }
79        let l: u32 = 64 - (d - 1).leading_zeros();
80        if l >= 64 {
81            return Self {
82                divisor: d,
83                mult: 0,
84                shift: 64,
85                is_pow2: false,
86            };
87        }
88        let pow: u128 = 1u128 << (64 + l);
89        let m_full: u128 = (pow + u128::from(d) - 1) / u128::from(d);
90        let mult: u64 = (m_full - (1u128 << 64)) as u64;
91        Self {
92            divisor: d,
93            mult,
94            shift: l - 1,
95            is_pow2: false,
96        }
97    }
98
99    /// Computes exact `n / self.divisor` without executing a hardware `udiv` instruction.
100    ///
101    /// # Arguments
102    ///
103    /// - `u64` - Dividend.
104    ///
105    /// # Returns
106    ///
107    /// - `u64` - Exact unsigned integer quotient.
108    #[inline(always)]
109    pub(crate) fn div(self, n: u64) -> u64 {
110        let Self {
111            divisor,
112            mult,
113            shift,
114            is_pow2,
115        } = self;
116        if is_pow2 {
117            return n >> shift;
118        }
119        if shift >= 64 {
120            return u64::from(n >= divisor);
121        }
122        let t: u64 = ((u128::from(n) * u128::from(mult)) >> 64) as u64;
123        (((n - t) >> 1) + t) >> shift
124    }
125
126    /// Computes exact `(n / self.divisor, n % self.divisor)` in one reciprocal multiply.
127    ///
128    /// # Arguments
129    ///
130    /// - `u64` - Dividend.
131    ///
132    /// # Returns
133    ///
134    /// - `(u64, u64)` - Exact `(quotient, remainder)`.
135    #[inline(always)]
136    pub(crate) fn div_rem(self, n: u64) -> (u64, u64) {
137        let q: u64 = self.div(n);
138        let Self { divisor, .. } = self;
139        (q, n - q.wrapping_mul(divisor))
140    }
141}
142
143/// Implements `fmt::Write` for [`StackFmtWriter`].
144impl Write for StackFmtWriter<'_> {
145    /// Copies `s` into the underlying stack byte slice if capacity permits.
146    ///
147    /// # Arguments
148    ///
149    /// - `&str` - UTF-8 chunk to append.
150    ///
151    /// # Returns
152    ///
153    /// - `fmt::Result` - `Ok(())` on success or `Err(fmt::Error)` on overflow.
154    #[inline]
155    fn write_str(&mut self, s: &str) -> fmt::Result {
156        let Self { buf, len } = self;
157        let bytes: &[u8] = s.as_bytes();
158        let next: usize = *len + bytes.len();
159        if next > buf.len() {
160            return Err(fmt::Error);
161        }
162        buf[*len..next].copy_from_slice(bytes);
163        *len = next;
164        Ok(())
165    }
166}
167
168/// Default construction for [`RateLimitPolicy`].
169impl Default for RateLimitPolicy {
170    /// Constructs a default [`RateLimitPolicy`] (100 req / 60 s, GCRA, 65 536 max keys).
171    fn default() -> Self {
172        Self {
173            requests_per_window: DEFAULT_RATE_LIMIT_REQUESTS,
174            window_ms: DEFAULT_RATE_LIMIT_WINDOW_MS,
175            burst: DEFAULT_RATE_LIMIT_BURST,
176            algorithm: RateLimitAlgorithm::Gcra,
177            max_keys: DEFAULT_RATE_LIMIT_MAX_KEYS,
178            include_headers: true,
179            exempt_paths: Vec::new(),
180        }
181    }
182}
183
184/// Inherent fluent builders for [`RateLimitPolicy`].
185impl RateLimitPolicy {
186    /// Constructs a policy with `requests_per_window` allowed over `window_ms`.
187    ///
188    /// # Arguments
189    ///
190    /// - `u64` - Sustained requests per window.
191    /// - `u64` - Window duration in milliseconds.
192    ///
193    /// # Returns
194    ///
195    /// - `Self` - Constructed rate-limit policy.
196    pub fn new(requests_per_window: u64, window_ms: u64) -> Self {
197        let count: u64 = requests_per_window.max(1);
198        Self {
199            requests_per_window: count,
200            window_ms: window_ms.max(1),
201            burst: count,
202            algorithm: RateLimitAlgorithm::Gcra,
203            max_keys: DEFAULT_RATE_LIMIT_MAX_KEYS,
204            include_headers: true,
205            exempt_paths: Vec::new(),
206        }
207    }
208
209    /// Sets the burst allowance for GCRA enforcement.
210    ///
211    /// # Arguments
212    ///
213    /// - `u64` - Maximum instantaneous burst capacity.
214    ///
215    /// # Returns
216    ///
217    /// - `Self` - Updated policy.
218    pub fn with_burst(mut self, burst: u64) -> Self {
219        self.set_burst(burst.max(1));
220        self
221    }
222
223    /// Sets the rate-limiting algorithm (`Gcra` or `FixedWindow`).
224    ///
225    /// # Arguments
226    ///
227    /// - `RateLimitAlgorithm` - Desired enforcement algorithm.
228    ///
229    /// # Returns
230    ///
231    /// - `Self` - Updated policy.
232    pub fn with_algorithm(mut self, algorithm: RateLimitAlgorithm) -> Self {
233        self.set_algorithm(algorithm);
234        self
235    }
236
237    /// Sets the maximum tracked key capacity across all 64 shards.
238    ///
239    /// # Arguments
240    ///
241    /// - `usize` - Maximum number of concurrent tracked keys.
242    ///
243    /// # Returns
244    ///
245    /// - `Self` - Updated policy.
246    pub fn with_max_keys(mut self, max_keys: usize) -> Self {
247        self.set_max_keys(max_keys.max(1));
248        self
249    }
250
251    /// Enables or disables `RateLimit-*` response headers.
252    ///
253    /// # Arguments
254    ///
255    /// - `bool` - Whether to attach headers.
256    ///
257    /// # Returns
258    ///
259    /// - `Self` - Updated policy.
260    pub fn with_include_headers(mut self, include_headers: bool) -> Self {
261        self.set_include_headers(include_headers);
262        self
263    }
264
265    /// Sets exact request paths exempted from rate limiting.
266    ///
267    /// # Arguments
268    ///
269    /// - `I` - Iterator of exact exempt paths.
270    ///
271    /// # Returns
272    ///
273    /// - `Self` - Updated policy.
274    pub fn with_exempt_paths<I, S>(mut self, paths: I) -> Self
275    where
276        I: IntoIterator<Item = S>,
277        S: Into<String>,
278    {
279        self.set_exempt_paths(paths.into_iter().map(Into::into).collect());
280        self
281    }
282}
283
284/// Inherent implementation of [`BucketEntry`].
285impl BucketEntry {
286    /// Creates a fresh zero-initialized atomic bucket entry.
287    ///
288    /// # Arguments
289    ///
290    /// - `u64` - Current timestamp in nanoseconds since limiter epoch.
291    ///
292    /// # Returns
293    ///
294    /// - `Self` - Initialized atomic bucket.
295    pub(crate) fn new(now_ns: u64) -> Self {
296        Self {
297            primary: AtomicU64::new(0),
298            counter: AtomicU64::new(0),
299            last_seen_ns: AtomicU64::new(now_ns),
300        }
301    }
302
303    /// Refreshes `last_seen_ns` only when elapsed time exceeds `step_ns` to avoid dirtying hot cache lines.
304    ///
305    /// # Arguments
306    ///
307    /// - `u64` - Current monotonic timestamp in nanoseconds.
308    /// - `u64` - Refresh interval step in nanoseconds.
309    #[inline(always)]
310    fn touch_last_seen(&self, now_ns: u64, step_ns: u64) {
311        let Self { last_seen_ns, .. } = self;
312        let prev: u64 = last_seen_ns.load(Ordering::Relaxed);
313        if now_ns.saturating_sub(prev) >= step_ns {
314            last_seen_ns.store(now_ns, Ordering::Relaxed);
315        }
316    }
317
318    /// Evaluates one GCRA request atomically using a lock-free CAS loop and reciprocal division.
319    ///
320    /// # Arguments
321    ///
322    /// - `u64` - Current elapsed nanoseconds since limiter epoch.
323    /// - `u64` - Emission interval in nanoseconds per token.
324    /// - `FastDiv64` - Precomputed reciprocal divider for `emission_interval_ns`.
325    /// - `u64` - Burst tolerance in nanoseconds (`emission_interval_ns * burst`).
326    /// - `u64` - Effective burst limit.
327    /// - `u64` - Lazy `last_seen_ns` refresh step in nanoseconds.
328    ///
329    /// # Returns
330    ///
331    /// - `RateLimitDecision` - Admission decision and remaining tokens.
332    #[inline]
333    pub(crate) fn check_gcra(
334        &self,
335        now_ns: u64,
336        emission_interval_ns: u64,
337        emission_div: FastDiv64,
338        burst_tolerance_ns: u64,
339        limit: u64,
340        last_seen_step_ns: u64,
341    ) -> RateLimitDecision {
342        let Self { primary, .. } = self;
343        self.touch_last_seen(now_ns, last_seen_step_ns);
344        let max_tat: u64 = now_ns.saturating_add(burst_tolerance_ns);
345        let mut observed: u64 = primary.load(Ordering::Relaxed);
346        loop {
347            let base: u64 = observed.max(now_ns);
348            let next_tat: u64 = base.saturating_add(emission_interval_ns);
349            if next_tat > max_tat {
350                let wait_ns: u64 = next_tat.saturating_sub(max_tat);
351                let reset_ns: u64 = observed.saturating_sub(now_ns);
352                return RateLimitDecision {
353                    allowed: false,
354                    limit,
355                    remaining: 0,
356                    reset_after_secs: ceil_nanos_to_secs(reset_ns),
357                    retry_after_secs: ceil_nanos_to_secs(wait_ns).max(1),
358                };
359            }
360            match primary.compare_exchange_weak(
361                observed,
362                next_tat,
363                Ordering::AcqRel,
364                Ordering::Relaxed,
365            ) {
366                Ok(_) => {
367                    let headroom_ns: u64 = max_tat.saturating_sub(next_tat);
368                    let remaining: u64 = emission_div.div(headroom_ns);
369                    let reset_ns: u64 = next_tat.saturating_sub(now_ns);
370                    return RateLimitDecision {
371                        allowed: true,
372                        limit,
373                        remaining,
374                        reset_after_secs: ceil_nanos_to_secs(reset_ns),
375                        retry_after_secs: 0,
376                    };
377                }
378                Err(actual) => observed = actual,
379            }
380        }
381    }
382
383    /// Evaluates one fixed-window request atomically via a single packed `(window_id, count)` CAS when representable.
384    ///
385    /// # Arguments
386    ///
387    /// - `u64` - Current elapsed nanoseconds since limiter epoch.
388    /// - `u64` - Window size in nanoseconds.
389    /// - `FastDiv64` - Precomputed reciprocal divider for `window_ns`.
390    /// - `u64` - Maximum requests permitted in one window.
391    /// - `u64` - Lazy `last_seen_ns` refresh step in nanoseconds.
392    ///
393    /// # Returns
394    ///
395    /// - `RateLimitDecision` - Admission decision and remaining quota.
396    #[inline]
397    pub(crate) fn check_fixed_window(
398        &self,
399        now_ns: u64,
400        window_ns: u64,
401        window_div: FastDiv64,
402        limit: u64,
403        last_seen_step_ns: u64,
404    ) -> RateLimitDecision {
405        let Self {
406            primary, counter, ..
407        } = self;
408        self.touch_last_seen(now_ns, last_seen_step_ns);
409        let (win_quot, elapsed_in_win): (u64, u64) = window_div.div_rem(now_ns);
410        let current_win: u64 = win_quot.saturating_add(1);
411        let reset_ns: u64 = window_ns.saturating_sub(elapsed_in_win);
412        let reset_secs: u64 = ceil_nanos_to_secs(reset_ns).max(1);
413        if limit <= FIXED_WIN_COUNT_MASK && current_win <= FIXED_WIN_COUNT_MASK {
414            let win_prefix: u64 = current_win << FIXED_WIN_PACK_SHIFT;
415            let mut packed: u64 = primary.load(Ordering::Relaxed);
416            loop {
417                let cur_count: u64 = if (packed >> FIXED_WIN_PACK_SHIFT) == current_win {
418                    packed & FIXED_WIN_COUNT_MASK
419                } else {
420                    0
421                };
422                if cur_count >= limit {
423                    return RateLimitDecision {
424                        allowed: false,
425                        limit,
426                        remaining: 0,
427                        reset_after_secs: reset_secs,
428                        retry_after_secs: reset_secs,
429                    };
430                }
431                let next_count: u64 = cur_count + 1;
432                let next_packed: u64 = win_prefix | next_count;
433                match primary.compare_exchange_weak(
434                    packed,
435                    next_packed,
436                    Ordering::AcqRel,
437                    Ordering::Relaxed,
438                ) {
439                    Ok(_) => {
440                        return RateLimitDecision {
441                            allowed: true,
442                            limit,
443                            remaining: limit.saturating_sub(next_count),
444                            reset_after_secs: reset_secs,
445                            retry_after_secs: 0,
446                        };
447                    }
448                    Err(actual) => packed = actual,
449                }
450            }
451        }
452        let observed_win: u64 = primary.load(Ordering::Acquire);
453        if observed_win != current_win
454            && primary
455                .compare_exchange(
456                    observed_win,
457                    current_win,
458                    Ordering::AcqRel,
459                    Ordering::Acquire,
460                )
461                .is_ok()
462        {
463            counter.store(1, Ordering::Release);
464            return RateLimitDecision {
465                allowed: true,
466                limit,
467                remaining: limit.saturating_sub(1),
468                reset_after_secs: reset_secs,
469                retry_after_secs: 0,
470            };
471        }
472        let mut cur: u64 = counter.load(Ordering::Relaxed);
473        loop {
474            if cur >= limit {
475                return RateLimitDecision {
476                    allowed: false,
477                    limit,
478                    remaining: 0,
479                    reset_after_secs: reset_secs,
480                    retry_after_secs: reset_secs,
481                };
482            }
483            match counter.compare_exchange_weak(cur, cur + 1, Ordering::AcqRel, Ordering::Relaxed) {
484                Ok(_) => {
485                    return RateLimitDecision {
486                        allowed: true,
487                        limit,
488                        remaining: limit.saturating_sub(cur + 1),
489                        reset_after_secs: reset_secs,
490                        retry_after_secs: 0,
491                    };
492                }
493                Err(actual) => cur = actual,
494            }
495        }
496    }
497}
498
499/// Inherent implementation of [`ShardedRateLimiter`].
500impl ShardedRateLimiter {
501    /// Builds a 64-way cache-aligned sharded lock-free [`ShardedRateLimiter`] governed by `policy`.
502    ///
503    /// # Arguments
504    ///
505    /// - `RateLimitPolicy` - Quota, window, burst, algorithm, and memory cap settings.
506    ///
507    /// # Returns
508    ///
509    /// - `Self` - Ready rate limiter.
510    pub fn new(policy: RateLimitPolicy) -> Self {
511        let window_ns: u64 = policy.get_window_ms().max(1).saturating_mul(NANOS_PER_MS);
512        let rpw: u64 = policy.get_requests_per_window().max(1);
513        let burst: u64 = policy.get_burst().max(1);
514        let emission_interval_ns: u64 = (window_ns / rpw).max(1);
515        let burst_tolerance_ns: u64 = emission_interval_ns.saturating_mul(burst);
516        let emission_div: FastDiv64 = FastDiv64::new(emission_interval_ns);
517        let window_div: FastDiv64 = FastDiv64::new(window_ns);
518        let last_seen_step_ns: u64 = (window_ns >> 3).min(NANOS_PER_SEC);
519        let shards: Box<[RateLimitShard; RATE_LIMIT_SHARD_COUNT]> =
520            Box::new(from_fn(|_: usize| RateLimitShard {
521                map: RwLock::new(HashMap::default()),
522            }));
523        Self {
524            inner: Arc::new(ShardedRateLimiterInner {
525                policy,
526                epoch: Instant::now(),
527                emission_interval_ns,
528                emission_div,
529                burst_tolerance_ns,
530                window_ns,
531                window_div,
532                last_seen_step_ns,
533                key_count: AtomicUsize::new(0),
534                shards,
535            }),
536        }
537    }
538
539    /// Returns the number of currently tracked distinct keys in `O(1)` time without locking.
540    ///
541    /// # Returns
542    ///
543    /// - `usize` - Active tracked key count.
544    pub fn tracked_keys(&self) -> usize {
545        let Self { inner } = self;
546        inner.key_count.load(Ordering::Relaxed)
547    }
548
549    /// Evaluates one decision against `entry` using the configured lock-free algorithm.
550    ///
551    /// # Arguments
552    ///
553    /// - `&BucketEntry` - Target atomic bucket entry.
554    /// - `u64` - Current timestamp in nanoseconds since limiter epoch.
555    ///
556    /// # Returns
557    ///
558    /// - `RateLimitDecision` - Admission decision and remaining quota.
559    #[inline(always)]
560    fn eval_entry(&self, entry: &BucketEntry, now_ns: u64) -> RateLimitDecision {
561        let Self { inner } = self;
562        match inner.policy.get_algorithm() {
563            RateLimitAlgorithm::Gcra => entry.check_gcra(
564                now_ns,
565                inner.emission_interval_ns,
566                inner.emission_div,
567                inner.burst_tolerance_ns,
568                inner.policy.get_burst().max(1),
569                inner.last_seen_step_ns,
570            ),
571            RateLimitAlgorithm::FixedWindow => entry.check_fixed_window(
572                now_ns,
573                inner.window_ns,
574                inner.window_div,
575                inner.policy.get_requests_per_window().max(1),
576                inner.last_seen_step_ns,
577            ),
578        }
579    }
580
581    /// Computes the eviction staleness cutoff accounting for `window_ns`, `burst_tolerance_ns`, and `last_seen_step_ns` lag.
582    ///
583    /// # Arguments
584    ///
585    /// - `u64` - Current timestamp in nanoseconds since limiter epoch.
586    ///
587    /// # Returns
588    ///
589    /// - `u64` - Cutoff timestamp below or equal to which idle buckets may be evicted.
590    #[inline(always)]
591    fn stale_cutoff_ns(&self, now_ns: u64) -> u64 {
592        let Self { inner } = self;
593        let retention_ns: u64 = inner
594            .window_ns
595            .max(inner.burst_tolerance_ns)
596            .saturating_add(inner.last_seen_step_ns);
597        now_ns.saturating_sub(retention_ns)
598    }
599
600    /// Reports whether `entry` must be retained because it is within the retention window or carries live quota state.
601    ///
602    /// # Arguments
603    ///
604    /// - `&BucketEntry` - Candidate bucket entry.
605    /// - `u64` - Current timestamp in nanoseconds since limiter epoch.
606    /// - `u64` - Precomputed staleness cutoff timestamp.
607    /// - `u64` - Current fixed-window identifier (`0` for GCRA).
608    ///
609    /// # Returns
610    ///
611    /// - `bool` - `true` when the bucket must not be evicted.
612    #[inline(always)]
613    fn is_entry_live(
614        &self,
615        entry: &BucketEntry,
616        now_ns: u64,
617        stale_cutoff: u64,
618        current_win: u64,
619    ) -> bool {
620        if entry.last_seen_ns.load(Ordering::Relaxed) > stale_cutoff {
621            return true;
622        }
623        let Self { inner } = self;
624        match inner.policy.get_algorithm() {
625            RateLimitAlgorithm::Gcra => entry.primary.load(Ordering::Relaxed) > now_ns,
626            RateLimitAlgorithm::FixedWindow => {
627                let limit: u64 = inner.policy.get_requests_per_window().max(1);
628                let primary_val: u64 = entry.primary.load(Ordering::Relaxed);
629                let entry_win: u64 =
630                    if limit <= FIXED_WIN_COUNT_MASK && current_win <= FIXED_WIN_COUNT_MASK {
631                        primary_val >> FIXED_WIN_PACK_SHIFT
632                    } else {
633                        primary_val
634                    };
635                entry_win == current_win
636            }
637        }
638    }
639
640    /// Evaluates one request against `key` under a write lock when the key is absent from the read fast path.
641    ///
642    /// # Arguments
643    ///
644    /// - `&str` - Bucket partition key.
645    /// - `usize` - Precomputed shard index.
646    /// - `u64` - Current timestamp in nanoseconds since limiter epoch.
647    ///
648    /// # Returns
649    ///
650    /// - `Option<RateLimitDecision>` - Decision once inserted or found, or `None` when capacity is full.
651    #[cold]
652    fn check_or_insert_slow(
653        &self,
654        key: &str,
655        idx: usize,
656        now_ns: u64,
657    ) -> Option<RateLimitDecision> {
658        let Self { inner } = self;
659        let max_keys: usize = inner.policy.get_max_keys();
660        if inner.key_count.load(Ordering::Relaxed) >= max_keys {
661            let _: usize = self.purge_expired();
662        }
663        let mut write_map: RwLockWriteGuard<'_, RateLimitShardMap> =
664            inner.shards[idx].map.write().ok()?;
665        if let Some(existing) = write_map.get(key) {
666            return Some(self.eval_entry(existing, now_ns));
667        }
668        if inner.key_count.load(Ordering::Relaxed) >= max_keys {
669            let stale_cutoff: u64 = self.stale_cutoff_ns(now_ns);
670            let current_win: u64 = inner.window_div.div(now_ns).saturating_add(1);
671            let before: usize = write_map.len();
672            write_map.retain(|_: &String, entry: &mut BucketEntry| {
673                self.is_entry_live(entry, now_ns, stale_cutoff, current_win)
674            });
675            let removed: usize = before.saturating_sub(write_map.len());
676            if removed > 0 {
677                inner.key_count.fetch_sub(removed, Ordering::Relaxed);
678            }
679            if inner.key_count.load(Ordering::Relaxed) >= max_keys {
680                return None;
681            }
682        }
683        let entry: BucketEntry = BucketEntry::new(now_ns);
684        let decision: RateLimitDecision = self.eval_entry(&entry, now_ns);
685        write_map.insert(key.to_owned(), entry);
686        inner.key_count.fetch_add(1, Ordering::Relaxed);
687        Some(decision)
688    }
689
690    /// Direct non-virtual quota evaluation fast path called by [`RateLimitPlugin`].
691    ///
692    /// # Arguments
693    ///
694    /// - `&str` - Bucket partition key.
695    ///
696    /// # Returns
697    ///
698    /// - `RateLimitDecision` - Admission decision and remaining quota.
699    #[inline]
700    pub(crate) fn check_direct(&self, key: &str) -> RateLimitDecision {
701        let Self { inner } = self;
702        let now_ns: u64 = inner.epoch.elapsed().as_nanos().min(u64::MAX as u128) as u64;
703        let idx: usize = rate_limit_shard_index(key);
704        if let Ok(read_map) = inner.shards[idx].map.read()
705            && let Some(existing) = read_map.get(key)
706        {
707            return self.eval_entry(existing, now_ns);
708        }
709        if let Some(decision) = self.check_or_insert_slow(key, idx, now_ns) {
710            return decision;
711        }
712        let limit: u64 = inner.policy.get_requests_per_window();
713        let reset_secs: u64 = ceil_nanos_to_secs(inner.window_ns).max(1);
714        RateLimitDecision {
715            allowed: false,
716            limit,
717            remaining: 0,
718            reset_after_secs: reset_secs,
719            retry_after_secs: reset_secs,
720        }
721    }
722}
723
724/// Implements [`RateLimitStore`] for [`ShardedRateLimiter`].
725impl RateLimitStore for ShardedRateLimiter {
726    /// Evaluates one request against `key` using the configured lock-free algorithm.
727    ///
728    /// # Arguments
729    ///
730    /// - `&str` - Bucket partition key.
731    ///
732    /// # Returns
733    ///
734    /// - `RateLimitDecision` - Admission decision and remaining quota.
735    #[inline]
736    fn check(&self, key: &str) -> RateLimitDecision {
737        self.check_direct(key)
738    }
739
740    /// Evicts entries whose idle age exceeds the configured window duration across all 64 shards.
741    ///
742    /// # Returns
743    ///
744    /// - `usize` - Total number of stale keys evicted.
745    fn purge_expired(&self) -> usize {
746        let Self { inner } = self;
747        let now_ns: u64 = inner.epoch.elapsed().as_nanos().min(u64::MAX as u128) as u64;
748        let stale_cutoff: u64 = self.stale_cutoff_ns(now_ns);
749        let current_win: u64 = inner.window_div.div(now_ns).saturating_add(1);
750        let mut evicted: usize = 0;
751        for shard in inner.shards.iter() {
752            let needs_evict: bool = shard
753                .map
754                .read()
755                .map(|map: RwLockReadGuard<'_, RateLimitShardMap>| !map.is_empty())
756                .unwrap_or(false);
757            if !needs_evict {
758                continue;
759            }
760            if let Ok(mut map) = shard.map.write() {
761                let before: usize = map.len();
762                map.retain(|_: &String, entry: &mut BucketEntry| {
763                    self.is_entry_live(entry, now_ns, stale_cutoff, current_win)
764                });
765                evicted += before.saturating_sub(map.len());
766            }
767        }
768        if evicted > 0 {
769            inner.key_count.fetch_sub(evicted, Ordering::Relaxed);
770        }
771        evicted
772    }
773}
774
775/// Inherent constructors for built-in key extractors.
776impl ClientIpKeyExtractor {
777    /// Creates a [`ClientIpKeyExtractor`] choosing whether to trust `X-Forwarded-For` / `X-Real-Ip`.
778    ///
779    /// # Arguments
780    ///
781    /// - `bool` - `true` when behind a trusted reverse proxy.
782    ///
783    /// # Returns
784    ///
785    /// - `Self` - Constructed key extractor.
786    pub fn new(trust_proxy_headers: bool) -> Self {
787        Self {
788            trust_proxy_headers,
789        }
790    }
791}
792
793/// Implements [`KeyExtractor`] for [`ClientIpKeyExtractor`].
794impl KeyExtractor for ClientIpKeyExtractor {
795    /// Extracts the client IP address as the bucket key.
796    ///
797    /// # Arguments
798    ///
799    /// - `&Stream` - Transport stream.
800    /// - `&Context` - Request context.
801    ///
802    /// # Returns
803    ///
804    /// - `String` - Client IP partition key.
805    fn extract(&self, stream: &Stream, ctx: &Context) -> String {
806        resolve_client_ip(stream, ctx, self.get_trust_proxy_headers())
807    }
808}
809
810/// Inherent constructors for [`HeaderKeyExtractor`].
811impl HeaderKeyExtractor {
812    /// Creates a [`HeaderKeyExtractor`] reading `header_name` with optional client-IP fallback.
813    ///
814    /// # Arguments
815    ///
816    /// - `H` - Header name convertible into `String`.
817    /// - `bool` - Whether to fall back to client IP when the header is absent.
818    ///
819    /// # Returns
820    ///
821    /// - `Self` - Constructed key extractor.
822    pub fn new<H>(header_name: H, fallback_to_ip: bool) -> Self
823    where
824        H: Into<String>,
825    {
826        Self {
827            header_name: header_name.into(),
828            fallback_to_ip,
829        }
830    }
831}
832
833/// Implements [`KeyExtractor`] for [`HeaderKeyExtractor`].
834impl KeyExtractor for HeaderKeyExtractor {
835    /// Extracts the configured request header value (or client IP fallback) as the bucket key.
836    ///
837    /// # Arguments
838    ///
839    /// - `&Stream` - Transport stream.
840    /// - `&Context` - Request context.
841    ///
842    /// # Returns
843    ///
844    /// - `String` - Header-derived partition key.
845    fn extract(&self, stream: &Stream, ctx: &Context) -> String {
846        if let Some(val) = get_request_header_back_ref(ctx.get_request(), self.get_header_name()) {
847            let trimmed: &str = val.trim();
848            if !trimmed.is_empty() {
849                return trimmed.to_owned();
850            }
851        }
852        if self.get_fallback_to_ip() {
853            resolve_client_ip(stream, ctx, false)
854        } else {
855            FALLBACK_CLIENT_KEY.to_owned()
856        }
857    }
858}
859
860/// Inherent constructors for [`PathAndIpKeyExtractor`].
861impl PathAndIpKeyExtractor {
862    /// Creates a [`PathAndIpKeyExtractor`] combining request path and client IP.
863    ///
864    /// # Arguments
865    ///
866    /// - `bool` - `true` when forwarding proxy headers are trusted.
867    ///
868    /// # Returns
869    ///
870    /// - `Self` - Constructed key extractor.
871    pub fn new(trust_proxy_headers: bool) -> Self {
872        Self {
873            trust_proxy_headers,
874        }
875    }
876}
877
878/// Implements [`KeyExtractor`] for [`PathAndIpKeyExtractor`].
879impl KeyExtractor for PathAndIpKeyExtractor {
880    /// Extracts `"<path>|<client_ip>"` as the partition key.
881    ///
882    /// # Arguments
883    ///
884    /// - `&Stream` - Transport stream.
885    /// - `&Context` - Request context.
886    ///
887    /// # Returns
888    ///
889    /// - `String` - Composite path-and-IP partition key.
890    fn extract(&self, stream: &Stream, ctx: &Context) -> String {
891        let path: &str = ctx.get_request().get_path();
892        let mut ip_buf: [u8; IP_STACK_BUF_LEN] = [0u8; IP_STACK_BUF_LEN];
893        let ip: &str =
894            resolve_client_ip_ref(stream, ctx, self.get_trust_proxy_headers(), &mut ip_buf);
895        let mut out: String = String::with_capacity(path.len() + ip.len() + 1);
896        out.push_str(path);
897        out.push(KEY_PATH_IP_SEPARATOR);
898        out.push_str(ip);
899        out
900    }
901}
902
903/// Inherent implementation of [`RateLimitPlugin`].
904impl RateLimitPlugin {
905    /// Initializes the global [`RateLimitPlugin`] with the default 64-shard limiter and client-IP extractor.
906    ///
907    /// # Arguments
908    ///
909    /// - `RateLimitPolicy` - Quota and algorithm policy.
910    ///
911    /// # Returns
912    ///
913    /// - `&'static Self` - Reference to the initialized global plugin.
914    pub fn init(policy: RateLimitPolicy) -> &'static Self {
915        let limiter: ShardedRateLimiter = ShardedRateLimiter::new(policy.clone());
916        let store: Arc<dyn RateLimitStore> = Arc::new(limiter.clone());
917        let expected_limit: u64 = match policy.get_algorithm() {
918            RateLimitAlgorithm::Gcra => policy.get_burst().max(1),
919            RateLimitAlgorithm::FixedWindow => policy.get_requests_per_window().max(1),
920        };
921        let preformatted_limit: String = expected_limit.to_string();
922        let key_extractor: Arc<dyn KeyExtractor> = Arc::new(ClientIpKeyExtractor::new(false));
923        RATE_LIMIT_PLUGIN.get_or_init(|| Self {
924            policy,
925            store,
926            fast_store: Some(limiter),
927            preformatted_limit,
928            expected_limit,
929            key_extractor,
930            use_default_ip_fast_path: true,
931        })
932    }
933
934    /// Initializes the global [`RateLimitPlugin`] with custom [`RateLimitStore`] and [`KeyExtractor`].
935    ///
936    /// # Arguments
937    ///
938    /// - `RateLimitPolicy` - Quota header and exempt-path policy.
939    /// - `Arc<dyn RateLimitStore>` - Custom or distributed backend store.
940    /// - `Arc<dyn KeyExtractor>` - Custom partition key extractor.
941    ///
942    /// # Returns
943    ///
944    /// - `&'static Self` - Reference to the initialized global plugin.
945    pub fn init_custom(
946        policy: RateLimitPolicy,
947        store: Arc<dyn RateLimitStore>,
948        key_extractor: Arc<dyn KeyExtractor>,
949    ) -> &'static Self {
950        let expected_limit: u64 = match policy.get_algorithm() {
951            RateLimitAlgorithm::Gcra => policy.get_burst().max(1),
952            RateLimitAlgorithm::FixedWindow => policy.get_requests_per_window().max(1),
953        };
954        let preformatted_limit: String = expected_limit.to_string();
955        RATE_LIMIT_PLUGIN.get_or_init(|| Self {
956            policy,
957            store,
958            fast_store: None,
959            preformatted_limit,
960            expected_limit,
961            key_extractor,
962            use_default_ip_fast_path: false,
963        })
964    }
965
966    /// Returns the initialized global [`RateLimitPlugin`], if initialized.
967    ///
968    /// # Returns
969    ///
970    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
971    pub fn get() -> Option<&'static Self> {
972        RATE_LIMIT_PLUGIN.get()
973    }
974
975    /// Returns the active [`RateLimitPolicy`].
976    ///
977    /// # Returns
978    ///
979    /// - `&RateLimitPolicy` - Active policy.
980    pub fn get_policy(&self) -> &RateLimitPolicy {
981        let Self { policy, .. } = self;
982        policy
983    }
984
985    /// Returns the active [`Arc<dyn RateLimitStore>`].
986    ///
987    /// # Returns
988    ///
989    /// - `&Arc<dyn RateLimitStore>` - Active backend store.
990    pub fn get_store(&self) -> &Arc<dyn RateLimitStore> {
991        let Self { store, .. } = self;
992        store
993    }
994
995    /// Returns the active [`Arc<dyn KeyExtractor>`].
996    ///
997    /// # Returns
998    ///
999    /// - `&Arc<dyn KeyExtractor>` - Active key extractor.
1000    pub fn get_key_extractor(&self) -> &Arc<dyn KeyExtractor> {
1001        let Self { key_extractor, .. } = self;
1002        key_extractor
1003    }
1004
1005    /// Reports whether the zero-allocation default peer-IP fast path is enabled.
1006    ///
1007    /// # Returns
1008    ///
1009    /// - `bool` - `true` when initialized with the default [`ClientIpKeyExtractor`].
1010    #[inline]
1011    pub(crate) fn is_default_ip_fast_path(&self) -> bool {
1012        let Self {
1013            use_default_ip_fast_path,
1014            ..
1015        } = self;
1016        *use_default_ip_fast_path
1017    }
1018
1019    /// Evaluates one request against `key` and attaches standard `RateLimit-*` response headers.
1020    ///
1021    /// # Arguments
1022    ///
1023    /// - `&str` - Partition key.
1024    /// - `&mut Context` - Request and response context.
1025    ///
1026    /// # Returns
1027    ///
1028    /// - `RateLimitDecision` - Quota decision for this request.
1029    #[inline]
1030    pub fn evaluate_key(&self, key: &str, ctx: &mut Context) -> RateLimitDecision {
1031        let Self {
1032            policy,
1033            store,
1034            fast_store,
1035            preformatted_limit,
1036            expected_limit,
1037            ..
1038        } = self;
1039        let decision: RateLimitDecision = match fast_store {
1040            Some(limiter) => limiter.check_direct(key),
1041            None => store.check(key),
1042        };
1043        let response: &mut Response = ctx.get_mut_response();
1044        if policy.get_include_headers() {
1045            let mut limit_buf: [u8; U64_STACK_BUF_LEN] = [0u8; U64_STACK_BUF_LEN];
1046            let mut rem_buf: [u8; U64_STACK_BUF_LEN] = [0u8; U64_STACK_BUF_LEN];
1047            let mut reset_buf: [u8; U64_STACK_BUF_LEN] = [0u8; U64_STACK_BUF_LEN];
1048            let limit_str: &str = if decision.get_limit() == *expected_limit {
1049                preformatted_limit.as_str()
1050            } else {
1051                format_u64_stack(decision.get_limit(), &mut limit_buf)
1052            };
1053            let rem_str: &str = format_u64_stack(decision.get_remaining(), &mut rem_buf);
1054            let reset_str: &str = format_u64_stack(decision.get_reset_after_secs(), &mut reset_buf);
1055            response
1056                .set_header(HEADER_RATE_LIMIT_LIMIT, limit_str)
1057                .set_header(HEADER_RATE_LIMIT_REMAINING, rem_str)
1058                .set_header(HEADER_RATE_LIMIT_RESET, reset_str);
1059        }
1060        if !decision.get_allowed() {
1061            let mut retry_buf: [u8; U64_STACK_BUF_LEN] = [0u8; U64_STACK_BUF_LEN];
1062            let retry_str: &str = format_u64_stack(decision.get_retry_after_secs(), &mut retry_buf);
1063            response
1064                .set_status_code(HttpStatus::TooManyRequests.code())
1065                .set_header(RETRY_AFTER, retry_str)
1066                .set_body(EMPTY_STR);
1067        }
1068        decision
1069    }
1070}
1071
1072/// Implements [`ServerHook`] for [`RateLimitHook`].
1073impl ServerHook for RateLimitHook {
1074    /// Constructs a per-request [`RateLimitHook`].
1075    ///
1076    /// # Arguments
1077    ///
1078    /// - `&mut Stream` - Connection stream.
1079    /// - `&mut Context` - Request context.
1080    ///
1081    /// # Returns
1082    ///
1083    /// - `Self` - Hook instance.
1084    async fn new(_: &mut Stream, _: &mut Context) -> Self {
1085        Self
1086    }
1087
1088    /// Enforces the configured rate limit and rejects excess traffic with `429 Too Many Requests`.
1089    ///
1090    /// # Arguments
1091    ///
1092    /// - `Self` - Hook instance.
1093    /// - `&mut Stream` - Connection stream.
1094    /// - `&mut Context` - Request context.
1095    ///
1096    /// # Returns
1097    ///
1098    /// - `Status` - `Status::Continue` when unconfigured, exempt, or admitted; `Status::Reject` when throttled.
1099    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
1100        let Some(plugin) = RateLimitPlugin::get() else {
1101            return Status::Continue;
1102        };
1103        let exempt_paths: &Vec<String> = plugin.get_policy().get_exempt_paths();
1104        if !exempt_paths.is_empty() {
1105            let path: &str = ctx.get_request().get_path();
1106            if exempt_paths.iter().any(|exempt: &String| exempt == path) {
1107                return Status::Continue;
1108            }
1109        }
1110        let decision: RateLimitDecision = if plugin.is_default_ip_fast_path() {
1111            let mut ip_buf: [u8; IP_STACK_BUF_LEN] = [0u8; IP_STACK_BUF_LEN];
1112            let peer_key: &str = if let Ok(addr) = stream.get_peer_addr() {
1113                format_ip_stack(addr.ip(), &mut ip_buf)
1114            } else {
1115                FALLBACK_CLIENT_KEY
1116            };
1117            plugin.evaluate_key(peer_key, ctx)
1118        } else {
1119            let key: String = plugin.get_key_extractor().extract(stream, ctx);
1120            plugin.evaluate_key(&key, ctx)
1121        };
1122        if decision.get_allowed() {
1123            return Status::Continue;
1124        }
1125        let _: Result<(), ResponseError> = ctx.try_send_response(stream).await;
1126        Status::Reject
1127    }
1128}