mf_core/runtime/
system_detector.rs

1//! 系统资源检测模块
2//!
3//! 提供自动检测系统硬件配置的功能,包括:
4//! - CPU核心数和线程数
5//! - 系统内存总量和可用量
6//! - 系统资源等级评估
7//!
8//! # 使用示例
9//!
10//! ```rust
11//! use mf_core::runtime::system_detector::SystemResources;
12//!
13//! let resources = SystemResources::detect();
14//! println!("CPU: {} 核心 / {} 线程", resources.cpu_cores, resources.cpu_threads);
15//! println!("内存: {} MB", resources.total_memory_mb);
16//! ```
17
18use sysinfo::System;
19
20/// 系统资源信息
21#[derive(Debug, Clone)]
22pub struct SystemResources {
23    /// CPU物理核心数
24    pub cpu_cores: usize,
25    /// CPU逻辑线程数
26    pub cpu_threads: usize,
27    /// 系统总内存(MB)
28    pub total_memory_mb: u64,
29    /// 系统可用内存(MB)
30    pub available_memory_mb: u64,
31}
32
33impl SystemResources {
34    /// 自动检测系统资源
35    ///
36    /// # 返回值
37    /// * `SystemResources` - 包含CPU和内存信息的系统资源结构
38    ///
39    /// # 示例
40    /// ```rust
41    /// let resources = SystemResources::detect();
42    /// assert!(resources.cpu_cores > 0);
43    /// assert!(resources.total_memory_mb > 0);
44    /// ```
45    pub fn detect() -> Self {
46        let mut sys = System::new_all();
47        sys.refresh_all();
48
49        Self {
50            cpu_cores: num_cpus::get_physical(),
51            cpu_threads: num_cpus::get(),
52            total_memory_mb: sys.total_memory() / 1024 / 1024,
53            available_memory_mb: sys.available_memory() / 1024 / 1024,
54        }
55    }
56
57    /// 判断系统资源等级
58    ///
59    /// 根据CPU核心数和内存大小评估系统资源等级:
60    /// - **High**: 8核以上 + 16GB以上内存
61    /// - **Medium**: 4核以上 + 8GB以上内存
62    /// - **Low**: 其他配置
63    ///
64    /// # 返回值
65    /// * `ResourceTier` - 系统资源等级枚举
66    ///
67    /// # 示例
68    /// ```rust
69    /// let resources = SystemResources::detect();
70    /// match resources.resource_tier() {
71    ///     ResourceTier::High => println!("高配系统"),
72    ///     ResourceTier::Medium => println!("中配系统"),
73    ///     ResourceTier::Low => println!("低配系统"),
74    /// }
75    /// ```
76    pub fn resource_tier(&self) -> ResourceTier {
77        match (self.cpu_cores, self.total_memory_mb) {
78            // 高配:8核以上 + 16GB以上
79            (cores, mem) if cores >= 8 && mem >= 16000 => ResourceTier::High,
80            // 中配:4核以上 + 8GB以上
81            (cores, mem) if cores >= 4 && mem >= 8000 => ResourceTier::Medium,
82            // 低配:其他
83            _ => ResourceTier::Low,
84        }
85    }
86
87    /// 获取系统资源等级的描述字符串
88    pub fn tier_description(&self) -> &'static str {
89        match self.resource_tier() {
90            ResourceTier::High => "高性能",
91            ResourceTier::Medium => "标准配置",
92            ResourceTier::Low => "基础配置",
93        }
94    }
95}
96
97/// 系统资源等级
98#[derive(Debug, Clone, Copy, PartialEq, Eq)]
99pub enum ResourceTier {
100    /// 低配机器(<4核 或 <8GB内存)
101    Low,
102    /// 中配机器(4-7核 + 8-15GB内存)
103    Medium,
104    /// 高配机器(≥8核 + ≥16GB内存)
105    High,
106}
107
108impl ResourceTier {
109    /// 获取资源等级的字符串表示
110    pub fn as_str(&self) -> &'static str {
111        match self {
112            ResourceTier::Low => "Low",
113            ResourceTier::Medium => "Medium",
114            ResourceTier::High => "High",
115        }
116    }
117}
118
119impl std::fmt::Display for ResourceTier {
120    fn fmt(
121        &self,
122        f: &mut std::fmt::Formatter<'_>,
123    ) -> std::fmt::Result {
124        write!(f, "{}", self.as_str())
125    }
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    #[test]
133    fn test_system_resources_detect() {
134        let resources = SystemResources::detect();
135
136        // 基本验证:任何系统都应该有CPU和内存
137        assert!(resources.cpu_cores > 0, "CPU核心数应该大于0");
138        assert!(resources.cpu_threads > 0, "CPU线程数应该大于0");
139        assert!(resources.total_memory_mb > 0, "总内存应该大于0");
140
141        // CPU线程数应该大于等于核心数
142        assert!(
143            resources.cpu_threads >= resources.cpu_cores,
144            "CPU线程数应该大于等于核心数"
145        );
146    }
147
148    #[test]
149    fn test_resource_tier() {
150        // 测试低配
151        let low_resources = SystemResources {
152            cpu_cores: 2,
153            cpu_threads: 2,
154            total_memory_mb: 4096,
155            available_memory_mb: 2048,
156        };
157        assert_eq!(low_resources.resource_tier(), ResourceTier::Low);
158
159        // 测试中配
160        let medium_resources = SystemResources {
161            cpu_cores: 4,
162            cpu_threads: 8,
163            total_memory_mb: 8192,
164            available_memory_mb: 4096,
165        };
166        assert_eq!(medium_resources.resource_tier(), ResourceTier::Medium);
167
168        // 测试高配
169        let high_resources = SystemResources {
170            cpu_cores: 8,
171            cpu_threads: 16,
172            total_memory_mb: 16384,
173            available_memory_mb: 8192,
174        };
175        assert_eq!(high_resources.resource_tier(), ResourceTier::High);
176    }
177
178    #[test]
179    fn test_tier_description() {
180        let resources = SystemResources::detect();
181        let description = resources.tier_description();
182        assert!(["高性能", "标准配置", "基础配置"].contains(&description));
183    }
184}