rok-rate-limit 0.3.0

Rate limiting Tower middleware and programmatic Limiter API for the rok ecosystem
Documentation
//! Rate limiting for the rok ecosystem.
//!
//! # Programmatic API
//!
//! ```rust,ignore
//! use rok_rate_limit::{Limiter, LimitResult};
//!
//! let limiter = Limiter::memory();
//!
//! let result = limiter
//!     .for_key("user:alice")
//!     .requests(100)
//!     .per(std::time::Duration::from_secs(60))
//!     .check();
//!
//! match result {
//!     LimitResult::Allowed { remaining, reset_epoch } => { /* proceed */ }
//!     LimitResult::Exceeded { retry_after_secs }      => { /* return 429 */ }
//! }
//! ```
//!
//! # Tower Middleware
//!
//! ```rust,ignore
//! use rok_rate_limit::ThrottleLayer;
//!
//! let app = Router::new()
//!     .route("/api/posts", get(list_posts))
//!     .layer(ThrottleLayer::by_ip("api", 100, 60)); // 100 req/min per IP
//! ```

pub mod backend;
pub mod fixed;
pub mod limiter;

#[cfg(feature = "axum")]
pub mod layer;

pub use fixed::{parse_duration, FixedRateLimiter, FIXED_LIMITER};
pub use limiter::{LimitBuilder, LimitResult, Limiter};

#[cfg(feature = "axum")]
pub use layer::{ThrottleLayer, ThrottleRule};

use std::sync::OnceLock;

static GLOBAL_LIMITER: OnceLock<Limiter> = OnceLock::new();

/// Return the process-global [`Limiter`] instance (memory-backed).
///
/// Used by the `#[throttle]` proc-macro and `ThrottleLayer::global()` /
/// `ThrottleLayer::by_ip()` factory methods.
pub fn global_limiter() -> &'static Limiter {
    GLOBAL_LIMITER.get_or_init(Limiter::memory)
}