token-bucket 10.11.0

Zero-dependency, lock-free atomic GCRA, Fixed-Window, Token-Bucket, and 64-way sharded bounded keyed rate-limiting engine.
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
use super::*;

/// Policy dispatch helpers for `RateLimitPolicy`.
impl RateLimitPolicy {
    /// Returns the configured burst or per-window limit of this policy.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The rate-limit policy.
    ///
    /// # Returns
    ///
    /// - `u64` - Configured burst or window limit.
    #[inline(always)]
    pub fn limit(&self) -> u64 {
        match self {
            Self::Gcra(cfg) => cfg.get_burst(),
            Self::FixedWindow(cfg) => cfg.get_limit(),
            Self::TokenBucket(cfg) => cfg.get_capacity(),
        }
    }

    /// Returns the initial raw `u64` atomic word for a brand-new key at `now_ns`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The rate-limit policy.
    /// - `u64` - Current monotonic timestamp in nanoseconds.
    ///
    /// # Returns
    ///
    /// - `u64` - Initial packed atomic state word.
    #[inline(always)]
    pub(crate) fn initial_state_at_ns(&self, now_ns: u64) -> u64 {
        match self {
            Self::Gcra(_) => 0,
            Self::FixedWindow(_) => 0,
            Self::TokenBucket(cfg) => {
                let step_low: u64 = (now_ns / cfg.get_step_ns()) & cfg.get_step_mask();
                (step_low << cfg.get_token_bits()) | cfg.get_capacity()
            }
        }
    }

    /// Checks whether a key entry's atomic state is currently idle at `now_ns`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The rate-limit policy.
    /// - `&AtomicU64` - Per-key atomic state storage.
    /// - `u64` - Current monotonic timestamp in nanoseconds.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the key has zero active debt or usage.
    #[inline(always)]
    pub(crate) fn is_idle_atomic(&self, atomic: &AtomicU64, now_ns: u64) -> bool {
        match self {
            Self::Gcra(_) => GcraCell::is_idle_atomic(atomic, now_ns),
            Self::FixedWindow(cfg) => FixedWindowCell::is_idle_atomic(atomic, cfg, now_ns),
            Self::TokenBucket(cfg) => TokenBucketCell::is_idle_atomic(atomic, cfg, now_ns),
        }
    }

    /// Performs a non-mutating availability probe on an existing key's atomic state.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The rate-limit policy.
    /// - `&AtomicU64` - Per-key atomic state storage.
    /// - `u64` - Current monotonic timestamp in nanoseconds.
    ///
    /// # Returns
    ///
    /// - `RateLimitDecision` - Availability snapshot.
    #[inline(always)]
    pub(crate) fn peek_atomic(&self, atomic: &AtomicU64, now_ns: u64) -> RateLimitDecision {
        match self {
            Self::Gcra(cfg) => GcraCell::peek_atomic(atomic, cfg, now_ns),
            Self::FixedWindow(cfg) => FixedWindowCell::peek_atomic(atomic, cfg, now_ns),
            Self::TokenBucket(cfg) => TokenBucketCell::peek_atomic(atomic, cfg, now_ns),
        }
    }

    /// Returns a fresh availability snapshot for an unseen key at `now_ns`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The rate-limit policy.
    /// - `u64` - Current monotonic timestamp in nanoseconds.
    ///
    /// # Returns
    ///
    /// - `RateLimitDecision` - Full-quota decision snapshot.
    #[inline(always)]
    pub(crate) fn peek_absent_at_ns(&self, now_ns: u64) -> RateLimitDecision {
        match self {
            Self::Gcra(cfg) => RateLimitDecision::new(true, cfg.get_burst(), 0, 0, cfg.get_burst()),
            Self::FixedWindow(cfg) => {
                let win_idx: u64 = now_ns / cfg.get_window_ns();
                let reset_ns: u64 = FixedWindowCell::window_remaining_ns(cfg, win_idx, now_ns);
                RateLimitDecision::new(true, cfg.get_limit(), reset_ns, 0, cfg.get_limit())
            }
            Self::TokenBucket(cfg) => {
                RateLimitDecision::new(true, cfg.get_capacity(), 0, 0, cfg.get_capacity())
            }
        }
    }

    /// Executes the lock-free atomic check-and-consume transition for `cost` units.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The rate-limit policy.
    /// - `&AtomicU64` - Per-key atomic state storage.
    /// - `u64` - Current monotonic timestamp in nanoseconds.
    /// - `u64` - Number of quota units to consume.
    ///
    /// # Returns
    ///
    /// - `RateLimitDecision` - Admission decision and nanosecond timings.
    #[inline(always)]
    pub(crate) fn check_n_atomic(
        &self,
        atomic: &AtomicU64,
        now_ns: u64,
        cost: u64,
    ) -> RateLimitDecision {
        match self {
            Self::Gcra(cfg) => GcraCell::check_n_atomic(atomic, cfg, now_ns, cost),
            Self::FixedWindow(cfg) => FixedWindowCell::check_n_atomic(atomic, cfg, now_ns, cost),
            Self::TokenBucket(cfg) => TokenBucketCell::check_n_atomic(atomic, cfg, now_ns, cost),
        }
    }
}

/// Converts a `GcraConfig` into `RateLimitPolicy::Gcra`.
impl From<GcraConfig> for RateLimitPolicy {
    /// Wraps a `GcraConfig` into `RateLimitPolicy`.
    ///
    /// # Arguments
    ///
    /// - `GcraConfig` - GCRA configuration.
    #[inline(always)]
    fn from(config: GcraConfig) -> Self {
        Self::Gcra(config)
    }
}

/// Converts a `FixedWindowConfig` into `RateLimitPolicy::FixedWindow`.
impl From<FixedWindowConfig> for RateLimitPolicy {
    /// Wraps a `FixedWindowConfig` into `RateLimitPolicy`.
    ///
    /// # Arguments
    ///
    /// - `FixedWindowConfig` - Fixed-window configuration.
    #[inline(always)]
    fn from(config: FixedWindowConfig) -> Self {
        Self::FixedWindow(config)
    }
}

/// Converts a `TokenBucketConfig` into `RateLimitPolicy::TokenBucket`.
impl From<TokenBucketConfig> for RateLimitPolicy {
    /// Wraps a `TokenBucketConfig` into `RateLimitPolicy`.
    ///
    /// # Arguments
    ///
    /// - `TokenBucketConfig` - Token-bucket configuration.
    #[inline(always)]
    fn from(config: TokenBucketConfig) -> Self {
        Self::TokenBucket(config)
    }
}

/// Accessors and timestamp helpers for `KeyEntry`.
impl KeyEntry {
    /// Creates a new `KeyEntry` initialized with raw atomic `state` and `now_ns`.
    ///
    /// # Arguments
    ///
    /// - `u64` - Initial algorithm-specific atomic state word.
    /// - `u64` - Initial access timestamp in nanoseconds.
    #[inline(always)]
    pub(crate) fn new(state: u64, now_ns: u64) -> Self {
        Self {
            state: AtomicU64::new(state),
            last_seen_ns: AtomicU64::new(now_ns),
        }
    }

    /// Returns a reference to the algorithm-specific atomic state word.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The key entry.
    ///
    /// # Returns
    ///
    /// - `&AtomicU64` - Reference to the atomic state word.
    #[inline(always)]
    pub(crate) fn get_state(&self) -> &AtomicU64 {
        &self.state
    }

    /// Returns a reference to the atomic last-seen timestamp.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The key entry.
    ///
    /// # Returns
    ///
    /// - `&AtomicU64` - Reference to the last-seen atomic timestamp.
    #[inline(always)]
    pub(crate) fn get_last_seen_ns(&self) -> &AtomicU64 {
        &self.last_seen_ns
    }

    /// Records the latest access timestamp without memory-ordering fence overhead.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The key entry.
    /// - `u64` - Current monotonic timestamp in nanoseconds.
    #[inline(always)]
    pub(crate) fn touch(&self, now_ns: u64) {
        self.get_last_seen_ns().store(now_ns, Ordering::Relaxed);
    }

    /// Loads the recorded last-seen timestamp in nanoseconds.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The key entry.
    ///
    /// # Returns
    ///
    /// - `u64` - Last-seen monotonic timestamp in nanoseconds.
    #[inline(always)]
    pub(crate) fn load_last_seen_ns(&self) -> u64 {
        self.get_last_seen_ns().load(Ordering::Relaxed)
    }
}

/// Partition accessors for `KeyedShard`.
impl<K> KeyedShard<K> {
    /// Creates an empty shard backed by `FastBuildHasher`.
    ///
    /// # Arguments
    ///
    /// - `FastBuildHasher` - Seeded fast hasher for the shard map.
    #[inline(always)]
    pub(crate) fn new(hasher: FastBuildHasher) -> Self {
        Self {
            map: RwLock::new(HashMap::with_hasher(hasher)),
        }
    }

    /// Returns a reference to the shard `RwLock`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The shard instance.
    ///
    /// # Returns
    ///
    /// - `&RwLock<HashMap<K, KeyEntry, FastBuildHasher>>` - Reference to the shard lock.
    #[inline(always)]
    pub(crate) fn get_map(&self) -> &RwLock<HashMap<K, KeyEntry, FastBuildHasher>> {
        &self.map
    }

    /// Acquires a shared read guard on the shard map, recovering cleanly if poisoned.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The shard instance.
    ///
    /// # Returns
    ///
    /// - `RwLockReadGuard<'_, HashMap<K, KeyEntry, FastBuildHasher>>` - Read guard.
    #[inline(always)]
    pub(crate) fn read_map(&self) -> RwLockReadGuard<'_, HashMap<K, KeyEntry, FastBuildHasher>> {
        match self.get_map().read() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        }
    }

    /// Acquires an exclusive write guard on the shard map, recovering cleanly if poisoned.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The shard instance.
    ///
    /// # Returns
    ///
    /// - `RwLockWriteGuard<'_, HashMap<K, KeyEntry, FastBuildHasher>>` - Write guard.
    #[inline(always)]
    pub(crate) fn write_map(&self) -> RwLockWriteGuard<'_, HashMap<K, KeyEntry, FastBuildHasher>> {
        match self.get_map().write() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        }
    }
}

/// Core 64-way sharded bounded rate-limiting operations for `KeyedRateLimiter`.
impl<K> KeyedRateLimiter<K>
where
    K: Eq + Hash,
{
    /// Creates a 64-way sharded bounded `KeyedRateLimiter` for the given `policy` and `max_entries`.
    ///
    /// # Arguments
    ///
    /// - `RateLimitPolicy` - Rate-limiting policy applied per key.
    /// - `usize` - Target maximum key capacity (`>= 1`).
    ///
    /// # Returns
    ///
    /// - `Result<Self, RateLimitError>` - Constructed limiter or `ZeroCapacity`.
    pub fn new(policy: RateLimitPolicy, max_entries: usize) -> Result<Self, RateLimitError> {
        Self::with_clock(policy, max_entries, MonotonicClock::new())
    }

    /// Creates a 64-way sharded bounded `KeyedRateLimiter` anchored at `clock`.
    ///
    /// # Arguments
    ///
    /// - `RateLimitPolicy` - Rate-limiting policy applied per key.
    /// - `usize` - Target maximum key capacity (`>= 1`).
    /// - `MonotonicClock` - Monotonic clock origin.
    ///
    /// # Returns
    ///
    /// - `Result<Self, RateLimitError>` - Constructed limiter or `ZeroCapacity`.
    pub fn with_clock(
        policy: RateLimitPolicy,
        max_entries: usize,
        clock: MonotonicClock,
    ) -> Result<Self, RateLimitError> {
        if max_entries == 0 {
            return Err(RateLimitError::ZeroCapacity);
        }
        let per_shard_capacity: usize = max_entries.div_ceil(KEYED_SHARD_COUNT).max(1);
        let addr_entropy: u64 = (&policy as *const RateLimitPolicy) as usize as u64;
        let time_entropy: u64 = clock.now_ns();
        let hasher: FastBuildHasher =
            FastBuildHasher::new(addr_entropy ^ time_entropy.wrapping_mul(SEED_MIX_SALT));
        let mut shard_vec: Vec<KeyedShard<K>> = Vec::with_capacity(KEYED_SHARD_COUNT);
        let mut idx: usize = 0;
        while idx < KEYED_SHARD_COUNT {
            shard_vec.push(KeyedShard::new(hasher));
            idx += 1;
        }
        Ok(Self {
            policy,
            clock,
            hasher,
            max_entries,
            per_shard_capacity,
            shards: shard_vec.into_boxed_slice(),
        })
    }

    /// Returns the configured rate-limiting policy.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The keyed limiter.
    ///
    /// # Returns
    ///
    /// - `RateLimitPolicy` - Copy of the active policy.
    #[inline(always)]
    pub fn get_policy(&self) -> RateLimitPolicy {
        self.policy
    }

    /// Returns the embedded monotonic clock.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The keyed limiter.
    ///
    /// # Returns
    ///
    /// - `&MonotonicClock` - Reference to the clock.
    #[inline(always)]
    pub fn get_clock(&self) -> &MonotonicClock {
        &self.clock
    }

    /// Returns the seeded internal hasher.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The keyed limiter.
    ///
    /// # Returns
    ///
    /// - `&FastBuildHasher` - Reference to the build hasher.
    #[inline(always)]
    pub(crate) fn get_hasher(&self) -> &FastBuildHasher {
        &self.hasher
    }

    /// Returns the caller-requested target entry capacity.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The keyed limiter.
    ///
    /// # Returns
    ///
    /// - `usize` - Requested maximum entries.
    #[inline(always)]
    pub fn get_max_entries(&self) -> usize {
        self.max_entries
    }

    /// Returns the hard entry capacity enforced per shard.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The keyed limiter.
    ///
    /// # Returns
    ///
    /// - `usize` - Maximum entries per shard.
    #[inline(always)]
    pub fn get_per_shard_capacity(&self) -> usize {
        self.per_shard_capacity
    }

    /// Returns the effective upper bound across all 64 shards (`64 * per_shard_capacity`).
    ///
    /// # Arguments
    ///
    /// - `&Self` - The keyed limiter.
    ///
    /// # Returns
    ///
    /// - `usize` - Total hard bound across all shards.
    #[inline(always)]
    pub fn effective_capacity(&self) -> usize {
        KEYED_SHARD_COUNT.saturating_mul(self.get_per_shard_capacity())
    }

    /// Returns the slice of 64 shards.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The keyed limiter.
    ///
    /// # Returns
    ///
    /// - `&[KeyedShard<K>]` - Shard slice.
    #[inline(always)]
    pub(crate) fn get_shards(&self) -> &[KeyedShard<K>] {
        &self.shards
    }

    /// Computes the shard index in `0..64` for `key`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The keyed limiter.
    /// - `&Q` - Borrowed key reference.
    ///
    /// # Returns
    ///
    /// - `usize` - Shard index in `0..64`.
    #[inline(always)]
    pub(crate) fn shard_index<Q>(&self, key: &Q) -> usize
    where
        K: Borrow<Q>,
        Q: Eq + Hash + ?Sized,
    {
        let hash: u64 = self.get_hasher().hash_value(key);
        ((hash >> KEYED_SHARD_SHIFT) as usize) & KEYED_SHARD_MASK
    }

    /// Checks and consumes 1 unit for `key` using the embedded monotonic clock.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The keyed limiter.
    /// - `&Q` - Borrowed key reference (zero allocation on existing keys).
    ///
    /// # Returns
    ///
    /// - `RateLimitDecision` - Admission decision and nanosecond timings.
    #[inline(always)]
    pub fn check<Q>(&self, key: &Q) -> RateLimitDecision
    where
        K: Borrow<Q>,
        Q: Eq + Hash + ToOwned<Owned = K> + ?Sized,
    {
        self.check_n_at_ns(key, self.get_clock().now_ns(), 1)
    }

    /// Checks and consumes `cost` units for `key` using the embedded monotonic clock.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The keyed limiter.
    /// - `&Q` - Borrowed key reference (zero allocation on existing keys).
    /// - `u64` - Number of quota units to consume.
    ///
    /// # Returns
    ///
    /// - `RateLimitDecision` - Admission decision and nanosecond timings.
    #[inline(always)]
    pub fn check_n<Q>(&self, key: &Q, cost: u64) -> RateLimitDecision
    where
        K: Borrow<Q>,
        Q: Eq + Hash + ToOwned<Owned = K> + ?Sized,
    {
        self.check_n_at_ns(key, self.get_clock().now_ns(), cost)
    }

    /// Checks and consumes 1 unit for `key` at an explicit monotonic timestamp.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The keyed limiter.
    /// - `&Q` - Borrowed key reference.
    /// - `u64` - Monotonic timestamp in nanoseconds.
    ///
    /// # Returns
    ///
    /// - `RateLimitDecision` - Admission decision and nanosecond timings.
    #[inline(always)]
    pub fn check_at_ns<Q>(&self, key: &Q, now_ns: u64) -> RateLimitDecision
    where
        K: Borrow<Q>,
        Q: Eq + Hash + ToOwned<Owned = K> + ?Sized,
    {
        self.check_n_at_ns(key, now_ns, 1)
    }

    /// Checks and consumes `cost` units for `key` at an explicit monotonic timestamp.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The keyed limiter.
    /// - `&Q` - Borrowed key reference (zero allocation on existing keys).
    /// - `u64` - Monotonic timestamp in nanoseconds.
    /// - `u64` - Number of quota units to consume.
    ///
    /// # Returns
    ///
    /// - `RateLimitDecision` - Admission decision and nanosecond timings.
    pub fn check_n_at_ns<Q>(&self, key: &Q, now_ns: u64, cost: u64) -> RateLimitDecision
    where
        K: Borrow<Q>,
        Q: Eq + Hash + ToOwned<Owned = K> + ?Sized,
    {
        let policy: RateLimitPolicy = self.get_policy();
        let shard: &KeyedShard<K> = &self.get_shards()[self.shard_index(key)];
        {
            let guard: RwLockReadGuard<'_, HashMap<K, KeyEntry, FastBuildHasher>> =
                shard.read_map();
            if let Some(entry) = guard.get(key) {
                entry.touch(now_ns);
                return policy.check_n_atomic(entry.get_state(), now_ns, cost);
            }
        }
        let mut guard: RwLockWriteGuard<'_, HashMap<K, KeyEntry, FastBuildHasher>> =
            shard.write_map();
        if let Some(entry) = guard.get(key) {
            entry.touch(now_ns);
            return policy.check_n_atomic(entry.get_state(), now_ns, cost);
        }
        let cap: usize = self.get_per_shard_capacity();
        if guard.len() >= cap {
            guard.retain(|_: &K, entry: &mut KeyEntry| {
                !policy.is_idle_atomic(entry.get_state(), now_ns)
            });
            if guard.len() >= cap {
                let oldest_key: Option<K> = guard
                    .iter()
                    .min_by_key(|(_, entry): &(&K, &KeyEntry)| entry.load_last_seen_ns())
                    .map(|(k, _): (&K, &KeyEntry)| k.borrow().to_owned());
                if let Some(evict_key) = oldest_key {
                    let _: Option<KeyEntry> = guard.remove(evict_key.borrow());
                }
            }
        }
        let entry: KeyEntry = KeyEntry::new(policy.initial_state_at_ns(now_ns), now_ns);
        let decision: RateLimitDecision = policy.check_n_atomic(entry.get_state(), now_ns, cost);
        let _: Option<KeyEntry> = guard.insert(key.to_owned(), entry);
        decision
    }

    /// Inspects availability for `key` using the embedded clock without mutating or inserting state.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The keyed limiter.
    /// - `&Q` - Borrowed key reference.
    ///
    /// # Returns
    ///
    /// - `RateLimitDecision` - Non-mutating availability snapshot.
    #[inline(always)]
    pub fn peek<Q>(&self, key: &Q) -> RateLimitDecision
    where
        K: Borrow<Q>,
        Q: Eq + Hash + ?Sized,
    {
        self.peek_at_ns(key, self.get_clock().now_ns())
    }

    /// Inspects availability for `key` at `now_ns` without mutating or inserting state.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The keyed limiter.
    /// - `&Q` - Borrowed key reference.
    /// - `u64` - Monotonic timestamp in nanoseconds.
    ///
    /// # Returns
    ///
    /// - `RateLimitDecision` - Non-mutating availability snapshot.
    #[inline(always)]
    pub fn peek_at_ns<Q>(&self, key: &Q, now_ns: u64) -> RateLimitDecision
    where
        K: Borrow<Q>,
        Q: Eq + Hash + ?Sized,
    {
        let policy: RateLimitPolicy = self.get_policy();
        let shard: &KeyedShard<K> = &self.get_shards()[self.shard_index(key)];
        let guard: RwLockReadGuard<'_, HashMap<K, KeyEntry, FastBuildHasher>> = shard.read_map();
        match guard.get(key) {
            Some(entry) => policy.peek_atomic(entry.get_state(), now_ns),
            None => policy.peek_absent_at_ns(now_ns),
        }
    }

    /// Removes `key` from its shard if present.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The keyed limiter.
    /// - `&Q` - Borrowed key reference.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if the key existed and was removed.
    pub fn remove<Q>(&self, key: &Q) -> bool
    where
        K: Borrow<Q>,
        Q: Eq + Hash + ?Sized,
    {
        let shard: &KeyedShard<K> = &self.get_shards()[self.shard_index(key)];
        let mut guard: RwLockWriteGuard<'_, HashMap<K, KeyEntry, FastBuildHasher>> =
            shard.write_map();
        guard.remove(key).is_some()
    }

    /// Evicts all currently idle entries across all 64 shards using the embedded monotonic clock.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The keyed limiter.
    ///
    /// # Returns
    ///
    /// - `usize` - Total number of evicted keys.
    pub fn evict_idle(&self) -> usize {
        self.evict_idle_at_ns(self.get_clock().now_ns())
    }

    /// Evicts all idle entries across all 64 shards at an explicit monotonic timestamp.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The keyed limiter.
    /// - `u64` - Monotonic timestamp in nanoseconds.
    ///
    /// # Returns
    ///
    /// - `usize` - Total number of evicted keys.
    pub fn evict_idle_at_ns(&self, now_ns: u64) -> usize {
        let policy: RateLimitPolicy = self.get_policy();
        let mut removed: usize = 0;
        for shard in self.get_shards() {
            let mut guard: RwLockWriteGuard<'_, HashMap<K, KeyEntry, FastBuildHasher>> =
                shard.write_map();
            let before: usize = guard.len();
            guard.retain(|_: &K, entry: &mut KeyEntry| {
                !policy.is_idle_atomic(entry.get_state(), now_ns)
            });
            removed += before - guard.len();
        }
        removed
    }

    /// Clears all tracked keys across all 64 shards.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The keyed limiter.
    pub fn clear(&self) {
        for shard in self.get_shards() {
            let mut guard: RwLockWriteGuard<'_, HashMap<K, KeyEntry, FastBuildHasher>> =
                shard.write_map();
            guard.clear();
        }
    }

    /// Returns the total number of tracked keys currently stored across all 64 shards.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The keyed limiter.
    ///
    /// # Returns
    ///
    /// - `usize` - Approximate total entry count across shards.
    pub fn len(&self) -> usize {
        let mut total: usize = 0;
        for shard in self.get_shards() {
            let guard: RwLockReadGuard<'_, HashMap<K, KeyEntry, FastBuildHasher>> =
                shard.read_map();
            total += guard.len();
        }
        total
    }

    /// Returns `true` if no keys are currently tracked across any shard.
    ///
    /// # Arguments
    ///
    /// - `&Self` - The keyed limiter.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when every shard is empty.
    pub fn is_empty(&self) -> bool {
        for shard in self.get_shards() {
            let guard: RwLockReadGuard<'_, HashMap<K, KeyEntry, FastBuildHasher>> =
                shard.read_map();
            if !guard.is_empty() {
                return false;
            }
        }
        true
    }
}