Skip to main content

git2db/
transaction.rs

1//! Transaction support for atomic registry operations
2//!
3//! v2.1 implementation using Arc-based handles and libgit2 worktrees.
4//! Provides true atomic operations with complete rollback capability.
5
6use crate::errors::{Git2DBError, Git2DBResult};
7use crate::registry::{Git2DB, RepoId, TrackedRepository};
8use git2::{Repository, WorktreeAddOptions, WorktreePruneOptions};
9use serde::{Deserialize, Serialize};
10use std::path::PathBuf;
11use std::sync::Arc;
12use tokio::fs;
13use tokio::sync::RwLock;
14use tracing::{debug, info, warn};
15use uuid::Uuid;
16
17/// Transaction handle for atomic registry operations
18///
19/// This is a clonable, Send + Sync + 'static handle that can be passed
20/// to async functions without lifetime issues.
21///
22/// # Examples
23///
24/// ```rust,ignore
25/// // Start a transaction
26/// let tx = registry.start_transaction().await?;
27///
28/// // Queue operations (they don't execute yet)
29/// let id1 = tx.clone_repo("repo1", "https://github.com/user/repo1.git").await?;
30/// let id2 = tx.clone_repo("repo2", "https://github.com/user/repo2.git").await?;
31///
32/// // Commit atomically (all operations succeed or all fail)
33/// tx.commit().await?;
34///
35/// // Or rollback (discards all operations)
36/// // tx.rollback().await?;
37/// ```
38#[derive(Clone)]
39pub struct TransactionHandle {
40    inner: Arc<RwLock<TransactionState>>,
41}
42
43struct TransactionState {
44    id: Uuid,
45    registry_path: PathBuf,
46    worktree_name: String,
47    worktree_path: PathBuf,
48    snapshot: RegistrySnapshot,
49    operations: Vec<Operation>,
50    isolation_mode: IsolationMode,
51    committed: bool,
52}
53
54/// Snapshot of registry state at transaction start
55#[derive(Clone, Debug, Serialize, Deserialize)]
56struct RegistrySnapshot {
57    version: String,
58    repositories: std::collections::HashMap<Uuid, TrackedRepository>,
59}
60
61/// Operation to be applied in transaction
62#[derive(Clone, Debug)]
63enum Operation {
64    Clone {
65        id: RepoId,
66        name: String,
67        url: String,
68    },
69    Remove {
70        id: RepoId,
71    },
72    Update {
73        id: RepoId,
74        url: Option<String>,
75    },
76    Upsert {
77        name: String,
78        url: String,
79        // Store the result ID to return
80        result_id: Arc<RwLock<Option<RepoId>>>,
81    },
82}
83
84/// Isolation mode for transactions
85#[derive(Clone, Debug)]
86pub enum IsolationMode {
87    /// Full worktree isolation using libgit2
88    /// - Safest: complete filesystem isolation
89    /// - Slowest: creates git worktree
90    Worktree,
91
92    /// Copy-on-write with metadata snapshots
93    /// - Balanced: snapshot metadata only
94    /// - Operations queue but can't rollback filesystem changes
95    CopyOnWrite,
96
97    /// Optimistic locking
98    /// - Fastest: just queue operations
99    /// - Check conflicts at commit time
100    Optimistic,
101}
102
103impl Git2DB {
104    /// Start a new transaction with default isolation (CopyOnWrite)
105    ///
106    /// # Examples
107    ///
108    /// ```rust,ignore
109    /// let tx = registry.start_transaction().await?;
110    /// let id = tx.clone_repo("my-repo", "https://github.com/user/repo.git").await?;
111    /// tx.commit().await?;
112    /// ```
113    pub async fn start_transaction(&self) -> Git2DBResult<TransactionHandle> {
114        self.start_transaction_with_mode(IsolationMode::CopyOnWrite)
115            .await
116    }
117
118    /// Start a transaction with specific isolation mode
119    ///
120    /// # Examples
121    ///
122    /// ```rust,ignore
123    /// use git2db::IsolationMode;
124    ///
125    /// // Full worktree isolation for maximum safety
126    /// let tx = registry.start_transaction_with_mode(IsolationMode::Worktree).await?;
127    ///
128    /// // Optimistic mode for maximum performance
129    /// let tx = registry.start_transaction_with_mode(IsolationMode::Optimistic).await?;
130    /// ```
131    pub async fn start_transaction_with_mode(
132        &self,
133        mode: IsolationMode,
134    ) -> Git2DBResult<TransactionHandle> {
135        let tx_id = Uuid::new_v4();
136        let tx_name = format!("tx-{tx_id}");
137        let worktree_path = self.registry_path().join(".worktrees").join(&tx_name);
138
139        info!("Starting transaction {} with mode {:?}", tx_id, mode);
140
141        // Create worktree based on isolation mode
142        match &mode {
143            IsolationMode::Worktree => {
144                // Create actual git worktree using libgit2
145                let registry_path = self.registry_path().to_path_buf();
146                let tx_name_clone = tx_name.clone();
147                let worktree_path_clone = worktree_path.clone();
148
149                tokio::task::spawn_blocking(move || -> Git2DBResult<()> {
150                    let repo = Repository::open(&registry_path).map_err(|e| {
151                        Git2DBError::repository(
152                            &registry_path,
153                            format!("Failed to open registry: {e}"),
154                        )
155                    })?;
156
157                    let mut opts = WorktreeAddOptions::new();
158                    opts.lock(false); // Don't lock by default
159
160                    repo.worktree(&tx_name_clone, &worktree_path_clone, Some(&opts))
161                        .map_err(|e| {
162                            Git2DBError::internal(format!("Failed to create worktree: {e}"))
163                        })?;
164
165                    Ok(())
166                })
167                .await
168                .map_err(|e| Git2DBError::internal(format!("Join error: {e}")))??;
169
170                info!("Created git worktree at {:?}", worktree_path);
171            }
172            IsolationMode::CopyOnWrite => {
173                // Just create directory for metadata snapshot
174                fs::create_dir_all(&worktree_path).await.map_err(|e| {
175                    Git2DBError::internal(format!("Failed to create snapshot directory: {e}"))
176                })?;
177            }
178            IsolationMode::Optimistic => {
179                // No isolation, just track operations
180            }
181        }
182
183        // Create snapshot of current registry state
184        let snapshot = RegistrySnapshot {
185            version: self.version().to_owned(),
186            repositories: self.list().map(|r| (r.id.0, r.clone())).collect(),
187        };
188
189        let state = TransactionState {
190            id: tx_id,
191            registry_path: self.registry_path().to_path_buf(),
192            worktree_name: tx_name,
193            worktree_path,
194            snapshot,
195            operations: Vec::new(),
196            isolation_mode: mode,
197            committed: false,
198        };
199
200        Ok(TransactionHandle {
201            inner: Arc::new(RwLock::new(state)),
202        })
203    }
204
205    /// Deprecated v2.0 API - provided for backward compatibility
206    ///
207    /// Use `start_transaction()` instead for the new Arc-based API.
208    #[deprecated(since = "2.1.0", note = "Use start_transaction() instead")]
209    pub async fn transaction<F, Fut, R>(&mut self, f: F) -> Git2DBResult<R>
210    where
211        F: FnOnce(&mut crate::transaction::Transaction<'_>) -> Fut,
212        Fut: std::future::Future<Output = Git2DBResult<R>>,
213    {
214        // Delegate to old implementation for backward compatibility
215        let mut tx = Transaction::new(self).await?;
216
217        match f(&mut tx).await {
218            Ok(result) => {
219                tx.commit().await?;
220                Ok(result)
221            }
222            Err(e) => {
223                tx.rollback().await?;
224                Err(e)
225            }
226        }
227    }
228}
229
230impl TransactionHandle {
231    /// Clone a repository within the transaction
232    ///
233    /// The operation is queued and will execute on commit.
234    pub async fn clone_repo(&self, name: &str, url: &str) -> Git2DBResult<RepoId> {
235        let repo_id = RepoId::new();
236        let mut state = self.inner.write().await;
237
238        if state.committed {
239            return Err(Git2DBError::internal("Transaction already committed"));
240        }
241
242        debug!(
243            "Transaction {}: queue clone {} from {}",
244            state.id, name, url
245        );
246
247        state.operations.push(Operation::Clone {
248            id: repo_id.clone(),
249            name: name.to_owned(),
250            url: url.to_owned(),
251        });
252
253        Ok(repo_id)
254    }
255
256    /// Remove a repository within the transaction
257    ///
258    /// The operation is queued and will execute on commit.
259    pub async fn remove(&self, id: &RepoId) -> Git2DBResult<()> {
260        let mut state = self.inner.write().await;
261
262        if state.committed {
263            return Err(Git2DBError::internal("Transaction already committed"));
264        }
265
266        // Validate repository exists in snapshot
267        if !state.snapshot.repositories.contains_key(&id.0) {
268            return Err(Git2DBError::invalid_repository(
269                id.to_string(),
270                "Repository not found",
271            ));
272        }
273
274        debug!("Transaction {}: queue remove {}", state.id, id);
275
276        state.operations.push(Operation::Remove { id: id.clone() });
277
278        Ok(())
279    }
280
281    /// Update a repository within the transaction
282    pub async fn update(&self, id: &RepoId, url: Option<String>) -> Git2DBResult<()> {
283        let mut state = self.inner.write().await;
284
285        if state.committed {
286            return Err(Git2DBError::internal("Transaction already committed"));
287        }
288
289        // Validate repository exists in snapshot
290        if !state.snapshot.repositories.contains_key(&id.0) {
291            return Err(Git2DBError::invalid_repository(
292                id.to_string(),
293                "Repository not found",
294            ));
295        }
296
297        debug!("Transaction {}: queue update {}", state.id, id);
298
299        state.operations.push(Operation::Update {
300            id: id.clone(),
301            url,
302        });
303
304        Ok(())
305    }
306
307    /// Ensure a repository exists (upsert operation)
308    ///
309    /// If a repository with the given name exists, returns its ID.
310    /// Otherwise, clones it and returns the new ID.
311    pub async fn ensure(&self, name: &str, url: &str) -> Git2DBResult<RepoId> {
312        let mut state = self.inner.write().await;
313
314        if state.committed {
315            return Err(Git2DBError::internal("Transaction already committed"));
316        }
317
318        // Check if repository already exists in snapshot
319        for repo in state.snapshot.repositories.values() {
320            if repo.name.as_deref() == Some(name) {
321                debug!(
322                    "Transaction {}: ensure {} - already exists as {}",
323                    state.id, name, repo.id
324                );
325                return Ok(repo.id.clone());
326            }
327        }
328
329        // Will need to clone - queue upsert operation
330        debug!(
331            "Transaction {}: queue ensure {} from {}",
332            state.id, name, url
333        );
334
335        let result_id = Arc::new(RwLock::new(None));
336        state.operations.push(Operation::Upsert {
337            name: name.to_owned(),
338            url: url.to_owned(),
339            result_id: Arc::clone(&result_id),
340        });
341
342        // Generate ID now for return
343        let id = RepoId::new();
344        *result_id.write().await = Some(id.clone());
345
346        Ok(id)
347    }
348
349    /// Get list of queued operations
350    pub async fn operations(&self) -> Vec<String> {
351        let state = self.inner.read().await;
352        state
353            .operations
354            .iter()
355            .map(|op| format!("{op:?}"))
356            .collect()
357    }
358
359    /// Commit the transaction, applying all operations atomically to the registry
360    ///
361    /// On success, all operations are applied to the registry.
362    /// On failure, the transaction is rolled back and all operations are discarded.
363    ///
364    /// # Examples
365    ///
366    /// ```rust,ignore
367    /// let tx = registry.start_transaction().await?;
368    /// let id = tx.clone_repo("repo", "https://github.com/user/repo.git").await?;
369    /// tx.commit_to(&mut registry).await?;  // Apply operations
370    /// ```
371    pub async fn commit_to(self, registry: &mut Git2DB) -> Git2DBResult<()> {
372        let state = self.inner.write().await;
373
374        if state.committed {
375            return Err(Git2DBError::internal("Transaction already committed"));
376        }
377
378        info!(
379            "Committing transaction {} with {} operations",
380            state.id,
381            state.operations.len()
382        );
383
384        // Apply each operation in order
385        // If any fails, we'll automatically rollback via Drop
386        for (i, operation) in state.operations.iter().enumerate() {
387            debug!("Applying operation {}/{}", i + 1, state.operations.len());
388
389            match operation {
390                Operation::Clone { id, name, url } => {
391                    debug!("Cloning {} from {} with ID {}", name, url, id);
392                    registry
393                        .add_repository_with_id(id.clone(), name, url)
394                        .await?;
395                }
396                Operation::Remove { id } => {
397                    debug!("Removing repository {}", id);
398                    registry.remove_repository(id).await?;
399                }
400                Operation::Update { id, url } => {
401                    debug!("Updating repository {}", id);
402                    registry.update_repository(id, url.clone()).await?;
403                }
404                Operation::Upsert {
405                    name,
406                    url,
407                    result_id,
408                } => {
409                    debug!("Upserting {} from {}", name, url);
410
411                    // Check if repository already exists
412                    if let Some(existing) = registry.get_by_name(name) {
413                        debug!(
414                            "Repository '{}' already exists with ID {}",
415                            name, existing.id
416                        );
417                        // Update result_id with existing ID
418                        *result_id.write().await = Some(existing.id.clone());
419                    } else {
420                        // Use the pre-generated ID from ensure()
421                        let expected_id = result_id.read().await.clone().ok_or_else(|| {
422                            Git2DBError::internal("Upsert operation missing pre-generated ID")
423                        })?;
424
425                        debug!(
426                            "Creating repository '{}' with pre-generated ID {}",
427                            name, expected_id
428                        );
429                        registry
430                            .add_repository_with_id(expected_id, name, url)
431                            .await?;
432                        // ID is already set in result_id from ensure()
433                    }
434                }
435            }
436        }
437
438        // Mark as committed before cleanup
439        drop(state);
440        let mut state = self.inner.write().await;
441        state.committed = true;
442        drop(state);
443
444        // Cleanup worktree
445        let state = self.inner.read().await;
446        self.cleanup_worktree(&state).await?;
447
448        info!("Transaction {} committed successfully", state.id);
449
450        Ok(())
451    }
452
453    /// Commit the transaction without a registry reference
454    ///
455    /// **Deprecated:** This method doesn't actually apply operations.
456    /// Use `commit_to(&mut registry)` instead.
457    #[deprecated(since = "2.1.0", note = "Use commit_to(&mut registry) instead")]
458    pub async fn commit(self) -> Git2DBResult<()> {
459        let state = self.inner.read().await;
460        warn!(
461            "Transaction {} committed without applying operations (use commit_to() instead)",
462            state.id
463        );
464
465        // Just cleanup, don't apply operations
466        self.cleanup_worktree(&state).await?;
467
468        Ok(())
469    }
470
471    /// Rollback the transaction, discarding all operations
472    ///
473    /// All queued operations are discarded and the worktree is removed.
474    pub async fn rollback(self) -> Git2DBResult<()> {
475        let state = self.inner.read().await;
476
477        if state.committed {
478            return Err(Git2DBError::internal("Transaction already committed"));
479        }
480
481        warn!(
482            "Rolling back transaction {} with {} operations",
483            state.id,
484            state.operations.len()
485        );
486
487        // Cleanup worktree
488        self.cleanup_worktree(&state).await?;
489
490        info!("Transaction {} rolled back successfully", state.id);
491
492        Ok(())
493    }
494
495    async fn cleanup_worktree(&self, state: &TransactionState) -> Git2DBResult<()> {
496        match &state.isolation_mode {
497            IsolationMode::Worktree => {
498                // Use libgit2 to prune the worktree
499                let registry_path = state.registry_path.clone();
500                let worktree_name = state.worktree_name.clone();
501                let worktree_name_log = worktree_name.clone();
502
503                tokio::task::spawn_blocking(move || -> Git2DBResult<()> {
504                    let repo = Repository::open(&registry_path).map_err(|e| {
505                        Git2DBError::repository(
506                            &registry_path,
507                            format!("Failed to open registry: {e}"),
508                        )
509                    })?;
510
511                    let worktree = repo.find_worktree(&worktree_name).map_err(|e| {
512                        Git2DBError::internal(format!("Failed to find worktree: {e}"))
513                    })?;
514
515                    let mut opts = WorktreePruneOptions::new();
516                    opts.working_tree(true); // Remove filesystem data
517
518                    worktree.prune(Some(&mut opts)).map_err(|e| {
519                        Git2DBError::internal(format!("Failed to prune worktree: {e}"))
520                    })?;
521
522                    Ok(())
523                })
524                .await
525                .map_err(|e| Git2DBError::internal(format!("Join error: {e}")))??;
526
527                info!("Pruned git worktree {}", worktree_name_log);
528            }
529            IsolationMode::CopyOnWrite => {
530                // Just remove the snapshot directory
531                if state.worktree_path.exists() {
532                    tokio::fs::remove_dir_all(&state.worktree_path)
533                        .await
534                        .map_err(|e| {
535                            Git2DBError::internal(format!("Failed to remove snapshot dir: {e}"))
536                        })?;
537                }
538            }
539            IsolationMode::Optimistic => {
540                // No cleanup needed
541            }
542        }
543
544        Ok(())
545    }
546}
547
548// Keep old Transaction struct for backward compatibility
549pub struct Transaction<'a> {
550    registry: &'a mut Git2DB,
551    worktree_path: PathBuf,
552    tx_id: String,
553    operations: Vec<String>,
554}
555
556impl<'a> Transaction<'a> {
557    pub(crate) async fn new(registry: &'a mut Git2DB) -> Git2DBResult<Self> {
558        let tx_id = Uuid::new_v4().to_string();
559        let worktree_path = registry.registry_path().join(".worktrees").join(&tx_id);
560
561        info!("Starting legacy transaction: {}", tx_id);
562
563        fs::create_dir_all(&worktree_path).await.map_err(|e| {
564            Git2DBError::internal(format!("Failed to create worktree directory: {e}"))
565        })?;
566
567        Ok(Self {
568            registry,
569            worktree_path,
570            tx_id,
571            operations: Vec::new(),
572        })
573    }
574
575    pub async fn remove(&mut self, id: &RepoId) -> Git2DBResult<()> {
576        debug!("Legacy transaction {}: remove {}", self.tx_id, id);
577        self.operations.push(format!("remove {id}"));
578        self.registry.remove_repository(id).await
579    }
580
581    pub async fn ensure(&mut self, name: &str, url: &str) -> Git2DBResult<RepoId> {
582        debug!(
583            "Legacy transaction {}: ensure {} from {}",
584            self.tx_id, name, url
585        );
586        self.operations.push(format!("ensure {name} from {url}"));
587        self.registry.upsert_repository(name, url).await
588    }
589
590    pub async fn clone(&mut self, name: &str, url: &str) -> Git2DBResult<RepoId> {
591        debug!(
592            "Legacy transaction {}: clone {} from {}",
593            self.tx_id, name, url
594        );
595        self.operations.push(format!("clone {name} from {url}"));
596        self.registry.add_repository(name, url).await
597    }
598
599    pub async fn update(&mut self, id: &RepoId, new_url: Option<String>) -> Git2DBResult<()> {
600        debug!("Legacy transaction {}: update {}", self.tx_id, id);
601        self.operations.push(format!("update {id}"));
602        self.registry.update_repository(id, new_url).await
603    }
604
605    pub fn operations(&self) -> &[String] {
606        &self.operations
607    }
608
609    async fn commit(self) -> Git2DBResult<()> {
610        info!(
611            "Legacy transaction {} committed: {} operations",
612            self.tx_id,
613            self.operations.len()
614        );
615
616        if self.worktree_path.exists() {
617            fs::remove_dir_all(&self.worktree_path)
618                .await
619                .map_err(|e| Git2DBError::internal(format!("Failed to cleanup worktree: {e}")))?;
620        }
621
622        Ok(())
623    }
624
625    async fn rollback(self) -> Git2DBResult<()> {
626        warn!(
627            "Legacy transaction {} rolled back: {} operations",
628            self.tx_id,
629            self.operations.len()
630        );
631
632        if self.worktree_path.exists() {
633            fs::remove_dir_all(&self.worktree_path)
634                .await
635                .map_err(|e| Git2DBError::internal(format!("Failed to cleanup worktree: {e}")))?;
636        }
637
638        Ok(())
639    }
640}
641
642#[cfg(test)]
643mod tests {
644
645    // Integration tests will be in tests/ directory
646}