Skip to main content

aurelin_framework/auth/
rate_limit.rs

1use std::{
2    collections::HashMap,
3    sync::Arc,
4    time::{Duration, Instant},
5};
6
7use tokio::sync::Mutex;
8
9#[derive(Clone, Debug)]
10pub struct FixedWindowRateLimiter {
11    limit: u32,
12    window: Duration,
13    entries: Arc<Mutex<HashMap<String, Window>>>,
14}
15
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub enum RateLimitOutcome {
18    Allowed { remaining: u32 },
19    Limited { retry_after: Duration },
20}
21
22#[derive(Clone, Copy, Debug)]
23struct Window {
24    hits: u32,
25    expires_at: Instant,
26}
27
28impl FixedWindowRateLimiter {
29    pub fn new(limit: u32, window: Duration) -> Self {
30        Self { limit, window, entries: Arc::new(Mutex::new(HashMap::new())) }
31    }
32
33    pub async fn retry_after(&self, key: &str) -> Option<Duration> {
34        let now = Instant::now();
35        let mut entries = self.entries.lock().await;
36        entries.retain(|_, window| window.expires_at > now);
37        let window = entries.get(key)?;
38        (window.hits >= self.limit).then(|| window.expires_at.saturating_duration_since(now))
39    }
40
41    pub async fn attempt(&self, key: &str) -> RateLimitOutcome {
42        let now = Instant::now();
43        let mut entries = self.entries.lock().await;
44        entries.retain(|_, window| window.expires_at > now);
45
46        let window = entries.entry(key.to_owned()).or_insert(Window { hits: 0, expires_at: now + self.window });
47        if window.hits >= self.limit {
48            return RateLimitOutcome::Limited { retry_after: window.expires_at.saturating_duration_since(now) };
49        }
50
51        window.hits += 1;
52        RateLimitOutcome::Allowed { remaining: self.limit - window.hits }
53    }
54
55    pub async fn hit(&self, key: &str) {
56        let now = Instant::now();
57        let mut entries = self.entries.lock().await;
58        entries.retain(|_, window| window.expires_at > now);
59        entries
60            .entry(key.to_owned())
61            .and_modify(|window| window.hits += 1)
62            .or_insert(Window { hits: 1, expires_at: now + self.window });
63    }
64
65    pub async fn clear(&self, key: &str) {
66        self.entries.lock().await.remove(key);
67    }
68}