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 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.
Auto Trait Implementations§
impl !Freeze for RateLimiter
impl RefUnwindSafe for RateLimiter
impl Send for RateLimiter
impl Sync for RateLimiter
impl Unpin for RateLimiter
impl UnsafeUnpin for RateLimiter
impl UnwindSafe for RateLimiter
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more