1use 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#[derive(Debug, Clone, Serialize, Deserialize)]
21pub struct TransactionConfig {
22 pub max_retries: u32,
24 pub base_delay: Duration,
26 pub max_delay: Duration,
28 pub timeout: Duration,
30 pub isolation_level: IsolationLevel,
32 pub enable_statement_caching: bool,
34 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#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
54pub enum IsolationLevel {
55 ReadUncommitted,
56 ReadCommitted,
57 RepeatableRead,
58 Serializable,
59}
60
61impl IsolationLevel {
62 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#[derive(Debug, Clone)]
86pub struct TransactionContext {
87 pub id: String,
89 pub start_time: Instant,
91 pub retry_count: u32,
93 pub config: TransactionConfig,
95 pub metadata: HashMap<String, String>,
97}
98
99impl TransactionContext {
100 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 pub fn add_metadata(&mut self, key: &str, value: &str) {
113 self.metadata.insert(key.to_string(), value.to_string());
114 }
115
116 pub fn has_timed_out(&self) -> bool {
118 self.start_time.elapsed() > self.config.timeout
119 }
120
121 pub fn can_retry(&self) -> bool {
123 self.retry_count < self.config.max_retries
124 }
125
126 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#[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, last_used: Instant,
145 use_count: u64,
146}
147
148impl StatementCache {
149 pub fn new(max_size: usize) -> Self {
151 Self {
152 statements: Arc::new(RwLock::new(HashMap::new())),
153 max_size,
154 }
155 }
156
157 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 let result = Some(cached.sql.clone());
165 drop(statements);
166 self.update_usage(&sql_key).await;
168 return result;
169 }
170 }
171 None
172 }
173
174 pub async fn cache(&self, sql: &str) {
176 let mut statements = self.statements.write().await;
177
178 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 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 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 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 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#[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#[derive(Debug)]
251pub struct TransactionManager {
252 pool: PgPool,
253 cache: StatementCache,
254 default_config: TransactionConfig,
255}
256
257impl TransactionManager {
258 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 pub fn new_default(pool: PgPool) -> Self {
271 Self::new(pool, TransactionConfig::default())
272 }
273
274 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 if context.has_timed_out() {
291 return Err(anyhow!(
292 "Transaction timed out after {:?}",
293 context.config.timeout
294 ));
295 }
296
297 match self.execute_transaction(&context, &f).await {
299 Ok(result) => return Ok(result),
300 Err(e) => {
301 if self.is_retryable_error(&e) && context.can_retry() {
303 context.retry_count += 1;
304 let delay = context.next_retry_delay();
305
306 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 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 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 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 let result = f(&mut transaction).await?;
360
361 transaction.commit().await?;
363
364 Ok(result)
365 }
366
367 fn is_retryable_error(&self, error: &SqlxError) -> bool {
369 match error {
370 SqlxError::Database(db_error) => {
371 if let Some(code) = db_error.code() {
373 match code.as_ref() {
374 "40001" => true, "40P01" => true, "57014" => true, "08000" => true, "08003" => true, "08006" => true, "08001" => true, "08004" => true, "08007" => true, _ => false,
384 }
385 } else {
386 false
387 }
388 }
389 SqlxError::Io(_) => true, SqlxError::Protocol(_) => true, _ => false,
392 }
393 }
394
395 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 if self.default_config.enable_statement_caching {
403 if let Some(_cached) = self.cache.get(sql).await {
404 }
406 }
407
408 let result = sqlx::query(sql).execute(&self.pool).await?;
410
411 if self.default_config.enable_statement_caching {
413 self.cache.cache(sql).await;
414 }
415
416 Ok(result)
417 }
418
419 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#[derive(Debug, Clone)]
432pub struct TransactionManagerStats {
433 pub cache_stats: CacheStats,
434 pub default_config: TransactionConfig,
435}
436
437pub 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
448pub 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.cache("SELECT * FROM users").await;
499 cache.cache("SELECT * FROM posts").await;
500
501 let result = cache.get("SELECT * FROM users").await;
503 assert!(result.is_some());
504
505 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 let io_error = SqlxError::Io(std::io::Error::new(
521 std::io::ErrorKind::ConnectionRefused,
522 "test",
523 ));
524
525 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 assert!(matches!(io_error, SqlxError::Io(_)));
534 assert!(matches!(parse_error, SqlxError::ColumnDecode { .. }));
535 }
536}