1use crate::error::Result;
10use crate::infrastructure::security::rate_limit::RateLimitResult;
11use chrono::{DateTime, Duration, Timelike, Utc};
12use dashmap::DashMap;
13use parking_lot::RwLock;
14use serde::{Deserialize, Serialize};
15use std::sync::Arc;
16
17#[derive(Debug, Clone, Serialize, Deserialize)]
19pub struct AdaptiveRateLimitConfig {
20 pub enabled: bool,
22
23 pub min_rate_limit: u32,
25
26 pub max_rate_limit: u32,
28
29 pub learning_window_hours: i64,
31
32 pub adjustment_factor: f64,
34
35 pub enable_anomaly_throttling: bool,
37
38 pub enable_load_based_adjustment: bool,
40
41 pub enable_pattern_prediction: bool,
43}
44
45impl Default for AdaptiveRateLimitConfig {
46 fn default() -> Self {
47 Self {
48 enabled: true,
49 min_rate_limit: 10,
50 max_rate_limit: 10_000,
51 learning_window_hours: 24 * 7, adjustment_factor: 0.3,
53 enable_anomaly_throttling: true,
54 enable_load_based_adjustment: true,
55 enable_pattern_prediction: true,
56 }
57 }
58}
59
60#[derive(Debug, Clone, Serialize, Deserialize)]
62struct TenantUsageProfile {
63 tenant_id: String,
64
65 hourly_averages: Vec<f64>, daily_averages: Vec<f64>, peak_times: Vec<u32>, avg_requests_per_hour: f64,
72 stddev_requests_per_hour: f64,
73 max_requests_per_hour: f64,
74
75 current_limit: u32,
77 base_limit: u32,
78 adjustment_history: Vec<LimitAdjustment>,
79
80 last_updated: DateTime<Utc>,
82 data_points: usize,
83}
84
85#[derive(Debug, Clone, Serialize, Deserialize)]
86struct LimitAdjustment {
87 timestamp: DateTime<Utc>,
88 old_limit: u32,
89 new_limit: u32,
90 reason: AdjustmentReason,
91}
92
93#[derive(Debug, Clone, Serialize, Deserialize)]
94enum AdjustmentReason {
95 NormalLearning,
96 AnomalyDetected,
97 HighLoad,
98 AttackMitigation,
99 PatternPrediction,
100}
101
102#[derive(Debug, Clone)]
104pub struct SystemLoad {
105 pub cpu_usage: f64,
106 pub memory_usage: f64,
107 pub active_connections: usize,
108 pub queue_depth: usize,
109}
110
111pub struct AdaptiveRateLimiter {
113 config: Arc<RwLock<AdaptiveRateLimitConfig>>,
114
115 profiles: Arc<DashMap<String, TenantUsageProfile>>,
117
118 recent_requests: Arc<RwLock<Vec<RequestRecord>>>,
120
121 load_history: Arc<RwLock<Vec<(DateTime<Utc>, SystemLoad)>>>,
123}
124
125#[derive(Debug, Clone)]
126struct RequestRecord {
127 tenant_id: String,
128 timestamp: DateTime<Utc>,
129 allowed: bool,
130 cost: f64,
131}
132
133impl AdaptiveRateLimiter {
134 pub fn new(config: AdaptiveRateLimitConfig) -> Self {
136 Self {
137 config: Arc::new(RwLock::new(config)),
138 profiles: Arc::new(DashMap::new()),
139 recent_requests: Arc::new(RwLock::new(Vec::new())),
140 load_history: Arc::new(RwLock::new(Vec::new())),
141 }
142 }
143
144 pub fn check_adaptive_limit(&self, tenant_id: &str) -> Result<RateLimitResult> {
146 let config = self.config.read();
147
148 if !config.enabled {
149 return Ok(RateLimitResult {
150 allowed: true,
151 remaining: u32::MAX,
152 retry_after: None,
153 limit: u32::MAX,
154 });
155 }
156
157 let mut profile = self.profiles.entry(tenant_id.to_string()).or_insert_with(|| {
159 TenantUsageProfile::new(tenant_id.to_string(), config.max_rate_limit)
160 });
161
162 self.record_request(tenant_id, true, 1.0);
164
165 let recent = self.recent_requests.read();
167 let cutoff = Utc::now() - Duration::hours(1);
168 let recent_count = recent
169 .iter()
170 .filter(|r| r.tenant_id.as_str() == tenant_id && r.timestamp > cutoff)
171 .count();
172
173 let allowed = (recent_count as u32) < profile.current_limit;
175
176 let result = RateLimitResult {
177 allowed,
178 remaining: if allowed {
179 profile.current_limit.saturating_sub(recent_count as u32)
180 } else {
181 0
182 },
183 retry_after: if allowed {
184 None
185 } else {
186 Some(std::time::Duration::from_secs(60))
187 },
188 limit: profile.current_limit,
189 };
190
191 profile.data_points += 1;
193 profile.last_updated = Utc::now();
194
195 Ok(result)
196 }
197
198 pub fn update_adaptive_limits(&self) -> Result<()> {
200 let config = self.config.read();
201
202 if !config.enabled {
203 return Ok(());
204 }
205
206 for mut entry in self.profiles.iter_mut() {
207 let tenant_id = entry.key().clone();
208 let profile = entry.value_mut();
209
210 if profile.data_points < 100 {
211 continue; }
213
214 let mut new_limit = profile.current_limit;
215 let mut reason = AdjustmentReason::NormalLearning;
216
217 if profile.data_points >= 1000 {
219 let usage_factor = profile.avg_requests_per_hour / profile.current_limit as f64;
220
221 if usage_factor > 0.8 {
222 new_limit =
224 ((profile.current_limit as f64) * (1.0 + config.adjustment_factor)) as u32;
225 reason = AdjustmentReason::NormalLearning;
226 } else if usage_factor < 0.3 {
227 new_limit = ((profile.current_limit as f64)
229 * (1.0 - config.adjustment_factor * 0.5))
230 as u32;
231 reason = AdjustmentReason::NormalLearning;
232 }
233 }
234
235 if config.enable_anomaly_throttling {
237 let recent = self.recent_requests.read();
238 let cutoff = Utc::now() - Duration::minutes(5);
239 let very_recent_count = recent
240 .iter()
241 .filter(|r| r.tenant_id.as_str() == tenant_id && r.timestamp > cutoff)
242 .count();
243
244 let expected_in_5min = profile.avg_requests_per_hour / 12.0;
246 if very_recent_count as f64 > expected_in_5min * 3.0 {
247 new_limit = ((profile.current_limit as f64) * 0.5) as u32;
248 reason = AdjustmentReason::AnomalyDetected;
249 }
250 }
251
252 if config.enable_load_based_adjustment {
254 if let Some(load) = self.get_current_load() {
255 if load.cpu_usage > 0.8 || load.memory_usage > 0.8 {
256 new_limit = ((profile.current_limit as f64) * 0.7) as u32;
258 reason = AdjustmentReason::HighLoad;
259 }
260 }
261 }
262
263 new_limit = new_limit.clamp(config.min_rate_limit, config.max_rate_limit);
265
266 if new_limit != profile.current_limit {
268 profile.adjustment_history.push(LimitAdjustment {
269 timestamp: Utc::now(),
270 old_limit: profile.current_limit,
271 new_limit,
272 reason,
273 });
274
275 profile.current_limit = new_limit;
276
277 if profile.adjustment_history.len() > 100 {
279 profile.adjustment_history.remove(0);
280 }
281 }
282 }
283
284 Ok(())
285 }
286
287 pub fn predict_and_adjust(&self, tenant_id: &str) -> Result<u32> {
289 let config = self.config.read();
290
291 if !config.enable_pattern_prediction {
292 return Ok(0);
293 }
294
295 if let Some(profile_ref) = self.profiles.get(tenant_id) {
296 let profile = profile_ref.value();
297 if profile.data_points < 1000 {
298 return Ok(profile.current_limit);
299 }
300
301 let current_hour = Utc::now().hour();
303
304 if profile.peak_times.contains(¤t_hour) {
305 let predicted_limit = ((profile.current_limit as f64) * 1.2) as u32;
307 return Ok(predicted_limit.min(config.max_rate_limit));
308 }
309 }
310
311 Ok(0)
312 }
313
314 pub fn record_system_load(&self, load: SystemLoad) {
316 let mut history = self.load_history.write();
317 history.push((Utc::now(), load));
318
319 let cutoff = Utc::now() - Duration::hours(1);
321 history.retain(|(ts, _)| *ts > cutoff);
322 }
323
324 fn get_current_load(&self) -> Option<SystemLoad> {
325 let history = self.load_history.read();
326 history.last().map(|(_, load)| load.clone())
327 }
328
329 fn record_request(&self, tenant_id: &str, allowed: bool, cost: f64) {
330 let mut requests = self.recent_requests.write();
331 requests.push(RequestRecord {
332 tenant_id: tenant_id.to_string(),
333 timestamp: Utc::now(),
334 allowed,
335 cost,
336 });
337
338 let cutoff = Utc::now() - Duration::hours(self.config.read().learning_window_hours);
340 requests.retain(|r| r.timestamp > cutoff);
341 }
342
343 pub fn get_tenant_stats(&self, tenant_id: &str) -> Option<AdaptiveLimitStats> {
345 self.profiles.get(tenant_id).map(|profile_ref| {
346 let profile = profile_ref.value();
347 let recent = self.recent_requests.read();
348 let cutoff = Utc::now() - Duration::hours(1);
349 let requests_last_hour = recent
350 .iter()
351 .filter(|r| r.tenant_id.as_str() == tenant_id && r.timestamp > cutoff)
352 .count();
353
354 AdaptiveLimitStats {
355 current_limit: profile.current_limit,
356 base_limit: profile.base_limit,
357 requests_last_hour: requests_last_hour as u32,
358 avg_requests_per_hour: profile.avg_requests_per_hour,
359 utilization: requests_last_hour as f64 / profile.current_limit as f64,
360 total_adjustments: profile.adjustment_history.len(),
361 last_adjustment: profile.adjustment_history.last().map(|a| a.timestamp),
362 }
363 })
364 }
365
366 pub fn get_stats(&self) -> AdaptiveRateLimiterStats {
368 let recent = self.recent_requests.read();
369
370 AdaptiveRateLimiterStats {
371 total_tenants: self.profiles.len(),
372 total_requests: recent.len(),
373 config: self.config.read().clone(),
374 }
375 }
376}
377
378impl TenantUsageProfile {
379 fn new(tenant_id: String, base_limit: u32) -> Self {
380 Self {
381 tenant_id,
382 hourly_averages: vec![0.0; 24],
383 daily_averages: vec![0.0; 7],
384 peak_times: Vec::new(),
385 avg_requests_per_hour: 0.0,
386 stddev_requests_per_hour: 0.0,
387 max_requests_per_hour: 0.0,
388 current_limit: base_limit,
389 base_limit,
390 adjustment_history: Vec::new(),
391 last_updated: Utc::now(),
392 data_points: 0,
393 }
394 }
395}
396
397#[derive(Debug, Clone, Serialize, Deserialize)]
398pub struct AdaptiveLimitStats {
399 pub current_limit: u32,
400 pub base_limit: u32,
401 pub requests_last_hour: u32,
402 pub avg_requests_per_hour: f64,
403 pub utilization: f64,
404 pub total_adjustments: usize,
405 pub last_adjustment: Option<DateTime<Utc>>,
406}
407
408#[derive(Debug, Clone, Serialize, Deserialize)]
409pub struct AdaptiveRateLimiterStats {
410 pub total_tenants: usize,
411 pub total_requests: usize,
412 pub config: AdaptiveRateLimitConfig,
413}
414
415#[cfg(test)]
416mod tests {
417 use super::*;
418
419 #[test]
420 fn test_adaptive_limiter_creation() {
421 let limiter = AdaptiveRateLimiter::new(AdaptiveRateLimitConfig::default());
422 let stats = limiter.get_stats();
423
424 assert_eq!(stats.total_tenants, 0);
425 assert_eq!(stats.total_requests, 0);
426 }
427
428 #[test]
429 fn test_adaptive_limit_checking() {
430 let limiter = AdaptiveRateLimiter::new(AdaptiveRateLimitConfig {
431 enabled: true,
432 min_rate_limit: 10,
433 max_rate_limit: 100,
434 ..Default::default()
435 });
436
437 let result = limiter.check_adaptive_limit("tenant1").unwrap();
439 assert!(result.allowed);
440 }
441
442 #[test]
443 fn test_limit_adjustment() {
444 let config = AdaptiveRateLimitConfig {
445 min_rate_limit: 10,
446 max_rate_limit: 1000,
447 ..Default::default()
448 };
449
450 let limiter = AdaptiveRateLimiter::new(config);
451
452 {
454 let mut profile = TenantUsageProfile::new("tenant1".to_string(), 100);
455 profile.data_points = 1500;
456 profile.avg_requests_per_hour = 90.0; profile.current_limit = 100;
458 limiter.profiles.insert("tenant1".to_string(), profile);
459 }
460
461 limiter.update_adaptive_limits().unwrap();
463
464 let stats = limiter.get_tenant_stats("tenant1").unwrap();
466 assert!(stats.current_limit > 100); }
468
469 #[test]
470 fn test_load_based_adjustment() {
471 let limiter = AdaptiveRateLimiter::new(AdaptiveRateLimitConfig::default());
472
473 {
475 let mut profile = TenantUsageProfile::new("tenant1".to_string(), 100);
476 profile.data_points = 1000;
477 profile.current_limit = 100;
478 limiter.profiles.insert("tenant1".to_string(), profile);
479 }
480
481 limiter.record_system_load(SystemLoad {
483 cpu_usage: 0.9,
484 memory_usage: 0.85,
485 active_connections: 1000,
486 queue_depth: 500,
487 });
488
489 limiter.update_adaptive_limits().unwrap();
491
492 let stats = limiter.get_tenant_stats("tenant1").unwrap();
494 assert!(stats.current_limit < 100); }
496
497 #[test]
498 fn test_disabled_adaptive_limiting() {
499 let config = AdaptiveRateLimitConfig {
500 enabled: false,
501 ..Default::default()
502 };
503
504 let limiter = AdaptiveRateLimiter::new(config);
505 let result = limiter.check_adaptive_limit("tenant1").unwrap();
506
507 assert!(result.allowed);
508 assert_eq!(result.remaining, u32::MAX);
509 }
510
511 #[test]
512 fn test_safety_limits() {
513 let limiter = AdaptiveRateLimiter::new(AdaptiveRateLimitConfig {
514 min_rate_limit: 50,
515 max_rate_limit: 200,
516 ..Default::default()
517 });
518
519 {
521 let mut profile = TenantUsageProfile::new("tenant1".to_string(), 100);
522 profile.data_points = 1500;
523 profile.avg_requests_per_hour = 180.0; profile.current_limit = 190;
525 limiter.profiles.insert("tenant1".to_string(), profile);
526 }
527
528 limiter.update_adaptive_limits().unwrap();
529
530 let stats = limiter.get_tenant_stats("tenant1").unwrap();
531 assert!(stats.current_limit <= 200); assert!(stats.current_limit >= 50); }
534
535 #[test]
536 fn test_default_config() {
537 let config = AdaptiveRateLimitConfig::default();
538 assert!(config.enabled);
539 assert!(config.min_rate_limit > 0);
540 assert!(config.max_rate_limit > config.min_rate_limit);
541 }
542
543 #[test]
544 fn test_config_serde() {
545 let config = AdaptiveRateLimitConfig::default();
546 let json = serde_json::to_string(&config).unwrap();
547 let parsed: AdaptiveRateLimitConfig = serde_json::from_str(&json).unwrap();
548 assert_eq!(parsed.enabled, config.enabled);
549 assert_eq!(parsed.min_rate_limit, config.min_rate_limit);
550 }
551
552 #[test]
553 fn test_system_load_clone() {
554 let load = SystemLoad {
555 cpu_usage: 0.5,
556 memory_usage: 0.6,
557 active_connections: 100,
558 queue_depth: 50,
559 };
560
561 let cloned = load.clone();
562 assert_eq!(cloned.cpu_usage, load.cpu_usage);
563 assert_eq!(cloned.active_connections, load.active_connections);
564 }
565
566 #[test]
567 fn test_get_tenant_stats_none() {
568 let limiter = AdaptiveRateLimiter::new(AdaptiveRateLimitConfig::default());
569 let stats = limiter.get_tenant_stats("nonexistent");
570 assert!(stats.is_none());
571 }
572
573 #[test]
574 fn test_adaptive_limit_stats_serde() {
575 let stats = AdaptiveLimitStats {
576 current_limit: 100,
577 base_limit: 50,
578 requests_last_hour: 25,
579 avg_requests_per_hour: 30.0,
580 utilization: 0.25,
581 total_adjustments: 5,
582 last_adjustment: Some(Utc::now()),
583 };
584
585 let json = serde_json::to_string(&stats).unwrap();
586 let parsed: AdaptiveLimitStats = serde_json::from_str(&json).unwrap();
587 assert_eq!(parsed.current_limit, stats.current_limit);
588 assert_eq!(parsed.utilization, stats.utilization);
589 }
590
591 #[test]
592 fn test_record_system_load() {
593 let limiter = AdaptiveRateLimiter::new(AdaptiveRateLimitConfig::default());
594
595 for i in 0..5 {
597 limiter.record_system_load(SystemLoad {
598 cpu_usage: i as f64 * 0.1,
599 memory_usage: 0.5,
600 active_connections: i * 10,
601 queue_depth: i,
602 });
603 }
604
605 let stats = limiter.get_stats();
606 assert_eq!(stats.total_tenants, 0); }
608
609 #[test]
610 fn test_multiple_tenants() {
611 let limiter = AdaptiveRateLimiter::new(AdaptiveRateLimitConfig {
612 enabled: true,
613 ..Default::default()
614 });
615
616 limiter.check_adaptive_limit("tenant1").unwrap();
618 limiter.check_adaptive_limit("tenant2").unwrap();
619 limiter.check_adaptive_limit("tenant3").unwrap();
620
621 let stats = limiter.get_stats();
622 assert_eq!(stats.total_tenants, 3);
623 }
624
625 #[test]
626 fn test_adaptive_limiter_stats_serde() {
627 let stats = AdaptiveRateLimiterStats {
628 total_tenants: 10,
629 total_requests: 1000,
630 config: AdaptiveRateLimitConfig::default(),
631 };
632
633 let json = serde_json::to_string(&stats).unwrap();
634 let parsed: AdaptiveRateLimiterStats = serde_json::from_str(&json).unwrap();
635 assert_eq!(parsed.total_tenants, stats.total_tenants);
636 assert_eq!(parsed.total_requests, stats.total_requests);
637 }
638
639 #[test]
640 fn test_tenant_profile_initialization() {
641 let limiter = AdaptiveRateLimiter::new(AdaptiveRateLimitConfig {
642 enabled: true,
643 ..Default::default()
644 });
645
646 limiter.check_adaptive_limit("new_tenant").unwrap();
648
649 let stats = limiter.get_tenant_stats("new_tenant");
650 assert!(stats.is_some());
651 }
652}