Skip to main content

allsource_core/infrastructure/security/
rate_limit.rs

1// Copyright 2024-2025 AllSource Team
2// Licensed under the Business Source License 1.1 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6//     See LICENSE-BSL in the repository root
7//
8// Change Date: 2029-03-01
9// Change License: Apache License, Version 2.0
10
11/// Rate limiting implementation using token bucket algorithm
12///
13/// Features:
14/// - Per-tenant rate limiting
15/// - Per-user rate limiting
16/// - Per-API key rate limiting
17/// - Configurable limits
18/// - Efficient in-memory storage with DashMap
19/// - Automatic token replenishment
20use crate::infrastructure::{
21    hash_state::{FastDashMap, fast_dashmap},
22    memory::ledger::{MapCharge, Owner, Tally},
23};
24use chrono::{DateTime, Utc};
25use std::{mem::size_of, sync::Arc, time::Duration};
26
27/// Rate limit configuration for different resource types
28#[derive(Debug, Clone)]
29pub struct RateLimitConfig {
30    /// Maximum requests per minute
31    pub requests_per_minute: u32,
32    /// Maximum burst size
33    pub burst_size: u32,
34}
35
36impl RateLimitConfig {
37    /// Free tier: 60 requests/min
38    pub fn free_tier() -> Self {
39        Self {
40            requests_per_minute: 60,
41            burst_size: 100,
42        }
43    }
44
45    /// Professional tier: 600 requests/min
46    pub fn professional() -> Self {
47        Self {
48            requests_per_minute: 600,
49            burst_size: 1000,
50        }
51    }
52
53    /// Unlimited tier: 10,000 requests/min
54    pub fn unlimited() -> Self {
55        Self {
56            requests_per_minute: 10_000,
57            burst_size: 20_000,
58        }
59    }
60
61    /// Development mode: Very high limits
62    pub fn dev_mode() -> Self {
63        Self {
64            requests_per_minute: 100_000,
65            burst_size: 200_000,
66        }
67    }
68}
69
70/// Token bucket for rate limiting
71#[derive(Debug, Clone)]
72struct TokenBucket {
73    /// Current number of tokens
74    tokens: f64,
75    /// Maximum tokens (burst size)
76    max_tokens: f64,
77    /// Tokens added per second
78    refill_rate: f64,
79    /// Last refill timestamp
80    last_refill: DateTime<Utc>,
81}
82
83impl TokenBucket {
84    fn new(config: &RateLimitConfig) -> Self {
85        let max_tokens = f64::from(config.burst_size);
86        Self {
87            tokens: max_tokens,
88            max_tokens,
89            refill_rate: f64::from(config.requests_per_minute) / 60.0, // tokens per second
90            last_refill: Utc::now(),
91        }
92    }
93
94    /// Try to consume a token. Returns true if successful.
95    fn try_consume(&mut self, tokens: f64) -> bool {
96        self.refill();
97
98        if self.tokens >= tokens {
99            self.tokens -= tokens;
100            true
101        } else {
102            false
103        }
104    }
105
106    /// Refill tokens based on time elapsed
107    fn refill(&mut self) {
108        let now = Utc::now();
109        let elapsed = (now - self.last_refill).num_milliseconds() as f64 / 1000.0;
110
111        if elapsed > 0.0 {
112            let new_tokens = elapsed * self.refill_rate;
113            self.tokens = (self.tokens + new_tokens).min(self.max_tokens);
114            self.last_refill = now;
115        }
116    }
117
118    /// Get remaining tokens
119    fn remaining(&mut self) -> u32 {
120        self.refill();
121        self.tokens.floor() as u32
122    }
123
124    /// Get time until next token is available
125    fn retry_after(&mut self) -> Duration {
126        self.refill();
127
128        if self.tokens >= 1.0 {
129            Duration::from_secs(0)
130        } else {
131            let tokens_needed = 1.0 - self.tokens;
132            let seconds = tokens_needed / self.refill_rate;
133            Duration::from_secs_f64(seconds)
134        }
135    }
136}
137
138/// Rate limiter using token bucket algorithm
139pub struct RateLimiter {
140    /// Buckets keyed by identifier (tenant_id, user_id, or api_key_id)
141    buckets: Arc<FastDashMap<String, TokenBucket>>,
142    buckets_charge: MapCharge,
143    /// Default configuration
144    default_config: RateLimitConfig,
145    /// Custom configs for specific identifiers
146    custom_configs: Arc<FastDashMap<String, RateLimitConfig>>,
147    configs_charge: MapCharge,
148    /// Heap of the limiter's tables at startup, measured for the S0 fixture.
149    _startup: Tally,
150}
151
152/// Bytes the limiter's tables hold before any identifier is seen.
153const STARTUP_BYTES: u64 = 528_394;
154
155impl RateLimiter {
156    pub fn new(default_config: RateLimitConfig) -> Self {
157        let startup = Tally::new(Owner::RateLimiter);
158        startup.add(STARTUP_BYTES);
159        Self {
160            buckets: Arc::new(fast_dashmap()),
161            buckets_charge: MapCharge::new(Owner::RateLimiter, size_of::<(String, TokenBucket)>()),
162            default_config,
163            custom_configs: Arc::new(fast_dashmap()),
164            configs_charge: MapCharge::new(
165                Owner::RateLimiter,
166                size_of::<(String, RateLimitConfig)>(),
167            ),
168            _startup: startup,
169        }
170    }
171
172    /// Set custom config for a specific identifier
173    pub fn set_config(&self, identifier: &str, config: RateLimitConfig) {
174        self.configs_charge.ensure(
175            &self.custom_configs,
176            identifier,
177            || identifier.to_string(),
178            || config.clone(),
179            identifier.len() as u64,
180        );
181        self.custom_configs.insert(identifier.to_string(), config);
182
183        // Reset bucket with new config
184        if self.buckets.remove(identifier).is_some() {
185            self.buckets_charge.release_owned(identifier.len() as u64);
186        }
187    }
188
189    /// Check if request is allowed
190    pub fn check_rate_limit(&self, identifier: &str) -> RateLimitResult {
191        self.check_rate_limit_with_cost(identifier, 1.0)
192    }
193
194    /// Check rate limit with custom cost (for expensive operations)
195    pub fn check_rate_limit_with_cost(&self, identifier: &str, cost: f64) -> RateLimitResult {
196        let config = self
197            .custom_configs
198            .get(identifier)
199            .map_or_else(|| self.default_config.clone(), |c| c.clone());
200
201        self.buckets_charge.ensure(
202            &self.buckets,
203            identifier,
204            || identifier.to_string(),
205            || TokenBucket::new(&config),
206            identifier.len() as u64,
207        );
208        let mut entry = self
209            .buckets
210            .entry(identifier.to_string())
211            .or_insert_with(|| TokenBucket::new(&config));
212
213        let allowed = entry.try_consume(cost);
214        let remaining = entry.remaining();
215        let retry_after = if allowed {
216            None
217        } else {
218            Some(entry.retry_after())
219        };
220
221        RateLimitResult {
222            allowed,
223            remaining,
224            retry_after,
225            limit: config.requests_per_minute,
226        }
227    }
228
229    /// Get current stats for an identifier
230    pub fn get_stats(&self, identifier: &str) -> Option<RateLimitStats> {
231        self.buckets
232            .get_mut(identifier)
233            .map(|mut bucket| RateLimitStats {
234                remaining: bucket.remaining(),
235                retry_after: bucket.retry_after(),
236            })
237    }
238
239    /// Cleanup old buckets (call periodically)
240    pub fn cleanup(&self) {
241        let now = Utc::now();
242        let mut released = 0u64;
243        self.buckets.retain(|key, bucket| {
244            // Remove buckets that haven't been used in the last hour
245            let keep = (now - bucket.last_refill).num_hours() < 1;
246            if !keep {
247                released += key.len() as u64;
248            }
249            keep
250        });
251        self.buckets_charge.release_owned(released);
252    }
253}
254
255impl Default for RateLimiter {
256    fn default() -> Self {
257        Self::new(RateLimitConfig::professional())
258    }
259}
260
261/// Result of a rate limit check
262#[derive(Debug, Clone)]
263pub struct RateLimitResult {
264    /// Whether the request is allowed
265    pub allowed: bool,
266    /// Remaining requests
267    pub remaining: u32,
268    /// Time to wait before retrying (if not allowed)
269    pub retry_after: Option<Duration>,
270    /// Total limit per minute
271    pub limit: u32,
272}
273
274/// Current rate limit statistics
275#[derive(Debug, Clone)]
276pub struct RateLimitStats {
277    /// Remaining requests
278    pub remaining: u32,
279    /// Time until next token
280    pub retry_after: Duration,
281}
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286    use std::{thread, time::Duration as StdDuration};
287
288    #[test]
289    fn test_token_bucket_creation() {
290        let config = RateLimitConfig::free_tier();
291        let bucket = TokenBucket::new(&config);
292
293        assert_eq!(bucket.max_tokens, 100.0);
294        assert_eq!(bucket.tokens, 100.0);
295    }
296
297    #[test]
298    fn test_token_consumption() {
299        let config = RateLimitConfig::free_tier();
300        let mut bucket = TokenBucket::new(&config);
301
302        assert!(bucket.try_consume(1.0));
303        assert_eq!(bucket.remaining(), 99);
304
305        assert!(bucket.try_consume(10.0));
306        assert_eq!(bucket.remaining(), 89);
307    }
308
309    #[test]
310    fn test_rate_limit_enforcement() {
311        let config = RateLimitConfig {
312            requests_per_minute: 60,
313            burst_size: 10,
314        };
315        let mut bucket = TokenBucket::new(&config);
316
317        // Should allow up to burst size
318        for _ in 0..10 {
319            assert!(bucket.try_consume(1.0));
320        }
321
322        // Should deny after burst exhausted
323        assert!(!bucket.try_consume(1.0));
324    }
325
326    #[test]
327    fn test_token_refill() {
328        let config = RateLimitConfig {
329            requests_per_minute: 60, // 1 per second
330            burst_size: 10,
331        };
332        let mut bucket = TokenBucket::new(&config);
333
334        // Consume all tokens
335        for _ in 0..10 {
336            bucket.try_consume(1.0);
337        }
338
339        assert_eq!(bucket.remaining(), 0);
340
341        // Wait for refill (simulate)
342        thread::sleep(StdDuration::from_secs(2));
343
344        // Should have ~2 tokens refilled
345        let remaining = bucket.remaining();
346        assert!(
347            (1..=3).contains(&remaining),
348            "Expected 1-3 tokens, got {remaining}"
349        );
350    }
351
352    #[test]
353    fn test_rate_limiter_per_identifier() {
354        let limiter = RateLimiter::new(RateLimitConfig {
355            requests_per_minute: 60,
356            burst_size: 5,
357        });
358
359        // Different identifiers have separate buckets
360        let result1 = limiter.check_rate_limit("user1");
361        let result2 = limiter.check_rate_limit("user2");
362
363        assert!(result1.allowed);
364        assert!(result2.allowed);
365        assert_eq!(result1.remaining, 4);
366        assert_eq!(result2.remaining, 4);
367    }
368
369    #[test]
370    fn test_custom_config() {
371        let limiter = RateLimiter::new(RateLimitConfig::free_tier());
372
373        limiter.set_config("premium_user", RateLimitConfig::unlimited());
374
375        let free_result = limiter.check_rate_limit("free_user");
376        let premium_result = limiter.check_rate_limit("premium_user");
377
378        assert!(free_result.limit < premium_result.limit);
379    }
380
381    #[test]
382    fn test_rate_limit_with_cost() {
383        let limiter = RateLimiter::new(RateLimitConfig {
384            requests_per_minute: 60,
385            burst_size: 10,
386        });
387
388        // Expensive operation costs 5 tokens
389        let result = limiter.check_rate_limit_with_cost("user1", 5.0);
390        assert!(result.allowed);
391        assert_eq!(result.remaining, 5);
392    }
393}