token-bucket 11.2.0

Zero-dependency, lock-free atomic GCRA, Fixed-Window, Token-Bucket, and 64-way sharded bounded keyed rate-limiting engine.
Documentation
use super::*;

/// Compact 16-byte per-key atomic state stored inside a `KeyedRateLimiter` shard.
#[derive(Debug)]
pub(crate) struct KeyEntry {
    /// Algorithm-specific lock-free atomic state word.
    pub(crate) state: AtomicU64,
    /// Last monotonic access timestamp in nanoseconds for bounded LRU eviction.
    pub(crate) last_seen_ns: AtomicU64,
}

/// Occupied entry stored inside a single `ShardMap` bucket.
#[derive(Debug)]
pub(crate) struct ShardSlot<K> {
    /// Precomputed 64-bit hash of `key` avoiding redundant re-hashing on probe or rehash.
    pub(crate) hash: u64,
    /// Owned key value.
    pub(crate) key: K,
    /// Per-key atomic rate-limit state and LRU timestamp.
    pub(crate) entry: KeyEntry,
}

/// Zero-dependency open-addressing shard map keyed by precomputed 64-bit hash and `K`.
#[derive(Debug)]
pub(crate) struct ShardMap<K> {
    /// 1-byte per-slot control metadata (`0` empty, `1` tombstone, `0x80|h2` occupied).
    pub(crate) ctrl: Vec<u8>,
    /// Parallel slot storage holding occupied `(hash, key, entry)` records.
    pub(crate) slots: Vec<Option<ShardSlot<K>>>,
    /// Number of live keys stored in the table.
    pub(crate) len: usize,
    /// Number of tombstone markers currently present in `ctrl`.
    pub(crate) tombstones: usize,
}

/// Cache-line-isolated per-thread reader counter eliminating cross-core RWLock bouncing.
#[repr(align(128))]
#[derive(Debug)]
pub(crate) struct ReaderSlot {
    /// Active concurrent reader count for threads assigned to this cache line.
    pub(crate) readers: AtomicU32,
}

/// Asymmetric reader-zero-sharing RW lock paired with limiter-wide `ReaderSlot` counters.
pub(crate) struct ShardRwLock<T> {
    /// Exclusive writer flag (`0` unlocked, `1` writer active or draining readers).
    pub(crate) writer_flag: AtomicU32,
    /// Protected shard map storage.
    pub(crate) data: UnsafeCell<T>,
}

/// Panic-safe RAII shared read guard releasing its thread-local `ReaderSlot` on drop.
pub(crate) struct ShardReadGuard<'a, T> {
    /// Thread-local reader counter slot decremented on drop.
    pub(crate) slot: &'a ReaderSlot,
    /// Raw pointer to the protected shard map (avoids live `&T` aliasing across `Drop`).
    pub(crate) data: *const T,
}

/// Panic-safe RAII exclusive write guard clearing `writer_flag` on drop.
pub(crate) struct ShardWriteGuard<'a, T> {
    /// Parent shard lock released on drop.
    pub(crate) lock: &'a ShardRwLock<T>,
}

/// Cache-line-aligned shard protecting a partition of keyed rate-limit entries.
#[repr(align(128))]
#[derive(Debug)]
pub(crate) struct KeyedShard<K> {
    /// Read-mostly partition map protected by asymmetric `ShardRwLock`.
    pub(crate) map: ShardRwLock<ShardMap<K>>,
    /// Atomic live key count mirrored for O(1) empty-shard skipping during eviction and clear.
    pub(crate) count: AtomicUsize,
}

/// 64-way cache-line-aligned sharded, bounded, lock-free-CAS keyed rate limiter.
#[derive(Debug)]
pub struct KeyedRateLimiter<K> {
    /// Shared algorithm policy applied uniformly to all keys.
    pub(crate) policy: RateLimitPolicy,
    /// Monotonic nanosecond clock shared across all shards.
    pub(crate) clock: MonotonicClock,
    /// Seeded zero-dependency hasher shared across shard selection and maps.
    pub(crate) hasher: FastBuildHasher,
    /// Requested maximum key capacity across the limiter.
    pub(crate) max_entries: usize,
    /// Hard upper bound enforced per individual shard.
    pub(crate) per_shard_capacity: usize,
    /// Atomic total live entry counter across all shards for O(1) `len` / `is_empty`.
    pub(crate) total_len: AtomicUsize,
    /// Fixed array of 32 cache-line-isolated per-thread reader counters.
    pub(crate) reader_slots: Box<[ReaderSlot]>,
    /// Fixed array of 64 cache-line-aligned shards.
    pub(crate) shards: Box<[KeyedShard<K>]>,
}