Skip to main content

rok_rate_limit/
lib.rs

1//! Rate limiting for the rok ecosystem.
2//!
3//! # Programmatic API
4//!
5//! ```rust,ignore
6//! use rok_rate_limit::{Limiter, LimitResult};
7//!
8//! let limiter = Limiter::memory();
9//!
10//! let result = limiter
11//!     .for_key("user:alice")
12//!     .requests(100)
13//!     .per(std::time::Duration::from_secs(60))
14//!     .check();
15//!
16//! match result {
17//!     LimitResult::Allowed { remaining, reset_epoch } => { /* proceed */ }
18//!     LimitResult::Exceeded { retry_after_secs }      => { /* return 429 */ }
19//! }
20//! ```
21//!
22//! # Tower Middleware
23//!
24//! ```rust,ignore
25//! use rok_rate_limit::ThrottleLayer;
26//!
27//! let app = Router::new()
28//!     .route("/api/posts", get(list_posts))
29//!     .layer(ThrottleLayer::by_ip("api", 100, 60)); // 100 req/min per IP
30//! ```
31
32pub mod backend;
33pub mod fixed;
34pub mod limiter;
35
36#[cfg(feature = "axum")]
37pub mod layer;
38
39pub use fixed::{parse_duration, FixedRateLimiter, FIXED_LIMITER};
40pub use limiter::{LimitBuilder, LimitResult, Limiter};
41
42#[cfg(feature = "axum")]
43pub use layer::{ThrottleLayer, ThrottleRule};
44
45use std::sync::OnceLock;
46
47static GLOBAL_LIMITER: OnceLock<Limiter> = OnceLock::new();
48
49/// Return the process-global [`Limiter`] instance (memory-backed).
50///
51/// Used by the `#[throttle]` proc-macro and `ThrottleLayer::global()` /
52/// `ThrottleLayer::by_ip()` factory methods.
53pub fn global_limiter() -> &'static Limiter {
54    GLOBAL_LIMITER.get_or_init(Limiter::memory)
55}