Skip to main content

token_bucket/keyed/
struct.rs

1use super::*;
2
3/// Compact 16-byte per-key atomic state stored inside a `KeyedRateLimiter` shard.
4#[derive(Debug)]
5pub(crate) struct KeyEntry {
6    /// Algorithm-specific lock-free atomic state word.
7    pub(crate) state: AtomicU64,
8    /// Last monotonic access timestamp in nanoseconds for bounded LRU eviction.
9    pub(crate) last_seen_ns: AtomicU64,
10}
11
12/// Occupied entry stored inside a single `ShardMap` bucket.
13#[derive(Debug)]
14pub(crate) struct ShardSlot<K> {
15    /// Precomputed 64-bit hash of `key` avoiding redundant re-hashing on probe or rehash.
16    pub(crate) hash: u64,
17    /// Owned key value.
18    pub(crate) key: K,
19    /// Per-key atomic rate-limit state and LRU timestamp.
20    pub(crate) entry: KeyEntry,
21}
22
23/// Zero-dependency open-addressing shard map keyed by precomputed 64-bit hash and `K`.
24#[derive(Debug)]
25pub(crate) struct ShardMap<K> {
26    /// 1-byte per-slot control metadata (`0` empty, `1` tombstone, `0x80|h2` occupied).
27    pub(crate) ctrl: Vec<u8>,
28    /// Parallel slot storage holding occupied `(hash, key, entry)` records.
29    pub(crate) slots: Vec<Option<ShardSlot<K>>>,
30    /// Number of live keys stored in the table.
31    pub(crate) len: usize,
32    /// Number of tombstone markers currently present in `ctrl`.
33    pub(crate) tombstones: usize,
34}
35
36/// Cache-line-isolated per-thread reader counter eliminating cross-core RWLock bouncing.
37#[repr(align(128))]
38#[derive(Debug)]
39pub(crate) struct ReaderSlot {
40    /// Active concurrent reader count for threads assigned to this cache line.
41    pub(crate) readers: AtomicU32,
42}
43
44/// Asymmetric reader-zero-sharing RW lock paired with limiter-wide `ReaderSlot` counters.
45pub(crate) struct ShardRwLock<T> {
46    /// Exclusive writer flag (`0` unlocked, `1` writer active or draining readers).
47    pub(crate) writer_flag: AtomicU32,
48    /// Protected shard map storage.
49    pub(crate) data: UnsafeCell<T>,
50}
51
52/// Panic-safe RAII shared read guard releasing its thread-local `ReaderSlot` on drop.
53pub(crate) struct ShardReadGuard<'a, T> {
54    /// Thread-local reader counter slot decremented on drop.
55    pub(crate) slot: &'a ReaderSlot,
56    /// Raw pointer to the protected shard map (avoids live `&T` aliasing across `Drop`).
57    pub(crate) data: *const T,
58}
59
60/// Panic-safe RAII exclusive write guard clearing `writer_flag` on drop.
61pub(crate) struct ShardWriteGuard<'a, T> {
62    /// Parent shard lock released on drop.
63    pub(crate) lock: &'a ShardRwLock<T>,
64}
65
66/// Cache-line-aligned shard protecting a partition of keyed rate-limit entries.
67#[repr(align(128))]
68#[derive(Debug)]
69pub(crate) struct KeyedShard<K> {
70    /// Read-mostly partition map protected by asymmetric `ShardRwLock`.
71    pub(crate) map: ShardRwLock<ShardMap<K>>,
72    /// Atomic live key count mirrored for O(1) empty-shard skipping during eviction and clear.
73    pub(crate) count: AtomicUsize,
74}
75
76/// 64-way cache-line-aligned sharded, bounded, lock-free-CAS keyed rate limiter.
77#[derive(Debug)]
78pub struct KeyedRateLimiter<K> {
79    /// Shared algorithm policy applied uniformly to all keys.
80    pub(crate) policy: RateLimitPolicy,
81    /// Monotonic nanosecond clock shared across all shards.
82    pub(crate) clock: MonotonicClock,
83    /// Seeded zero-dependency hasher shared across shard selection and maps.
84    pub(crate) hasher: FastBuildHasher,
85    /// Requested maximum key capacity across the limiter.
86    pub(crate) max_entries: usize,
87    /// Hard upper bound enforced per individual shard.
88    pub(crate) per_shard_capacity: usize,
89    /// Atomic total live entry counter across all shards for O(1) `len` / `is_empty`.
90    pub(crate) total_len: AtomicUsize,
91    /// Fixed array of 32 cache-line-isolated per-thread reader counters.
92    pub(crate) reader_slots: Box<[ReaderSlot]>,
93    /// Fixed array of 64 cache-line-aligned shards.
94    pub(crate) shards: Box<[KeyedShard<K>]>,
95}