98 lines
2.8 KiB
Rust
98 lines
2.8 KiB
Rust
use dashmap::DashMap;
|
|
use std::time::Instant;
|
|
|
|
/// Sliding window rate limiter.
|
|
pub struct RateLimiter {
|
|
/// Map of key -> list of request timestamps
|
|
windows: DashMap<String, Vec<Instant>>,
|
|
/// Maximum requests per window
|
|
max_requests: u64,
|
|
/// Window duration in seconds
|
|
window_seconds: u64,
|
|
}
|
|
|
|
impl RateLimiter {
|
|
pub fn new(max_requests: u64, window_seconds: u64) -> Self {
|
|
Self {
|
|
windows: DashMap::new(),
|
|
max_requests,
|
|
window_seconds,
|
|
}
|
|
}
|
|
|
|
/// Check if a request is allowed for the given key.
|
|
/// Returns true if allowed, false if rate limited.
|
|
pub fn check(&self, key: &str) -> bool {
|
|
let now = Instant::now();
|
|
let window = std::time::Duration::from_secs(self.window_seconds);
|
|
|
|
let mut entry = self.windows.entry(key.to_string()).or_default();
|
|
let timestamps = entry.value_mut();
|
|
|
|
// Remove expired entries
|
|
timestamps.retain(|t| now.duration_since(*t) < window);
|
|
|
|
if timestamps.len() as u64 >= self.max_requests {
|
|
false
|
|
} else {
|
|
timestamps.push(now);
|
|
true
|
|
}
|
|
}
|
|
|
|
/// Clean up expired entries (call periodically).
|
|
pub fn cleanup(&self) {
|
|
let now = Instant::now();
|
|
let window = std::time::Duration::from_secs(self.window_seconds);
|
|
|
|
self.windows.retain(|_, timestamps| {
|
|
timestamps.retain(|t| now.duration_since(*t) < window);
|
|
!timestamps.is_empty()
|
|
});
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn test_allow_under_limit() {
|
|
let limiter = RateLimiter::new(5, 60);
|
|
for _ in 0..5 {
|
|
assert!(limiter.check("client-1"));
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_block_over_limit() {
|
|
let limiter = RateLimiter::new(3, 60);
|
|
assert!(limiter.check("client-1"));
|
|
assert!(limiter.check("client-1"));
|
|
assert!(limiter.check("client-1"));
|
|
assert!(!limiter.check("client-1")); // 4th request blocked
|
|
}
|
|
|
|
#[test]
|
|
fn test_different_keys_independent() {
|
|
let limiter = RateLimiter::new(2, 60);
|
|
assert!(limiter.check("client-a"));
|
|
assert!(limiter.check("client-a"));
|
|
assert!(!limiter.check("client-a")); // blocked
|
|
// Different key should still be allowed
|
|
assert!(limiter.check("client-b"));
|
|
assert!(limiter.check("client-b"));
|
|
}
|
|
|
|
#[test]
|
|
fn test_cleanup_removes_expired() {
|
|
let limiter = RateLimiter::new(100, 0); // 0 second window = immediately expired
|
|
limiter.check("client-1");
|
|
// Sleep briefly to let entries expire
|
|
std::thread::sleep(std::time::Duration::from_millis(10));
|
|
limiter.cleanup();
|
|
// After cleanup, the key should be allowed again (entries expired)
|
|
assert!(limiter.check("client-1"));
|
|
}
|
|
}
|