rush_sync_server/commands/performance/
manager.rs

1use crate::core::prelude::*;
2
3pub struct PerformanceManager;
4
5impl PerformanceManager {
6    pub fn get_status() -> Result<String> {
7        let config_data = Self::load_config_values()?;
8        let performance_analysis = Self::analyze_performance(&config_data);
9
10        Self::format_comprehensive_report(&config_data, &performance_analysis)
11    }
12
13    fn load_config_values() -> Result<ConfigData> {
14        let paths = crate::setup::setup_toml::get_config_paths();
15
16        for path in paths {
17            if path.exists() {
18                if let Ok(content) = std::fs::read_to_string(&path) {
19                    let mut config_data = ConfigData::default();
20
21                    for line in content.lines() {
22                        let line = line.trim();
23                        Self::parse_config_line(line, &mut config_data);
24                    }
25
26                    return Ok(config_data);
27                }
28            }
29        }
30
31        Err(AppError::Validation("No config found".to_string()))
32    }
33
34    fn parse_config_line(line: &str, config_data: &mut ConfigData) {
35        if let Some((key, value)) = line.split_once('=') {
36            let key = key.trim();
37            let value = value.trim().trim_matches('"');
38
39            match key {
40                "poll_rate" => {
41                    if let Ok(val) = value.parse::<u64>() {
42                        config_data.poll_rate = val;
43                    }
44                }
45                "typewriter_delay" => {
46                    if let Ok(val) = value.parse::<u64>() {
47                        config_data.typewriter_delay = val;
48                    }
49                }
50                "max_messages" => {
51                    if let Ok(val) = value.parse::<u64>() {
52                        config_data.max_messages = val;
53                    }
54                }
55                "max_history" => {
56                    if let Ok(val) = value.parse::<u64>() {
57                        config_data.max_history = val;
58                    }
59                }
60                "log_level" => {
61                    config_data.log_level = value.to_string();
62                }
63                "current_theme" => {
64                    config_data.current_theme = value.to_string();
65                }
66                _ => {}
67            }
68        }
69    }
70
71    fn analyze_performance(config: &ConfigData) -> PerformanceAnalysis {
72        let fps = if config.poll_rate > 0 {
73            1000.0 / config.poll_rate as f64
74        } else {
75            0.0
76        };
77
78        let poll_status = match config.poll_rate {
79            0 => PerformanceStatus::Critical,
80            1..=15 => PerformanceStatus::Critical,
81            16..=33 => PerformanceStatus::Optimal,
82            34..=50 => PerformanceStatus::Good,
83            51..=100 => PerformanceStatus::Slow,
84            _ => PerformanceStatus::VerySlow,
85        };
86
87        let typewriter_info = if config.typewriter_delay == 0 {
88            TypewriterInfo {
89                chars_per_sec: None,
90                is_active: false,
91            }
92        } else {
93            let chars_per_sec = if config.typewriter_delay > 0 {
94                1000.0 / config.typewriter_delay as f64
95            } else {
96                f64::INFINITY // Unendlich schnell wenn delay = 0
97            };
98            TypewriterInfo {
99                chars_per_sec: Some(chars_per_sec),
100                is_active: true,
101            }
102        };
103
104        let memory_usage = Self::estimate_memory_usage(config);
105
106        PerformanceAnalysis {
107            fps,
108            poll_status,
109            typewriter_info,
110            memory_usage,
111            recommendations: Self::generate_recommendations(config),
112        }
113    }
114
115    fn estimate_memory_usage(config: &ConfigData) -> MemoryUsage {
116        let message_buffer_mb = (config.max_messages * 100) as f64 / 1024.0 / 1024.0;
117        let history_buffer_mb = (config.max_history * 50) as f64 / 1024.0 / 1024.0;
118        let i18n_cache_mb = 0.5;
119
120        MemoryUsage {
121            total_estimated_mb: message_buffer_mb + history_buffer_mb + i18n_cache_mb,
122            message_buffer_mb,
123            history_buffer_mb,
124            i18n_cache_mb,
125        }
126    }
127
128    fn generate_recommendations(config: &ConfigData) -> Vec<String> {
129        let mut recommendations = Vec::new();
130
131        if config.poll_rate < 16 {
132            recommendations
133                .push("⚔ poll_rate < 16ms: Very high CPU load - recommended: 16-33ms".to_string());
134        }
135
136        if config.max_messages > 1000 {
137            recommendations
138                .push("šŸ’¾ Too many messages in buffer - recommended: max 500".to_string());
139        }
140
141        if config.typewriter_delay > 0 && config.typewriter_delay < 10 {
142            recommendations
143                .push("āŒØļø typewriter_delay < 10ms: Very fast - recommended: 30-100ms".to_string());
144        }
145
146        if recommendations.is_empty() {
147            recommendations.push("āœ… All settings optimally configured".to_string());
148        }
149
150        recommendations
151    }
152
153    fn format_comprehensive_report(
154        config: &ConfigData,
155        analysis: &PerformanceAnalysis,
156    ) -> Result<String> {
157        let mut report = String::new();
158
159        report.push_str("šŸ“Š COMPREHENSIVE PERFORMANCE REPORT\n");
160        report.push_str("=".repeat(50).as_str());
161        report.push_str("\n\n");
162
163        report.push_str("šŸŽÆ System Performance\n");
164        report.push_str(&format!(
165            "   • Poll Rate: {}ms ({:.1} FPS) {}\n",
166            config.poll_rate,
167            analysis.fps,
168            Self::get_status_icon(&analysis.poll_status)
169        ));
170
171        if analysis.typewriter_info.is_active {
172            report.push_str(&format!(
173                "   • Typewriter Speed: {}ms ({:.1} chars/sec)\n",
174                config.typewriter_delay,
175                analysis.typewriter_info.chars_per_sec.unwrap_or(0.0)
176            ));
177        } else {
178            report.push_str("   • Typewriter Speed: DISABLED\n");
179        }
180
181        report.push_str("\nšŸ’¾ Memory Usage\n");
182        report.push_str(&format!(
183            "   • Total Estimated: {:.2} MB\n",
184            analysis.memory_usage.total_estimated_mb
185        ));
186        report.push_str(&format!(
187            "   • Message Buffer: {:.2} MB\n",
188            analysis.memory_usage.message_buffer_mb
189        ));
190        report.push_str(&format!(
191            "   • History Buffer: {:.2} MB\n",
192            analysis.memory_usage.history_buffer_mb
193        ));
194        report.push_str(&format!(
195            "   • i18n Cache: {:.2} MB\n",
196            analysis.memory_usage.i18n_cache_mb
197        ));
198
199        report.push_str("\nšŸ’” Recommendations\n");
200        for recommendation in &analysis.recommendations {
201            report.push_str(&format!("   • {}\n", recommendation));
202        }
203
204        report.push_str("\nšŸ”§ Related Commands\n");
205        report.push_str("   • log-level debug - Enable debug logging\n");
206
207        Ok(report)
208    }
209
210    fn get_status_icon(status: &PerformanceStatus) -> &'static str {
211        match status {
212            PerformanceStatus::Critical => "šŸ”„",
213            PerformanceStatus::Optimal => "āœ…",
214            PerformanceStatus::Good => "āœ…",
215            PerformanceStatus::Slow => "āš ļø",
216            PerformanceStatus::VerySlow => "āŒ",
217        }
218    }
219}
220
221#[derive(Debug, Default)]
222struct ConfigData {
223    poll_rate: u64,
224    typewriter_delay: u64,
225    max_messages: u64,
226    max_history: u64,
227    log_level: String,
228    current_theme: String,
229}
230
231#[derive(Debug)]
232struct PerformanceAnalysis {
233    fps: f64,
234    poll_status: PerformanceStatus,
235    typewriter_info: TypewriterInfo,
236    memory_usage: MemoryUsage,
237    recommendations: Vec<String>,
238}
239
240#[derive(Debug)]
241struct MemoryUsage {
242    total_estimated_mb: f64,
243    message_buffer_mb: f64,
244    history_buffer_mb: f64,
245    i18n_cache_mb: f64,
246}
247
248#[derive(Debug)]
249enum PerformanceStatus {
250    Critical,
251    Optimal,
252    Good,
253    Slow,
254    VerySlow,
255}
256
257#[derive(Debug)]
258struct TypewriterInfo {
259    chars_per_sec: Option<f64>,
260    is_active: bool,
261}