Skip to main content

ggen_core/codegen/
transaction.rs

1//! File system transaction support for atomic writes and rollback
2//!
3//! Provides bulletproof file operations with automatic cleanup on failure.
4//! Constitutional Rule: No partial state - either all changes succeed or all are rolled back.
5
6use crate::utils::error::{Error, Result};
7use parking_lot::Mutex;
8use std::collections::HashMap;
9use std::fs;
10use std::path::{Path, PathBuf};
11use std::sync::atomic::{AtomicBool, Ordering};
12use tempfile::NamedTempFile;
13
14/// File operation tracking for rollback
15#[derive(Debug, Clone)]
16enum FileOperation {
17    /// File was created (didn't exist before)
18    Created { path: PathBuf },
19    /// File was modified (backup saved at location)
20    Modified { path: PathBuf, backup: PathBuf },
21}
22
23/// Transaction manager for atomic file operations
24///
25/// Thread-safe: allows multiple threads to perform atomic writes concurrently.
26/// Atomic: either all writes succeed and are committed, or all are rolled back.
27#[derive(Debug)]
28pub struct FileTransaction {
29    operations: Mutex<Vec<FileOperation>>,
30    backup_dir: Option<PathBuf>,
31    committed: AtomicBool,
32}
33
34impl FileTransaction {
35    /// Create a new transaction
36    pub fn new() -> Result<Self> {
37        Ok(Self {
38            operations: Mutex::new(Vec::new()),
39            backup_dir: None,
40            committed: AtomicBool::new(false),
41        })
42    }
43
44    /// Create a new transaction with backup directory
45    pub fn with_backup_dir(backup_dir: impl AsRef<Path>) -> Result<Self> {
46        let backup_path = backup_dir.as_ref().to_path_buf();
47        fs::create_dir_all(&backup_path).map_err(|e| {
48            Error::new(&format!(
49                "Failed to create backup directory {}: {}",
50                backup_path.display(),
51                e
52            ))
53        })?;
54
55        Ok(Self {
56            operations: Mutex::new(Vec::new()),
57            backup_dir: Some(backup_path),
58            committed: AtomicBool::new(false),
59        })
60    }
61
62    /// Write file atomically - either succeeds completely or has no effect
63    ///
64    /// Uses temp file + rename for atomic operation:
65    /// 1. Write to temporary file
66    /// 2. Atomically rename to target (OS-level atomic operation)
67    /// 3. Track operation for potential rollback
68    pub fn write_file(&self, path: impl AsRef<Path>, content: &str) -> Result<()> {
69        let path = path.as_ref();
70
71        // Check if file exists (for rollback tracking)
72        let existed = path.exists();
73
74        // Create parent directories if needed
75        if let Some(parent) = path.parent() {
76            fs::create_dir_all(parent).map_err(|e| {
77                Error::new(&format!(
78                    "Failed to create parent directory {}: {}",
79                    parent.display(),
80                    e
81                ))
82            })?;
83        }
84
85        // Create backup if file exists
86        let backup_path = if existed {
87            let backup = self.create_backup(path)?;
88            Some(backup)
89        } else {
90            None
91        };
92
93        // Write to temporary file in same directory (ensures same filesystem)
94        let temp_dir = path.parent().unwrap_or_else(|| Path::new("."));
95        let mut temp_file = NamedTempFile::new_in(temp_dir).map_err(|e| {
96            Error::new(&format!(
97                "Failed to create temporary file in {}: {}",
98                temp_dir.display(),
99                e
100            ))
101        })?;
102
103        use std::io::Write;
104        temp_file
105            .write_all(content.as_bytes())
106            .map_err(|e| Error::new(&format!("Failed to write to temporary file: {}", e)))?;
107
108        // Atomic rename (this is the critical atomic operation)
109        temp_file.persist(path).map_err(|e| {
110            Error::new(&format!(
111                "Failed to atomically write to {}: {}",
112                path.display(),
113                e
114            ))
115        })?;
116
117        // Track operation for potential rollback
118        let operation = if let Some(backup) = backup_path {
119            FileOperation::Modified {
120                path: path.to_path_buf(),
121                backup,
122            }
123        } else {
124            FileOperation::Created {
125                path: path.to_path_buf(),
126            }
127        };
128        self.operations.lock().push(operation);
129
130        Ok(())
131    }
132
133    /// Create backup of existing file
134    fn create_backup(&self, path: &Path) -> Result<PathBuf> {
135        let backup_path = if let Some(backup_dir) = &self.backup_dir {
136            // Use dedicated backup directory
137            let filename = path
138                .file_name()
139                .ok_or_else(|| Error::new(&format!("Invalid path: {}", path.display())))?;
140            backup_dir.join(format!(
141                "{}.backup.{}",
142                filename.to_string_lossy(),
143                chrono::Utc::now().timestamp()
144            ))
145        } else {
146            // Use .backup suffix in same directory
147            path.with_extension(format!(
148                "{}.backup",
149                path.extension().and_then(|e| e.to_str()).unwrap_or("txt")
150            ))
151        };
152
153        fs::copy(path, &backup_path).map_err(|e| {
154            Error::new(&format!(
155                "Failed to create backup of {} to {}: {}",
156                path.display(),
157                backup_path.display(),
158                e
159            ))
160        })?;
161
162        Ok(backup_path)
163    }
164
165    /// Commit transaction - mark as successful
166    ///
167    /// After commit, backups are kept but rollback is disabled
168    pub fn commit(self) -> Result<TransactionReceipt> {
169        self.committed.store(true, Ordering::SeqCst);
170
171        let operations = self.operations.lock();
172        let receipt = TransactionReceipt {
173            files_created: operations
174                .iter()
175                .filter_map(|op| match op {
176                    FileOperation::Created { path } => Some(path.clone()),
177                    FileOperation::Modified { .. } => None,
178                })
179                .collect(),
180            files_modified: operations
181                .iter()
182                .filter_map(|op| match op {
183                    FileOperation::Modified { path, .. } => Some(path.clone()),
184                    FileOperation::Created { .. } => None,
185                })
186                .collect(),
187            backups: operations
188                .iter()
189                .filter_map(|op| match op {
190                    FileOperation::Modified { path, backup } => {
191                        Some((path.clone(), backup.clone()))
192                    }
193                    FileOperation::Created { .. } => None,
194                })
195                .collect(),
196        };
197
198        Ok(receipt)
199    }
200
201    /// Rollback all operations on drop (if not committed)
202    fn rollback(&self) {
203        if self.committed.load(Ordering::SeqCst) {
204            return;
205        }
206
207        let operations = self.operations.lock();
208        // Rollback in reverse order
209        for operation in operations.iter().rev() {
210            match operation {
211                FileOperation::Created { path } => {
212                    // Remove created file
213                    if let Err(e) = fs::remove_file(path) {
214                        eprintln!(
215                            "Warning: Failed to remove {} during rollback: {}",
216                            path.display(),
217                            e
218                        );
219                    }
220                }
221                FileOperation::Modified { path, backup } => {
222                    // Restore from backup
223                    if let Err(e) = fs::copy(backup, path) {
224                        eprintln!(
225                            "Warning: Failed to restore {} from backup during rollback: {}",
226                            path.display(),
227                            e
228                        );
229                    }
230                    // Clean up backup
231                    let _ = fs::remove_file(backup);
232                }
233            }
234        }
235    }
236}
237
238impl Drop for FileTransaction {
239    fn drop(&mut self) {
240        if !self.committed.load(Ordering::SeqCst) {
241            self.rollback();
242        }
243    }
244}
245
246/// Receipt of completed transaction
247#[derive(Debug, Clone)]
248pub struct TransactionReceipt {
249    pub files_created: Vec<PathBuf>,
250    pub files_modified: Vec<PathBuf>,
251    pub backups: HashMap<PathBuf, PathBuf>,
252}
253
254impl TransactionReceipt {
255    /// Clean up backups after successful operation
256    pub fn clean_backups(&self) -> Result<()> {
257        for backup in self.backups.values() {
258            if let Err(e) = fs::remove_file(backup) {
259                eprintln!(
260                    "Warning: Failed to remove backup {}: {}",
261                    backup.display(),
262                    e
263                );
264            }
265        }
266        Ok(())
267    }
268
269    /// Total files affected
270    pub fn total_files(&self) -> usize {
271        self.files_created.len() + self.files_modified.len()
272    }
273}
274
275#[cfg(test)]
276mod tests {
277    use super::*;
278    use std::fs;
279    use tempfile::tempdir;
280
281    #[test]
282    fn test_atomic_write_new_file() {
283        let dir = tempdir().unwrap();
284        let file_path = dir.path().join("test.txt");
285
286        let tx = FileTransaction::new().unwrap();
287        tx.write_file(&file_path, "test content").unwrap();
288
289        assert!(file_path.exists());
290        assert_eq!(fs::read_to_string(&file_path).unwrap(), "test content");
291
292        let receipt = tx.commit().unwrap();
293        assert_eq!(receipt.files_created.len(), 1);
294        assert_eq!(receipt.files_modified.len(), 0);
295    }
296
297    #[test]
298    fn test_atomic_write_existing_file() {
299        let dir = tempdir().unwrap();
300        let file_path = dir.path().join("test.txt");
301
302        // Create initial file
303        fs::write(&file_path, "original").unwrap();
304
305        let tx = FileTransaction::new().unwrap();
306        tx.write_file(&file_path, "modified").unwrap();
307
308        assert_eq!(fs::read_to_string(&file_path).unwrap(), "modified");
309
310        let receipt = tx.commit().unwrap();
311        assert_eq!(receipt.files_created.len(), 0);
312        assert_eq!(receipt.files_modified.len(), 1);
313        assert_eq!(receipt.backups.len(), 1);
314    }
315
316    #[test]
317    fn test_rollback_on_drop() {
318        let dir = tempdir().unwrap();
319        let file_path = dir.path().join("test.txt");
320
321        {
322            let tx = FileTransaction::new().unwrap();
323            tx.write_file(&file_path, "test content").unwrap();
324            assert!(file_path.exists());
325            // Drop without commit triggers rollback
326        }
327
328        // File should be removed
329        assert!(!file_path.exists());
330    }
331
332    #[test]
333    fn test_rollback_restores_original() {
334        let dir = tempdir().unwrap();
335        let file_path = dir.path().join("test.txt");
336
337        // Create initial file
338        fs::write(&file_path, "original").unwrap();
339
340        {
341            let tx = FileTransaction::new().unwrap();
342            tx.write_file(&file_path, "modified").unwrap();
343            assert_eq!(fs::read_to_string(&file_path).unwrap(), "modified");
344            // Drop without commit triggers rollback
345        }
346
347        // File should be restored
348        assert_eq!(fs::read_to_string(&file_path).unwrap(), "original");
349    }
350
351    #[test]
352    fn test_multiple_operations_rollback() {
353        let dir = tempdir().unwrap();
354        let file1 = dir.path().join("file1.txt");
355        let file2 = dir.path().join("file2.txt");
356
357        {
358            let tx = FileTransaction::new().unwrap();
359            tx.write_file(&file1, "content1").unwrap();
360            tx.write_file(&file2, "content2").unwrap();
361            assert!(file1.exists());
362            assert!(file2.exists());
363            // Drop without commit
364        }
365
366        // Both files should be removed
367        assert!(!file1.exists());
368        assert!(!file2.exists());
369    }
370}