| 1 | use std::{ |
| 2 | collections::HashMap, |
| 3 | sync::{Arc, Mutex}, |
| 4 | }; |
| 5 | |
| 6 | use common::{ |
| 7 | error::Error, |
| 8 | time::{MINUTE_MILLIS, now_ms}, |
| 9 | }; |
| 10 | |
| 11 | const PRUNE_LENGTH: usize = 4096; |
| 12 | |
| 13 | #[derive(Clone, Default)] |
| 14 | pub struct RateLimit(Arc<Mutex<HashMap<String, (u64, u32)>>>); |
| 15 | |
| 16 | impl RateLimit { |
| 17 | pub fn allow(&self, key: &str, limit: u32) -> Result<(), Error> { |
| 18 | if limit == 0 { |
| 19 | return Ok(()); |
| 20 | } |
| 21 | |
| 22 | let now = now_ms(); |
| 23 | let mut windows = self.0.lock().unwrap(); |
| 24 | if windows.len() > PRUNE_LENGTH { |
| 25 | windows.retain(|_, (start, _)| now.saturating_sub(*start) < MINUTE_MILLIS); |
| 26 | } |
| 27 | |
| 28 | let window = windows.entry(key.to_string()).or_insert((now, 0)); |
| 29 | if now.saturating_sub(window.0) >= MINUTE_MILLIS { |
| 30 | *window = (now, 0); |
| 31 | } |
| 32 | if window.1 >= limit { |
| 33 | let wait = MINUTE_MILLIS - now.saturating_sub(window.0); |
| 34 | return Err(Error::RateLimited { |
| 35 | retry_after_seconds: wait.div_ceil(1000), |
| 36 | }); |
| 37 | } |
| 38 | window.1 += 1; |
| 39 | |
| 40 | Ok(()) |
| 41 | } |
| 42 | } |