use std::{ collections::HashMap, sync::{Arc, Mutex}, }; use common::{ error::Error, time::{MINUTE_MILLIS, now_ms}, }; const PRUNE_LENGTH: usize = 4096; #[derive(Clone, Default)] pub struct RateLimit(Arc>>); impl RateLimit { pub fn allow(&self, key: &str, limit: u32) -> Result<(), Error> { if limit == 0 { return Ok(()); } let now = now_ms(); let mut windows = self.0.lock().unwrap(); if windows.len() > PRUNE_LENGTH { windows.retain(|_, (start, _)| now.saturating_sub(*start) < MINUTE_MILLIS); } let window = windows.entry(key.to_string()).or_insert((now, 0)); if now.saturating_sub(window.0) >= MINUTE_MILLIS { *window = (now, 0); } if window.1 >= limit { let wait = MINUTE_MILLIS - now.saturating_sub(window.0); return Err(Error::RateLimited { retry_after_seconds: wait.div_ceil(1000), }); } window.1 += 1; Ok(()) } }