memscope_rs/export/
system_optimizer.rs

1//! System optimizer module
2//!
3//! This module provides system resource detection, configuration optimization recommendations, and performance analysis tools.
4
5use crate::core::types::TrackingResult;
6use crate::export::fast_export_coordinator::FastExportConfigBuilder;
7use crate::export::performance_testing::{OptimizationTarget, PerformanceTestResult};
8
9use serde::{Deserialize, Serialize};
10
11/// System resource information
12#[derive(Debug, Clone, Serialize, Deserialize)]
13pub struct SystemResources {
14    /// Number of CPU cores
15    pub cpu_cores: usize,
16    /// Available memory (MB)
17    pub available_memory_mb: usize,
18    /// System load
19    pub system_load: f64,
20    /// Available disk space (MB)
21    pub disk_space_mb: usize,
22    /// System type
23    pub system_type: SystemType,
24}
25
26/// System type
27#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
28pub enum SystemType {
29    /// High performance server
30    HighPerformanceServer,
31    /// Development workstation
32    DevelopmentWorkstation,
33    /// Desktop
34    Desktop,
35    /// Laptop
36    Laptop,
37    /// Embedded system
38    Embedded,
39    /// Unknown system
40    Unknown,
41}
42
43/// Configuration recommendation
44#[derive(Debug, Clone, Serialize, Deserialize)]
45pub struct ConfigurationRecommendation {
46    /// Recommended shard size
47    pub recommended_shard_size: usize,
48    /// Recommended thread count
49    pub recommended_thread_count: usize,
50    /// Recommended buffer size
51    pub recommended_buffer_size: usize,
52    /// Optimization target
53    pub optimization_target: OptimizationTarget,
54    /// Expected performance gain
55    pub expected_performance_gain: f64,
56    /// Expected memory usage
57    pub expected_memory_usage_mb: f64,
58    /// Reasoning
59    pub reasoning: Vec<String>,
60    /// Configuration confidence (0.0-1.0)
61    pub confidence: f64,
62}
63
64/// Performance diagnosis result
65#[derive(Debug, Clone, Serialize, Deserialize)]
66pub struct PerformanceDiagnosis {
67    /// Diagnosis time (Unix timestamp)
68    pub diagnosis_time: u64,
69    /// System resource status
70    pub system_status: SystemResourceStatus,
71    /// Performance bottlenecks
72    pub bottlenecks: Vec<PerformanceBottleneck>,
73    /// Optimization suggestions
74    pub optimization_suggestions: Vec<OptimizationSuggestion>,
75    /// Overall health score (0-100)
76    pub health_score: u8,
77}
78
79/// System resource status
80#[derive(Debug, Clone, Serialize, Deserialize)]
81pub struct SystemResourceStatus {
82    /// CPU usage percentage
83    pub cpu_usage_percent: f64,
84    /// Memory usage percentage
85    pub memory_usage_percent: f64,
86    /// Disk usage percentage
87    pub disk_usage_percent: f64,
88    /// System load status
89    pub load_status: LoadStatus,
90}
91
92/// Load status
93#[derive(Debug, Clone, Serialize, Deserialize)]
94pub enum LoadStatus {
95    /// Low load
96    Low,
97    /// Medium load
98    Medium,
99    /// High load
100    High,
101    /// Overloaded
102    Overloaded,
103}
104
105/// Performance bottlenecks
106#[derive(Debug, Clone, Serialize, Deserialize)]
107pub struct PerformanceBottleneck {
108    /// Bottleneck type
109    pub bottleneck_type: BottleneckType,
110    /// Severity level (1-10)
111    pub severity: u8,
112    /// Description
113    pub description: String,
114    /// Impact
115    pub impact: String,
116    /// Suggested solutions
117    pub suggested_solutions: Vec<String>,
118}
119
120/// Bottleneck type
121#[derive(Debug, Clone, Serialize, Deserialize)]
122pub enum BottleneckType {
123    /// CPU bottleneck
124    Cpu,
125    /// Memory bottleneck
126    Memory,
127    /// I/O bottleneck
128    Io,
129    /// Network bottleneck
130    Network,
131    /// Configuration bottleneck
132    Configuration,
133}
134
135/// Optimization suggestions
136#[derive(Debug, Clone, Serialize, Deserialize)]
137pub struct OptimizationSuggestion {
138    /// 建议类型
139    pub suggestion_type: SuggestionType,
140    /// 优先级 (1-10)
141    pub priority: u8,
142    /// 标题
143    pub title: String,
144    /// Detailed description
145    pub description: String,
146    /// 预期效果
147    pub expected_impact: String,
148    /// 实施难度 (1-10)
149    pub implementation_difficulty: u8,
150}
151
152/// 建议类型
153#[derive(Debug, Clone, Serialize, Deserialize)]
154pub enum SuggestionType {
155    /// 配置调整
156    ConfigurationTuning,
157    /// 硬件升级
158    HardwareUpgrade,
159    /// 软件优化
160    SoftwareOptimization,
161    /// 环境调整
162    EnvironmentTuning,
163}
164
165/// 系统优化器
166pub struct SystemOptimizer {
167    /// System resource information
168    system_resources: SystemResources,
169    /// 历史性能数据
170    performance_history: Vec<PerformanceTestResult>,
171    /// 配置验证规则
172    validation_rules: ConfigurationValidationRules,
173}
174
175/// 配置验证规则
176#[derive(Debug, Clone)]
177pub struct ConfigurationValidationRules {
178    /// 最小分片大小
179    pub min_shard_size: usize,
180    /// 最大分片大小
181    pub max_shard_size: usize,
182    /// 最小线程数
183    pub min_thread_count: usize,
184    /// 最大线程数
185    pub max_thread_count: usize,
186    /// 最小缓冲区大小
187    pub min_buffer_size: usize,
188    /// 最大缓冲区大小
189    pub max_buffer_size: usize,
190    /// 最大内存使用限制 (MB)
191    pub max_memory_limit_mb: usize,
192}
193
194impl Default for ConfigurationValidationRules {
195    fn default() -> Self {
196        Self {
197            min_shard_size: 100,
198            max_shard_size: 10000,
199            min_thread_count: 1,
200            max_thread_count: 32,
201            min_buffer_size: 16 * 1024,        // 16KB
202            max_buffer_size: 16 * 1024 * 1024, // 16MB
203            max_memory_limit_mb: 512,
204        }
205    }
206}
207
208impl SystemOptimizer {
209    /// Create new system optimizer
210    pub fn new() -> TrackingResult<Self> {
211        let system_resources = Self::detect_system_resources()?;
212
213        Ok(Self {
214            system_resources,
215            performance_history: Vec::new(),
216            validation_rules: ConfigurationValidationRules::default(),
217        })
218    }
219
220    /// Detect system resources
221    pub fn detect_system_resources() -> TrackingResult<SystemResources> {
222        let cpu_cores = num_cpus::get();
223        let available_memory_mb = Self::get_available_memory_mb();
224        let system_load = Self::get_system_load();
225        let disk_space_mb = Self::get_disk_space_mb();
226        let system_type = Self::classify_system_type(cpu_cores, available_memory_mb);
227
228        Ok(SystemResources {
229            cpu_cores,
230            available_memory_mb,
231            system_load,
232            disk_space_mb,
233            system_type,
234        })
235    }
236
237    /// Get available memory (MB)
238    fn get_available_memory_mb() -> usize {
239        // 简化实现 - 在实际应用中可以使用 sysinfo 等库获取准确信息
240        #[cfg(target_os = "linux")]
241        {
242            if let Ok(meminfo) = std::fs::read_to_string("/proc/meminfo") {
243                for line in meminfo.lines() {
244                    if line.starts_with("MemAvailable:") {
245                        if let Some(kb_str) = line.split_whitespace().nth(1) {
246                            if let Ok(kb) = kb_str.parse::<usize>() {
247                                return kb / 1024; // 转换为 MB
248                            }
249                        }
250                    }
251                }
252            }
253        }
254
255        // 回退到估算值
256        4096 // 假设 4GB 可用内存
257    }
258
259    /// Get system load
260    fn get_system_load() -> f64 {
261        // 简化实现 - 在实际应用中可以读取 /proc/loadavg
262        #[cfg(target_os = "linux")]
263        {
264            if let Ok(loadavg) = std::fs::read_to_string("/proc/loadavg") {
265                if let Some(load_str) = loadavg.split_whitespace().next() {
266                    if let Ok(load) = load_str.parse::<f64>() {
267                        return load;
268                    }
269                }
270            }
271        }
272
273        0.5 // 默认低负载
274    }
275
276    /// Get available disk space (MB)
277    fn get_disk_space_mb() -> usize {
278        // 简化实现 - 在实际应用中可以使用 statvfs 系统调用
279        10240 // 假设 10GB 可用空间
280    }
281
282    /// Classify system type
283    fn classify_system_type(cpu_cores: usize, memory_mb: usize) -> SystemType {
284        match (cpu_cores, memory_mb) {
285            (cores, mem) if cores >= 16 && mem >= 32768 => SystemType::HighPerformanceServer,
286            (cores, mem) if cores >= 8 && mem >= 16384 => SystemType::DevelopmentWorkstation,
287            (cores, mem) if cores >= 4 && mem >= 8192 => SystemType::Desktop,
288            (cores, mem) if cores >= 2 && mem >= 4096 => SystemType::Laptop,
289            (cores, mem) if cores >= 1 && mem >= 1024 => SystemType::Embedded,
290            _ => SystemType::Unknown,
291        }
292    }
293
294    /// Generate configuration recommendations
295    pub fn generate_configuration_recommendation(
296        &self,
297        target: OptimizationTarget,
298        dataset_size: Option<usize>,
299    ) -> ConfigurationRecommendation {
300        let dataset_size = dataset_size.unwrap_or(10000);
301
302        let (shard_size, thread_count, buffer_size, reasoning) = match target {
303            OptimizationTarget::Speed => self.optimize_for_speed(dataset_size),
304            OptimizationTarget::Memory => self.optimize_for_memory(dataset_size),
305            OptimizationTarget::Balanced => self.optimize_for_balance(dataset_size),
306        };
307
308        let expected_performance_gain =
309            self.estimate_performance_gain(&target, shard_size, thread_count);
310        let expected_memory_usage =
311            self.estimate_memory_usage(shard_size, thread_count, buffer_size);
312        let confidence = self.calculate_confidence(&target);
313
314        ConfigurationRecommendation {
315            recommended_shard_size: shard_size,
316            recommended_thread_count: thread_count,
317            recommended_buffer_size: buffer_size,
318            optimization_target: target,
319            expected_performance_gain,
320            expected_memory_usage_mb: expected_memory_usage,
321            reasoning,
322            confidence,
323        }
324    }
325
326    /// Speed optimization
327    fn optimize_for_speed(&self, dataset_size: usize) -> (usize, usize, usize, Vec<String>) {
328        let mut reasoning = Vec::new();
329
330        // 基于系统资源和数据集大小优化
331        let base_shard_size = match self.system_resources.system_type {
332            SystemType::HighPerformanceServer => 5000,
333            SystemType::DevelopmentWorkstation => 3000,
334            SystemType::Desktop => 2000,
335            SystemType::Laptop => 1500,
336            SystemType::Embedded => 500,
337            SystemType::Unknown => 1000,
338        };
339
340        // 根据数据集大小调整分片大小
341        let shard_size = if dataset_size > 50000 {
342            base_shard_size * 2
343        } else if dataset_size > 20000 {
344            (base_shard_size as f64 * 1.5) as usize
345        } else {
346            base_shard_size
347        }
348        .min(self.validation_rules.max_shard_size);
349
350        reasoning.push(format!(
351            "基于 {:?} 系统类型,推荐分片大小: {}",
352            self.system_resources.system_type, shard_size
353        ));
354
355        // 线程数优化 - 充分利用 CPU 核心
356        let thread_count = match self.system_resources.system_load {
357            load if load < 0.5 => self.system_resources.cpu_cores,
358            load if load < 1.0 => (self.system_resources.cpu_cores * 3 / 4).max(1),
359            load if load < 2.0 => (self.system_resources.cpu_cores / 2).max(1),
360            _ => (self.system_resources.cpu_cores / 4).max(1),
361        }
362        .min(self.validation_rules.max_thread_count);
363
364        reasoning.push(format!(
365            "基于系统负载 {:.2},推荐线程数: {}",
366            self.system_resources.system_load, thread_count
367        ));
368
369        // 缓冲区大小 - 大缓冲区提高 I/O 性能
370        let buffer_size = match self.system_resources.available_memory_mb {
371            mem if mem >= 8192 => 2 * 1024 * 1024, // 2MB
372            mem if mem >= 4096 => 1024 * 1024,     // 1MB
373            mem if mem >= 2048 => 512 * 1024,      // 512KB
374            _ => 256 * 1024,                       // 256KB
375        }
376        .min(self.validation_rules.max_buffer_size);
377
378        reasoning.push(format!(
379            "基于可用内存 {} MB,推荐缓冲区大小: {} KB",
380            self.system_resources.available_memory_mb,
381            buffer_size / 1024
382        ));
383
384        (shard_size, thread_count, buffer_size, reasoning)
385    }
386
387    /// Memory optimization
388    fn optimize_for_memory(&self, _dataset_size: usize) -> (usize, usize, usize, Vec<String>) {
389        let mut reasoning = Vec::new();
390
391        // 小分片减少内存占用
392        let shard_size = match self.system_resources.available_memory_mb {
393            mem if mem >= 4096 => 1000,
394            mem if mem >= 2048 => 750,
395            mem if mem >= 1024 => 500,
396            _ => 250,
397        }
398        .max(self.validation_rules.min_shard_size);
399
400        reasoning.push(format!("为节省内存,推荐较小分片大小: {}", shard_size));
401
402        // 少线程减少并发内存使用
403        let thread_count = match self.system_resources.available_memory_mb {
404            mem if mem >= 4096 => 4,
405            mem if mem >= 2048 => 2,
406            _ => 1,
407        }
408        .min(self.system_resources.cpu_cores / 2)
409        .max(1);
410
411        reasoning.push(format!("为控制内存使用,推荐线程数: {}", thread_count));
412
413        // 小缓冲区节省内存
414        let buffer_size = match self.system_resources.available_memory_mb {
415            mem if mem >= 2048 => 256 * 1024, // 256KB
416            mem if mem >= 1024 => 128 * 1024, // 128KB
417            _ => 64 * 1024,                   // 64KB
418        }
419        .max(self.validation_rules.min_buffer_size);
420
421        reasoning.push(format!(
422            "为节省内存,推荐较小缓冲区: {} KB",
423            buffer_size / 1024
424        ));
425
426        (shard_size, thread_count, buffer_size, reasoning)
427    }
428
429    /// 平衡优化
430    fn optimize_for_balance(&self, dataset_size: usize) -> (usize, usize, usize, Vec<String>) {
431        let mut reasoning = Vec::new();
432
433        // 平衡分片大小
434        let shard_size = match (self.system_resources.cpu_cores, dataset_size) {
435            (cores, size) if cores >= 8 && size > 20000 => 2000,
436            (cores, size) if cores >= 4 && size > 10000 => 1500,
437            (cores, _) if cores >= 2 => 1000,
438            _ => 750,
439        }
440        .min(self.validation_rules.max_shard_size);
441
442        reasoning.push(format!("平衡性能和内存,推荐分片大小: {}", shard_size));
443
444        // 适中的线程数
445        let thread_count = (self.system_resources.cpu_cores / 2)
446            .max(2)
447            .min(6)
448            .min(self.validation_rules.max_thread_count);
449
450        reasoning.push(format!(
451            "平衡并行度和资源使用,推荐线程数: {}",
452            thread_count
453        ));
454
455        // 中等缓冲区大小
456        let buffer_size = match self.system_resources.available_memory_mb {
457            mem if mem >= 4096 => 512 * 1024, // 512KB
458            mem if mem >= 2048 => 256 * 1024, // 256KB
459            _ => 128 * 1024,                  // 128KB
460        };
461
462        reasoning.push(format!(
463            "平衡 I/O 性能和内存使用,推荐缓冲区: {} KB",
464            buffer_size / 1024
465        ));
466
467        (shard_size, thread_count, buffer_size, reasoning)
468    }
469
470    /// 估算性能提升
471    fn estimate_performance_gain(
472        &self,
473        target: &OptimizationTarget,
474        shard_size: usize,
475        thread_count: usize,
476    ) -> f64 {
477        let base_gain = match target {
478            OptimizationTarget::Speed => 3.0,
479            OptimizationTarget::Memory => 1.5,
480            OptimizationTarget::Balanced => 2.0,
481        };
482
483        // 基于线程数的额外提升
484        let thread_multiplier = (thread_count as f64).sqrt();
485
486        // 基于分片大小的调整
487        let shard_multiplier = if shard_size > 2000 {
488            1.2
489        } else if shard_size < 500 {
490            0.8
491        } else {
492            1.0
493        };
494
495        base_gain * thread_multiplier * shard_multiplier
496    }
497
498    /// 估算内存使用
499    fn estimate_memory_usage(
500        &self,
501        shard_size: usize,
502        thread_count: usize,
503        buffer_size: usize,
504    ) -> f64 {
505        // 基础内存使用
506        let base_memory = 20.0; // 20MB 基础开销
507
508        // 分片内存使用 (每个分配大约 500 字节)
509        let shard_memory = (shard_size as f64 * 500.0 * thread_count as f64) / (1024.0 * 1024.0);
510
511        // 缓冲区内存使用
512        let buffer_memory = (buffer_size as f64 * thread_count as f64) / (1024.0 * 1024.0);
513
514        base_memory + shard_memory + buffer_memory
515    }
516
517    /// 计算配置置信度
518    fn calculate_confidence(&self, target: &OptimizationTarget) -> f64 {
519        let mut confidence: f64 = 0.7; // 基础置信度
520
521        // 基于系统类型调整置信度
522        confidence += match self.system_resources.system_type {
523            SystemType::HighPerformanceServer => 0.2,
524            SystemType::DevelopmentWorkstation => 0.15,
525            SystemType::Desktop => 0.1,
526            SystemType::Laptop => 0.05,
527            SystemType::Embedded => -0.1,
528            SystemType::Unknown => -0.2,
529        };
530
531        // 基于历史数据调整置信度
532        if !self.performance_history.is_empty() {
533            confidence += 0.1;
534        }
535
536        // 基于优化目标调整置信度
537        confidence += match target {
538            OptimizationTarget::Balanced => 0.1,
539            OptimizationTarget::Speed => 0.05,
540            OptimizationTarget::Memory => 0.05,
541        };
542
543        confidence.min(1.0).max(0.0)
544    }
545
546    /// 验证配置
547    pub fn validate_configuration(
548        &self,
549        _config: &FastExportConfigBuilder,
550    ) -> ConfigurationValidationResult {
551        let mut errors = Vec::new();
552        let mut warnings = Vec::new();
553        let mut suggestions = Vec::new();
554
555        // 这里需要从 FastExportConfigBuilder 中提取配置值
556        // 由于 FastExportConfigBuilder 可能没有公开的 getter 方法,
557        // 我们需要创建一个配置并检查其值
558
559        // 验证分片大小
560        let shard_size = 1000; // 默认值,实际应该从配置中获取
561        if shard_size < self.validation_rules.min_shard_size {
562            errors.push(format!(
563                "分片大小 {} 小于最小值 {}",
564                shard_size, self.validation_rules.min_shard_size
565            ));
566        } else if shard_size > self.validation_rules.max_shard_size {
567            errors.push(format!(
568                "分片大小 {} 超过最大值 {}",
569                shard_size, self.validation_rules.max_shard_size
570            ));
571        }
572
573        // 验证线程数
574        let thread_count = num_cpus::get(); // 默认值
575        if thread_count > self.system_resources.cpu_cores * 2 {
576            warnings.push(format!(
577                "线程数 {} 超过 CPU 核心数的两倍 ({}), 可能导致上下文切换开销",
578                thread_count, self.system_resources.cpu_cores
579            ));
580        }
581
582        // 验证内存使用
583        let estimated_memory = self.estimate_memory_usage(shard_size, thread_count, 256 * 1024);
584        if estimated_memory > self.system_resources.available_memory_mb as f64 * 0.8 {
585            errors.push(format!(
586                "预估内存使用 {:.1} MB 超过可用内存的 80% ({:.1} MB)",
587                estimated_memory,
588                self.system_resources.available_memory_mb as f64 * 0.8
589            ));
590        }
591
592        // 生成优化建议
593        if shard_size < 500 && self.system_resources.cpu_cores >= 4 {
594            suggestions.push("考虑增加分片大小以提高并行效率".to_string());
595        }
596
597        if thread_count == 1 && self.system_resources.cpu_cores > 2 {
598            suggestions.push("考虑启用多线程处理以提高性能".to_string());
599        }
600
601        ConfigurationValidationResult {
602            is_valid: errors.is_empty(),
603            errors,
604            warnings,
605            suggestions,
606            estimated_performance_impact: self
607                .estimate_configuration_impact(shard_size, thread_count),
608        }
609    }
610
611    /// 估算配置影响
612    fn estimate_configuration_impact(
613        &self,
614        shard_size: usize,
615        thread_count: usize,
616    ) -> ConfigurationImpact {
617        let performance_score = match (shard_size, thread_count) {
618            (s, t) if s >= 2000 && t >= 4 => 9,
619            (s, t) if s >= 1000 && t >= 2 => 7,
620            (s, t) if s >= 500 && t >= 1 => 5,
621            _ => 3,
622        };
623
624        let memory_efficiency = if shard_size <= 1000 && thread_count <= 4 {
625            8
626        } else {
627            6
628        };
629        let stability_score = if thread_count <= self.system_resources.cpu_cores {
630            9
631        } else {
632            6
633        };
634
635        ConfigurationImpact {
636            performance_score,
637            memory_efficiency,
638            stability_score,
639            overall_score: (performance_score + memory_efficiency + stability_score) / 3,
640        }
641    }
642
643    /// 诊断性能问题
644    pub fn diagnose_performance(&self) -> PerformanceDiagnosis {
645        let system_status = self.get_system_resource_status();
646        let bottlenecks = self.identify_bottlenecks(&system_status);
647        let optimization_suggestions = self.generate_optimization_suggestions(&bottlenecks);
648        let health_score = self.calculate_health_score(&system_status, &bottlenecks);
649
650        PerformanceDiagnosis {
651            diagnosis_time: std::time::SystemTime::now()
652                .duration_since(std::time::UNIX_EPOCH)
653                .unwrap()
654                .as_secs(),
655            system_status,
656            bottlenecks,
657            optimization_suggestions,
658            health_score,
659        }
660    }
661
662    /// 获取系统资源状态
663    fn get_system_resource_status(&self) -> SystemResourceStatus {
664        let cpu_usage = self.get_cpu_usage();
665        let memory_usage =
666            (self.system_resources.available_memory_mb as f64 / 8192.0 * 100.0).min(100.0);
667        let disk_usage = 50.0; // 简化实现
668
669        let load_status = match self.system_resources.system_load {
670            load if load < 1.0 => LoadStatus::Low,
671            load if load < 2.0 => LoadStatus::Medium,
672            load if load < 4.0 => LoadStatus::High,
673            _ => LoadStatus::Overloaded,
674        };
675
676        SystemResourceStatus {
677            cpu_usage_percent: cpu_usage,
678            memory_usage_percent: memory_usage,
679            disk_usage_percent: disk_usage,
680            load_status,
681        }
682    }
683
684    /// 获取 CPU 使用率
685    fn get_cpu_usage(&self) -> f64 {
686        // 简化实现 - 基于系统负载估算
687        (self.system_resources.system_load / self.system_resources.cpu_cores as f64 * 100.0)
688            .min(100.0)
689    }
690
691    /// 识别性能瓶颈
692    fn identify_bottlenecks(&self, status: &SystemResourceStatus) -> Vec<PerformanceBottleneck> {
693        let mut bottlenecks = Vec::new();
694
695        // CPU 瓶颈检测
696        if status.cpu_usage_percent > 80.0 {
697            bottlenecks.push(PerformanceBottleneck {
698                bottleneck_type: BottleneckType::Cpu,
699                severity: if status.cpu_usage_percent > 95.0 {
700                    9
701                } else {
702                    7
703                },
704                description: format!("CPU 使用率过高: {:.1}%", status.cpu_usage_percent),
705                impact: "导出性能显著下降,响应时间增加".to_string(),
706                suggested_solutions: vec![
707                    "减少并行线程数".to_string(),
708                    "增加分片大小以减少线程切换开销".to_string(),
709                    "考虑在系统负载较低时进行导出".to_string(),
710                ],
711            });
712        }
713
714        // 内存瓶颈检测
715        if status.memory_usage_percent > 85.0 {
716            bottlenecks.push(PerformanceBottleneck {
717                bottleneck_type: BottleneckType::Memory,
718                severity: if status.memory_usage_percent > 95.0 {
719                    10
720                } else {
721                    8
722                },
723                description: format!("内存使用率过高: {:.1}%", status.memory_usage_percent),
724                impact: "可能导致内存不足,系统变慢或崩溃".to_string(),
725                suggested_solutions: vec![
726                    "减少分片大小".to_string(),
727                    "减少并行线程数".to_string(),
728                    "减少缓冲区大小".to_string(),
729                    "启用流式处理模式".to_string(),
730                ],
731            });
732        }
733
734        // 配置瓶颈检测
735        if self.system_resources.cpu_cores >= 8 && status.cpu_usage_percent < 30.0 {
736            bottlenecks.push(PerformanceBottleneck {
737                bottleneck_type: BottleneckType::Configuration,
738                severity: 5,
739                description: "CPU 资源未充分利用".to_string(),
740                impact: "导出性能未达到最优".to_string(),
741                suggested_solutions: vec![
742                    "增加并行线程数".to_string(),
743                    "减少分片大小以增加并行度".to_string(),
744                    "启用速度优化模式".to_string(),
745                ],
746            });
747        }
748
749        bottlenecks
750    }
751
752    /// 生成优化建议
753    fn generate_optimization_suggestions(
754        &self,
755        bottlenecks: &[PerformanceBottleneck],
756    ) -> Vec<OptimizationSuggestion> {
757        let mut suggestions = Vec::new();
758
759        // 基于瓶颈生成建议
760        for bottleneck in bottlenecks {
761            match bottleneck.bottleneck_type {
762                BottleneckType::Cpu => {
763                    suggestions.push(OptimizationSuggestion {
764                        suggestion_type: SuggestionType::ConfigurationTuning,
765                        priority: bottleneck.severity,
766                        title: "优化 CPU 使用".to_string(),
767                        description: "调整并行配置以优化 CPU 使用率".to_string(),
768                        expected_impact: "提高导出速度 20-40%".to_string(),
769                        implementation_difficulty: 3,
770                    });
771                }
772                BottleneckType::Memory => {
773                    suggestions.push(OptimizationSuggestion {
774                        suggestion_type: SuggestionType::ConfigurationTuning,
775                        priority: bottleneck.severity,
776                        title: "优化内存使用".to_string(),
777                        description: "调整分片和缓冲区配置以减少内存使用".to_string(),
778                        expected_impact: "减少内存使用 30-50%".to_string(),
779                        implementation_difficulty: 2,
780                    });
781                }
782                BottleneckType::Configuration => {
783                    suggestions.push(OptimizationSuggestion {
784                        suggestion_type: SuggestionType::ConfigurationTuning,
785                        priority: bottleneck.severity,
786                        title: "优化配置参数".to_string(),
787                        description: "调整配置以充分利用系统资源".to_string(),
788                        expected_impact: "提高整体性能 15-30%".to_string(),
789                        implementation_difficulty: 1,
790                    });
791                }
792                _ => {}
793            }
794        }
795
796        // 通用优化建议
797        if self.system_resources.system_type == SystemType::HighPerformanceServer {
798            suggestions.push(OptimizationSuggestion {
799                suggestion_type: SuggestionType::ConfigurationTuning,
800                priority: 6,
801                title: "启用高性能模式".to_string(),
802                description: "在高性能服务器上启用最大性能配置".to_string(),
803                expected_impact: "提高导出速度 50-80%".to_string(),
804                implementation_difficulty: 2,
805            });
806        }
807
808        suggestions
809    }
810
811    /// 计算健康评分
812    fn calculate_health_score(
813        &self,
814        status: &SystemResourceStatus,
815        bottlenecks: &[PerformanceBottleneck],
816    ) -> u8 {
817        let mut score = 100u8;
818
819        // 基于资源使用率扣分
820        if status.cpu_usage_percent > 80.0 {
821            score = score.saturating_sub(20);
822        } else if status.cpu_usage_percent > 60.0 {
823            score = score.saturating_sub(10);
824        }
825
826        if status.memory_usage_percent > 85.0 {
827            score = score.saturating_sub(25);
828        } else if status.memory_usage_percent > 70.0 {
829            score = score.saturating_sub(15);
830        }
831
832        // 基于瓶颈扣分
833        for bottleneck in bottlenecks {
834            score = score.saturating_sub(bottleneck.severity * 2);
835        }
836
837        score.max(10) // 最低分数 10
838    }
839
840    /// 添加性能历史数据
841    pub fn add_performance_data(&mut self, result: PerformanceTestResult) {
842        self.performance_history.push(result);
843
844        // 保持历史数据在合理范围内
845        if self.performance_history.len() > 100 {
846            self.performance_history.remove(0);
847        }
848    }
849
850    /// 获取系统资源信息
851    pub fn get_system_resources(&self) -> &SystemResources {
852        &self.system_resources
853    }
854
855    /// 更新系统资源信息
856    pub fn refresh_system_resources(&mut self) -> TrackingResult<()> {
857        self.system_resources = Self::detect_system_resources()?;
858        Ok(())
859    }
860}
861
862impl Default for SystemOptimizer {
863    fn default() -> Self {
864        Self::new().unwrap_or_else(|_| Self {
865            system_resources: SystemResources {
866                cpu_cores: num_cpus::get(),
867                available_memory_mb: 4096,
868                system_load: 0.5,
869                disk_space_mb: 10240,
870                system_type: SystemType::Unknown,
871            },
872            performance_history: Vec::new(),
873            validation_rules: ConfigurationValidationRules::default(),
874        })
875    }
876}
877
878/// 配置验证结果
879#[derive(Debug, Clone, Serialize, Deserialize)]
880pub struct ConfigurationValidationResult {
881    /// 配置是否有效
882    pub is_valid: bool,
883    /// 错误列表
884    pub errors: Vec<String>,
885    /// 警告列表
886    pub warnings: Vec<String>,
887    /// 建议列表
888    pub suggestions: Vec<String>,
889    /// 预估性能影响
890    pub estimated_performance_impact: ConfigurationImpact,
891}
892
893/// 配置影响
894#[derive(Debug, Clone, Serialize, Deserialize)]
895pub struct ConfigurationImpact {
896    /// 性能评分 (1-10)
897    pub performance_score: u8,
898    /// 内存效率 (1-10)
899    pub memory_efficiency: u8,
900    /// 稳定性评分 (1-10)
901    pub stability_score: u8,
902    /// 总体评分 (1-10)
903    pub overall_score: u8,
904}