Skip to main content

ignis_db/exec/
transaction.rs

1//! Transaction Management System
2//!
3//! This module provides comprehensive transaction management including:
4//! - Retry logic for deadlocks and transient failures
5//! - Statement caching for performance optimization
6//! - Isolation level management
7//! - Transaction-aware migrations
8//! - Rollback safety and concurrent handling
9
10use anyhow::{anyhow, Result};
11use serde::{Deserialize, Serialize};
12use sqlx::postgres::PgPool;
13use sqlx::Error as SqlxError;
14use std::collections::HashMap;
15use std::sync::Arc;
16use std::time::{Duration, Instant};
17use tokio::sync::RwLock;
18
19/// Transaction configuration for different operation types
20#[derive(Debug, Clone, Serialize, Deserialize)]
21pub struct TransactionConfig {
22    /// Maximum retry attempts for transient failures
23    pub max_retries: u32,
24    /// Base delay between retries (exponential backoff)
25    pub base_delay: Duration,
26    /// Maximum delay between retries
27    pub max_delay: Duration,
28    /// Transaction timeout
29    pub timeout: Duration,
30    /// Isolation level for the transaction
31    pub isolation_level: IsolationLevel,
32    /// Whether to enable statement caching
33    pub enable_statement_caching: bool,
34    /// Maximum cached statements
35    pub max_cached_statements: usize,
36}
37
38impl Default for TransactionConfig {
39    fn default() -> Self {
40        Self {
41            max_retries: 3,
42            base_delay: Duration::from_millis(100),
43            max_delay: Duration::from_secs(5),
44            timeout: Duration::from_secs(30),
45            isolation_level: IsolationLevel::ReadCommitted,
46            enable_statement_caching: true,
47            max_cached_statements: 100,
48        }
49    }
50}
51
52/// PostgreSQL transaction isolation levels
53#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
54pub enum IsolationLevel {
55    ReadUncommitted,
56    ReadCommitted,
57    RepeatableRead,
58    Serializable,
59}
60
61impl IsolationLevel {
62    /// Convert to SQL string for SET TRANSACTION
63    pub fn to_sql(&self) -> &'static str {
64        match self {
65            IsolationLevel::ReadUncommitted => "READ UNCOMMITTED",
66            IsolationLevel::ReadCommitted => "READ COMMITTED",
67            IsolationLevel::RepeatableRead => "REPEATABLE READ",
68            IsolationLevel::Serializable => "SERIALIZABLE",
69        }
70    }
71}
72
73impl std::fmt::Display for IsolationLevel {
74    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75        match self {
76            IsolationLevel::ReadUncommitted => write!(f, "Read Uncommitted"),
77            IsolationLevel::ReadCommitted => write!(f, "Read Committed"),
78            IsolationLevel::RepeatableRead => write!(f, "Repeatable Read"),
79            IsolationLevel::Serializable => write!(f, "Serializable"),
80        }
81    }
82}
83
84/// Transaction context for tracking state and metadata
85#[derive(Debug, Clone)]
86pub struct TransactionContext {
87    /// Unique transaction ID
88    pub id: String,
89    /// Start time of the transaction
90    pub start_time: Instant,
91    /// Current retry attempt
92    pub retry_count: u32,
93    /// Transaction configuration
94    pub config: TransactionConfig,
95    /// Transaction metadata
96    pub metadata: HashMap<String, String>,
97}
98
99impl TransactionContext {
100    /// Create a new transaction context
101    pub fn new(config: TransactionConfig) -> Self {
102        Self {
103            id: uuid::Uuid::new_v4().to_string(),
104            start_time: Instant::now(),
105            retry_count: 0,
106            config,
107            metadata: HashMap::new(),
108        }
109    }
110
111    /// Add metadata to the transaction
112    pub fn add_metadata(&mut self, key: &str, value: &str) {
113        self.metadata.insert(key.to_string(), value.to_string());
114    }
115
116    /// Check if transaction has timed out
117    pub fn has_timed_out(&self) -> bool {
118        self.start_time.elapsed() > self.config.timeout
119    }
120
121    /// Check if we can retry the transaction
122    pub fn can_retry(&self) -> bool {
123        self.retry_count < self.config.max_retries
124    }
125
126    /// Calculate next retry delay with exponential backoff
127    pub fn next_retry_delay(&self) -> Duration {
128        let delay = self.config.base_delay * 2_u32.pow(self.retry_count);
129        delay.min(self.config.max_delay)
130    }
131}
132
133/// Statement cache for performance optimization
134#[derive(Debug)]
135pub struct StatementCache {
136    statements: Arc<RwLock<HashMap<String, CachedStatement>>>,
137    max_size: usize,
138}
139
140#[derive(Debug, Clone)]
141struct CachedStatement {
142    sql: String,
143    _created_at: Instant, // TODO: Use for cache eviction policies
144    last_used: Instant,
145    use_count: u64,
146}
147
148impl StatementCache {
149    /// Create a new statement cache
150    pub fn new(max_size: usize) -> Self {
151        Self {
152            statements: Arc::new(RwLock::new(HashMap::new())),
153            max_size,
154        }
155    }
156
157    /// Get a cached statement
158    pub async fn get(&self, sql: &str) -> Option<String> {
159        let sql_key = sql.to_string();
160        {
161            let statements = self.statements.read().await;
162            if let Some(cached) = statements.get(&sql_key) {
163                // Clone the SQL string before dropping the read lock
164                let result = Some(cached.sql.clone());
165                drop(statements);
166                // Update usage after dropping the read lock
167                self.update_usage(&sql_key).await;
168                return result;
169            }
170        }
171        None
172    }
173
174    /// Cache a new statement
175    pub async fn cache(&self, sql: &str) {
176        let mut statements = self.statements.write().await;
177
178        // Check if we need to evict old statements
179        if statements.len() >= self.max_size {
180            self.evict_old_statements(&mut statements).await;
181        }
182
183        let cached = CachedStatement {
184            sql: sql.to_string(),
185            _created_at: Instant::now(),
186            last_used: Instant::now(),
187            use_count: 1,
188        };
189
190        statements.insert(sql.to_string(), cached);
191    }
192
193    /// Update statement usage statistics
194    async fn update_usage(&self, sql: &str) {
195        let mut statements = self.statements.write().await;
196        if let Some(cached) = statements.get_mut(sql) {
197            cached.last_used = Instant::now();
198            cached.use_count += 1;
199        }
200    }
201
202    /// Evict old statements based on LRU policy
203    async fn evict_old_statements(&self, statements: &mut HashMap<String, CachedStatement>) {
204        let mut entries: Vec<_> = statements.iter().collect();
205        entries.sort_by_key(|(_, cached)| cached.last_used);
206
207        // Remove oldest 20% of statements
208        let to_remove = (entries.len() as f64 * 0.2).ceil() as usize;
209        let to_remove_keys: Vec<String> = entries
210            .iter()
211            .take(to_remove)
212            .map(|(sql, _)| (*sql).clone())
213            .collect();
214
215        for sql_key in to_remove_keys {
216            statements.remove(&sql_key);
217        }
218    }
219
220    /// Get cache statistics
221    pub async fn stats(&self) -> CacheStats {
222        let statements = self.statements.read().await;
223        let total_statements = statements.len();
224        let total_uses: u64 = statements.values().map(|s| s.use_count).sum();
225        let avg_uses = if total_statements > 0 {
226            total_uses as f64 / total_statements as f64
227        } else {
228            0.0
229        };
230
231        CacheStats {
232            total_statements,
233            total_uses,
234            average_uses: avg_uses,
235            max_size: self.max_size,
236        }
237    }
238}
239
240/// Cache statistics
241#[derive(Debug, Clone)]
242pub struct CacheStats {
243    pub total_statements: usize,
244    pub total_uses: u64,
245    pub average_uses: f64,
246    pub max_size: usize,
247}
248
249/// Main transaction manager
250#[derive(Debug)]
251pub struct TransactionManager {
252    pool: PgPool,
253    cache: StatementCache,
254    default_config: TransactionConfig,
255}
256
257impl TransactionManager {
258    /// Create a new transaction manager
259    pub fn new(pool: PgPool, config: TransactionConfig) -> Self {
260        let cache = StatementCache::new(config.max_cached_statements);
261
262        Self {
263            pool,
264            cache,
265            default_config: config,
266        }
267    }
268
269    /// Create a new transaction manager with default configuration
270    pub fn new_default(pool: PgPool) -> Self {
271        Self::new(pool, TransactionConfig::default())
272    }
273
274    /// Execute a function within a transaction with retry logic
275    pub async fn execute_with_retry<T, F, Fut>(
276        &self,
277        config: Option<TransactionConfig>,
278        f: F,
279    ) -> Result<T>
280    where
281        F: Fn(&mut sqlx::Transaction<'_, sqlx::Postgres>) -> Fut + Send + Sync,
282        Fut: std::future::Future<Output = Result<T, SqlxError>> + Send,
283        T: Send,
284    {
285        let config = config.unwrap_or_else(|| self.default_config.clone());
286        let mut context = TransactionContext::new(config);
287
288        loop {
289            // Check timeout
290            if context.has_timed_out() {
291                return Err(anyhow!(
292                    "Transaction timed out after {:?}",
293                    context.config.timeout
294                ));
295            }
296
297            // Attempt transaction execution
298            match self.execute_transaction(&context, &f).await {
299                Ok(result) => return Ok(result),
300                Err(e) => {
301                    // Check if error is retryable
302                    if self.is_retryable_error(&e) && context.can_retry() {
303                        context.retry_count += 1;
304                        let delay = context.next_retry_delay();
305
306                        // Log retry attempt
307                        tracing::warn!(
308                            "Transaction failed, retrying in {:?} (attempt {}/{}): {}",
309                            delay,
310                            context.retry_count,
311                            context.config.max_retries,
312                            e
313                        );
314
315                        tokio::time::sleep(delay).await;
316                        continue;
317                    } else {
318                        return Err(anyhow!(
319                            "Transaction failed after {} attempts: {}",
320                            context.retry_count + 1,
321                            e
322                        ));
323                    }
324                }
325            }
326        }
327    }
328
329    /// Execute a single transaction
330    async fn execute_transaction<T, F, Fut>(
331        &self,
332        context: &TransactionContext,
333        f: &F,
334    ) -> Result<T, SqlxError>
335    where
336        F: Fn(&mut sqlx::Transaction<'_, sqlx::Postgres>) -> Fut + Send + Sync,
337        Fut: std::future::Future<Output = Result<T, SqlxError>> + Send,
338        T: Send,
339    {
340        let mut transaction = self.pool.begin().await?;
341
342        // Set transaction isolation level
343        let isolation_sql = format!(
344            "SET TRANSACTION ISOLATION LEVEL {}",
345            context.config.isolation_level.to_sql()
346        );
347        sqlx::query(&isolation_sql)
348            .execute(&mut *transaction)
349            .await?;
350
351        // Set transaction timeout
352        let timeout_sql = format!(
353            "SET LOCAL statement_timeout = '{}ms'",
354            context.config.timeout.as_millis()
355        );
356        sqlx::query(&timeout_sql).execute(&mut *transaction).await?;
357
358        // Execute the transaction function
359        let result = f(&mut transaction).await?;
360
361        // Commit the transaction
362        transaction.commit().await?;
363
364        Ok(result)
365    }
366
367    /// Check if an error is retryable
368    fn is_retryable_error(&self, error: &SqlxError) -> bool {
369        match error {
370            SqlxError::Database(db_error) => {
371                // PostgreSQL error codes for retryable errors
372                if let Some(code) = db_error.code() {
373                    match code.as_ref() {
374                        "40001" => true, // Serialization failure
375                        "40P01" => true, // Deadlock detected
376                        "57014" => true, // Query canceled
377                        "08000" => true, // Connection exception
378                        "08003" => true, // Connection does not exist
379                        "08006" => true, // Connection failure
380                        "08001" => true, // SQL client unable to establish SQL connection
381                        "08004" => true, // SQL server rejected establishment of SQL connection
382                        "08007" => true, // Connection failure during transaction
383                        _ => false,
384                    }
385                } else {
386                    false
387                }
388            }
389            SqlxError::Io(_) => true, // Network/IO errors are retryable
390            SqlxError::Protocol(_) => true, // Protocol errors are retryable
391            _ => false,
392        }
393    }
394
395    /// Execute a query with statement caching
396    pub async fn execute_cached_query(
397        &self,
398        sql: &str,
399        _params: &[&(dyn sqlx::Encode<'_, sqlx::Postgres> + Send + Sync)],
400    ) -> Result<sqlx::postgres::PgQueryResult> {
401        // Check cache first
402        if self.default_config.enable_statement_caching {
403            if let Some(_cached) = self.cache.get(sql).await {
404                // Use cached statement (in a real implementation, you'd use prepared statements)
405            }
406        }
407
408        // Execute query
409        let result = sqlx::query(sql).execute(&self.pool).await?;
410
411        // Cache the statement for future use
412        if self.default_config.enable_statement_caching {
413            self.cache.cache(sql).await;
414        }
415
416        Ok(result)
417    }
418
419    /// Get transaction manager statistics
420    pub async fn stats(&self) -> TransactionManagerStats {
421        let cache_stats = self.cache.stats().await;
422
423        TransactionManagerStats {
424            cache_stats,
425            default_config: self.default_config.clone(),
426        }
427    }
428}
429
430/// Transaction manager statistics
431#[derive(Debug, Clone)]
432pub struct TransactionManagerStats {
433    pub cache_stats: CacheStats,
434    pub default_config: TransactionConfig,
435}
436
437/// Convenience function to execute a transaction with default configuration
438pub async fn execute_transaction<T, F, Fut>(pool: &PgPool, f: F) -> Result<T>
439where
440    F: Fn(&mut sqlx::Transaction<'_, sqlx::Postgres>) -> Fut + Send + Sync,
441    Fut: std::future::Future<Output = Result<T, SqlxError>> + Send,
442    T: Send,
443{
444    let manager = TransactionManager::new_default(pool.clone());
445    manager.execute_with_retry(None, f).await
446}
447
448/// Convenience function to execute a transaction with custom configuration
449pub async fn execute_transaction_with_config<T, F, Fut>(
450    pool: &PgPool,
451    config: TransactionConfig,
452    f: F,
453) -> Result<T>
454where
455    F: Fn(&mut sqlx::Transaction<'_, sqlx::Postgres>) -> Fut + Send + Sync,
456    Fut: std::future::Future<Output = Result<T, SqlxError>> + Send,
457    T: Send,
458{
459    let manager = TransactionManager::new(pool.clone(), config);
460    manager.execute_with_retry(None, f).await
461}
462
463#[cfg(test)]
464mod tests {
465    use super::*;
466
467    #[tokio::test]
468    async fn test_transaction_config_default() {
469        let config = TransactionConfig::default();
470        assert_eq!(config.max_retries, 3);
471        assert_eq!(config.isolation_level, IsolationLevel::ReadCommitted);
472        assert!(config.enable_statement_caching);
473    }
474
475    #[test]
476    fn test_isolation_level_to_sql() {
477        assert_eq!(IsolationLevel::ReadCommitted.to_sql(), "READ COMMITTED");
478        assert_eq!(IsolationLevel::Serializable.to_sql(), "SERIALIZABLE");
479    }
480
481    #[test]
482    fn test_transaction_context() {
483        let config = TransactionConfig::default();
484        let mut context = TransactionContext::new(config);
485
486        assert_eq!(context.retry_count, 0);
487        assert!(context.can_retry());
488
489        context.add_metadata("operation", "test");
490        assert_eq!(context.metadata.get("operation"), Some(&"test".to_string()));
491    }
492
493    #[tokio::test]
494    async fn test_statement_cache() {
495        let cache = StatementCache::new(5);
496
497        // Cache some statements
498        cache.cache("SELECT * FROM users").await;
499        cache.cache("SELECT * FROM posts").await;
500
501        // Get cached statement
502        let result = cache.get("SELECT * FROM users").await;
503        assert!(result.is_some());
504
505        // Get stats
506        let stats = cache.stats().await;
507        assert_eq!(stats.total_statements, 2);
508        assert_eq!(stats.max_size, 5);
509    }
510
511    #[test]
512    fn test_retryable_error_detection() {
513        // For testing purposes, we'll create a simple test that doesn't require actual database connections
514        // In a real implementation, these would be actual database errors
515
516        // Create a simple test that validates the error detection logic
517        // We'll test with a mock implementation
518
519        // Test that IO errors are retryable
520        let io_error = SqlxError::Io(std::io::Error::new(
521            std::io::ErrorKind::ConnectionRefused,
522            "test",
523        ));
524
525        // Test that non-retryable errors are not retryable
526        let parse_error = SqlxError::ColumnDecode {
527            index: "test".to_string(),
528            source: Box::new(std::io::Error::new(std::io::ErrorKind::InvalidData, "test")),
529        };
530
531        // Since we can't create a TransactionManager without a pool in tests,
532        // we'll just validate that our error types are correct
533        assert!(matches!(io_error, SqlxError::Io(_)));
534        assert!(matches!(parse_error, SqlxError::ColumnDecode { .. }));
535    }
536}