heroforge-core 0.2.2

Pure Rust core library for reading and writing Fossil SCM repositories
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//! Transaction management for filesystem operations
//!
//! This module handles grouping multiple filesystem operations into atomic,
//! committable units. Transactions ensure that either all operations succeed
//! or all are rolled back.

use crate::fs::errors::{FsError, FsResult};
use crate::fs::operations::{FsOperation, OperationSummary};
use sha3::{Digest, Sha3_256};
use std::sync::{Arc, Mutex};

/// Transaction mode
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TransactionMode {
    /// Read-only transaction - no writes allowed
    ReadOnly,

    /// Read-write transaction - can read and write
    ReadWrite,

    /// Exclusive transaction - no concurrent access
    Exclusive,
}

impl TransactionMode {
    /// Check if mode allows writes
    pub fn allows_writes(&self) -> bool {
        matches!(
            self,
            TransactionMode::ReadWrite | TransactionMode::Exclusive
        )
    }

    /// Check if mode is exclusive
    pub fn is_exclusive(&self) -> bool {
        *self == TransactionMode::Exclusive
    }
}

/// Transaction state
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TransactionState {
    /// Transaction is active and accepting operations
    Active,

    /// Transaction has been committed
    Committed,

    /// Transaction has been rolled back
    RolledBack,

    /// Transaction encountered an error
    Error,
}

/// A single transaction containing multiple operations
///
/// # Example
///
/// ```no_run
/// use heroforge_core::Repository;
/// use heroforge_core::fs::{Transaction, TransactionMode};
///
/// // Create a transaction
/// let tx = Transaction::new(TransactionMode::ReadWrite);
///
/// // Transactions are typically used internally by FileSystem and Modify
/// // For high-level operations, use those APIs instead
/// # Ok::<(), heroforge_core::FossilError>(())
/// ```
#[derive(Clone)]
pub struct Transaction {
    /// Unique transaction ID
    id: String,

    /// Transaction mode
    mode: TransactionMode,

    /// Current state
    state: Arc<Mutex<TransactionState>>,

    /// Operations accumulated in this transaction
    operations: Arc<Mutex<Vec<FsOperation>>>,

    /// Operation summary
    summary: Arc<Mutex<OperationSummary>>,

    /// Parent commit hash (if any)
    parent_commit: Option<String>,

    /// Branch name (if applicable)
    branch: Option<String>,

    /// Timestamp of transaction creation
    created_at: i64,

    /// Maximum operations allowed (0 = unlimited)
    max_operations: usize,
}

impl Transaction {
    /// Create a new transaction
    pub fn new(mode: TransactionMode) -> Self {
        let id = uuid::Uuid::new_v4().to_string();
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs() as i64;

        Self {
            id,
            mode,
            state: Arc::new(Mutex::new(TransactionState::Active)),
            operations: Arc::new(Mutex::new(Vec::new())),
            summary: Arc::new(Mutex::new(OperationSummary::new())),
            parent_commit: None,
            branch: None,
            created_at: now,
            max_operations: 0,
        }
    }

    /// Get transaction ID
    pub fn id(&self) -> &str {
        &self.id
    }

    /// Get current state
    pub fn state(&self) -> TransactionState {
        *self.state.lock().unwrap()
    }

    /// Check if transaction is active
    pub fn is_active(&self) -> bool {
        self.state() == TransactionState::Active
    }

    /// Check if transaction allows writes
    pub fn allows_writes(&self) -> bool {
        self.mode.allows_writes()
    }

    /// Get transaction mode
    pub fn mode(&self) -> TransactionMode {
        self.mode
    }

    /// Get number of operations in transaction
    pub fn operation_count(&self) -> usize {
        self.operations.lock().unwrap().len()
    }

    /// Get all operations
    pub fn operations(&self) -> Vec<FsOperation> {
        self.operations.lock().unwrap().clone()
    }

    /// Get operation summary
    pub fn summary(&self) -> OperationSummary {
        self.summary.lock().unwrap().clone()
    }

    /// Add an operation to the transaction
    pub fn add_operation(&self, op: FsOperation) -> FsResult<()> {
        // Check if transaction is active
        if !self.is_active() {
            return Err(FsError::TransactionError(
                "Cannot add operation to inactive transaction".to_string(),
            ));
        }

        // Check if mode allows this operation
        if !self.allows_writes() {
            return Err(FsError::TransactionError(
                "Cannot add write operation to read-only transaction".to_string(),
            ));
        }

        // Check operation limit
        if self.max_operations > 0 && self.operation_count() >= self.max_operations {
            return Err(FsError::TransactionError(format!(
                "Transaction operation limit ({}) exceeded",
                self.max_operations
            )));
        }

        let mut ops = self.operations.lock().unwrap();
        ops.push(op);

        Ok(())
    }

    /// Set parent commit for this transaction
    pub fn set_parent(&mut self, commit_hash: String) {
        self.parent_commit = Some(commit_hash);
    }

    /// Set branch for this transaction
    pub fn set_branch(&mut self, branch: String) {
        self.branch = Some(branch);
    }

    /// Get parent commit hash
    pub fn parent_commit(&self) -> Option<&str> {
        self.parent_commit.as_deref()
    }

    /// Get branch name
    pub fn branch(&self) -> Option<&str> {
        self.branch.as_deref()
    }

    /// Commit the transaction
    ///
    /// This finalizes all operations and creates a new commit in the repository.
    ///
    /// # Arguments
    ///
    /// * `message` - Commit message describing the changes
    /// * `author` - Author of the commit
    ///
    /// # Returns
    ///
    /// Returns the commit hash on success
    pub fn commit(&self, message: &str, author: &str) -> FsResult<String> {
        // Verify transaction is active
        if !self.is_active() {
            return Err(FsError::TransactionError(format!(
                "Cannot commit {} transaction",
                match self.state() {
                    TransactionState::Committed => "already-committed",
                    TransactionState::RolledBack => "rolled-back",
                    TransactionState::Error => "error",
                    TransactionState::Active => "unknown",
                }
            )));
        }

        let ops = self.operations.lock().unwrap();
        if ops.is_empty() {
            return Err(FsError::TransactionError(
                "Cannot commit empty transaction".to_string(),
            ));
        }

        // TODO: Perform actual commit in repository
        let mut hasher = Sha3_256::new();
        hasher.update(format!("{}{}{}", message, author, self.id).as_bytes());
        let hash = hasher.finalize();
        let commit_hash = format!("commit_{:x}", hash);

        // Mark as committed
        *self.state.lock().unwrap() = TransactionState::Committed;

        Ok(commit_hash)
    }

    /// Rollback the transaction
    ///
    /// This discards all pending operations.
    pub fn rollback(&self) -> FsResult<()> {
        if !self.is_active() {
            return Err(FsError::TransactionError(
                "Cannot rollback inactive transaction".to_string(),
            ));
        }

        self.operations.lock().unwrap().clear();
        *self.state.lock().unwrap() = TransactionState::RolledBack;

        Ok(())
    }

    /// Set error state
    pub fn set_error(&self) {
        *self.state.lock().unwrap() = TransactionState::Error;
    }

    /// Create a savepoint within the transaction
    ///
    /// Returns a handle that can be used to rollback to this point.
    pub fn savepoint(&self) -> FsResult<SavePoint> {
        if !self.is_active() {
            return Err(FsError::TransactionError(
                "Cannot create savepoint in inactive transaction".to_string(),
            ));
        }

        let ops = self.operations.lock().unwrap();
        Ok(SavePoint {
            transaction_id: self.id.clone(),
            operation_count: ops.len(),
        })
    }

    /// Rollback to a specific savepoint
    pub fn rollback_to_savepoint(&self, savepoint: &SavePoint) -> FsResult<()> {
        if self.id != savepoint.transaction_id {
            return Err(FsError::TransactionError(
                "Savepoint is from a different transaction".to_string(),
            ));
        }

        let mut ops = self.operations.lock().unwrap();
        if savepoint.operation_count < ops.len() {
            ops.truncate(savepoint.operation_count);
            Ok(())
        } else {
            Err(FsError::TransactionError(
                "Invalid savepoint state".to_string(),
            ))
        }
    }
}

impl std::fmt::Debug for Transaction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Transaction")
            .field("id", &self.id)
            .field("mode", &self.mode)
            .field("state", &self.state())
            .field("operations", &self.operation_count())
            .field("parent_commit", &self.parent_commit)
            .field("branch", &self.branch)
            .field("created_at", &self.created_at)
            .finish()
    }
}

/// A savepoint within a transaction
#[derive(Debug, Clone)]
pub struct SavePoint {
    /// ID of the transaction this savepoint belongs to
    transaction_id: String,

    /// Number of operations at this savepoint
    operation_count: usize,
}

impl SavePoint {
    /// Get the transaction ID
    pub fn transaction_id(&self) -> &str {
        &self.transaction_id
    }

    /// Get the operation count at this savepoint
    pub fn operation_count(&self) -> usize {
        self.operation_count
    }
}

/// Handle for managing a transaction's lifecycle
pub struct TransactionHandle {
    transaction: Arc<Transaction>,
}

impl TransactionHandle {
    /// Create a new transaction handle
    pub fn new(mode: TransactionMode) -> Self {
        Self {
            transaction: Arc::new(Transaction::new(mode)),
        }
    }

    /// Get reference to the underlying transaction
    pub fn transaction(&self) -> &Transaction {
        &self.transaction
    }

    /// Commit and consume the handle
    pub fn commit(self, message: &str, author: &str) -> FsResult<String> {
        self.transaction.commit(message, author)
    }

    /// Rollback and consume the handle
    pub fn rollback(self) -> FsResult<()> {
        self.transaction.rollback()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_transaction_creation() {
        let tx = Transaction::new(TransactionMode::ReadWrite);
        assert!(tx.is_active());
        assert!(tx.allows_writes());
        assert_eq!(tx.operation_count(), 0);
    }

    #[test]
    fn test_transaction_state() {
        let tx = Transaction::new(TransactionMode::ReadOnly);
        assert_eq!(tx.state(), TransactionState::Active);
        assert!(!tx.allows_writes());
    }

    #[test]
    fn test_transaction_mode() {
        let rw = TransactionMode::ReadWrite;
        let ro = TransactionMode::ReadOnly;

        assert!(rw.allows_writes());
        assert!(!ro.allows_writes());
        assert!(!rw.is_exclusive());
        assert!(TransactionMode::Exclusive.is_exclusive());
    }

    #[test]
    fn test_operation_count() {
        let tx = Transaction::new(TransactionMode::ReadWrite);
        assert_eq!(tx.operation_count(), 0);
    }
}