1use 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#[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#[derive(Clone, Debug, Serialize, Deserialize)]
56struct RegistrySnapshot {
57 version: String,
58 repositories: std::collections::HashMap<Uuid, TrackedRepository>,
59}
60
61#[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 result_id: Arc<RwLock<Option<RepoId>>>,
81 },
82}
83
84#[derive(Clone, Debug)]
86pub enum IsolationMode {
87 Worktree,
91
92 CopyOnWrite,
96
97 Optimistic,
101}
102
103impl Git2DB {
104 pub async fn start_transaction(&self) -> Git2DBResult<TransactionHandle> {
114 self.start_transaction_with_mode(IsolationMode::CopyOnWrite)
115 .await
116 }
117
118 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 match &mode {
143 IsolationMode::Worktree => {
144 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(®istry_path).map_err(|e| {
151 Git2DBError::repository(
152 ®istry_path,
153 format!("Failed to open registry: {e}"),
154 )
155 })?;
156
157 let mut opts = WorktreeAddOptions::new();
158 opts.lock(false); 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 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 }
181 }
182
183 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(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 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 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 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 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 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 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 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 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 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 let id = RepoId::new();
344 *result_id.write().await = Some(id.clone());
345
346 Ok(id)
347 }
348
349 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 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 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 if let Some(existing) = registry.get_by_name(name) {
413 debug!(
414 "Repository '{}' already exists with ID {}",
415 name, existing.id
416 );
417 *result_id.write().await = Some(existing.id.clone());
419 } else {
420 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 }
434 }
435 }
436 }
437
438 drop(state);
440 let mut state = self.inner.write().await;
441 state.committed = true;
442 drop(state);
443
444 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 #[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 self.cleanup_worktree(&state).await?;
467
468 Ok(())
469 }
470
471 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 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 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(®istry_path).map_err(|e| {
505 Git2DBError::repository(
506 ®istry_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); 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 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 }
542 }
543
544 Ok(())
545 }
546}
547
548pub 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 }