1use crate::exec::transaction::{IsolationLevel, TransactionConfig};
7use anyhow::{Context, Result};
8use serde::{Deserialize, Serialize};
9use std::time::Duration;
10
11#[derive(Debug, Clone, Serialize, Deserialize)]
13pub struct IgnisConfig {
14 pub database: DatabaseConfig,
16 pub pool: PoolConfig,
18 pub transaction: TransactionConfig,
20 pub cache: CacheConfig,
22 pub performance: PerformanceConfig,
24 pub monitoring: MonitoringConfig,
26}
27
28impl Default for IgnisConfig {
29 fn default() -> Self {
30 Self {
31 database: DatabaseConfig::default(),
32 pool: PoolConfig::default(),
33 transaction: TransactionConfig::default(),
34 cache: CacheConfig::default(),
35 performance: PerformanceConfig::default(),
36 monitoring: MonitoringConfig::default(),
37 }
38 }
39}
40
41impl IgnisConfig {
42 pub fn from_yaml_file(path: &str) -> Result<Self> {
44 let content = std::fs::read_to_string(path)
45 .with_context(|| format!("Failed to read config file: {}", path))?;
46
47 let config: Self = serde_yaml::from_str(&content)
48 .with_context(|| format!("Failed to parse YAML config from: {}", path))?;
49
50 Ok(config)
51 }
52
53 pub fn from_env() -> Result<Self> {
55 let mut config = Self::default();
56
57 if let Ok(url) = std::env::var("IGNIS_DATABASE_URL") {
59 config.database.url = url;
60 }
61
62 if let Ok(max_conn) = std::env::var("IGNIS_MAX_CONNECTIONS") {
64 config.pool.max_connections = max_conn.parse().ok();
65 }
66
67 if let Ok(min_conn) = std::env::var("IGNIS_MIN_CONNECTIONS") {
68 config.pool.min_connections = min_conn.parse().ok();
69 }
70
71 if let Ok(timeout) = std::env::var("IGNIS_TRANSACTION_TIMEOUT") {
73 if let Ok(secs) = timeout.parse::<u64>() {
74 config.transaction.timeout = Duration::from_secs(secs);
75 }
76 }
77
78 Ok(config)
79 }
80
81 pub fn save_to_yaml_file(&self, path: &str) -> Result<()> {
83 let content =
84 serde_yaml::to_string(self).with_context(|| "Failed to serialize config to YAML")?;
85
86 std::fs::write(path, content)
87 .with_context(|| format!("Failed to write config file: {}", path))?;
88
89 Ok(())
90 }
91
92 pub fn validate(&self) -> Result<()> {
94 if self.database.url.is_empty() {
96 anyhow::bail!("Database URL cannot be empty");
97 }
98
99 if let (Some(min), Some(max)) = (self.pool.min_connections, self.pool.max_connections) {
101 if min > max {
102 anyhow::bail!("min_connections cannot be greater than max_connections");
103 }
104 }
105
106 if self.pool.acquire_timeout.unwrap_or(Duration::from_secs(30)) < Duration::from_secs(1) {
108 anyhow::bail!("acquire_timeout must be at least 1 second");
109 }
110
111 Ok(())
112 }
113}
114
115#[derive(Debug, Clone, Serialize, Deserialize)]
117pub struct DatabaseConfig {
118 pub url: String,
120 pub name: Option<String>,
122 pub default_schema: Option<String>,
124 pub ssl_mode: Option<SslMode>,
126 pub connect_timeout: Option<Duration>,
128}
129
130impl Default for DatabaseConfig {
131 fn default() -> Self {
132 Self {
133 url: "postgresql://localhost/ignis_test".to_string(),
134 name: None,
135 default_schema: Some("public".to_string()),
136 ssl_mode: Some(SslMode::Prefer),
137 connect_timeout: Some(Duration::from_secs(10)),
138 }
139 }
140}
141
142#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
144pub enum SslMode {
145 Disable,
146 Allow,
147 Prefer,
148 Require,
149 VerifyCa,
150 VerifyFull,
151}
152
153impl std::fmt::Display for SslMode {
154 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155 match self {
156 SslMode::Disable => write!(f, "disable"),
157 SslMode::Allow => write!(f, "allow"),
158 SslMode::Prefer => write!(f, "prefer"),
159 SslMode::Require => write!(f, "require"),
160 SslMode::VerifyCa => write!(f, "verify-ca"),
161 SslMode::VerifyFull => write!(f, "verify-full"),
162 }
163 }
164}
165
166#[derive(Debug, Clone, Serialize, Deserialize)]
168pub struct PoolConfig {
169 pub max_connections: Option<u32>,
171 pub min_connections: Option<u32>,
173 pub acquire_timeout: Option<Duration>,
175 pub idle_timeout: Option<Duration>,
177 pub max_lifetime: Option<Duration>,
179 pub test_before_acquire: Option<bool>,
181 pub health_check_sql: Option<String>,
183}
184
185impl Default for PoolConfig {
186 fn default() -> Self {
187 Self {
188 max_connections: Some(10),
189 min_connections: Some(2),
190 acquire_timeout: Some(Duration::from_secs(30)),
191 idle_timeout: Some(Duration::from_secs(600)), max_lifetime: Some(Duration::from_secs(1800)), test_before_acquire: Some(true),
194 health_check_sql: Some("SELECT 1".to_string()),
195 }
196 }
197}
198
199#[derive(Debug, Clone, Serialize, Deserialize)]
201pub struct CacheConfig {
202 pub enable_caching: bool,
204 pub max_cached_queries: usize,
206 pub cache_ttl: Duration,
208 pub enable_lru_eviction: bool,
210 pub lru_eviction_threshold: u8,
212}
213
214impl Default for CacheConfig {
215 fn default() -> Self {
216 Self {
217 enable_caching: true,
218 max_cached_queries: 1000,
219 cache_ttl: Duration::from_secs(300), enable_lru_eviction: true,
221 lru_eviction_threshold: 80, }
223 }
224}
225
226#[derive(Debug, Clone, Serialize, Deserialize)]
228pub struct PerformanceConfig {
229 pub enable_query_monitoring: bool,
231 pub enable_pool_monitoring: bool,
233 pub enable_statement_caching: bool,
235 pub max_prepared_statements: usize,
237 pub enable_connection_pooling: bool,
239 pub pool_size_multiplier: f32,
241}
242
243impl Default for PerformanceConfig {
244 fn default() -> Self {
245 Self {
246 enable_query_monitoring: true,
247 enable_pool_monitoring: true,
248 enable_statement_caching: true,
249 max_prepared_statements: 100,
250 enable_connection_pooling: true,
251 pool_size_multiplier: 1.0,
252 }
253 }
254}
255
256#[derive(Debug, Clone, Serialize, Deserialize)]
258pub struct MonitoringConfig {
259 pub enable_query_monitoring: bool,
261 pub enable_pool_monitoring: bool,
263 pub enable_transaction_monitoring: bool,
265 pub enable_cache_monitoring: bool,
267 pub metrics_interval: Duration,
269 pub enable_slow_query_logging: bool,
271 pub slow_query_threshold: Duration,
273 pub enable_error_logging: bool,
275 pub log_level: LogLevel,
277}
278
279impl Default for MonitoringConfig {
280 fn default() -> Self {
281 Self {
282 enable_query_monitoring: true,
283 enable_pool_monitoring: true,
284 enable_transaction_monitoring: true,
285 enable_cache_monitoring: true,
286 metrics_interval: Duration::from_secs(60), enable_slow_query_logging: true,
288 slow_query_threshold: Duration::from_secs(1), enable_error_logging: true,
290 log_level: LogLevel::Info,
291 }
292 }
293}
294
295#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
297pub enum LogLevel {
298 None,
300 Error,
302 Warn,
304 Info,
306 Debug,
308 Trace,
310}
311
312impl std::fmt::Display for LogLevel {
313 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
314 match self {
315 LogLevel::None => write!(f, "none"),
316 LogLevel::Error => write!(f, "error"),
317 LogLevel::Warn => write!(f, "warn"),
318 LogLevel::Info => write!(f, "info"),
319 LogLevel::Debug => write!(f, "debug"),
320 LogLevel::Trace => write!(f, "trace"),
321 }
322 }
323}
324
325#[derive(Debug)]
327pub struct IgnisConfigBuilder {
328 config: IgnisConfig,
329}
330
331impl IgnisConfigBuilder {
332 pub fn new() -> Self {
334 Self {
335 config: IgnisConfig::default(),
336 }
337 }
338
339 pub fn database_url(mut self, url: impl Into<String>) -> Self {
341 self.config.database.url = url.into();
342 self
343 }
344
345 pub fn max_connections(mut self, max: u32) -> Self {
347 self.config.pool.max_connections = Some(max);
348 self
349 }
350
351 pub fn min_connections(mut self, min: u32) -> Self {
353 self.config.pool.min_connections = Some(min);
354 self
355 }
356
357 pub fn transaction_timeout(mut self, timeout: Duration) -> Self {
359 self.config.transaction.timeout = timeout;
360 self
361 }
362
363 pub fn isolation_level(mut self, level: IsolationLevel) -> Self {
365 self.config.transaction.isolation_level = level;
366 self
367 }
368
369 pub fn enable_query_monitoring(mut self, enable: bool) -> Self {
371 self.config.monitoring.enable_query_monitoring = enable;
372 self
373 }
374
375 pub fn build(self) -> Result<IgnisConfig> {
377 self.config.validate()?;
378 Ok(self.config)
379 }
380}
381
382impl Default for IgnisConfigBuilder {
383 fn default() -> Self {
384 Self::new()
385 }
386}