use std::{collections::HashMap, net::IpAddr, time::Instant};
pub(crate) struct RateLimiter {
buckets: HashMap<IpAddr, (Instant, f64)>,
max_pps: f64,
burst: f64,
ticks: u32,
}
const PRUNE_INTERVAL_TICKS: u32 = 48;
impl RateLimiter {
pub(crate) fn new(max_pps: f64, burst: f64) -> Self {
Self {
buckets: HashMap::new(),
max_pps,
burst,
ticks: 0,
}
}
pub(crate) fn allow(&mut self, ip: IpAddr) -> bool {
let now = Instant::now();
let (last, tokens) = self.buckets.entry(ip).or_insert((now, self.burst));
let elapsed = now.duration_since(*last).as_secs_f64();
*tokens = (*tokens + self.max_pps * elapsed).min(self.burst);
*last = now;
if *tokens >= 1.0 {
*tokens -= 1.0;
true
} else {
false
}
}
pub(crate) fn tick_prune(&mut self) {
self.ticks += 1;
if !self.ticks.is_multiple_of(PRUNE_INTERVAL_TICKS) {
return;
}
if let Some(cutoff) = Instant::now().checked_sub(std::time::Duration::from_mins(1)) {
self.buckets.retain(|_, (last, _)| *last > cutoff);
}
}
}