mofa_runtime/config/
mod.rs1use mofa_kernel::config::load_config;
12use serde::{Deserialize, Serialize};
13use std::collections::HashMap;
14use std::path::Path;
15use thiserror::Error;
16
17#[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
36pub struct ConfigLoader {
38 config: FrameworkConfig,
39}
40
41impl ConfigLoader {
42 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 pub fn from_env() -> Result<Self, ConfigError> {
59 Ok(Self {
62 config: FrameworkConfig::default(),
63 })
64 }
65
66 pub fn config(&self) -> &FrameworkConfig {
68 &self.config
69 }
70
71 pub fn database_config(&self) -> &DatabaseConfig {
73 &self.config.database
74 }
75
76 pub fn cache_config(&self) -> &CacheConfig {
78 &self.config.cache
79 }
80
81 pub fn message_queue_config(&self) -> &MessageQueueConfig {
83 &self.config.message_queue
84 }
85}
86
87#[derive(Debug, Serialize, Deserialize, Default)]
89pub struct DatabaseConfig {
90 pub r#type: String,
92
93 pub url: String,
95
96 pub max_connections: Option<u32>,
98
99 pub connection_timeout: Option<u32>,
101
102 pub idle_timeout: Option<u32>,
104
105 pub extra: Option<HashMap<String, String>>,
107}
108
109#[derive(Debug, Serialize, Deserialize, Default)]
111pub struct CacheConfig {
112 pub r#type: String,
114
115 pub servers: Vec<String>,
117
118 pub prefix: Option<String>,
120
121 pub default_ttl: Option<u32>,
123
124 pub max_size: Option<usize>,
126
127 pub extra: Option<HashMap<String, String>>,
129}
130
131#[derive(Debug, Serialize, Deserialize, Default)]
133pub struct MessageQueueConfig {
134 pub r#type: String,
136
137 pub brokers: Vec<String>,
139
140 pub topic: Option<String>,
142
143 pub group_id: Option<String>,
145
146 pub extra: Option<HashMap<String, String>>,
148}
149
150#[derive(Debug, Serialize, Deserialize, Default)]
152pub struct FrameworkConfig {
153 pub database: DatabaseConfig,
155
156 pub cache: CacheConfig,
158
159 pub message_queue: MessageQueueConfig,
161
162 pub framework_name: Option<String>,
164
165 pub framework_version: Option<String>,
167
168 pub environment: Option<String>,
170}