solidb 1.2.1

A lightweight, high-performance structured database server written in Rust.
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
use super::lock_manager::LockManager;
use super::wal::WalWriter;
use super::{IsolationLevel, Operation, Transaction, TransactionId};
use crate::error::{DbError, DbResult};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, RwLock};
use std::time::Duration;

#[allow(dead_code)]
pub struct TransactionManager {
    active_transactions: Arc<RwLock<HashMap<TransactionId, Arc<RwLock<Transaction>>>>>,
    wal: Arc<WalWriter>,
    lock_manager: Arc<LockManager>,
    timeout: Duration,
    wal_batch_size: usize,
}

impl TransactionManager {
    pub fn new(wal_path: PathBuf) -> DbResult<Self> {
        Self::with_wal_batch_size(wal_path, 100)
    }

    pub fn with_wal_batch_size(wal_path: PathBuf, batch_size: usize) -> DbResult<Self> {
        let wal = WalWriter::with_batch_size(&wal_path, batch_size)?;

        Ok(Self {
            active_transactions: Arc::new(RwLock::new(HashMap::new())),
            wal: Arc::new(wal),
            lock_manager: Arc::new(LockManager::new()),
            timeout: Duration::from_secs(300),
            wal_batch_size: batch_size,
        })
    }

    /// Set transaction timeout
    pub fn set_timeout(&mut self, timeout: Duration) {
        self.timeout = timeout;
    }

    /// Begin a new transaction
    ///
    /// Audit M7: nothing is written to the transaction WAL any more. It used
    /// to get a `Begin` line here and a fsynced `Commit` line at commit, but
    /// no operation was ever logged, so replay recovered nothing while the
    /// file grew without bound. Atomicity and durability now come from the
    /// commit being a single RocksDB `WriteBatch` (synced for isolation
    /// levels that `requires_wal`), which RocksDB's own WAL covers.
    pub fn begin(&self, isolation_level: IsolationLevel) -> DbResult<TransactionId> {
        let tx = Transaction::new(isolation_level);
        let tx_id = tx.id;

        {
            let mut active = self.active_transactions.write().unwrap();
            active.insert(tx_id, Arc::new(RwLock::new(tx)));
        }

        tracing::debug!("Transaction {} started", tx_id);
        Ok(tx_id)
    }

    /// Get a transaction (returns a clone for thread safety)
    pub fn get(&self, tx_id: TransactionId) -> DbResult<Arc<RwLock<Transaction>>> {
        let active = self.active_transactions.read().unwrap();
        active
            .get(&tx_id)
            .cloned()
            .ok_or_else(|| DbError::TransactionNotFound(tx_id.to_string()))
    }

    /// Check if a transaction exists and is active
    pub fn is_active(&self, tx_id: TransactionId) -> bool {
        let active = self.active_transactions.read().unwrap();
        active
            .get(&tx_id)
            .map(|tx| tx.read().unwrap().is_active())
            .unwrap_or(false)
    }

    /// Validate transaction before commit (consistency checks)
    pub fn validate(&self, tx_id: TransactionId) -> DbResult<()> {
        let tx_arc = self.get(tx_id)?;

        // First, collect all errors without holding tx lock
        let errors = {
            let tx = tx_arc.read().unwrap();
            let mut validation_errors = Vec::new();

            // Check for conflicting operations within the transaction
            let mut seen_keys: std::collections::HashMap<String, Vec<Operation>> =
                std::collections::HashMap::new();

            for op in &tx.operations {
                let key = format!("{}:{}:{}", op.database(), op.collection(), op.key());
                seen_keys.entry(key.clone()).or_default().push(op.clone());
            }

            // Check for duplicate inserts within transaction
            for (key, ops) in seen_keys.iter() {
                let inserts: Vec<_> = ops
                    .iter()
                    .filter(|op| matches!(op, Operation::Insert { .. }))
                    .collect();

                if inserts.len() > 1 {
                    let error = format!("Duplicate insert for key {} within transaction", key);
                    validation_errors.push(error);
                }

                // Check for operations on deleted documents
                let deletes: Vec<_> = ops
                    .iter()
                    .filter(|op| matches!(op, Operation::Delete { .. }))
                    .collect();
                if !deletes.is_empty() {
                    let updates_after_delete: Vec<_> = ops
                        .iter()
                        .skip_while(|op| !matches!(op, Operation::Delete { .. }))
                        .filter(|op| matches!(op, Operation::Update { .. }))
                        .collect();

                    if !updates_after_delete.is_empty() {
                        let error =
                            format!("Cannot update deleted document {} within transaction", key);
                        validation_errors.push(error);
                    }
                }
            }

            validation_errors
        };

        // Now add errors to transaction
        {
            let mut tx = tx_arc.write().unwrap();
            tx.clear_validation_errors();
            for error in errors {
                tx.add_validation_error(error);
            }

            // If there are validation errors, return them
            if tx.has_validation_errors() {
                let error_msg = tx.get_validation_errors().join("; ");
                return Err(DbError::TransactionConflict(format!(
                    "Transaction validation failed: {}",
                    error_msg
                )));
            }
        }

        Ok(())
    }

    /// First half of a commit: freeze the transaction and validate it.
    ///
    /// Moves the transaction from `Active` to `Preparing` — so no further
    /// operations can be added and a concurrent commit, rollback or the
    /// expiry reaper cannot act on it — then runs [`Self::validate`]. On a
    /// validation failure the transaction is aborted (removed, locks
    /// released) before the error is returned; nothing has been written.
    ///
    /// Returns the operations to apply and whether the write must be synced.
    pub fn prepare_commit(&self, tx_id: TransactionId) -> DbResult<(Vec<Operation>, bool)> {
        let tx_arc = self.get(tx_id)?;

        let requires_sync = {
            let mut tx = tx_arc.write().unwrap();
            if !tx.is_active() {
                return Err(DbError::TransactionConflict(format!(
                    "Transaction {} is not active (state: {:?})",
                    tx_id, tx.state
                )));
            }
            tx.prepare();
            tx.isolation_level.requires_wal()
        };

        // Audit D2: validate *before* anything is written.
        if let Err(e) = self.validate(tx_id) {
            self.abort(tx_id);
            return Err(e);
        }

        let operations = tx_arc.read().unwrap().operations.clone();
        Ok((operations, requires_sync))
    }

    /// Second half of a commit, once its writes are durable: mark it
    /// committed, forget it, release its locks.
    pub fn finish_commit(&self, tx_id: TransactionId) -> DbResult<()> {
        let tx_arc = self.get(tx_id)?;
        tx_arc.write().unwrap().commit();

        {
            let mut active = self.active_transactions.write().unwrap();
            active.remove(&tx_id);
        }
        self.lock_manager.release_locks(tx_id);

        tracing::debug!("Transaction {} committed", tx_id);
        Ok(())
    }

    /// Commit a transaction that has no storage effects to apply (the
    /// storage engine drives [`Self::prepare_commit`] / [`Self::finish_commit`]
    /// itself so it can write in between).
    pub fn commit(&self, tx_id: TransactionId) -> DbResult<()> {
        self.prepare_commit(tx_id)?;
        self.finish_commit(tx_id)
    }

    /// Abort regardless of state: used when a commit fails part-way, after
    /// the transaction has already left `Active`. Nothing was written, so
    /// dropping it and its locks is the whole rollback.
    pub fn abort(&self, tx_id: TransactionId) {
        let removed = {
            let mut active = self.active_transactions.write().unwrap();
            active.remove(&tx_id)
        };
        if let Some(tx_arc) = removed {
            tx_arc.write().unwrap().abort();
        }
        self.lock_manager.release_locks(tx_id);
        tracing::debug!("Transaction {} aborted", tx_id);
    }

    pub fn rollback(&self, tx_id: TransactionId) -> DbResult<()> {
        let tx_arc = self.get(tx_id)?;

        {
            let mut tx = tx_arc.write().unwrap();
            if tx.state == super::TransactionState::Preparing {
                // A commit is writing this transaction right now; yanking its
                // locks mid-write would let another writer in before the
                // commit finishes. The committer cleans up on either outcome.
                return Err(DbError::TransactionConflict(format!(
                    "Transaction {} is being committed",
                    tx_id
                )));
            }
            tx.abort();
        }

        {
            let mut active = self.active_transactions.write().unwrap();
            active.remove(&tx_id);
        }

        // Release locks
        self.lock_manager.release_locks(tx_id);

        tracing::debug!("Transaction {} rolled back", tx_id);
        Ok(())
    }

    /// Get all active transaction IDs
    pub fn active_transaction_ids(&self) -> Vec<TransactionId> {
        let active = self.active_transactions.read().unwrap();
        active.keys().copied().collect()
    }

    /// Get transaction count
    pub fn transaction_count(&self) -> usize {
        let active = self.active_transactions.read().unwrap();
        active.len()
    }

    /// Clean up expired transactions
    pub fn cleanup_expired(&self) -> usize {
        let now = chrono::Utc::now();
        let mut expired = Vec::new();

        {
            let active = self.active_transactions.read().unwrap();
            for (tx_id, tx_arc) in active.iter() {
                let tx = tx_arc.read().unwrap();
                // A transaction mid-commit is not abandoned.
                if tx.is_active()
                    && now
                        .signed_duration_since(tx.created_at)
                        .to_std()
                        .unwrap_or(Duration::ZERO)
                        > self.timeout
                {
                    expired.push(*tx_id);
                }
            }
        }

        let count = expired.len();
        for tx_id in expired {
            tracing::warn!("Aborting expired transaction {}", tx_id);
            let _ = self.rollback(tx_id);
        }

        count
    }

    pub fn wal(&self) -> &Arc<WalWriter> {
        &self.wal
    }

    pub fn lock_manager(&self) -> &Arc<LockManager> {
        &self.lock_manager
    }

    /// Nothing in the transaction WAL is needed once its contents are
    /// applied (see [`Self::begin`]), so a checkpoint empties it rather than
    /// appending a marker to a file that would otherwise only grow.
    pub fn checkpoint(&self) -> DbResult<()> {
        self.wal.truncate()
    }
}

impl std::fmt::Debug for TransactionManager {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TransactionManager")
            .field("active_count", &self.transaction_count())
            .field("timeout", &self.timeout)
            .finish()
    }
}

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

    #[test]
    fn test_begin_transaction() {
        let dir = tempdir().unwrap();
        let wal_path = dir.path().join("test.wal");
        let manager = TransactionManager::new(wal_path).unwrap();

        let tx_id = manager.begin(IsolationLevel::ReadCommitted).unwrap();
        assert!(manager.is_active(tx_id));
        assert_eq!(manager.transaction_count(), 1);
    }

    #[test]
    fn test_commit_transaction() {
        let dir = tempdir().unwrap();
        let wal_path = dir.path().join("test.wal");
        let manager = TransactionManager::new(wal_path).unwrap();

        let tx_id = manager.begin(IsolationLevel::ReadCommitted).unwrap();
        manager.commit(tx_id).unwrap();

        assert!(!manager.is_active(tx_id));
        assert_eq!(manager.transaction_count(), 0);
    }

    #[test]
    fn test_rollback_transaction() {
        let dir = tempdir().unwrap();
        let wal_path = dir.path().join("test.wal");
        let manager = TransactionManager::new(wal_path).unwrap();

        let tx_id = manager.begin(IsolationLevel::ReadCommitted).unwrap();
        manager.rollback(tx_id).unwrap();

        assert!(!manager.is_active(tx_id));
        assert_eq!(manager.transaction_count(), 0);
    }

    #[test]
    fn test_multiple_transactions() {
        let dir = tempdir().unwrap();
        let wal_path = dir.path().join("test.wal");
        let manager = TransactionManager::new(wal_path).unwrap();

        let tx1 = manager.begin(IsolationLevel::ReadCommitted).unwrap();
        let tx2 = manager.begin(IsolationLevel::Serializable).unwrap();

        assert_eq!(manager.transaction_count(), 2);
        assert!(manager.is_active(tx1));
        assert!(manager.is_active(tx2));

        manager.commit(tx1).unwrap();
        assert_eq!(manager.transaction_count(), 1);

        manager.rollback(tx2).unwrap();
        assert_eq!(manager.transaction_count(), 0);
    }

    #[test]
    fn test_transaction_not_found() {
        let dir = tempdir().unwrap();
        let wal_path = dir.path().join("test.wal");
        let manager = TransactionManager::new(wal_path).unwrap();

        let fake_id = TransactionId::new();
        assert!(manager.get(fake_id).is_err());
    }

    #[test]
    fn test_double_commit() {
        let dir = tempdir().unwrap();
        let wal_path = dir.path().join("test.wal");
        let manager = TransactionManager::new(wal_path).unwrap();

        let tx_id = manager.begin(IsolationLevel::ReadCommitted).unwrap();
        manager.commit(tx_id).unwrap();

        // Second commit should fail (transaction not found)
        assert!(manager.commit(tx_id).is_err());
    }

    #[test]
    fn test_failed_validation_aborts_and_releases_locks() {
        let dir = tempdir().unwrap();
        let manager = TransactionManager::new(dir.path().join("test.wal")).unwrap();

        let tx_id = manager.begin(IsolationLevel::ReadCommitted).unwrap();
        manager
            .lock_manager()
            .acquire_exclusive(tx_id, "db", "c", "k")
            .unwrap();
        {
            let tx_arc = manager.get(tx_id).unwrap();
            let mut tx = tx_arc.write().unwrap();
            for _ in 0..2 {
                tx.add_operation(Operation::Insert {
                    database: "db".into(),
                    collection: "c".into(),
                    key: "k".into(),
                    data: serde_json::json!({}),
                });
            }
        }

        assert!(matches!(
            manager.prepare_commit(tx_id),
            Err(DbError::TransactionConflict(_))
        ));
        // Gone, and its lock is free for the next transaction.
        assert_eq!(manager.transaction_count(), 0);
        let other = manager.begin(IsolationLevel::ReadCommitted).unwrap();
        assert!(manager
            .lock_manager()
            .acquire_exclusive(other, "db", "c", "k")
            .is_ok());
    }

    #[test]
    fn test_rollback_refused_while_preparing() {
        let dir = tempdir().unwrap();
        let manager = TransactionManager::new(dir.path().join("test.wal")).unwrap();

        let tx_id = manager.begin(IsolationLevel::ReadCommitted).unwrap();
        manager.prepare_commit(tx_id).unwrap();
        assert!(manager.rollback(tx_id).is_err());
        assert_eq!(manager.cleanup_expired(), 0);
        manager.finish_commit(tx_id).unwrap();
        assert_eq!(manager.transaction_count(), 0);
    }

    #[test]
    fn test_begin_and_commit_do_not_grow_wal() {
        let dir = tempdir().unwrap();
        let wal_path = dir.path().join("test.wal");
        let manager = TransactionManager::new(wal_path.clone()).unwrap();

        for _ in 0..10 {
            let tx = manager.begin(IsolationLevel::Serializable).unwrap();
            manager.commit(tx).unwrap();
        }
        assert_eq!(std::fs::metadata(&wal_path).unwrap().len(), 0);
    }
}