mf_core/runtime/
builder.rs

1//! 统一运行时构建器
2//!
3//! 提供统一的运行时创建接口,支持:
4//! 1. 自动检测系统资源并选择最优运行时
5//! 2. 手动指定运行时类型
6//! 3. 使用配置文件创建运行时
7//!
8//! # 使用示例
9//!
10//! ## 完全自动(推荐)
11//! ```rust
12//! use mf_core::runtime::builder::ForgeRuntimeBuilder;
13//!
14//! // 自动检测系统资源,选择最优运行时和配置
15//! let runtime = ForgeRuntimeBuilder::auto().await?;
16//! ```
17//!
18//! ## 手动指定类型
19//! ```rust
20//! use mf_core::runtime::builder::ForgeRuntimeBuilder;
21//! use mf_core::config::RuntimeType;
22//!
23//! // 明确使用Actor运行时
24//! let runtime = ForgeRuntimeBuilder::with_type(RuntimeType::Actor).await?;
25//! ```
26//!
27//! ## 使用配置
28//! ```rust
29//! use mf_core::runtime::builder::ForgeRuntimeBuilder;
30//! use mf_core::config::{ForgeConfig, RuntimeType, RuntimeConfig};
31//!
32//! let config = ForgeConfig {
33//!     runtime: RuntimeConfig {
34//!         runtime_type: RuntimeType::Async,
35//!     },
36//!     ..Default::default()
37//! };
38//! let runtime = ForgeRuntimeBuilder::from_config(config, None).await?;
39//! ```
40
41use crate::{
42    config::{ForgeConfig, RuntimeType},
43    debug::info,
44    runtime::{
45        adaptive::AdaptiveRuntimeSelector, actor_runtime::ForgeActorRuntime,
46        async_runtime::ForgeAsyncRuntime, runtime::ForgeRuntime,
47        runtime_trait::RuntimeTrait, system_detector::SystemResources,
48    },
49    types::RuntimeOptions,
50    ForgeResult,
51};
52
53/// 统一运行时构建器
54///
55/// 提供多种创建运行时的方式:
56/// - `auto()`: 完全自动,根据系统资源选择
57/// - `with_type()`: 手动指定运行时类型
58/// - `from_config()`: 从配置创建
59pub struct ForgeRuntimeBuilder;
60
61impl ForgeRuntimeBuilder {
62    /// 🎯 完全自动创建 - 检测系统资源并创建最优运行时
63    ///
64    /// 这是推荐的创建方式,会:
65    /// 1. 自动检测CPU核心数和内存大小
66    /// 2. 根据系统资源选择最优运行时类型
67    /// 3. 生成优化的配置参数
68    /// 4. 输出检测和配置信息
69    ///
70    /// # 参数
71    /// * `options` - 可选的运行时选项(为None时使用默认值)
72    ///
73    /// # 返回值
74    /// * `ForgeResult<Box<dyn RuntimeTrait>>` - 运行时实例或错误
75    ///
76    /// # 示例
77    /// ```rust
78    /// // 使用默认选项
79    /// let runtime = ForgeRuntimeBuilder::auto(None).await?;
80    ///
81    /// // 使用自定义选项
82    /// let options = RuntimeOptions::default();
83    /// let runtime = ForgeRuntimeBuilder::auto(Some(options)).await?;
84    ///
85    /// // 输出示例:
86    /// // 🖥️  系统资源: 8 核心, 16 GB 内存 (高性能)
87    /// // ⚡ 运行时类型: Actor
88    /// // 📊 并发任务数: 6
89    /// // 💾 队列大小: 1600
90    /// ```
91    pub async fn auto(
92        options: Option<RuntimeOptions>
93    ) -> ForgeResult<Box<dyn RuntimeTrait>> {
94        // 1. 检测系统资源
95        let resources = SystemResources::detect();
96
97        // 2. 生成自适应配置
98        let config = AdaptiveRuntimeSelector::generate_config(&resources);
99
100        // 3. 输出配置信息
101        info!(
102            "🖥️  系统资源: {} 核心 / {} 线程, {} GB 内存 ({})",
103            resources.cpu_cores,
104            resources.cpu_threads,
105            resources.total_memory_mb / 1024,
106            resources.tier_description()
107        );
108        info!("⚡ 运行时类型: {:?}", config.runtime.runtime_type);
109        info!("📊 并发任务数: {}", config.processor.max_concurrent_tasks);
110        info!("💾 队列大小: {}", config.processor.max_queue_size);
111
112        // 4. 创建运行时
113        Self::from_config(config, options).await
114    }
115
116    /// 使用指定的运行时类型创建
117    ///
118    /// 仍然会检测系统资源并优化配置,但强制使用指定的运行时类型。
119    ///
120    /// # 参数
121    /// * `runtime_type` - 指定的运行时类型
122    ///
123    /// # 返回值
124    /// * `ForgeResult<Box<dyn RuntimeTrait>>` - 运行时实例或错误
125    ///
126    /// # 示例
127    /// ```rust
128    /// use mf_core::config::RuntimeType;
129    ///
130    /// // 强制使用Actor运行时,但配置参数仍然自适应
131    /// let runtime = ForgeRuntimeBuilder::with_type(RuntimeType::Actor).await?;
132    /// ```
133    pub async fn with_type(
134        runtime_type: RuntimeType,
135        options: Option<RuntimeOptions>,
136    ) -> ForgeResult<Box<dyn RuntimeTrait>> {
137        let resources = SystemResources::detect();
138        let mut config = AdaptiveRuntimeSelector::generate_config(&resources);
139        config.runtime.runtime_type = runtime_type;
140
141        info!("⚡ 使用指定运行时: {:?}", runtime_type);
142        Self::from_config(config, options).await
143    }
144
145    /// 从配置创建运行时
146    ///
147    /// 如果配置中的运行时类型为 `Auto`,会自动检测系统资源。
148    ///
149    /// # 参数
150    /// * `config` - Forge配置
151    /// * `options` - 可选的运行时选项(为None时使用默认值)
152    ///
153    /// # 返回值
154    /// * `ForgeResult<Box<dyn RuntimeTrait>>` - 运行时实例或错误
155    ///
156    /// # 示例
157    /// ```rust
158    /// let config = ForgeConfig {
159    ///     runtime: RuntimeConfig {
160    ///         runtime_type: RuntimeType::Auto, // 自动检测
161    ///     },
162    ///     ..Default::default()
163    /// };
164    /// let runtime = ForgeRuntimeBuilder::from_config(config, None).await?;
165    /// ```
166    pub async fn from_config(
167        config: ForgeConfig,
168        options: Option<RuntimeOptions>,
169    ) -> ForgeResult<Box<dyn RuntimeTrait>> {
170        let options = options.unwrap_or_default();
171
172        // 如果是Auto,检测系统资源并选择运行时
173        let runtime_type = match config.runtime.runtime_type {
174            RuntimeType::Auto => {
175                let resources = SystemResources::detect();
176                AdaptiveRuntimeSelector::select_runtime(&resources)
177            },
178            rt => rt,
179        };
180
181        Self::create_with_type(runtime_type, options, config).await
182    }
183
184    /// 内部方法:根据运行时类型创建实例
185    async fn create_with_type(
186        runtime_type: RuntimeType,
187        options: RuntimeOptions,
188        config: ForgeConfig,
189    ) -> ForgeResult<Box<dyn RuntimeTrait>> {
190        match runtime_type {
191            RuntimeType::Sync => Ok(Box::new(
192                ForgeRuntime::create_with_config(options, config).await?,
193            )),
194            RuntimeType::Async => Ok(Box::new(
195                ForgeAsyncRuntime::create_with_config(options, config).await?,
196            )),
197            RuntimeType::Actor => Ok(Box::new(
198                ForgeActorRuntime::create_with_config(options, config).await?,
199            )),
200            RuntimeType::Auto => {
201                unreachable!("Auto should be resolved before this point")
202            },
203        }
204    }
205}
206
207/// 为RuntimeTrait添加辅助方法
208pub trait RuntimeExt {
209    /// 获取运行时类型描述
210    fn runtime_type_name(&self) -> &'static str;
211}
212
213impl RuntimeExt for Box<dyn RuntimeTrait> {
214    fn runtime_type_name(&self) -> &'static str {
215        // 简单返回"Runtime",因为trait object无法直接判断具体类型
216        // 如需准确类型,可在RuntimeTrait中添加type_name方法
217        "Runtime"
218    }
219}
220
221#[cfg(test)]
222mod tests {
223    use super::*;
224
225    #[tokio::test]
226    async fn test_auto_creation() {
227        // 测试自动创建
228        let result = ForgeRuntimeBuilder::auto(None).await;
229
230        // 应该成功创建
231        assert!(result.is_ok(), "自动创建运行时应该成功");
232    }
233
234    #[tokio::test]
235    async fn test_with_type_creation() {
236        // 测试指定类型创建
237        let result =
238            ForgeRuntimeBuilder::with_type(RuntimeType::Sync, None).await;
239
240        assert!(result.is_ok(), "指定类型创建应该成功");
241    }
242
243    #[tokio::test]
244    async fn test_from_config_auto() {
245        let config = ForgeConfig {
246            runtime: crate::config::RuntimeConfig {
247                runtime_type: RuntimeType::Auto,
248            },
249            ..Default::default()
250        };
251
252        let result = ForgeRuntimeBuilder::from_config(config, None).await;
253        assert!(result.is_ok(), "从Auto配置创建应该成功");
254    }
255
256    #[tokio::test]
257    async fn test_from_config_sync() {
258        let config = ForgeConfig {
259            runtime: crate::config::RuntimeConfig {
260                runtime_type: RuntimeType::Sync,
261            },
262            ..Default::default()
263        };
264
265        let result = ForgeRuntimeBuilder::from_config(config, None).await;
266        assert!(result.is_ok(), "从Sync配置创建应该成功");
267    }
268}