Skip to main content

mofa_runtime/config/
mod.rs

1//! 统一配置管理模块
2//!
3//! 提供框架级的配置加载、解析和访问接口,支持:
4//! - 多种配置格式 (YAML, TOML, JSON, INI, RON, JSON5)
5//! - 数据库配置
6//! - 缓存配置
7//! - 消息队列配置
8//! - 多环境支持
9//! - 配置热加载
10
11use mofa_kernel::config::load_config;
12use serde::{Deserialize, Serialize};
13use std::collections::HashMap;
14use std::path::Path;
15use thiserror::Error;
16
17/// 配置错误类型
18#[derive(Error, Debug)]
19pub enum ConfigError {
20    #[error("IO error: {0}")]
21    Io(#[from] std::io::Error),
22
23    #[error("Config parse error: {0}")]
24    Parse(String),
25
26    #[error("Config field missing: {0}")]
27    FieldMissing(&'static str),
28
29    #[error("Invalid config value: {0}")]
30    InvalidValue(&'static str),
31
32    #[error("Unsupported config format: {0}")]
33    UnsupportedFormat(String),
34}
35
36/// 配置加载器
37pub struct ConfigLoader {
38    config: FrameworkConfig,
39}
40
41impl ConfigLoader {
42    /// 从文件加载配置 (自动检测格式)
43    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, ConfigError> {
44        let path_str = path.as_ref().to_string_lossy().to_string();
45        let config = load_config(&path_str).map_err(|e| match e {
46            mofa_kernel::config::ConfigError::Io(e) => ConfigError::Io(e),
47            mofa_kernel::config::ConfigError::Parse(e) => ConfigError::Parse(e.to_string()),
48            mofa_kernel::config::ConfigError::Serialization(e) => ConfigError::Parse(e),
49            mofa_kernel::config::ConfigError::UnsupportedFormat(e) => {
50                ConfigError::UnsupportedFormat(e)
51            }
52        })?;
53
54        Ok(Self { config })
55    }
56
57    /// 从环境变量加载配置
58    pub fn from_env() -> Result<Self, ConfigError> {
59        // 从环境变量构建配置
60        // 这里实现简化版本,实际可以使用 envy 等库
61        Ok(Self {
62            config: FrameworkConfig::default(),
63        })
64    }
65
66    /// 获取完整配置
67    pub fn config(&self) -> &FrameworkConfig {
68        &self.config
69    }
70
71    /// 获取数据库配置
72    pub fn database_config(&self) -> &DatabaseConfig {
73        &self.config.database
74    }
75
76    /// 获取缓存配置
77    pub fn cache_config(&self) -> &CacheConfig {
78        &self.config.cache
79    }
80
81    /// 获取消息队列配置
82    pub fn message_queue_config(&self) -> &MessageQueueConfig {
83        &self.config.message_queue
84    }
85}
86
87/// 数据库配置
88#[derive(Debug, Serialize, Deserialize, Default)]
89pub struct DatabaseConfig {
90    /// 数据库类型
91    pub r#type: String,
92
93    /// 数据库连接URL
94    pub url: String,
95
96    /// 最大连接数
97    pub max_connections: Option<u32>,
98
99    /// 连接超时时间(秒)
100    pub connection_timeout: Option<u32>,
101
102    /// 空闲连接超时时间(秒)
103    pub idle_timeout: Option<u32>,
104
105    /// 额外配置参数
106    pub extra: Option<HashMap<String, String>>,
107}
108
109/// 缓存配置
110#[derive(Debug, Serialize, Deserialize, Default)]
111pub struct CacheConfig {
112    /// 缓存类型
113    pub r#type: String,
114
115    /// 缓存服务器地址
116    pub servers: Vec<String>,
117
118    /// 缓存前缀
119    pub prefix: Option<String>,
120
121    /// 默认过期时间(秒)
122    pub default_ttl: Option<u32>,
123
124    /// 最大容量
125    pub max_size: Option<usize>,
126
127    /// 额外配置参数
128    pub extra: Option<HashMap<String, String>>,
129}
130
131/// 消息队列配置
132#[derive(Debug, Serialize, Deserialize, Default)]
133pub struct MessageQueueConfig {
134    /// 消息队列类型
135    pub r#type: String,
136
137    /// 消息队列服务器地址
138    pub brokers: Vec<String>,
139
140    /// 消息队列主题
141    pub topic: Option<String>,
142
143    /// 消费组
144    pub group_id: Option<String>,
145
146    /// 额外配置参数
147    pub extra: Option<HashMap<String, String>>,
148}
149
150/// 框架核心配置
151#[derive(Debug, Serialize, Deserialize, Default)]
152pub struct FrameworkConfig {
153    /// 数据库配置
154    pub database: DatabaseConfig,
155
156    /// 缓存配置
157    pub cache: CacheConfig,
158
159    /// 消息队列配置
160    pub message_queue: MessageQueueConfig,
161
162    /// 框架名称
163    pub framework_name: Option<String>,
164
165    /// 框架版本
166    pub framework_version: Option<String>,
167
168    /// 环境名称
169    pub environment: Option<String>,
170}