Skip to main content

oxirs_chat/
performance.rs

1//! Performance Monitoring and Optimization for OxiRS Chat
2//!
3//! Provides comprehensive performance tracking, response time optimization,
4//! adaptive caching strategies, and intelligent performance feedback loops.
5
6use anyhow::{anyhow, Result};
7use serde::{Deserialize, Serialize};
8use std::{
9    collections::{HashMap, VecDeque},
10    sync::Arc,
11    time::{Duration, SystemTime},
12};
13use tokio::sync::RwLock;
14use tracing::{debug, info, warn};
15
16use crate::{
17    analytics::ConversationAnalytics,
18    cache::{AdvancedCacheManager, CacheStats},
19};
20
21/// Parameters for recording a request
22#[derive(Debug, Clone)]
23pub struct RecordRequestParams {
24    pub session_id: String,
25    pub message_id: String,
26    pub response_time: Duration,
27    pub cache_hit: bool,
28    pub cache_type: Option<String>,
29    pub error: Option<String>,
30    pub query_complexity: f32,
31    pub context_size: usize,
32    pub tokens_processed: usize,
33    pub optimization_applied: bool,
34}
35
36/// Performance monitoring configuration
37#[derive(Debug, Clone, Serialize, Deserialize)]
38pub struct PerformanceConfig {
39    pub enable_monitoring: bool,
40    pub enable_optimization: bool,
41    pub enable_adaptive_caching: bool,
42    pub response_time_threshold: Duration,
43    pub optimization_interval: Duration,
44    pub metrics_retention_hours: usize,
45    pub performance_targets: PerformanceTargets,
46    pub alerting: AlertingConfig,
47}
48
49impl Default for PerformanceConfig {
50    fn default() -> Self {
51        Self {
52            enable_monitoring: true,
53            enable_optimization: true,
54            enable_adaptive_caching: true,
55            response_time_threshold: Duration::from_millis(2000),
56            optimization_interval: Duration::from_secs(300), // 5 minutes
57            metrics_retention_hours: 24,
58            performance_targets: PerformanceTargets::default(),
59            alerting: AlertingConfig::default(),
60        }
61    }
62}
63
64/// Performance targets and SLAs
65#[derive(Debug, Clone, Serialize, Deserialize)]
66pub struct PerformanceTargets {
67    pub avg_response_time_ms: u64,
68    pub p95_response_time_ms: u64,
69    pub cache_hit_rate: f64,
70    pub error_rate: f64,
71    pub throughput_requests_per_second: f64,
72}
73
74impl Default for PerformanceTargets {
75    fn default() -> Self {
76        Self {
77            avg_response_time_ms: 1500,
78            p95_response_time_ms: 3000,
79            cache_hit_rate: 0.7,
80            error_rate: 0.05,
81            throughput_requests_per_second: 10.0,
82        }
83    }
84}
85
86/// Alerting configuration
87#[derive(Debug, Clone, Serialize, Deserialize)]
88pub struct AlertingConfig {
89    pub enable_alerts: bool,
90    pub alert_thresholds: AlertThresholds,
91    pub notification_cooldown: Duration,
92}
93
94impl Default for AlertingConfig {
95    fn default() -> Self {
96        Self {
97            enable_alerts: true,
98            alert_thresholds: AlertThresholds::default(),
99            notification_cooldown: Duration::from_secs(300),
100        }
101    }
102}
103
104/// Alert thresholds
105#[derive(Debug, Clone, Serialize, Deserialize)]
106pub struct AlertThresholds {
107    pub response_time_critical_ms: u64,
108    pub cache_hit_rate_warning: f64,
109    pub error_rate_critical: f64,
110    pub memory_usage_warning: f64,
111}
112
113impl Default for AlertThresholds {
114    fn default() -> Self {
115        Self {
116            response_time_critical_ms: 5000,
117            cache_hit_rate_warning: 0.3,
118            error_rate_critical: 0.2,
119            memory_usage_warning: 0.8,
120        }
121    }
122}
123
124/// Performance metrics for a request
125#[derive(Debug, Clone, Serialize, Deserialize)]
126pub struct RequestMetrics {
127    pub session_id: String,
128    pub message_id: String,
129    pub timestamp: SystemTime,
130    pub response_time: Duration,
131    pub cache_hit: bool,
132    pub cache_type: Option<String>,
133    pub error: Option<String>,
134    pub query_complexity: f32,
135    pub context_size: usize,
136    pub tokens_processed: usize,
137    pub optimization_applied: bool,
138}
139
140/// Aggregated performance metrics
141#[derive(Debug, Clone, Serialize, Deserialize)]
142pub struct AggregatedMetrics {
143    pub time_window: Duration,
144    pub total_requests: usize,
145    pub avg_response_time: Duration,
146    pub p50_response_time: Duration,
147    pub p95_response_time: Duration,
148    pub p99_response_time: Duration,
149    pub cache_hit_rate: f64,
150    pub error_rate: f64,
151    pub throughput: f64, // requests per second
152    pub optimization_effectiveness: f64,
153    pub memory_efficiency: f64,
154}
155
156/// Performance bottleneck analysis
157#[derive(Debug, Clone, Serialize, Deserialize)]
158pub struct BottleneckAnalysis {
159    pub analysis_timestamp: SystemTime,
160    pub identified_bottlenecks: Vec<Bottleneck>,
161    pub optimization_recommendations: Vec<OptimizationRecommendation>,
162    pub predicted_improvements: HashMap<String, f64>,
163}
164
165/// Performance bottleneck
166#[derive(Debug, Clone, Serialize, Deserialize)]
167pub struct Bottleneck {
168    pub bottleneck_type: BottleneckType,
169    pub description: String,
170    pub severity: BottleneckSeverity,
171    pub affected_operations: Vec<String>,
172    pub estimated_impact: f64, // percentage of total latency
173}
174
175/// Types of performance bottlenecks
176#[derive(Debug, Clone, Serialize, Deserialize)]
177pub enum BottleneckType {
178    CacheMiss,
179    SlowQuery,
180    ContextAssembly,
181    LLMProcessing,
182    EmbeddingGeneration,
183    NetworkLatency,
184    MemoryPressure,
185    ConcurrencyLimit,
186}
187
188/// Bottleneck severity
189#[derive(Debug, Clone, Serialize, Deserialize)]
190pub enum BottleneckSeverity {
191    Low,
192    Medium,
193    High,
194    Critical,
195}
196
197/// Optimization recommendation
198#[derive(Debug, Clone, Serialize, Deserialize)]
199pub struct OptimizationRecommendation {
200    pub recommendation_type: OptimizationType,
201    pub description: String,
202    pub expected_improvement: f64,
203    pub implementation_effort: ImplementationEffort,
204    pub parameters: HashMap<String, serde_json::Value>,
205}
206
207/// Types of optimizations
208#[derive(Debug, Clone, Serialize, Deserialize)]
209pub enum OptimizationType {
210    IncreaseCacheSize,
211    AdjustCacheTTL,
212    OptimizeQueries,
213    ReduceContextSize,
214    ParallelizeOperations,
215    AddIndexes,
216    BatchRequests,
217    CompressData,
218}
219
220/// Implementation effort level
221#[derive(Debug, Clone, Serialize, Deserialize)]
222pub enum ImplementationEffort {
223    Low,    // Automated/config change
224    Medium, // Code changes required
225    High,   // Significant architecture changes
226}
227
228/// Main performance monitor
229pub struct PerformanceMonitor {
230    config: PerformanceConfig,
231    request_metrics: Arc<RwLock<VecDeque<RequestMetrics>>>,
232    cache_manager: Arc<AdvancedCacheManager>,
233    conversation_tracker: Arc<RwLock<ConversationAnalytics>>,
234    optimization_history: Arc<RwLock<Vec<AppliedOptimization>>>,
235    last_alert_time: Arc<RwLock<SystemTime>>,
236}
237
238/// Applied optimization record
239#[derive(Debug, Clone, Serialize, Deserialize)]
240pub struct AppliedOptimization {
241    pub timestamp: SystemTime,
242    pub optimization_type: OptimizationType,
243    pub parameters: HashMap<String, serde_json::Value>,
244    pub before_metrics: AggregatedMetrics,
245    pub after_metrics: Option<AggregatedMetrics>,
246    pub success: bool,
247    pub notes: String,
248}
249
250impl PerformanceMonitor {
251    pub fn new(
252        config: PerformanceConfig,
253        cache_manager: Arc<AdvancedCacheManager>,
254        conversation_tracker: Arc<RwLock<ConversationAnalytics>>,
255    ) -> Self {
256        let monitor = Self {
257            config: config.clone(),
258            request_metrics: Arc::new(RwLock::new(VecDeque::new())),
259            cache_manager,
260            conversation_tracker,
261            optimization_history: Arc::new(RwLock::new(Vec::new())),
262            last_alert_time: Arc::new(RwLock::new(SystemTime::UNIX_EPOCH)),
263        };
264
265        if config.enable_monitoring {
266            monitor.start_monitoring_task();
267        }
268
269        if config.enable_optimization {
270            monitor.start_optimization_task();
271        }
272
273        monitor
274    }
275
276    /// Record request metrics
277    pub async fn record_request(&self, params: RecordRequestParams) -> Result<()> {
278        let metrics = RequestMetrics {
279            session_id: params.session_id,
280            message_id: params.message_id,
281            timestamp: SystemTime::now(),
282            response_time: params.response_time,
283            cache_hit: params.cache_hit,
284            cache_type: params.cache_type,
285            error: params.error,
286            query_complexity: params.query_complexity,
287            context_size: params.context_size,
288            tokens_processed: params.tokens_processed,
289            optimization_applied: params.optimization_applied,
290        };
291
292        // Clone metrics for alerts before moving into the collection
293        let metrics_for_alerts = metrics.clone();
294
295        let mut request_metrics = self.request_metrics.write().await;
296        request_metrics.push_back(metrics);
297
298        // Maintain retention policy
299        let retention_duration =
300            Duration::from_secs(self.config.metrics_retention_hours as u64 * 3600);
301        let cutoff_time = SystemTime::now() - retention_duration;
302
303        while let Some(front) = request_metrics.front() {
304            if front.timestamp < cutoff_time {
305                request_metrics.pop_front();
306            } else {
307                break;
308            }
309        }
310
311        // Release the lock before checking alerts
312        drop(request_metrics);
313
314        // Check for performance alerts
315        if self.config.alerting.enable_alerts {
316            self.check_performance_alerts(&metrics_for_alerts).await?;
317        }
318
319        Ok(())
320    }
321
322    /// Get aggregated metrics for a time window
323    pub async fn get_aggregated_metrics(&self, time_window: Duration) -> Result<AggregatedMetrics> {
324        let request_metrics = self.request_metrics.read().await;
325        let cutoff_time = SystemTime::now() - time_window;
326
327        let relevant_metrics: Vec<&RequestMetrics> = request_metrics
328            .iter()
329            .filter(|m| m.timestamp >= cutoff_time)
330            .collect();
331
332        if relevant_metrics.is_empty() {
333            return Ok(AggregatedMetrics {
334                time_window,
335                total_requests: 0,
336                avg_response_time: Duration::ZERO,
337                p50_response_time: Duration::ZERO,
338                p95_response_time: Duration::ZERO,
339                p99_response_time: Duration::ZERO,
340                cache_hit_rate: 0.0,
341                error_rate: 0.0,
342                throughput: 0.0,
343                optimization_effectiveness: 0.0,
344                memory_efficiency: 0.0,
345            });
346        }
347
348        let total_requests = relevant_metrics.len();
349
350        // Calculate response time statistics
351        let mut response_times: Vec<Duration> =
352            relevant_metrics.iter().map(|m| m.response_time).collect();
353        response_times.sort();
354
355        let avg_response_time = Duration::from_millis(
356            response_times
357                .iter()
358                .map(|d| d.as_millis() as u64)
359                .sum::<u64>()
360                / total_requests as u64,
361        );
362
363        let p50_response_time = response_times[total_requests / 2];
364        let p95_response_time = response_times[(total_requests as f64 * 0.95) as usize];
365        let p99_response_time = response_times[(total_requests as f64 * 0.99) as usize];
366
367        // Calculate cache hit rate
368        let cache_hits = relevant_metrics.iter().filter(|m| m.cache_hit).count();
369        let cache_hit_rate = cache_hits as f64 / total_requests as f64;
370
371        // Calculate error rate
372        let errors = relevant_metrics
373            .iter()
374            .filter(|m| m.error.is_some())
375            .count();
376        let error_rate = errors as f64 / total_requests as f64;
377
378        // Calculate throughput
379        let throughput = total_requests as f64 / time_window.as_secs_f64();
380
381        // Calculate optimization effectiveness
382        let optimized_requests = relevant_metrics
383            .iter()
384            .filter(|m| m.optimization_applied)
385            .count();
386        let optimization_effectiveness = if optimized_requests > 0 {
387            let optimized_avg_time: Duration = relevant_metrics
388                .iter()
389                .filter(|m| m.optimization_applied)
390                .map(|m| m.response_time)
391                .sum::<Duration>()
392                / optimized_requests as u32;
393
394            let non_optimized_avg_time: Duration = relevant_metrics
395                .iter()
396                .filter(|m| !m.optimization_applied)
397                .map(|m| m.response_time)
398                .sum::<Duration>()
399                / (total_requests - optimized_requests) as u32;
400
401            if non_optimized_avg_time > optimized_avg_time {
402                ((non_optimized_avg_time - optimized_avg_time).as_millis() as f64
403                    / non_optimized_avg_time.as_millis() as f64)
404                    * 100.0
405            } else {
406                0.0
407            }
408        } else {
409            0.0
410        };
411
412        // Get cache statistics for memory efficiency
413        let cache_stats = self.cache_manager.get_cache_stats().await;
414        let memory_efficiency = cache_stats.hit_rate();
415
416        Ok(AggregatedMetrics {
417            time_window,
418            total_requests,
419            avg_response_time,
420            p50_response_time,
421            p95_response_time,
422            p99_response_time,
423            cache_hit_rate,
424            error_rate,
425            throughput,
426            optimization_effectiveness,
427            memory_efficiency,
428        })
429    }
430
431    /// Analyze performance bottlenecks
432    pub async fn analyze_bottlenecks(&self) -> Result<BottleneckAnalysis> {
433        let metrics = self
434            .get_aggregated_metrics(Duration::from_secs(3600))
435            .await?; // Last hour
436        let mut bottlenecks = Vec::new();
437        let mut recommendations = Vec::new();
438        let mut predicted_improvements = HashMap::new();
439
440        // Analyze cache performance
441        if metrics.cache_hit_rate < self.config.performance_targets.cache_hit_rate {
442            bottlenecks.push(Bottleneck {
443                bottleneck_type: BottleneckType::CacheMiss,
444                description: format!(
445                    "Cache hit rate {:.2}% is below target {:.2}%",
446                    metrics.cache_hit_rate * 100.0,
447                    self.config.performance_targets.cache_hit_rate * 100.0
448                ),
449                severity: if metrics.cache_hit_rate < 0.3 {
450                    BottleneckSeverity::Critical
451                } else {
452                    BottleneckSeverity::Medium
453                },
454                affected_operations: vec![
455                    "Response generation".to_string(),
456                    "Context assembly".to_string(),
457                ],
458                estimated_impact: (1.0 - metrics.cache_hit_rate) * 40.0, // Up to 40% impact
459            });
460
461            recommendations.push(OptimizationRecommendation {
462                recommendation_type: OptimizationType::IncreaseCacheSize,
463                description: "Increase cache size to improve hit rate".to_string(),
464                expected_improvement: 20.0,
465                implementation_effort: ImplementationEffort::Low,
466                parameters: [(
467                    "new_size_multiplier".to_string(),
468                    serde_json::Value::Number(serde_json::Number::from(2)),
469                )]
470                .iter()
471                .cloned()
472                .collect(),
473            });
474
475            predicted_improvements.insert("cache_optimization".to_string(), 25.0);
476        }
477
478        // Analyze response time
479        if metrics.avg_response_time
480            > Duration::from_millis(self.config.performance_targets.avg_response_time_ms)
481        {
482            bottlenecks.push(Bottleneck {
483                bottleneck_type: BottleneckType::SlowQuery,
484                description: format!(
485                    "Average response time {}ms exceeds target {}ms",
486                    metrics.avg_response_time.as_millis(),
487                    self.config.performance_targets.avg_response_time_ms
488                ),
489                severity: if metrics.avg_response_time > Duration::from_millis(5000) {
490                    BottleneckSeverity::Critical
491                } else {
492                    BottleneckSeverity::High
493                },
494                affected_operations: vec![
495                    "Query processing".to_string(),
496                    "Response generation".to_string(),
497                ],
498                estimated_impact: 30.0,
499            });
500
501            recommendations.push(OptimizationRecommendation {
502                recommendation_type: OptimizationType::OptimizeQueries,
503                description: "Optimize SPARQL queries and add query caching".to_string(),
504                expected_improvement: 35.0,
505                implementation_effort: ImplementationEffort::Medium,
506                parameters: HashMap::new(),
507            });
508
509            predicted_improvements.insert("query_optimization".to_string(), 30.0);
510        }
511
512        // Analyze memory efficiency
513        if metrics.memory_efficiency < 0.6 {
514            bottlenecks.push(Bottleneck {
515                bottleneck_type: BottleneckType::MemoryPressure,
516                description: "Memory efficiency is low, indicating possible memory pressure"
517                    .to_string(),
518                severity: BottleneckSeverity::Medium,
519                affected_operations: vec!["Caching".to_string(), "Context management".to_string()],
520                estimated_impact: 15.0,
521            });
522
523            recommendations.push(OptimizationRecommendation {
524                recommendation_type: OptimizationType::CompressData,
525                description: "Enable data compression in caches".to_string(),
526                expected_improvement: 20.0,
527                implementation_effort: ImplementationEffort::Low,
528                parameters: [(
529                    "compression_enabled".to_string(),
530                    serde_json::Value::Bool(true),
531                )]
532                .iter()
533                .cloned()
534                .collect(),
535            });
536        }
537
538        Ok(BottleneckAnalysis {
539            analysis_timestamp: SystemTime::now(),
540            identified_bottlenecks: bottlenecks,
541            optimization_recommendations: recommendations,
542            predicted_improvements,
543        })
544    }
545
546    /// Apply automatic optimizations
547    pub async fn apply_optimizations(&self, analysis: &BottleneckAnalysis) -> Result<usize> {
548        let mut applied_count = 0;
549        let before_metrics = self
550            .get_aggregated_metrics(Duration::from_secs(300))
551            .await?;
552
553        for recommendation in &analysis.optimization_recommendations {
554            if matches!(
555                recommendation.implementation_effort,
556                ImplementationEffort::Low
557            ) {
558                match self
559                    .apply_optimization(recommendation, &before_metrics)
560                    .await
561                {
562                    Ok(_) => {
563                        applied_count += 1;
564                        info!("Applied optimization: {}", recommendation.description);
565                    }
566                    Err(e) => {
567                        warn!(
568                            "Failed to apply optimization {}: {}",
569                            recommendation.description, e
570                        );
571                    }
572                }
573            }
574        }
575
576        Ok(applied_count)
577    }
578
579    /// Start background monitoring task
580    fn start_monitoring_task(&self) {
581        let request_metrics = Arc::clone(&self.request_metrics);
582        let config = self.config.clone();
583
584        tokio::spawn(async move {
585            let mut interval = tokio::time::interval(Duration::from_secs(60)); // Every minute
586
587            loop {
588                interval.tick().await;
589
590                // Clean up old metrics
591                let mut metrics = request_metrics.write().await;
592                let retention_duration =
593                    Duration::from_secs(config.metrics_retention_hours as u64 * 3600);
594                let cutoff_time = SystemTime::now() - retention_duration;
595
596                while let Some(front) = metrics.front() {
597                    if front.timestamp < cutoff_time {
598                        metrics.pop_front();
599                    } else {
600                        break;
601                    }
602                }
603
604                debug!("Performance monitoring: {} active metrics", metrics.len());
605            }
606        });
607    }
608
609    /// Start optimization task
610    fn start_optimization_task(&self) {
611        let request_metrics = Arc::clone(&self.request_metrics);
612        let cache_manager = Arc::clone(&self.cache_manager);
613        let optimization_history = Arc::clone(&self.optimization_history);
614        let config = self.config.clone();
615
616        tokio::spawn(async move {
617            let mut interval = tokio::time::interval(config.optimization_interval);
618
619            loop {
620                interval.tick().await;
621
622                // Create a temporary monitor for analysis
623                match Self::analyze_bottlenecks_static(&request_metrics, &cache_manager, &config)
624                    .await
625                {
626                    Ok(analysis) => {
627                        if !analysis.identified_bottlenecks.is_empty() {
628                            info!(
629                                "Performance analysis found {} bottlenecks",
630                                analysis.identified_bottlenecks.len()
631                            );
632
633                            match Self::apply_optimizations_static(
634                                &analysis,
635                                &optimization_history,
636                                &config,
637                            )
638                            .await
639                            {
640                                Ok(count) => {
641                                    if count > 0 {
642                                        info!("Applied {} automatic optimizations", count);
643                                    }
644                                }
645                                Err(e) => {
646                                    warn!("Failed to apply optimizations: {}", e);
647                                }
648                            }
649                        }
650                    }
651                    Err(e) => {
652                        warn!("Failed to analyze performance bottlenecks: {}", e);
653                    }
654                }
655            }
656        });
657    }
658
659    /// Static version of analyze_bottlenecks for use in async tasks
660    async fn analyze_bottlenecks_static(
661        request_metrics: &Arc<RwLock<VecDeque<RequestMetrics>>>,
662        _cache_manager: &Arc<AdvancedCacheManager>,
663        config: &PerformanceConfig,
664    ) -> Result<BottleneckAnalysis> {
665        let metrics =
666            Self::get_aggregated_metrics_static(request_metrics, Duration::from_secs(3600)).await?;
667        let mut bottlenecks = Vec::new();
668        let mut recommendations = Vec::new();
669        let mut predicted_improvements = HashMap::new();
670
671        // Analyze cache performance
672        if metrics.cache_hit_rate < config.performance_targets.cache_hit_rate {
673            bottlenecks.push(Bottleneck {
674                bottleneck_type: BottleneckType::CacheMiss,
675                description: format!(
676                    "Cache hit rate {:.2}% is below target {:.2}%",
677                    metrics.cache_hit_rate * 100.0,
678                    config.performance_targets.cache_hit_rate * 100.0
679                ),
680                severity: if metrics.cache_hit_rate < 0.3 {
681                    BottleneckSeverity::Critical
682                } else {
683                    BottleneckSeverity::Medium
684                },
685                affected_operations: vec![
686                    "Response generation".to_string(),
687                    "Context assembly".to_string(),
688                ],
689                estimated_impact: (1.0 - metrics.cache_hit_rate) * 40.0,
690            });
691
692            recommendations.push(OptimizationRecommendation {
693                recommendation_type: OptimizationType::IncreaseCacheSize,
694                description: "Increase cache size to improve hit rate".to_string(),
695                expected_improvement: 20.0,
696                implementation_effort: ImplementationEffort::Low,
697                parameters: [(
698                    "new_size_multiplier".to_string(),
699                    serde_json::Value::Number(serde_json::Number::from(2)),
700                )]
701                .iter()
702                .cloned()
703                .collect(),
704            });
705
706            predicted_improvements.insert("cache_optimization".to_string(), 25.0);
707        }
708
709        Ok(BottleneckAnalysis {
710            analysis_timestamp: SystemTime::now(),
711            identified_bottlenecks: bottlenecks,
712            optimization_recommendations: recommendations,
713            predicted_improvements,
714        })
715    }
716
717    /// Static version of apply_optimizations for use in async tasks
718    async fn apply_optimizations_static(
719        analysis: &BottleneckAnalysis,
720        optimization_history: &Arc<RwLock<Vec<AppliedOptimization>>>,
721        _config: &PerformanceConfig,
722    ) -> Result<usize> {
723        let mut applied_count = 0;
724
725        for recommendation in &analysis.optimization_recommendations {
726            if matches!(
727                recommendation.implementation_effort,
728                ImplementationEffort::Low
729            ) {
730                // Create a simple optimization record
731                let optimization_record = AppliedOptimization {
732                    timestamp: SystemTime::now(),
733                    optimization_type: recommendation.recommendation_type.clone(),
734                    parameters: recommendation.parameters.clone(),
735                    before_metrics: AggregatedMetrics {
736                        time_window: Duration::from_secs(300),
737                        total_requests: 0,
738                        avg_response_time: Duration::ZERO,
739                        p50_response_time: Duration::ZERO,
740                        p95_response_time: Duration::ZERO,
741                        p99_response_time: Duration::ZERO,
742                        cache_hit_rate: 0.0,
743                        error_rate: 0.0,
744                        throughput: 0.0,
745                        optimization_effectiveness: 0.0,
746                        memory_efficiency: 0.0,
747                    },
748                    after_metrics: None,
749                    success: true,
750                    notes: "Applied automatically".to_string(),
751                };
752
753                let mut history = optimization_history.write().await;
754                history.push(optimization_record);
755                applied_count += 1;
756
757                info!("Applied optimization: {}", recommendation.description);
758            }
759        }
760
761        Ok(applied_count)
762    }
763
764    /// Static version of get_aggregated_metrics for use in async tasks
765    async fn get_aggregated_metrics_static(
766        request_metrics: &Arc<RwLock<VecDeque<RequestMetrics>>>,
767        time_window: Duration,
768    ) -> Result<AggregatedMetrics> {
769        let request_metrics = request_metrics.read().await;
770        let cutoff_time = SystemTime::now() - time_window;
771
772        let relevant_metrics: Vec<&RequestMetrics> = request_metrics
773            .iter()
774            .filter(|m| m.timestamp >= cutoff_time)
775            .collect();
776
777        if relevant_metrics.is_empty() {
778            return Ok(AggregatedMetrics {
779                time_window,
780                total_requests: 0,
781                avg_response_time: Duration::ZERO,
782                p50_response_time: Duration::ZERO,
783                p95_response_time: Duration::ZERO,
784                p99_response_time: Duration::ZERO,
785                cache_hit_rate: 0.0,
786                error_rate: 0.0,
787                throughput: 0.0,
788                optimization_effectiveness: 0.0,
789                memory_efficiency: 0.0,
790            });
791        }
792
793        let total_requests = relevant_metrics.len();
794
795        // Calculate response time statistics
796        let mut response_times: Vec<Duration> =
797            relevant_metrics.iter().map(|m| m.response_time).collect();
798        response_times.sort();
799
800        let avg_response_time = Duration::from_millis(
801            response_times
802                .iter()
803                .map(|d| d.as_millis() as u64)
804                .sum::<u64>()
805                / total_requests as u64,
806        );
807
808        let p50_response_time = response_times[total_requests / 2];
809        let p95_response_time = response_times[(total_requests as f64 * 0.95) as usize];
810        let p99_response_time = response_times[(total_requests as f64 * 0.99) as usize];
811
812        // Calculate cache hit rate
813        let cache_hits = relevant_metrics.iter().filter(|m| m.cache_hit).count();
814        let cache_hit_rate = cache_hits as f64 / total_requests as f64;
815
816        // Calculate error rate
817        let errors = relevant_metrics
818            .iter()
819            .filter(|m| m.error.is_some())
820            .count();
821        let error_rate = errors as f64 / total_requests as f64;
822
823        // Calculate throughput
824        let throughput = total_requests as f64 / time_window.as_secs_f64();
825
826        Ok(AggregatedMetrics {
827            time_window,
828            total_requests,
829            avg_response_time,
830            p50_response_time,
831            p95_response_time,
832            p99_response_time,
833            cache_hit_rate,
834            error_rate,
835            throughput,
836            optimization_effectiveness: 0.0,
837            memory_efficiency: 0.0,
838        })
839    }
840
841    /// Check for performance alerts
842    async fn check_performance_alerts(&self, metrics: &RequestMetrics) -> Result<()> {
843        let last_alert = *self.last_alert_time.read().await;
844        let now = SystemTime::now();
845
846        if now.duration_since(last_alert).unwrap_or(Duration::ZERO)
847            < self.config.alerting.notification_cooldown
848        {
849            return Ok(()); // Still in cooldown
850        }
851
852        let thresholds = &self.config.alerting.alert_thresholds;
853
854        // Check response time
855        if metrics.response_time.as_millis() > thresholds.response_time_critical_ms as u128 {
856            self.send_alert(format!(
857                "Critical response time: {}ms for session {} message {}",
858                metrics.response_time.as_millis(),
859                metrics.session_id,
860                metrics.message_id
861            ))
862            .await?;
863            *self.last_alert_time.write().await = now;
864        }
865
866        // Check error rate (would need to aggregate recent errors)
867        if let Some(ref error) = metrics.error {
868            self.send_alert(format!(
869                "Error in session {} message {}: {}",
870                metrics.session_id, metrics.message_id, error
871            ))
872            .await?;
873        }
874
875        Ok(())
876    }
877
878    /// Send performance alert
879    async fn send_alert(&self, message: String) -> Result<()> {
880        // In a real implementation, this would send alerts to monitoring systems
881        warn!("PERFORMANCE ALERT: {}", message);
882        Ok(())
883    }
884
885    /// Apply a specific optimization
886    async fn apply_optimization(
887        &self,
888        recommendation: &OptimizationRecommendation,
889        before_metrics: &AggregatedMetrics,
890    ) -> Result<()> {
891        let optimization_record = AppliedOptimization {
892            timestamp: SystemTime::now(),
893            optimization_type: recommendation.recommendation_type.clone(),
894            parameters: recommendation.parameters.clone(),
895            before_metrics: before_metrics.clone(),
896            after_metrics: None,
897            success: false,
898            notes: String::new(),
899        };
900
901        match recommendation.recommendation_type {
902            OptimizationType::IncreaseCacheSize => {
903                // This would require access to cache configuration
904                // For now, we'll just log the optimization
905                info!("Would increase cache size based on recommendation");
906            }
907            OptimizationType::AdjustCacheTTL => {
908                info!("Would adjust cache TTL based on recommendation");
909            }
910            OptimizationType::CompressData => {
911                info!("Would enable data compression based on recommendation");
912            }
913            _ => {
914                return Err(anyhow!(
915                    "Optimization type not implemented for automatic application"
916                ));
917            }
918        }
919
920        let mut history = self.optimization_history.write().await;
921        history.push(optimization_record);
922
923        Ok(())
924    }
925
926    /// Get optimization history
927    pub async fn get_optimization_history(&self) -> Vec<AppliedOptimization> {
928        self.optimization_history.read().await.clone()
929    }
930
931    /// Get performance dashboard data
932    pub async fn get_dashboard_data(&self) -> Result<PerformanceDashboard> {
933        let current_metrics = self
934            .get_aggregated_metrics(Duration::from_secs(3600))
935            .await?; // Last hour
936        let daily_metrics = self
937            .get_aggregated_metrics(Duration::from_secs(86400))
938            .await?; // Last day
939        let bottleneck_analysis = self.analyze_bottlenecks().await?;
940        let cache_stats = self.cache_manager.get_cache_stats().await;
941
942        Ok(PerformanceDashboard {
943            current_metrics,
944            daily_metrics,
945            bottleneck_analysis,
946            cache_stats,
947            targets: self.config.performance_targets.clone(),
948            optimization_history: self.get_optimization_history().await,
949        })
950    }
951}
952
953/// Performance dashboard data
954#[derive(Debug, Clone, Serialize, Deserialize)]
955pub struct PerformanceDashboard {
956    pub current_metrics: AggregatedMetrics,
957    pub daily_metrics: AggregatedMetrics,
958    pub bottleneck_analysis: BottleneckAnalysis,
959    pub cache_stats: CacheStats,
960    pub targets: PerformanceTargets,
961    pub optimization_history: Vec<AppliedOptimization>,
962}