touch_ratelimit 0.1.0

A composable, extensible rate limiting crate for Rust
Documentation
//! Rate limiting algorithms.
//!
//! This module defines the core abstraction for rate limiting algorithms
//! used by the crate.
//!
//! A rate limiter represents the state and logic required to enforce
//! limits for **a single identity** (e.g. one user or one IP).
//!
//! Higher-level components (stores and middleware) are responsible for
//! managing *multiple* rate limiters and mapping them to request keys.

pub mod token_bucket;

/// A rate limiting algorithm for a single identity.
///
/// Implementations of this trait encapsulate the logic required to decide
/// whether an action is allowed at a given point in time.
///
/// ## Important
///
/// - A `RateLimiter` instance is **not shared** across identities.
/// - Implementations are expected to be **stateful**.
/// - Concurrency control is handled by the store, not the limiter itself.
///
/// This trait is intentionally minimal so that different algorithms
/// (token bucket, sliding window, leaky bucket, etc.) can be implemented
/// interchangeably.
pub trait RateLimiter: Send + Sync + 'static {
    /// Attempt to consume a single unit.
    ///
    /// Returns `true` if the action is allowed, or `false` if the
    /// rate limit has been exceeded.
    fn allow(&mut self) -> bool;

    /// Attempt to consume `n` units.
    ///
    /// This allows algorithms to support weighted or batched requests.
    fn allow_n(&mut self, n: f64) -> bool;

    /// Return the number of tokens currently available.
    ///
    /// Implementations may perform internal state updates (e.g. refilling)
    /// before returning this value.
    fn available_tokens(&mut self) -> f64;
}