|
| 1 | +use crate::services::{LockManager, TransactionProcessor}; |
| 2 | +use std::time::Duration; |
| 3 | +use tracing::{info, warn}; |
| 4 | +use uuid::Uuid; |
| 5 | + |
| 6 | +/// Example: Process transaction with distributed lock |
| 7 | +pub async fn process_transaction_with_lock( |
| 8 | + lock_manager: &LockManager, |
| 9 | + processor: &TransactionProcessor, |
| 10 | + tx_id: Uuid, |
| 11 | +) -> anyhow::Result<bool> { |
| 12 | + let resource = format!("transaction:{}", tx_id); |
| 13 | + let timeout = Duration::from_secs(5); |
| 14 | + |
| 15 | + // Try to acquire lock |
| 16 | + let lock = match lock_manager.acquire(&resource, timeout).await? { |
| 17 | + Some(lock) => lock, |
| 18 | + None => { |
| 19 | + warn!("Could not acquire lock for transaction {}", tx_id); |
| 20 | + return Ok(false); |
| 21 | + } |
| 22 | + }; |
| 23 | + |
| 24 | + info!("Processing transaction {} with lock", tx_id); |
| 25 | + |
| 26 | + // Process transaction |
| 27 | + let result = processor.process_transaction(tx_id).await; |
| 28 | + |
| 29 | + // Release lock |
| 30 | + lock.release().await?; |
| 31 | + |
| 32 | + result.map(|_| true) |
| 33 | +} |
| 34 | + |
| 35 | +/// Example: Long-running operation with auto-renewal |
| 36 | +pub async fn long_running_with_lock( |
| 37 | + lock_manager: &LockManager, |
| 38 | + resource: &str, |
| 39 | +) -> anyhow::Result<()> { |
| 40 | + let timeout = Duration::from_secs(5); |
| 41 | + |
| 42 | + let lock = match lock_manager.acquire(resource, timeout).await? { |
| 43 | + Some(lock) => lock, |
| 44 | + None => { |
| 45 | + return Err(anyhow::anyhow!("Could not acquire lock")); |
| 46 | + } |
| 47 | + }; |
| 48 | + |
| 49 | + // Spawn auto-renewal task |
| 50 | + let renewal_lock = lock.clone(); |
| 51 | + tokio::spawn(async move { |
| 52 | + renewal_lock.auto_renew_task().await; |
| 53 | + }); |
| 54 | + |
| 55 | + // Do long-running work |
| 56 | + tokio::time::sleep(Duration::from_secs(60)).await; |
| 57 | + |
| 58 | + // Lock will be released on drop |
| 59 | + Ok(()) |
| 60 | +} |
| 61 | + |
| 62 | +/// Example: Using with_lock helper |
| 63 | +pub async fn process_with_helper( |
| 64 | + lock_manager: &LockManager, |
| 65 | + processor: &TransactionProcessor, |
| 66 | + tx_id: Uuid, |
| 67 | +) -> anyhow::Result<Option<()>> { |
| 68 | + let resource = format!("transaction:{}", tx_id); |
| 69 | + let timeout = Duration::from_secs(5); |
| 70 | + |
| 71 | + lock_manager |
| 72 | + .with_lock(&resource, timeout, || { |
| 73 | + Box::pin(async move { |
| 74 | + processor |
| 75 | + .process_transaction(tx_id) |
| 76 | + .await |
| 77 | + .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>) |
| 78 | + }) |
| 79 | + }) |
| 80 | + .await |
| 81 | + .map_err(|e| anyhow::anyhow!("Lock error: {}", e)) |
| 82 | +} |
0 commit comments