pub struct RateLimiter { /* private fields */ }Expand description
A sliding-window per-key rate limiter.
Each call to RateLimiter::check records a timestamp for the given key
and returns true when the number of calls within the current window is
still below max_requests. Returns false once the limit is exceeded.
Thread-safe: the internal state is behind a Mutex so it can be shared
across threads via global or wrapped in an Arc.
§Example
use rust_web_server::rate_limit::RateLimiter;
let limiter = RateLimiter::new(100, 60); // 100 req / 60 s
if limiter.check("192.168.1.1") {
// process request
} else {
// return 429 Too Many Requests
}Implementations§
Source§impl RateLimiter
impl RateLimiter
Sourcepub fn new(max_requests: u32, window_secs: u64) -> Self
pub fn new(max_requests: u32, window_secs: u64) -> Self
Create a new limiter allowing max_requests per window_secs-second window.
Sourcepub fn set_limits(&self, max_requests: u32, window_secs: u64)
pub fn set_limits(&self, max_requests: u32, window_secs: u64)
Update the limits on a live limiter without restarting.
Changes take effect on the next call to [check] or [remaining].
Called automatically by crate::config_reload::reload on SIGHUP.
Sourcepub fn check(&self, key: &str) -> bool
pub fn check(&self, key: &str) -> bool
Returns true if key (typically a client IP) is within the rate limit,
or false if the limit has been exceeded.
A permitted call is always recorded so it counts toward future limits.