Skip to main content

adk_awp/
rate_limit.rs

1//! Per-trust-level sliding window rate limiter.
2
3use std::collections::{HashMap, VecDeque};
4use std::time::Duration;
5
6use async_trait::async_trait;
7use awp_types::TrustLevel;
8use dashmap::DashMap;
9use tokio::time::Instant;
10
11/// Trait for checking whether a request should be rate-limited.
12#[async_trait]
13pub trait RateLimiter: Send + Sync {
14    /// Check if a request is allowed.
15    ///
16    /// Returns `Ok(())` if allowed, or `Err(retry_after_secs)` if the caller
17    /// should wait before retrying.
18    async fn check(&self, key: &str, trust_level: TrustLevel) -> Result<(), u64>;
19}
20
21/// Per-trust-level rate limit configuration.
22#[derive(Debug, Clone, Copy)]
23pub struct RateLimitConfig {
24    /// Maximum number of requests allowed within the window.
25    pub max_requests: u64,
26    /// Window duration in seconds.
27    pub window_secs: u64,
28}
29
30/// In-memory sliding window rate limiter backed by [`DashMap`].
31///
32/// Each unique `"{trust_level}:{client_id}"` key gets its own sliding window.
33/// Timestamps older than the window are pruned on every check.
34///
35/// Default limits:
36/// - Anonymous: 30 requests/minute
37/// - Known: 120 requests/minute
38/// - Partner: 600 requests/minute
39/// - Internal: unlimited (not tracked)
40pub struct InMemoryRateLimiter {
41    windows: DashMap<String, VecDeque<Instant>>,
42    limits: HashMap<TrustLevel, RateLimitConfig>,
43}
44
45impl InMemoryRateLimiter {
46    /// Create a rate limiter with default limits.
47    pub fn new() -> Self {
48        let mut limits = HashMap::new();
49        limits.insert(TrustLevel::Anonymous, RateLimitConfig { max_requests: 30, window_secs: 60 });
50        limits.insert(TrustLevel::Known, RateLimitConfig { max_requests: 120, window_secs: 60 });
51        limits.insert(TrustLevel::Partner, RateLimitConfig { max_requests: 600, window_secs: 60 });
52        // Internal is unlimited — no entry in the map
53
54        Self { windows: DashMap::new(), limits }
55    }
56
57    /// Create a rate limiter with custom per-trust-level limits.
58    pub fn with_config(limits: HashMap<TrustLevel, RateLimitConfig>) -> Self {
59        Self { windows: DashMap::new(), limits }
60    }
61}
62
63impl Default for InMemoryRateLimiter {
64    fn default() -> Self {
65        Self::new()
66    }
67}
68
69#[async_trait]
70impl RateLimiter for InMemoryRateLimiter {
71    async fn check(&self, key: &str, trust_level: TrustLevel) -> Result<(), u64> {
72        // Internal trust level is unlimited
73        let config = match self.limits.get(&trust_level) {
74            Some(c) => *c,
75            None => return Ok(()),
76        };
77
78        let composite_key = format!("{trust_level}:{key}");
79        let now = Instant::now();
80        let window_size = Duration::from_secs(config.window_secs.max(1));
81        let window_start = now - window_size;
82
83        let mut entry = self.windows.entry(composite_key).or_default();
84        let deque = entry.value_mut();
85
86        // Remove expired timestamps
87        while deque.front().is_some_and(|t| *t < window_start) {
88            deque.pop_front();
89        }
90
91        if deque.len() as u64 >= config.max_requests {
92            // Calculate retry-after from the oldest entry in the window
93            let oldest = deque.front().copied().unwrap_or(now);
94            let expires_at = oldest + window_size;
95            let retry_after = expires_at.duration_since(now).as_secs().max(1);
96            return Err(retry_after);
97        }
98
99        deque.push_back(now);
100        Ok(())
101    }
102}
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107
108    #[tokio::test]
109    async fn test_anonymous_under_limit() {
110        let limiter = InMemoryRateLimiter::new();
111        for _ in 0..30 {
112            assert!(limiter.check("client1", TrustLevel::Anonymous).await.is_ok());
113        }
114    }
115
116    #[tokio::test]
117    async fn test_anonymous_over_limit() {
118        let limiter = InMemoryRateLimiter::new();
119        for _ in 0..30 {
120            limiter.check("client1", TrustLevel::Anonymous).await.unwrap();
121        }
122        let result = limiter.check("client1", TrustLevel::Anonymous).await;
123        assert!(result.is_err());
124        let retry_after = result.unwrap_err();
125        assert!(retry_after > 0);
126    }
127
128    #[tokio::test]
129    async fn test_internal_unlimited() {
130        let limiter = InMemoryRateLimiter::new();
131        for _ in 0..1000 {
132            assert!(limiter.check("client1", TrustLevel::Internal).await.is_ok());
133        }
134    }
135
136    #[tokio::test]
137    async fn test_different_keys_independent() {
138        let limiter = InMemoryRateLimiter::new();
139        for _ in 0..30 {
140            limiter.check("client1", TrustLevel::Anonymous).await.unwrap();
141        }
142        // client2 should still be allowed
143        assert!(limiter.check("client2", TrustLevel::Anonymous).await.is_ok());
144    }
145
146    #[tokio::test]
147    async fn test_different_trust_levels_independent() {
148        let limiter = InMemoryRateLimiter::new();
149        for _ in 0..30 {
150            limiter.check("client1", TrustLevel::Anonymous).await.unwrap();
151        }
152        // Same client at Known level should still be allowed
153        assert!(limiter.check("client1", TrustLevel::Known).await.is_ok());
154    }
155
156    #[tokio::test]
157    async fn test_custom_config() {
158        let mut limits = HashMap::new();
159        limits.insert(TrustLevel::Anonymous, RateLimitConfig { max_requests: 2, window_secs: 1 });
160        let limiter = InMemoryRateLimiter::with_config(limits);
161
162        assert!(limiter.check("c", TrustLevel::Anonymous).await.is_ok());
163        assert!(limiter.check("c", TrustLevel::Anonymous).await.is_ok());
164        assert!(limiter.check("c", TrustLevel::Anonymous).await.is_err());
165    }
166
167    #[tokio::test(start_paused = true)]
168    async fn test_each_limit_uses_its_configured_window() {
169        let limits = HashMap::from([(
170            TrustLevel::Anonymous,
171            RateLimitConfig { max_requests: 1, window_secs: 2 },
172        )]);
173        let limiter = InMemoryRateLimiter::with_config(limits);
174
175        limiter.check("c", TrustLevel::Anonymous).await.unwrap();
176        assert!(limiter.check("c", TrustLevel::Anonymous).await.is_err());
177        tokio::time::advance(Duration::from_secs(3)).await;
178        assert!(limiter.check("c", TrustLevel::Anonymous).await.is_ok());
179    }
180
181    #[tokio::test]
182    async fn test_known_higher_limit() {
183        let limiter = InMemoryRateLimiter::new();
184        for _ in 0..120 {
185            assert!(limiter.check("client1", TrustLevel::Known).await.is_ok());
186        }
187        assert!(limiter.check("client1", TrustLevel::Known).await.is_err());
188    }
189
190    #[tokio::test]
191    async fn test_partner_higher_limit() {
192        let limiter = InMemoryRateLimiter::new();
193        for _ in 0..600 {
194            assert!(limiter.check("client1", TrustLevel::Partner).await.is_ok());
195        }
196        assert!(limiter.check("client1", TrustLevel::Partner).await.is_err());
197    }
198}