use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize};
use sqlx::postgres::PgPool;
use sqlx::Error as SqlxError;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::RwLock;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TransactionConfig {
pub max_retries: u32,
pub base_delay: Duration,
pub max_delay: Duration,
pub timeout: Duration,
pub isolation_level: IsolationLevel,
pub enable_statement_caching: bool,
pub max_cached_statements: usize,
}
impl Default for TransactionConfig {
fn default() -> Self {
Self {
max_retries: 3,
base_delay: Duration::from_millis(100),
max_delay: Duration::from_secs(5),
timeout: Duration::from_secs(30),
isolation_level: IsolationLevel::ReadCommitted,
enable_statement_caching: true,
max_cached_statements: 100,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum IsolationLevel {
ReadUncommitted,
ReadCommitted,
RepeatableRead,
Serializable,
}
impl IsolationLevel {
pub fn to_sql(&self) -> &'static str {
match self {
IsolationLevel::ReadUncommitted => "READ UNCOMMITTED",
IsolationLevel::ReadCommitted => "READ COMMITTED",
IsolationLevel::RepeatableRead => "REPEATABLE READ",
IsolationLevel::Serializable => "SERIALIZABLE",
}
}
}
impl std::fmt::Display for IsolationLevel {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
IsolationLevel::ReadUncommitted => write!(f, "Read Uncommitted"),
IsolationLevel::ReadCommitted => write!(f, "Read Committed"),
IsolationLevel::RepeatableRead => write!(f, "Repeatable Read"),
IsolationLevel::Serializable => write!(f, "Serializable"),
}
}
}
#[derive(Debug, Clone)]
pub struct TransactionContext {
pub id: String,
pub start_time: Instant,
pub retry_count: u32,
pub config: TransactionConfig,
pub metadata: HashMap<String, String>,
}
impl TransactionContext {
pub fn new(config: TransactionConfig) -> Self {
Self {
id: uuid::Uuid::new_v4().to_string(),
start_time: Instant::now(),
retry_count: 0,
config,
metadata: HashMap::new(),
}
}
pub fn add_metadata(&mut self, key: &str, value: &str) {
self.metadata.insert(key.to_string(), value.to_string());
}
pub fn has_timed_out(&self) -> bool {
self.start_time.elapsed() > self.config.timeout
}
pub fn can_retry(&self) -> bool {
self.retry_count < self.config.max_retries
}
pub fn next_retry_delay(&self) -> Duration {
let delay = self.config.base_delay * 2_u32.pow(self.retry_count);
delay.min(self.config.max_delay)
}
}
#[derive(Debug)]
pub struct StatementCache {
statements: Arc<RwLock<HashMap<String, CachedStatement>>>,
max_size: usize,
}
#[derive(Debug, Clone)]
struct CachedStatement {
sql: String,
_created_at: Instant, last_used: Instant,
use_count: u64,
}
impl StatementCache {
pub fn new(max_size: usize) -> Self {
Self {
statements: Arc::new(RwLock::new(HashMap::new())),
max_size,
}
}
pub async fn get(&self, sql: &str) -> Option<String> {
let sql_key = sql.to_string();
{
let statements = self.statements.read().await;
if let Some(cached) = statements.get(&sql_key) {
let result = Some(cached.sql.clone());
drop(statements);
self.update_usage(&sql_key).await;
return result;
}
}
None
}
pub async fn cache(&self, sql: &str) {
let mut statements = self.statements.write().await;
if statements.len() >= self.max_size {
self.evict_old_statements(&mut statements).await;
}
let cached = CachedStatement {
sql: sql.to_string(),
_created_at: Instant::now(),
last_used: Instant::now(),
use_count: 1,
};
statements.insert(sql.to_string(), cached);
}
async fn update_usage(&self, sql: &str) {
let mut statements = self.statements.write().await;
if let Some(cached) = statements.get_mut(sql) {
cached.last_used = Instant::now();
cached.use_count += 1;
}
}
async fn evict_old_statements(&self, statements: &mut HashMap<String, CachedStatement>) {
let mut entries: Vec<_> = statements.iter().collect();
entries.sort_by_key(|(_, cached)| cached.last_used);
let to_remove = (entries.len() as f64 * 0.2).ceil() as usize;
let to_remove_keys: Vec<String> = entries
.iter()
.take(to_remove)
.map(|(sql, _)| (*sql).clone())
.collect();
for sql_key in to_remove_keys {
statements.remove(&sql_key);
}
}
pub async fn stats(&self) -> CacheStats {
let statements = self.statements.read().await;
let total_statements = statements.len();
let total_uses: u64 = statements.values().map(|s| s.use_count).sum();
let avg_uses = if total_statements > 0 {
total_uses as f64 / total_statements as f64
} else {
0.0
};
CacheStats {
total_statements,
total_uses,
average_uses: avg_uses,
max_size: self.max_size,
}
}
}
#[derive(Debug, Clone)]
pub struct CacheStats {
pub total_statements: usize,
pub total_uses: u64,
pub average_uses: f64,
pub max_size: usize,
}
#[derive(Debug)]
pub struct TransactionManager {
pool: PgPool,
cache: StatementCache,
default_config: TransactionConfig,
}
impl TransactionManager {
pub fn new(pool: PgPool, config: TransactionConfig) -> Self {
let cache = StatementCache::new(config.max_cached_statements);
Self {
pool,
cache,
default_config: config,
}
}
pub fn new_default(pool: PgPool) -> Self {
Self::new(pool, TransactionConfig::default())
}
pub async fn execute_with_retry<T, F, Fut>(
&self,
config: Option<TransactionConfig>,
f: F,
) -> Result<T>
where
F: Fn(&mut sqlx::Transaction<'_, sqlx::Postgres>) -> Fut + Send + Sync,
Fut: std::future::Future<Output = Result<T, SqlxError>> + Send,
T: Send,
{
let config = config.unwrap_or_else(|| self.default_config.clone());
let mut context = TransactionContext::new(config);
loop {
if context.has_timed_out() {
return Err(anyhow!(
"Transaction timed out after {:?}",
context.config.timeout
));
}
match self.execute_transaction(&context, &f).await {
Ok(result) => return Ok(result),
Err(e) => {
if self.is_retryable_error(&e) && context.can_retry() {
context.retry_count += 1;
let delay = context.next_retry_delay();
tracing::warn!(
"Transaction failed, retrying in {:?} (attempt {}/{}): {}",
delay,
context.retry_count,
context.config.max_retries,
e
);
tokio::time::sleep(delay).await;
continue;
} else {
return Err(anyhow!(
"Transaction failed after {} attempts: {}",
context.retry_count + 1,
e
));
}
}
}
}
}
async fn execute_transaction<T, F, Fut>(
&self,
context: &TransactionContext,
f: &F,
) -> Result<T, SqlxError>
where
F: Fn(&mut sqlx::Transaction<'_, sqlx::Postgres>) -> Fut + Send + Sync,
Fut: std::future::Future<Output = Result<T, SqlxError>> + Send,
T: Send,
{
let mut transaction = self.pool.begin().await?;
let isolation_sql = format!(
"SET TRANSACTION ISOLATION LEVEL {}",
context.config.isolation_level.to_sql()
);
sqlx::query(&isolation_sql)
.execute(&mut *transaction)
.await?;
let timeout_sql = format!(
"SET LOCAL statement_timeout = '{}ms'",
context.config.timeout.as_millis()
);
sqlx::query(&timeout_sql).execute(&mut *transaction).await?;
let result = f(&mut transaction).await?;
transaction.commit().await?;
Ok(result)
}
fn is_retryable_error(&self, error: &SqlxError) -> bool {
match error {
SqlxError::Database(db_error) => {
if let Some(code) = db_error.code() {
match code.as_ref() {
"40001" => true, "40P01" => true, "57014" => true, "08000" => true, "08003" => true, "08006" => true, "08001" => true, "08004" => true, "08007" => true, _ => false,
}
} else {
false
}
}
SqlxError::Io(_) => true, SqlxError::Protocol(_) => true, _ => false,
}
}
pub async fn execute_cached_query(
&self,
sql: &str,
_params: &[&(dyn sqlx::Encode<'_, sqlx::Postgres> + Send + Sync)],
) -> Result<sqlx::postgres::PgQueryResult> {
if self.default_config.enable_statement_caching {
if let Some(_cached) = self.cache.get(sql).await {
}
}
let result = sqlx::query(sql).execute(&self.pool).await?;
if self.default_config.enable_statement_caching {
self.cache.cache(sql).await;
}
Ok(result)
}
pub async fn stats(&self) -> TransactionManagerStats {
let cache_stats = self.cache.stats().await;
TransactionManagerStats {
cache_stats,
default_config: self.default_config.clone(),
}
}
}
#[derive(Debug, Clone)]
pub struct TransactionManagerStats {
pub cache_stats: CacheStats,
pub default_config: TransactionConfig,
}
pub async fn execute_transaction<T, F, Fut>(pool: &PgPool, f: F) -> Result<T>
where
F: Fn(&mut sqlx::Transaction<'_, sqlx::Postgres>) -> Fut + Send + Sync,
Fut: std::future::Future<Output = Result<T, SqlxError>> + Send,
T: Send,
{
let manager = TransactionManager::new_default(pool.clone());
manager.execute_with_retry(None, f).await
}
pub async fn execute_transaction_with_config<T, F, Fut>(
pool: &PgPool,
config: TransactionConfig,
f: F,
) -> Result<T>
where
F: Fn(&mut sqlx::Transaction<'_, sqlx::Postgres>) -> Fut + Send + Sync,
Fut: std::future::Future<Output = Result<T, SqlxError>> + Send,
T: Send,
{
let manager = TransactionManager::new(pool.clone(), config);
manager.execute_with_retry(None, f).await
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_transaction_config_default() {
let config = TransactionConfig::default();
assert_eq!(config.max_retries, 3);
assert_eq!(config.isolation_level, IsolationLevel::ReadCommitted);
assert!(config.enable_statement_caching);
}
#[test]
fn test_isolation_level_to_sql() {
assert_eq!(IsolationLevel::ReadCommitted.to_sql(), "READ COMMITTED");
assert_eq!(IsolationLevel::Serializable.to_sql(), "SERIALIZABLE");
}
#[test]
fn test_transaction_context() {
let config = TransactionConfig::default();
let mut context = TransactionContext::new(config);
assert_eq!(context.retry_count, 0);
assert!(context.can_retry());
context.add_metadata("operation", "test");
assert_eq!(context.metadata.get("operation"), Some(&"test".to_string()));
}
#[tokio::test]
async fn test_statement_cache() {
let cache = StatementCache::new(5);
cache.cache("SELECT * FROM users").await;
cache.cache("SELECT * FROM posts").await;
let result = cache.get("SELECT * FROM users").await;
assert!(result.is_some());
let stats = cache.stats().await;
assert_eq!(stats.total_statements, 2);
assert_eq!(stats.max_size, 5);
}
#[test]
fn test_retryable_error_detection() {
let io_error = SqlxError::Io(std::io::Error::new(
std::io::ErrorKind::ConnectionRefused,
"test",
));
let parse_error = SqlxError::ColumnDecode {
index: "test".to_string(),
source: Box::new(std::io::Error::new(std::io::ErrorKind::InvalidData, "test")),
};
assert!(matches!(io_error, SqlxError::Io(_)));
assert!(matches!(parse_error, SqlxError::ColumnDecode { .. }));
}
}