Skip to main content

ignis_db/connection/
mod.rs

1//! Connection 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::config::IgnisConfig;
7use crate::exec::transaction::TransactionManager;
8use anyhow::{Context, Result};
9use sqlx::postgres::{PgConnectOptions, PgPool, PgPoolOptions};
10use std::str::FromStr;
11use std::sync::Arc;
12use std::time::Duration;
13
14/// Connection manager that handles pool creation and management
15#[derive(Debug)]
16pub struct ConnectionManager {
17    /// The managed connection pool
18    pool: PgPool,
19    /// Transaction manager using this pool
20    transaction_manager: Arc<TransactionManager>,
21    /// Configuration used to create this manager
22    config: IgnisConfig,
23}
24
25/// Connection pool statistics
26#[derive(Debug, Clone)]
27pub struct PoolStats {
28    /// Total number of connections in the pool
29    pub total_connections: u32,
30    /// Number of active (checked out) connections
31    pub active_connections: u32,
32    /// Number of idle connections
33    pub idle_connections: u32,
34    /// Maximum pool size
35    pub max_connections: u32,
36    /// Minimum pool size
37    pub min_connections: u32,
38}
39
40impl ConnectionManager {
41    /// Create a new connection manager from configuration
42    pub async fn from_config(config: IgnisConfig) -> Result<Self> {
43        // Validate configuration
44        config.validate()?;
45
46        // Create the connection pool
47        let pool = Self::create_pool(&config).await?;
48
49        // Create transaction manager with the pool
50        let transaction_manager = Arc::new(TransactionManager::new(
51            pool.clone(),
52            config.transaction.clone(),
53        ));
54
55        Ok(Self {
56            pool,
57            transaction_manager,
58            config,
59        })
60    }
61
62    /// Create a connection manager with default configuration
63    pub async fn new_default() -> Result<Self> {
64        let config = IgnisConfig::default();
65        Self::from_config(config).await
66    }
67
68    /// Create a connection manager from environment variables
69    pub async fn from_env() -> Result<Self> {
70        let config = IgnisConfig::from_env()?;
71        Self::from_config(config).await
72    }
73
74    /// Create a connection manager from YAML file
75    pub async fn from_yaml_file(path: &str) -> Result<Self> {
76        let config = IgnisConfig::from_yaml_file(path)?;
77        Self::from_config(config).await
78    }
79
80    /// Get a reference to the underlying pool
81    pub fn pool(&self) -> &PgPool {
82        &self.pool
83    }
84
85    /// Get a reference to the transaction manager
86    pub fn transaction_manager(&self) -> &Arc<TransactionManager> {
87        &self.transaction_manager
88    }
89
90    /// Get a reference to the configuration
91    pub fn config(&self) -> &IgnisConfig {
92        &self.config
93    }
94
95    /// Check if the connection pool is healthy
96    pub async fn health_check(&self) -> Result<bool> {
97        match sqlx::query("SELECT 1").fetch_one(&self.pool).await {
98            Ok(_) => Ok(true),
99            Err(_) => Ok(false),
100        }
101    }
102
103    /// Get connection pool statistics
104    pub async fn get_pool_stats(&self) -> Result<PoolStats> {
105        // Get pool state information
106        let pool_size = self.pool.size();
107        let max_size = self.config.pool.max_connections.unwrap_or(10) as u32;
108        let min_size = self.config.pool.min_connections.unwrap_or(1) as u32;
109
110        // Try to estimate active connections by checking how many we can acquire
111        // This is an approximation since sqlx doesn't expose detailed pool stats
112        let idle_connections = self.pool.num_idle() as u32;
113        let active_connections = (pool_size as u32).saturating_sub(idle_connections);
114
115        Ok(PoolStats {
116            total_connections: pool_size as u32,
117            active_connections,
118            idle_connections,
119            max_connections: max_size,
120            min_connections: min_size,
121        })
122    }
123
124    /// Close the connection pool
125    pub async fn close(&self) -> Result<()> {
126        self.pool.close().await;
127        Ok(())
128    }
129
130    /// Execute a query and return all results
131    pub async fn execute_query(&self, query: &str) -> Result<Vec<sqlx::postgres::PgRow>> {
132        let rows = sqlx::query(query)
133            .fetch_all(&self.pool)
134            .await
135            .with_context(|| format!("Failed to execute query: {}", query))?;
136        Ok(rows)
137    }
138
139    /// Execute a query and return one result
140    pub async fn execute_query_one(&self, query: &str) -> Result<Option<sqlx::postgres::PgRow>> {
141        let row = sqlx::query(query)
142            .fetch_optional(&self.pool)
143            .await
144            .with_context(|| format!("Failed to execute query: {}", query))?;
145        Ok(row)
146    }
147
148    /// Execute a command (INSERT, UPDATE, DELETE)
149    pub async fn execute_command(&self, query: &str) -> Result<u64> {
150        let result = sqlx::query(query)
151            .execute(&self.pool)
152            .await
153            .with_context(|| format!("Failed to execute command: {}", query))?;
154        Ok(result.rows_affected())
155    }
156
157    /// Test connection pool performance
158    pub async fn benchmark_pool(&self, concurrent_queries: usize) -> Result<PoolBenchmarkResult> {
159        use std::time::Instant;
160        use tokio::sync::Semaphore;
161
162        let start = Instant::now();
163        let semaphore = Arc::new(Semaphore::new(concurrent_queries));
164        let mut handles = Vec::new();
165
166        for i in 0..concurrent_queries {
167            let pool = self.pool.clone();
168            let permit = semaphore.clone().acquire_owned().await.unwrap();
169
170            let handle = tokio::spawn(async move {
171                let _permit = permit;
172                let query_start = Instant::now();
173                let result = sqlx::query("SELECT $1::int as test_value")
174                    .bind(i as i32)
175                    .fetch_one(&pool)
176                    .await;
177                let query_duration = query_start.elapsed();
178                (result.is_ok(), query_duration)
179            });
180
181            handles.push(handle);
182        }
183
184        let mut successful_queries = 0;
185        let mut total_query_time = Duration::ZERO;
186        let mut min_query_time = Duration::from_secs(u64::MAX);
187        let mut max_query_time = Duration::ZERO;
188
189        for handle in handles {
190            let (success, duration) = handle.await.unwrap();
191            if success {
192                successful_queries += 1;
193                total_query_time += duration;
194                min_query_time = min_query_time.min(duration);
195                max_query_time = max_query_time.max(duration);
196            }
197        }
198
199        let total_duration = start.elapsed();
200
201        Ok(PoolBenchmarkResult {
202            total_queries: concurrent_queries,
203            successful_queries,
204            failed_queries: concurrent_queries - successful_queries,
205            total_duration,
206            average_query_time: if successful_queries > 0 {
207                total_query_time / successful_queries as u32
208            } else {
209                Duration::ZERO
210            },
211            min_query_time: if successful_queries > 0 {
212                min_query_time
213            } else {
214                Duration::ZERO
215            },
216            max_query_time,
217            queries_per_second: if total_duration.as_secs_f64() > 0.0 {
218                successful_queries as f64 / total_duration.as_secs_f64()
219            } else {
220                0.0
221            },
222        })
223    }
224
225    /// Monitor pool health continuously
226    pub async fn start_health_monitor(&self, interval: Duration) -> Result<()> {
227        let pool = self.pool.clone();
228        let config = self.config.clone();
229
230        tokio::spawn(async move {
231            let mut interval_timer = tokio::time::interval(interval);
232
233            loop {
234                interval_timer.tick().await;
235
236                if config.monitoring.enable_pool_monitoring {
237                    match sqlx::query("SELECT 1").fetch_one(&pool).await {
238                        Ok(_) => {
239                            if config.monitoring.log_level == crate::config::LogLevel::Debug {
240                                println!("[IGNIS-DB] Pool health check: OK");
241                            }
242                        }
243                        Err(e) => {
244                            if config.monitoring.enable_error_logging {
245                                eprintln!("[IGNIS-DB] Pool health check failed: {}", e);
246                            }
247                        }
248                    }
249                }
250            }
251        });
252
253        Ok(())
254    }
255
256    /// Create a connection pool from configuration
257    async fn create_pool(config: &IgnisConfig) -> Result<PgPool> {
258        // Parse connection URL
259        let connect_options = PgConnectOptions::from_str(&config.database.url)
260            .with_context(|| format!("Failed to parse database URL: {}", config.database.url))?;
261
262        // Apply SSL mode if specified
263        let connect_options = if let Some(ssl_mode) = &config.database.ssl_mode {
264            match ssl_mode {
265                crate::config::SslMode::Disable => {
266                    connect_options.ssl_mode(sqlx::postgres::PgSslMode::Disable)
267                }
268                crate::config::SslMode::Allow => {
269                    connect_options.ssl_mode(sqlx::postgres::PgSslMode::Allow)
270                }
271                crate::config::SslMode::Prefer => {
272                    connect_options.ssl_mode(sqlx::postgres::PgSslMode::Prefer)
273                }
274                crate::config::SslMode::Require => {
275                    connect_options.ssl_mode(sqlx::postgres::PgSslMode::Require)
276                }
277                crate::config::SslMode::VerifyCa => {
278                    connect_options.ssl_mode(sqlx::postgres::PgSslMode::VerifyCa)
279                }
280                crate::config::SslMode::VerifyFull => {
281                    connect_options.ssl_mode(sqlx::postgres::PgSslMode::VerifyFull)
282                }
283            }
284        } else {
285            connect_options
286        };
287
288        // Apply connection timeout if specified
289        let connect_options = if let Some(_timeout) = config.database.connect_timeout {
290            // Note: sqlx doesn't have a direct connect_timeout method
291            // We'll use the pool-level timeout instead
292            connect_options
293        } else {
294            connect_options
295        };
296
297        // Create pool options
298        let mut pool_options = PgPoolOptions::new();
299
300        // Apply pool configuration
301        if let Some(max_connections) = config.pool.max_connections {
302            pool_options = pool_options.max_connections(max_connections);
303        }
304
305        if let Some(min_connections) = config.pool.min_connections {
306            pool_options = pool_options.min_connections(min_connections);
307        }
308
309        if let Some(acquire_timeout) = config.pool.acquire_timeout {
310            pool_options = pool_options.acquire_timeout(acquire_timeout);
311        }
312
313        if let Some(idle_timeout) = config.pool.idle_timeout {
314            pool_options = pool_options.idle_timeout(idle_timeout);
315        }
316
317        if let Some(max_lifetime) = config.pool.max_lifetime {
318            pool_options = pool_options.max_lifetime(max_lifetime);
319        }
320
321        if let Some(test_before_acquire) = config.pool.test_before_acquire {
322            if test_before_acquire {
323                pool_options = pool_options.test_before_acquire(true);
324            }
325        }
326
327        // Create the pool
328        let pool = pool_options
329            .connect_with(connect_options)
330            .await
331            .with_context(|| "Failed to create connection pool")?;
332
333        Ok(pool)
334    }
335}
336
337/// Connection pool statistics
338
339/// Pool benchmark results
340#[derive(Debug, Clone)]
341pub struct PoolBenchmarkResult {
342    /// Total number of queries attempted
343    pub total_queries: usize,
344    /// Number of successful queries
345    pub successful_queries: usize,
346    /// Number of failed queries
347    pub failed_queries: usize,
348    /// Total time for all queries
349    pub total_duration: Duration,
350    /// Average query execution time
351    pub average_query_time: Duration,
352    /// Minimum query execution time
353    pub min_query_time: Duration,
354    /// Maximum query execution time
355    pub max_query_time: Duration,
356    /// Queries executed per second
357    pub queries_per_second: f64,
358}
359
360impl PoolBenchmarkResult {
361    /// Get success rate as a percentage
362    pub fn success_rate(&self) -> f64 {
363        if self.total_queries == 0 {
364            0.0
365        } else {
366            (self.successful_queries as f64 / self.total_queries as f64) * 100.0
367        }
368    }
369
370    /// Get failure rate as a percentage
371    pub fn failure_rate(&self) -> f64 {
372        100.0 - self.success_rate()
373    }
374
375    /// Check if benchmark indicates healthy pool performance
376    pub fn is_healthy(&self) -> bool {
377        self.success_rate() > 95.0 && self.average_query_time < Duration::from_millis(100)
378    }
379
380    /// Get performance summary as a formatted string
381    pub fn summary(&self) -> String {
382        format!(
383            "Benchmark: {}/{} queries succeeded ({:.1}% success), {:.1} QPS, avg: {:.1}ms",
384            self.successful_queries,
385            self.total_queries,
386            self.success_rate(),
387            self.queries_per_second,
388            self.average_query_time.as_millis()
389        )
390    }
391}
392
393impl PoolStats {
394    /// Get connection utilization percentage
395    pub fn utilization_percentage(&self) -> f32 {
396        if self.max_connections == 0 {
397            0.0
398        } else {
399            (self.total_connections as f32 / self.max_connections as f32) * 100.0
400        }
401    }
402
403    /// Check if pool is at capacity
404    pub fn is_at_capacity(&self) -> bool {
405        self.total_connections >= self.max_connections
406    }
407}
408
409/// Builder for connection manager
410#[derive(Debug)]
411pub struct ConnectionManagerBuilder {
412    config: IgnisConfig,
413}
414
415impl ConnectionManagerBuilder {
416    /// Create a new connection manager builder
417    pub fn new() -> Self {
418        Self {
419            config: IgnisConfig::default(),
420        }
421    }
422
423    /// Set database URL
424    pub fn database_url(mut self, url: impl Into<String>) -> Self {
425        self.config.database.url = url.into();
426        self
427    }
428
429    /// Set maximum connections
430    pub fn max_connections(mut self, max: u32) -> Self {
431        self.config.pool.max_connections = Some(max);
432        self
433    }
434
435    /// Set minimum connections
436    pub fn min_connections(mut self, min: u32) -> Self {
437        self.config.pool.min_connections = Some(min);
438        self
439    }
440
441    /// Set transaction timeout
442    pub fn transaction_timeout(mut self, timeout: std::time::Duration) -> Self {
443        self.config.transaction.timeout = timeout;
444        self
445    }
446
447    /// Set isolation level
448    pub fn isolation_level(mut self, level: crate::exec::transaction::IsolationLevel) -> Self {
449        self.config.transaction.isolation_level = level;
450        self
451    }
452
453    /// Enable query monitoring
454    pub fn enable_query_monitoring(mut self, enable: bool) -> Self {
455        self.config.monitoring.enable_query_monitoring = enable;
456        self
457    }
458
459    /// Build the connection manager
460    pub async fn build(self) -> Result<ConnectionManager> {
461        ConnectionManager::from_config(self.config).await
462    }
463}
464
465impl Default for ConnectionManagerBuilder {
466    fn default() -> Self {
467        Self::new()
468    }
469}
470
471#[cfg(test)]
472mod tests {
473    use super::*;
474
475    #[tokio::test]
476    async fn test_connection_manager_builder() {
477        let manager = ConnectionManagerBuilder::new()
478            .database_url("postgresql://localhost/test")
479            .max_connections(5)
480            .min_connections(2)
481            .build()
482            .await;
483
484        // This will fail in test environment without real database
485        // but we can verify the builder pattern works
486        assert!(manager.is_err()); // Expected to fail without real DB
487    }
488
489    #[test]
490    fn test_pool_stats() {
491        let stats = PoolStats {
492            total_connections: 5,
493            active_connections: 3,
494            idle_connections: 2,
495            max_connections: 10,
496            min_connections: 1,
497        };
498
499        assert_eq!(stats.utilization_percentage(), 50.0);
500        assert!(!stats.is_at_capacity());
501
502        let at_capacity = PoolStats {
503            total_connections: 10,
504            active_connections: 8,
505            idle_connections: 2,
506            max_connections: 10,
507            min_connections: 1,
508        };
509
510        assert!(at_capacity.is_at_capacity());
511    }
512}