1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
// Rate Limiting Module
// Phase 2: Token bucket rate limiter with per-token limits
use lru::LruCache;
use std::num::NonZeroUsize;
use std::sync::Arc;
use std::time::{Duration, Instant};
use thiserror::Error;
use tokio::sync::Mutex;
use tracing::{debug, warn};
#[derive(Debug, Error)]
pub enum RateLimitError {
#[error("Rate limit exceeded for token {0}")]
LimitExceeded(String),
#[error("Too many active tokens (max: {0})")]
TooManyTokens(usize),
}
/// Token bucket for rate limiting
#[derive(Debug, Clone)]
struct TokenBucket {
/// Number of tokens currently available
tokens: f64,
/// Maximum number of tokens (burst size)
capacity: f64,
/// Tokens added per second
refill_rate: f64,
/// Last time bucket was refilled
last_refill: Instant,
/// When this bucket expires (for cleanup)
expires_at: Instant,
}
impl TokenBucket {
/// Create a new token bucket
fn new(capacity: usize, requests_per_minute: usize, ttl: Duration) -> Self {
let refill_rate = requests_per_minute as f64 / 60.0; // Convert per-minute to per-second
Self {
tokens: capacity as f64,
capacity: capacity as f64,
refill_rate,
last_refill: Instant::now(),
expires_at: Instant::now() + ttl,
}
}
/// Refill tokens based on time elapsed
fn refill(&mut self) {
let now = Instant::now();
let elapsed = now.duration_since(self.last_refill).as_secs_f64();
if elapsed > 0.0 {
let tokens_to_add = elapsed * self.refill_rate;
self.tokens = (self.tokens + tokens_to_add).min(self.capacity);
self.last_refill = now;
}
}
/// Try to consume one token
fn try_consume(&mut self) -> bool {
self.refill();
if self.tokens >= 1.0 {
self.tokens -= 1.0;
true
} else {
false
}
}
/// Check if bucket has expired
fn is_expired(&self) -> bool {
Instant::now() > self.expires_at
}
/// Reset expiry time (bucket is still in use)
fn reset_expiry(&mut self, ttl: Duration) {
self.expires_at = Instant::now() + ttl;
}
}
/// Rate limiter configuration
#[derive(Debug, Clone)]
pub struct RateLimiterConfig {
/// Maximum requests per minute per token
pub requests_per_minute: usize,
/// Maximum burst size (tokens in bucket)
pub burst_size: usize,
/// Time-to-live for inactive buckets (seconds)
pub bucket_ttl_seconds: u64,
/// Maximum number of token buckets to track
pub max_buckets: usize,
}
/// Per-token rate limiter with LRU cache
#[derive(Debug)]
pub struct RateLimiter {
config: RateLimiterConfig,
buckets: Arc<Mutex<LruCache<String, TokenBucket>>>,
}
impl RateLimiter {
/// Create a new rate limiter
pub fn new(config: RateLimiterConfig) -> Self {
let capacity =
NonZeroUsize::new(config.max_buckets).expect("max_buckets must be greater than 0");
Self {
config,
buckets: Arc::new(Mutex::new(LruCache::new(capacity))),
}
}
/// Check if request is allowed for given token using default configured limits
///
/// This is a convenience wrapper around `check_limit_with_override` that uses
/// the default rate limits from configuration.
pub async fn check_limit(&self, token_id: &str) -> Result<(), RateLimitError> {
self.check_limit_with_override(token_id, None).await
}
/// Check if request is allowed for given token with optional rate limit override
///
/// This method allows dynamic rate limiting based on user tier, subscription level,
/// or other criteria. When `requests_per_minute_override` is `Some`, it will use
/// that value instead of the configured default.
///
/// # Arguments
///
/// * `token_id` - Unique identifier for the rate limit bucket (e.g., JWT token ID)
/// * `requests_per_minute_override` - Optional override for requests per minute.
/// If `None`, uses the configured default. The burst size remains unchanged.
///
/// # Examples
///
/// ```rust,no_run
/// use derusted::{RateLimiter, RateLimiterConfig};
///
/// # async fn example() {
/// let config = RateLimiterConfig {
/// requests_per_minute: 100, // Default for free tier
/// burst_size: 10,
/// bucket_ttl_seconds: 3600,
/// max_buckets: 10000,
/// };
/// let limiter = RateLimiter::new(config);
///
/// // Use default limit (free tier: 100/min)
/// limiter.check_limit("free_user_token").await.unwrap();
///
/// // Override for pro tier (10,000/min)
/// limiter.check_limit_with_override("pro_user_token", Some(10000)).await.unwrap();
///
/// // Override for enterprise (100,000/min)
/// limiter.check_limit_with_override("enterprise_token", Some(100000)).await.unwrap();
/// # }
/// ```
pub async fn check_limit_with_override(
&self,
token_id: &str,
requests_per_minute_override: Option<usize>,
) -> Result<(), RateLimitError> {
let mut buckets = self.buckets.lock().await;
// Determine effective rate limit
let effective_requests_per_minute =
requests_per_minute_override.unwrap_or(self.config.requests_per_minute);
// Get or create bucket for this token
let bucket = buckets.get_mut(token_id);
match bucket {
Some(bucket) => {
// Check if bucket expired (inactive for too long)
if bucket.is_expired() {
debug!("Token bucket expired for {}, creating new one", token_id);
// Create new bucket with effective rate limit
let new_bucket = TokenBucket::new(
self.config.burst_size,
effective_requests_per_minute,
Duration::from_secs(self.config.bucket_ttl_seconds),
);
buckets.put(token_id.to_string(), new_bucket);
// Try to consume from new bucket
if let Some(bucket) = buckets.get_mut(token_id) {
if bucket.try_consume() {
Ok(())
} else {
Err(RateLimitError::LimitExceeded(token_id.to_string()))
}
} else {
// This shouldn't happen, but handle gracefully
Err(RateLimitError::LimitExceeded(token_id.to_string()))
}
} else {
// Bucket is active, reset expiry and try to consume
bucket.reset_expiry(Duration::from_secs(self.config.bucket_ttl_seconds));
if bucket.try_consume() {
debug!(
"Rate limit check passed for {} ({:.2} tokens remaining)",
token_id, bucket.tokens
);
Ok(())
} else {
warn!(
"Rate limit exceeded for {} (capacity: {}, refill: {}/min)",
token_id, self.config.burst_size, effective_requests_per_minute
);
Err(RateLimitError::LimitExceeded(token_id.to_string()))
}
}
}
None => {
// First request from this token
debug!("Creating new token bucket for {}", token_id);
// Check if we've hit max buckets limit
if buckets.len() >= self.config.max_buckets {
// Before rejecting, try to clean up expired buckets to free space
let mut expired_tokens = Vec::new();
for (tid, bucket) in buckets.iter() {
if bucket.is_expired() {
expired_tokens.push(tid.clone());
}
}
// Remove expired buckets
for tid in &expired_tokens {
buckets.pop(tid);
}
if !expired_tokens.is_empty() {
debug!(
"Cleaned up {} expired buckets to free space",
expired_tokens.len()
);
}
// Recheck capacity after cleanup
if buckets.len() >= self.config.max_buckets {
warn!(
"Max token buckets reached ({}) even after cleanup. Rejecting new token.",
self.config.max_buckets
);
return Err(RateLimitError::TooManyTokens(self.config.max_buckets));
}
}
// Create new bucket with effective rate limit
let mut bucket = TokenBucket::new(
self.config.burst_size,
effective_requests_per_minute,
Duration::from_secs(self.config.bucket_ttl_seconds),
);
// Try to consume token
if bucket.try_consume() {
buckets.put(token_id.to_string(), bucket);
Ok(())
} else {
// This shouldn't happen for a new bucket, but handle gracefully
Err(RateLimitError::LimitExceeded(token_id.to_string()))
}
}
}
}
/// Get current stats for monitoring
pub async fn get_stats(&self) -> RateLimiterStats {
let buckets = self.buckets.lock().await;
RateLimiterStats {
active_tokens: buckets.len(),
max_tokens: self.config.max_buckets,
requests_per_minute: self.config.requests_per_minute,
burst_size: self.config.burst_size,
}
}
/// Clean up expired buckets (call periodically)
pub async fn cleanup_expired(&self) {
let mut buckets = self.buckets.lock().await;
let mut expired_tokens = Vec::new();
// Find expired buckets
for (token_id, bucket) in buckets.iter() {
if bucket.is_expired() {
expired_tokens.push(token_id.clone());
}
}
// Remove expired buckets
for token_id in &expired_tokens {
buckets.pop(token_id);
}
if !expired_tokens.is_empty() {
debug!("Cleaned up {} expired token buckets", expired_tokens.len());
}
}
/// Start background cleanup task
/// This spawns a tokio task that periodically cleans up expired buckets
pub fn start_cleanup_task(limiter: SharedRateLimiter, interval_secs: u64) {
tokio::spawn(async move {
let mut interval =
tokio::time::interval(tokio::time::Duration::from_secs(interval_secs));
loop {
interval.tick().await;
limiter.cleanup_expired().await;
}
});
}
}
/// Rate limiter statistics
#[derive(Debug, Clone)]
pub struct RateLimiterStats {
pub active_tokens: usize,
pub max_tokens: usize,
pub requests_per_minute: usize,
pub burst_size: usize,
}
/// Thread-safe rate limiter (can be shared across async tasks)
pub type SharedRateLimiter = Arc<RateLimiter>;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_token_bucket_creation() {
let bucket = TokenBucket::new(100, 1000, Duration::from_secs(300));
assert_eq!(bucket.tokens, 100.0);
assert_eq!(bucket.capacity, 100.0);
assert!((bucket.refill_rate - 1000.0 / 60.0).abs() < 0.001);
}
#[test]
fn test_token_bucket_consume() {
let mut bucket = TokenBucket::new(2, 60, Duration::from_secs(300));
// Should allow first request
assert!(bucket.try_consume());
assert!((bucket.tokens - 1.0).abs() < 0.001);
// Should allow second request
assert!(bucket.try_consume());
assert!(bucket.tokens < 0.1);
// Should deny third request (burst exhausted)
assert!(!bucket.try_consume());
}
#[tokio::test]
async fn test_rate_limiter_basic() {
let config = RateLimiterConfig {
requests_per_minute: 60,
burst_size: 5,
bucket_ttl_seconds: 300,
max_buckets: 100,
};
let limiter = RateLimiter::new(config);
// First 5 requests should succeed (burst)
for i in 0..5 {
let result = limiter.check_limit("test_token").await;
assert!(result.is_ok(), "Request {} should succeed", i);
}
// 6th request should fail (burst exhausted)
let result = limiter.check_limit("test_token").await;
assert!(result.is_err(), "Request 6 should fail");
}
#[tokio::test]
async fn test_rate_limiter_multiple_tokens() {
let config = RateLimiterConfig {
requests_per_minute: 60,
burst_size: 2,
bucket_ttl_seconds: 300,
max_buckets: 100,
};
let limiter = RateLimiter::new(config);
// Token 1: 2 requests (should succeed)
assert!(limiter.check_limit("token1").await.is_ok());
assert!(limiter.check_limit("token1").await.is_ok());
// Token 2: 2 requests (should succeed)
assert!(limiter.check_limit("token2").await.is_ok());
assert!(limiter.check_limit("token2").await.is_ok());
// Token 1: 3rd request (should fail)
assert!(limiter.check_limit("token1").await.is_err());
// Token 2: 3rd request (should fail)
assert!(limiter.check_limit("token2").await.is_err());
}
#[tokio::test]
async fn test_rate_limiter_stats() {
let config = RateLimiterConfig {
requests_per_minute: 60,
burst_size: 5,
bucket_ttl_seconds: 300,
max_buckets: 100,
};
let limiter = RateLimiter::new(config);
// Initially no active tokens
let stats = limiter.get_stats().await;
assert_eq!(stats.active_tokens, 0);
// After request, should have 1 active token
let _ = limiter.check_limit("test_token").await;
let stats = limiter.get_stats().await;
assert_eq!(stats.active_tokens, 1);
}
#[tokio::test]
async fn test_too_many_tokens_error() {
let config = RateLimiterConfig {
requests_per_minute: 60,
burst_size: 5,
bucket_ttl_seconds: 300,
max_buckets: 3, // Very low limit to test
};
let limiter = RateLimiter::new(config);
// Add 3 tokens (should succeed)
assert!(limiter.check_limit("token1").await.is_ok());
assert!(limiter.check_limit("token2").await.is_ok());
assert!(limiter.check_limit("token3").await.is_ok());
// 4th token should fail with TooManyTokens
let result = limiter.check_limit("token4").await;
assert!(result.is_err());
match result.unwrap_err() {
RateLimitError::TooManyTokens(max) => {
assert_eq!(max, 3);
}
other => panic!("Expected TooManyTokens, got {:?}", other),
}
}
#[tokio::test]
async fn test_bucket_ttl_expiry() {
let config = RateLimiterConfig {
requests_per_minute: 6000, // High rate to allow refill
burst_size: 5,
bucket_ttl_seconds: 1, // Very short TTL for testing
max_buckets: 100,
};
let limiter = RateLimiter::new(config);
// Make first request
assert!(limiter.check_limit("test_token").await.is_ok());
// Wait for bucket to expire
tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
// Next request should create a new bucket (full capacity)
// If we can make 5 more requests, it's a new bucket
for i in 0..5 {
let result = limiter.check_limit("test_token").await;
assert!(
result.is_ok(),
"Request {} should succeed after TTL expiry",
i
);
}
}
#[tokio::test]
async fn test_cleanup_expired_buckets() {
let config = RateLimiterConfig {
requests_per_minute: 60,
burst_size: 5,
bucket_ttl_seconds: 1, // Short TTL for testing
max_buckets: 100,
};
let limiter = RateLimiter::new(config);
// Create 3 buckets
assert!(limiter.check_limit("token1").await.is_ok());
assert!(limiter.check_limit("token2").await.is_ok());
assert!(limiter.check_limit("token3").await.is_ok());
// Verify 3 active tokens
let stats = limiter.get_stats().await;
assert_eq!(stats.active_tokens, 3);
// Wait for buckets to expire
tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
// Clean up expired buckets
limiter.cleanup_expired().await;
// Should have no active tokens after cleanup
let stats = limiter.get_stats().await;
assert_eq!(stats.active_tokens, 0);
}
#[tokio::test]
async fn test_token_bucket_refill() {
let mut bucket = TokenBucket::new(2, 120, Duration::from_secs(300));
// Consume all tokens
assert!(bucket.try_consume());
assert!(bucket.try_consume());
assert!(!bucket.try_consume()); // Should fail
// Wait for refill (120 req/min = 2 req/sec)
tokio::time::sleep(tokio::time::Duration::from_millis(600)).await;
// Should be able to consume again after refill
assert!(bucket.try_consume());
}
#[tokio::test]
async fn test_concurrent_access() {
let config = RateLimiterConfig {
requests_per_minute: 600,
burst_size: 100,
bucket_ttl_seconds: 300,
max_buckets: 100,
};
let limiter = Arc::new(RateLimiter::new(config));
let mut handles = vec![];
// Spawn 10 concurrent tasks, each making 10 requests
for task_id in 0..10 {
let limiter_clone = Arc::clone(&limiter);
let handle = tokio::spawn(async move {
let token_id = format!("token_{}", task_id);
let mut success_count = 0;
for _ in 0..10 {
if limiter_clone.check_limit(&token_id).await.is_ok() {
success_count += 1;
}
}
success_count
});
handles.push(handle);
}
// Wait for all tasks to complete
let mut total_success = 0;
for handle in handles {
total_success += handle.await.unwrap();
}
// Should allow all 100 requests (within burst capacity)
assert_eq!(total_success, 100);
// Verify 10 active tokens
let stats = limiter.get_stats().await;
assert_eq!(stats.active_tokens, 10);
}
#[tokio::test]
async fn test_background_cleanup_task() {
let config = RateLimiterConfig {
requests_per_minute: 60,
burst_size: 5,
bucket_ttl_seconds: 1, // Short TTL
max_buckets: 100,
};
let limiter = Arc::new(RateLimiter::new(config));
// Create buckets
assert!(limiter.check_limit("token1").await.is_ok());
assert!(limiter.check_limit("token2").await.is_ok());
// Start cleanup task (runs every 2 seconds)
RateLimiter::start_cleanup_task(Arc::clone(&limiter), 2);
// Wait for buckets to expire
tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
// Wait for cleanup task to run
tokio::time::sleep(tokio::time::Duration::from_secs(3)).await;
// Buckets should be cleaned up automatically
let stats = limiter.get_stats().await;
assert_eq!(stats.active_tokens, 0);
}
#[tokio::test]
async fn test_cleanup_expired_before_too_many_tokens() {
// Phase 2.2: Test that expired buckets are purged before rejecting with TooManyTokens
let config = RateLimiterConfig {
requests_per_minute: 60,
burst_size: 5,
bucket_ttl_seconds: 1, // Very short TTL for testing
max_buckets: 3, // Low limit to trigger capacity check
};
let limiter = RateLimiter::new(config);
// Fill up to max capacity
assert!(limiter.check_limit("token1").await.is_ok());
assert!(limiter.check_limit("token2").await.is_ok());
assert!(limiter.check_limit("token3").await.is_ok());
// Verify we're at capacity
let stats = limiter.get_stats().await;
assert_eq!(stats.active_tokens, 3);
// Wait for buckets to expire
tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
// New token should succeed because expired buckets are cleaned up automatically
// Before Phase 2.2 fix, this would return TooManyTokens
let result = limiter.check_limit("token4").await;
assert!(
result.is_ok(),
"New token should succeed after expired buckets are purged"
);
// Verify old expired buckets were removed and new one was added
let stats = limiter.get_stats().await;
assert_eq!(
stats.active_tokens, 1,
"Should have only the new token after cleanup"
);
}
#[tokio::test]
async fn test_rate_limit_override_higher_limit() {
// Test that override allows higher rate than default
let config = RateLimiterConfig {
requests_per_minute: 60, // Default: 1 per second
burst_size: 2, // Small burst
bucket_ttl_seconds: 300,
max_buckets: 100,
};
let limiter = RateLimiter::new(config);
// Token with default limit exhausts burst quickly
assert!(limiter.check_limit("default_token").await.is_ok());
assert!(limiter.check_limit("default_token").await.is_ok());
assert!(
limiter.check_limit("default_token").await.is_err(),
"Default token should hit limit"
);
// Token with higher override gets more capacity (higher refill rate)
// With 6000/min override, new bucket gets burst_size tokens but refills faster
assert!(limiter
.check_limit_with_override("pro_token", Some(6000))
.await
.is_ok());
assert!(limiter
.check_limit_with_override("pro_token", Some(6000))
.await
.is_ok());
// Will hit burst limit, but bucket refills 100x faster
assert!(
limiter
.check_limit_with_override("pro_token", Some(6000))
.await
.is_err(),
"Pro token should also hit burst limit"
);
}
#[tokio::test]
async fn test_rate_limit_override_none_uses_default() {
// Test that None override uses default config
let config = RateLimiterConfig {
requests_per_minute: 60,
burst_size: 3,
bucket_ttl_seconds: 300,
max_buckets: 100,
};
let limiter = RateLimiter::new(config);
// Using override with None should behave same as check_limit
assert!(limiter
.check_limit_with_override("token1", None)
.await
.is_ok());
assert!(limiter
.check_limit_with_override("token1", None)
.await
.is_ok());
assert!(limiter
.check_limit_with_override("token1", None)
.await
.is_ok());
assert!(
limiter
.check_limit_with_override("token1", None)
.await
.is_err(),
"Should hit limit after burst"
);
}
#[tokio::test]
async fn test_rate_limit_different_tiers() {
// Simulate tiered SaaS rate limiting
let config = RateLimiterConfig {
requests_per_minute: 100, // Free tier default
burst_size: 5,
bucket_ttl_seconds: 300,
max_buckets: 100,
};
let limiter = RateLimiter::new(config);
// Free tier uses default
for _ in 0..5 {
assert!(limiter.check_limit("free_user").await.is_ok());
}
assert!(limiter.check_limit("free_user").await.is_err());
// Pro tier gets 10x the rate
for _ in 0..5 {
assert!(limiter
.check_limit_with_override("pro_user", Some(1000))
.await
.is_ok());
}
// Also hits burst limit (same burst_size), but refills 10x faster
assert!(limiter
.check_limit_with_override("pro_user", Some(1000))
.await
.is_err());
// Enterprise tier gets 100x the rate
for _ in 0..5 {
assert!(limiter
.check_limit_with_override("enterprise_user", Some(10000))
.await
.is_ok());
}
}
}