Skip to main content

ignis_db/config/
mod.rs

1//! Configuration Management for Ignis-DB
2//!
3//! This module provides configuration-driven database connection management
4//! that extends the existing TransactionManager without breaking existing APIs.
5
6use crate::exec::transaction::{IsolationLevel, TransactionConfig};
7use anyhow::{Context, Result};
8use serde::{Deserialize, Serialize};
9use std::time::Duration;
10
11/// Main configuration for Ignis-DB
12#[derive(Debug, Clone, Serialize, Deserialize)]
13pub struct IgnisConfig {
14    /// Database connection configuration
15    pub database: DatabaseConfig,
16    /// Connection pool configuration
17    pub pool: PoolConfig,
18    /// Transaction configuration (reuses existing TransactionConfig)
19    pub transaction: TransactionConfig,
20    /// Query cache configuration
21    pub cache: CacheConfig,
22    /// Performance tuning configuration
23    pub performance: PerformanceConfig,
24    /// Monitoring and logging configuration
25    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    /// Load configuration from YAML file
43    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    /// Load configuration from environment variables
54    pub fn from_env() -> Result<Self> {
55        let mut config = Self::default();
56
57        // Database URL
58        if let Ok(url) = std::env::var("IGNIS_DATABASE_URL") {
59            config.database.url = url;
60        }
61
62        // Pool settings
63        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        // Transaction settings
72        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    /// Save configuration to YAML file
82    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    /// Validate configuration
93    pub fn validate(&self) -> Result<()> {
94        // Validate database URL
95        if self.database.url.is_empty() {
96            anyhow::bail!("Database URL cannot be empty");
97        }
98
99        // Validate pool settings
100        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        // Validate timeouts
107        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/// Database connection configuration
116#[derive(Debug, Clone, Serialize, Deserialize)]
117pub struct DatabaseConfig {
118    /// Database connection URL
119    pub url: String,
120    /// Database name (extracted from URL if not specified)
121    pub name: Option<String>,
122    /// Schema to use by default
123    pub default_schema: Option<String>,
124    /// SSL mode
125    pub ssl_mode: Option<SslMode>,
126    /// Connection timeout
127    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/// SSL connection modes
143#[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/// Connection pool configuration
167#[derive(Debug, Clone, Serialize, Deserialize)]
168pub struct PoolConfig {
169    /// Maximum number of connections in the pool
170    pub max_connections: Option<u32>,
171    /// Minimum number of connections to maintain
172    pub min_connections: Option<u32>,
173    /// Maximum time to wait for a connection
174    pub acquire_timeout: Option<Duration>,
175    /// Maximum time a connection can be idle
176    pub idle_timeout: Option<Duration>,
177    /// Maximum lifetime of a connection
178    pub max_lifetime: Option<Duration>,
179    /// Test connections before use
180    pub test_before_acquire: Option<bool>,
181    /// Health check SQL query
182    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)), // 10 minutes
192            max_lifetime: Some(Duration::from_secs(1800)), // 30 minutes
193            test_before_acquire: Some(true),
194            health_check_sql: Some("SELECT 1".to_string()),
195        }
196    }
197}
198
199/// Query cache configuration
200#[derive(Debug, Clone, Serialize, Deserialize)]
201pub struct CacheConfig {
202    /// Enable query result caching
203    pub enable_caching: bool,
204    /// Maximum number of cached queries
205    pub max_cached_queries: usize,
206    /// Cache entry TTL
207    pub cache_ttl: Duration,
208    /// Enable LRU eviction
209    pub enable_lru_eviction: bool,
210    /// LRU eviction threshold (percentage)
211    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), // 5 minutes
220            enable_lru_eviction: true,
221            lru_eviction_threshold: 80, // Evict when 80% full
222        }
223    }
224}
225
226/// Performance tuning configuration
227#[derive(Debug, Clone, Serialize, Deserialize)]
228pub struct PerformanceConfig {
229    /// Enable query performance monitoring
230    pub enable_query_monitoring: bool,
231    /// Enable connection pool monitoring
232    pub enable_pool_monitoring: bool,
233    /// Enable statement caching
234    pub enable_statement_caching: bool,
235    /// Maximum prepared statements
236    pub max_prepared_statements: usize,
237    /// Enable connection pooling
238    pub enable_connection_pooling: bool,
239    /// Connection pool size multiplier
240    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/// Monitoring and logging configuration
257#[derive(Debug, Clone, Serialize, Deserialize)]
258pub struct MonitoringConfig {
259    /// Enable query performance monitoring
260    pub enable_query_monitoring: bool,
261    /// Enable connection pool monitoring
262    pub enable_pool_monitoring: bool,
263    /// Enable transaction monitoring
264    pub enable_transaction_monitoring: bool,
265    /// Enable cache performance monitoring
266    pub enable_cache_monitoring: bool,
267    /// Metrics collection interval
268    pub metrics_interval: Duration,
269    /// Enable slow query logging
270    pub enable_slow_query_logging: bool,
271    /// Slow query threshold
272    pub slow_query_threshold: Duration,
273    /// Enable error logging
274    pub enable_error_logging: bool,
275    /// Log level for database operations
276    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), // 1 minute
287            enable_slow_query_logging: true,
288            slow_query_threshold: Duration::from_secs(1), // 1 second
289            enable_error_logging: true,
290            log_level: LogLevel::Info,
291        }
292    }
293}
294
295/// Log level for database operations
296#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
297pub enum LogLevel {
298    /// No logging
299    None,
300    /// Error logging only
301    Error,
302    /// Warning and error logging
303    Warn,
304    /// Info, warning, and error logging
305    Info,
306    /// Debug, info, warning, and error logging
307    Debug,
308    /// Trace, debug, info, warning, and error logging
309    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/// Configuration builder for fluent configuration
326#[derive(Debug)]
327pub struct IgnisConfigBuilder {
328    config: IgnisConfig,
329}
330
331impl IgnisConfigBuilder {
332    /// Create a new configuration builder
333    pub fn new() -> Self {
334        Self {
335            config: IgnisConfig::default(),
336        }
337    }
338
339    /// Set database URL
340    pub fn database_url(mut self, url: impl Into<String>) -> Self {
341        self.config.database.url = url.into();
342        self
343    }
344
345    /// Set maximum connections
346    pub fn max_connections(mut self, max: u32) -> Self {
347        self.config.pool.max_connections = Some(max);
348        self
349    }
350
351    /// Set minimum connections
352    pub fn min_connections(mut self, min: u32) -> Self {
353        self.config.pool.min_connections = Some(min);
354        self
355    }
356
357    /// Set transaction timeout
358    pub fn transaction_timeout(mut self, timeout: Duration) -> Self {
359        self.config.transaction.timeout = timeout;
360        self
361    }
362
363    /// Set isolation level
364    pub fn isolation_level(mut self, level: IsolationLevel) -> Self {
365        self.config.transaction.isolation_level = level;
366        self
367    }
368
369    /// Enable query monitoring
370    pub fn enable_query_monitoring(mut self, enable: bool) -> Self {
371        self.config.monitoring.enable_query_monitoring = enable;
372        self
373    }
374
375    /// Build the configuration
376    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}