dbx-core 0.2.2

High-performance file-based database engine with 5-Tier Hybrid Storage
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
//! Write-Ahead Logging (WAL) module for crash recovery.
//!
//! The WAL ensures durability by logging all write operations before applying them
//! to the database. In case of a crash, the WAL can be replayed to restore the
//! database to a consistent state.
//!
//! # Architecture
//!
//! - **WalRecord**: Enum representing different types of log entries
//! - **WriteAheadLog**: Core WAL implementation with append/sync/replay
//! - **CheckpointManager**: Manages periodic checkpoints and WAL trimming
//!
//! # Example
//!
//! ```rust
//! use dbx_core::wal::{WriteAheadLog, WalRecord};
//! use std::path::Path;
//!
//! # fn main() -> dbx_core::DbxResult<()> {
//! let wal = WriteAheadLog::open(Path::new("./wal.log"))?;
//!
//! // Log an insert operation
//! let record = WalRecord::Insert {
//!     table: "users".to_string(),
//!     key: b"user:1".to_vec(),
//!     value: b"Alice".to_vec(),
//!     ts: 0,
//! };
//! let seq = wal.append(&record)?;
//! wal.sync()?;  // Ensure durability
//! # Ok(())
//! # }
//! ```

use crate::error::{DbxError, DbxResult};
use serde::{Deserialize, Serialize};
use std::fs::{File, OpenOptions};
use std::io::{BufReader, Write};
use std::path::Path;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};

pub mod buffer;
pub mod checkpoint;
pub mod encrypted_wal;
pub mod partitioned_wal;

/// WAL record types.
///
/// Each record represents a single operation that can be replayed during recovery.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum WalRecord {
    /// Insert operation: table, key, value
    /// Insert operation: table, key, value, timestamp
    Insert {
        table: String,
        key: Vec<u8>,
        value: Vec<u8>,
        ts: u64,
    },

    /// Delete operation: table, key, timestamp
    Delete {
        table: String,
        key: Vec<u8>,
        ts: u64,
    },

    /// Checkpoint marker: sequence number
    Checkpoint { sequence: u64 },

    /// Transaction commit: transaction ID
    Commit { tx_id: u64 },

    /// Transaction rollback: transaction ID
    Rollback { tx_id: u64 },

    /// Batch operation: table, list of (key, value) pairs
    Batch {
        table: String,
        rows: Vec<(Vec<u8>, Vec<u8>)>,
        ts: u64,
    },
}

/// Write-Ahead Log for crash recovery.
///
/// All write operations are logged to disk before being applied to the database.
/// This ensures that the database can be recovered to a consistent state after a crash.
///
/// # Thread Safety
///
/// `WriteAheadLog` is thread-safe and can be shared across multiple threads using `Arc`.
pub struct WriteAheadLog {
    /// Log file handle (protected by mutex for concurrent writes)
    log_file: Mutex<File>,

    /// Path to the WAL file (for replay)
    path: std::path::PathBuf,

    /// Monotonically increasing sequence number
    sequence: AtomicU64,
}

impl WriteAheadLog {
    /// Opens or creates a WAL file at the specified path.
    ///
    /// If the file exists, it will be opened in append mode.
    /// The sequence number is initialized to the highest sequence in the existing log.
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the WAL file
    ///
    /// # Example
    ///
    /// ```rust
    /// # use dbx_core::wal::WriteAheadLog;
    /// # use std::path::Path;
    /// # fn main() -> dbx_core::DbxResult<()> {
    /// let wal = WriteAheadLog::open(Path::new("./wal.log"))?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn open(path: &Path) -> DbxResult<Self> {
        let file = OpenOptions::new()
            .create(true)
            .read(true)
            .append(true)
            .open(path)?;

        // Scan existing log to find the highest sequence number
        let max_seq = Self::scan_max_sequence(path)?;

        Ok(Self {
            log_file: Mutex::new(file),
            path: path.to_path_buf(),
            sequence: AtomicU64::new(max_seq),
        })
    }

    /// Scans the WAL file to find the maximum sequence number.
    fn scan_max_sequence(path: &Path) -> DbxResult<u64> {
        let file = match File::open(path) {
            Ok(f) => f,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(0),
            Err(e) => return Err(e.into()),
        };

        let mut reader = BufReader::new(file);
        let mut max_seq = 0u64;

        while let Ok(len_buf) = {
            let mut buf = [0u8; 4];
            std::io::Read::read_exact(&mut reader, &mut buf).map(|_| buf)
        } {
            let len = u32::from_le_bytes(len_buf) as usize;
            let mut data = vec![0u8; len];
            if std::io::Read::read_exact(&mut reader, &mut data).is_err() {
                break;
            }
            if let Ok(WalRecord::Checkpoint { sequence }) = bincode::deserialize::<WalRecord>(&data)
            {
                max_seq = max_seq.max(sequence);
            }
        }

        Ok(max_seq)
    }

    /// Appends a record to the WAL.
    ///
    /// Returns the sequence number assigned to this record.
    /// The record is buffered in memory until `sync()` is called.
    ///
    /// # Arguments
    ///
    /// * `record` - The WAL record to append
    ///
    /// # Returns
    ///
    /// The sequence number assigned to this record
    ///
    /// # Example
    ///
    /// ```rust
    /// # use dbx_core::wal::{WriteAheadLog, WalRecord};
    /// # use std::path::Path;
    /// # fn main() -> dbx_core::DbxResult<()> {
    /// let wal = WriteAheadLog::open(Path::new("./wal.log"))?;
    /// let record = WalRecord::Insert {
    ///     table: "users".to_string(),
    ///     key: b"key1".to_vec(),
    ///     value: b"value1".to_vec(),
    ///     ts: 0,
    /// };
    /// let seq = wal.append(&record)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn append(&self, record: &WalRecord) -> DbxResult<u64> {
        let seq = self.sequence.fetch_add(1, Ordering::SeqCst);

        // Serialize record to Binary format
        let encoded = bincode::serialize(record)
            .map_err(|e| DbxError::Wal(format!("serialization failed: {}", e)))?;

        // Write to log file (Length-prefixed binary)
        let mut file = self
            .log_file
            .lock()
            .map_err(|e| DbxError::Wal(format!("lock failed: {}", e)))?;

        let len = (encoded.len() as u32).to_le_bytes();
        file.write_all(&len)?;
        file.write_all(&encoded)?;

        Ok(seq)
    }

    /// Synchronizes the WAL to disk (fsync).
    ///
    /// This ensures that all buffered writes are persisted to disk.
    /// Call this after critical operations to guarantee durability.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use dbx_core::wal::{WriteAheadLog, WalRecord};
    /// # use std::path::Path;
    /// # fn main() -> dbx_core::DbxResult<()> {
    /// let wal = WriteAheadLog::open(Path::new("./wal.log"))?;
    /// let record = WalRecord::Insert {
    ///     table: "users".to_string(),
    ///     key: b"key1".to_vec(),
    ///     value: b"value1".to_vec(),
    ///     ts: 0,
    /// };
    /// wal.append(&record)?;
    /// wal.sync()?;  // Ensure durability
    /// # Ok(())
    /// # }
    /// ```
    pub fn sync(&self) -> DbxResult<()> {
        let file = self
            .log_file
            .lock()
            .map_err(|e| DbxError::Wal(format!("lock failed: {}", e)))?;

        file.sync_all()?;
        Ok(())
    }

    /// Replays all records from the WAL.
    ///
    /// Reads the entire WAL file and returns all records in order.
    /// Used during database recovery to restore the state after a crash.
    ///
    /// # Returns
    ///
    /// A vector of all WAL records in the order they were written
    ///
    /// # Example
    ///
    /// ```rust
    /// # use dbx_core::wal::WriteAheadLog;
    /// # fn main() -> dbx_core::DbxResult<()> {
    /// let tmp = tempfile::NamedTempFile::new().unwrap();
    /// let wal = WriteAheadLog::open(tmp.path())?;
    /// let records = wal.replay()?;
    /// for record in records {
    ///     // Apply record to database
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn replay(&self) -> DbxResult<Vec<WalRecord>> {
        // Open a new file handle for reading from the beginning
        let file = File::open(&self.path)?;
        let mut reader = BufReader::new(file);
        let mut records = Vec::new();

        while let Ok(len_buf) = {
            let mut buf = [0u8; 4];
            std::io::Read::read_exact(&mut reader, &mut buf).map(|_| buf)
        } {
            let len = u32::from_le_bytes(len_buf) as usize;
            let mut data = vec![0u8; len];
            if std::io::Read::read_exact(&mut reader, &mut data).is_err() {
                break;
            }

            let record = bincode::deserialize::<WalRecord>(&data)
                .map_err(|e| DbxError::Wal(format!("deserialization failed: {}", e)))?;

            records.push(record);
        }

        Ok(records)
    }

    /// Returns the current sequence number.
    pub fn current_sequence(&self) -> u64 {
        self.sequence.load(Ordering::SeqCst)
    }
}

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

    #[test]
    fn wal_append_and_replay() {
        let temp_file = NamedTempFile::new().unwrap();
        let wal = WriteAheadLog::open(temp_file.path()).unwrap();

        // Append records
        let record1 = WalRecord::Insert {
            table: "users".to_string(),
            key: b"user:1".to_vec(),
            value: b"Alice".to_vec(),
            ts: 1,
        };
        let record2 = WalRecord::Delete {
            table: "users".to_string(),
            key: b"user:2".to_vec(),
            ts: 2,
        };

        let seq1 = wal.append(&record1).unwrap();
        let seq2 = wal.append(&record2).unwrap();
        wal.sync().unwrap();

        assert_eq!(seq1, 0);
        assert_eq!(seq2, 1);

        // Replay
        let records = wal.replay().unwrap();
        assert_eq!(records.len(), 2);
        assert_eq!(records[0], record1);
        assert_eq!(records[1], record2);
    }

    #[test]
    fn wal_sync_durability() {
        let temp_file = NamedTempFile::new().unwrap();
        let wal = WriteAheadLog::open(temp_file.path()).unwrap();

        let record = WalRecord::Insert {
            table: "test".to_string(),
            key: b"key".to_vec(),
            value: b"value".to_vec(),
            ts: 5,
        };

        wal.append(&record).unwrap();
        wal.sync().unwrap();

        // Re-open and verify
        let wal2 = WriteAheadLog::open(temp_file.path()).unwrap();
        let records = wal2.replay().unwrap();
        assert_eq!(records.len(), 1);
        assert_eq!(records[0], record);
    }

    #[test]
    fn wal_sequence_increments() {
        let temp_file = NamedTempFile::new().unwrap();
        let wal = WriteAheadLog::open(temp_file.path()).unwrap();

        assert_eq!(wal.current_sequence(), 0);

        let record = WalRecord::Commit { tx_id: 1 };
        wal.append(&record).unwrap();
        assert_eq!(wal.current_sequence(), 1);

        wal.append(&record).unwrap();
        assert_eq!(wal.current_sequence(), 2);
    }

    #[test]
    fn wal_empty_replay() {
        let temp_file = NamedTempFile::new().unwrap();
        let wal = WriteAheadLog::open(temp_file.path()).unwrap();

        let records = wal.replay().unwrap();
        assert_eq!(records.len(), 0);
    }

    #[test]
    fn wal_checkpoint_record() {
        let temp_file = NamedTempFile::new().unwrap();
        let wal = WriteAheadLog::open(temp_file.path()).unwrap();

        let checkpoint = WalRecord::Checkpoint { sequence: 42 };
        wal.append(&checkpoint).unwrap();
        wal.sync().unwrap();

        let records = wal.replay().unwrap();
        assert_eq!(records.len(), 1);
        assert_eq!(records[0], checkpoint);
    }
}