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
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
//! Checkpoint manager for WAL maintenance and crash recovery.
//!
//! The checkpoint manager coordinates with the WAL to:
//! - Apply WAL changes to the persistent storage
//! - Trim old WAL records after successful checkpoint
//! - Recover database state by replaying WAL records
//!
//! # Example
//!
//! ```rust
//! use dbx_core::wal::WriteAheadLog;
//! use dbx_core::wal::checkpoint::CheckpointManager;
//! use std::sync::Arc;
//! use std::path::Path;
//!
//! # fn main() -> dbx_core::DbxResult<()> {
//! let wal = Arc::new(WriteAheadLog::open(Path::new("./wal.log"))?);
//! let checkpoint_mgr = CheckpointManager::new(wal, Path::new("./wal.log"));
//!
//! // Perform checkpoint (apply WAL to storage)
//! // checkpoint_mgr.checkpoint(&db)?;
//! # Ok(())
//! # }
//! ```

use crate::error::{DbxError, DbxResult};
use crate::wal::{WalRecord, WriteAheadLog};
use std::fs::OpenOptions;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;

/// Checkpoint manager for WAL maintenance.
///
/// Manages periodic checkpoints and WAL trimming to keep the WAL file size bounded.
pub struct CheckpointManager {
    /// Reference to the WAL
    wal: Arc<WriteAheadLog>,

    /// Checkpoint interval (default: 30 seconds)
    interval: Duration,

    /// Path to the WAL file (for trimming)
    wal_path: PathBuf,
}

impl CheckpointManager {
    /// Creates a new checkpoint manager.
    ///
    /// # Arguments
    ///
    /// * `wal` - Shared reference to the WAL
    /// * `wal_path` - Path to the WAL file
    ///
    /// # Example
    ///
    /// ```rust
    /// # use dbx_core::wal::WriteAheadLog;
    /// # use dbx_core::wal::checkpoint::CheckpointManager;
    /// # use std::sync::Arc;
    /// # use std::path::Path;
    /// # fn main() -> dbx_core::DbxResult<()> {
    /// let wal = Arc::new(WriteAheadLog::open(Path::new("./wal.log"))?);
    /// let checkpoint_mgr = CheckpointManager::new(wal, Path::new("./wal.log"));
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(wal: Arc<WriteAheadLog>, wal_path: &Path) -> Self {
        Self {
            wal,
            interval: Duration::from_secs(30),
            wal_path: wal_path.to_path_buf(),
        }
    }

    /// Sets the checkpoint interval.
    ///
    /// # Arguments
    ///
    /// * `interval` - Duration between checkpoints
    pub fn with_interval(mut self, interval: Duration) -> Self {
        self.interval = interval;
        self
    }

    /// Performs a checkpoint.
    ///
    /// Applies all WAL records to the database and writes a checkpoint marker.
    /// This method should be called by the Database engine.
    ///
    /// # Arguments
    ///
    /// * `apply_fn` - Function to apply a WAL record to the database
    ///
    /// # Returns
    ///
    /// The sequence number of the checkpoint
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use dbx_core::wal::WriteAheadLog;
    /// # use dbx_core::wal::checkpoint::CheckpointManager;
    /// # use dbx_core::wal::WalRecord;
    /// # use std::sync::Arc;
    /// # use std::path::Path;
    /// # fn main() -> dbx_core::DbxResult<()> {
    /// let wal = Arc::new(WriteAheadLog::open(Path::new("./wal.log"))?);
    /// let checkpoint_mgr = CheckpointManager::new(wal, Path::new("./wal.log"));
    ///
    /// let apply_fn = |record: &WalRecord| -> dbx_core::DbxResult<()> {
    ///     // Apply record to database
    ///     Ok(())
    /// };
    ///
    /// let checkpoint_seq = checkpoint_mgr.checkpoint(apply_fn)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn checkpoint<F>(&self, apply_fn: F) -> DbxResult<u64>
    where
        F: Fn(&WalRecord) -> DbxResult<()>,
    {
        // Replay all WAL records
        let records = self.wal.replay()?;

        for record in &records {
            // Skip checkpoint markers
            if matches!(record, WalRecord::Checkpoint { .. }) {
                continue;
            }

            // Apply record to database
            apply_fn(record)?;
        }

        // Write checkpoint marker
        let seq = self.wal.current_sequence();
        let checkpoint_record = WalRecord::Checkpoint { sequence: seq };
        self.wal.append(&checkpoint_record)?;
        self.wal.sync()?;

        Ok(seq)
    }

    /// Recovers the database by replaying WAL records.
    ///
    /// This is called during database startup to restore the state after a crash.
    ///
    /// # Arguments
    ///
    /// * `wal_path` - Path to the WAL file
    /// * `apply_fn` - Function to apply a WAL record to the database
    ///
    /// # Returns
    ///
    /// The number of records replayed
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use dbx_core::wal::checkpoint::CheckpointManager;
    /// # use dbx_core::wal::WalRecord;
    /// # use std::path::Path;
    /// # fn main() -> dbx_core::DbxResult<()> {
    /// let apply_fn = |record: &WalRecord| -> dbx_core::DbxResult<()> {
    ///     // Apply record to database
    ///     Ok(())
    /// };
    ///
    /// let count = CheckpointManager::recover(Path::new("./wal.log"), apply_fn)?;
    /// println!("Replayed {} records", count);
    /// # Ok(())
    /// # }
    /// ```
    pub fn recover<F>(wal_path: &Path, apply_fn: F) -> DbxResult<usize>
    where
        F: Fn(&WalRecord) -> DbxResult<()>,
    {
        // Check if WAL file exists
        if !wal_path.exists() {
            return Ok(0);
        }

        let wal = WriteAheadLog::open(wal_path)?;
        let records = wal.replay()?;

        // Find the last checkpoint
        let mut last_checkpoint_idx = None;
        for (i, record) in records.iter().enumerate() {
            if matches!(record, WalRecord::Checkpoint { .. }) {
                last_checkpoint_idx = Some(i);
            }
        }

        // Replay records after the last checkpoint
        let start_idx = last_checkpoint_idx.map(|i| i + 1).unwrap_or(0);
        let replay_count = records.len() - start_idx;

        for record in &records[start_idx..] {
            apply_fn(record)?;
        }

        Ok(replay_count)
    }

    /// Trims the WAL file by removing records before the specified sequence.
    ///
    /// This is called after a successful checkpoint to keep the WAL file size bounded.
    ///
    /// # Arguments
    ///
    /// * `sequence` - Sequence number to trim before
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use dbx_core::wal::WriteAheadLog;
    /// # use dbx_core::wal::checkpoint::CheckpointManager;
    /// # use std::sync::Arc;
    /// # use std::path::Path;
    /// # fn main() -> dbx_core::DbxResult<()> {
    /// let wal = Arc::new(WriteAheadLog::open(Path::new("./wal.log"))?);
    /// let checkpoint_mgr = CheckpointManager::new(wal, Path::new("./wal.log"));
    ///
    /// // Trim records before sequence 100
    /// checkpoint_mgr.trim_before(100)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn trim_before(&self, sequence: u64) -> DbxResult<()> {
        // Read all records
        let records = self.wal.replay()?;

        // Find the last checkpoint with sequence >= target
        let mut last_checkpoint_idx = None;
        for (i, record) in records.iter().enumerate() {
            if let WalRecord::Checkpoint { sequence: seq } = record
                && *seq >= sequence
            {
                last_checkpoint_idx = Some(i);
            }
        }

        // Keep only records from the last checkpoint onwards
        let trimmed_records: Vec<WalRecord> = if let Some(idx) = last_checkpoint_idx {
            records.into_iter().skip(idx).collect()
        } else {
            // No checkpoint found, keep all records
            records
        };

        // Write trimmed records to a temporary file
        let temp_path = self.wal_path.with_extension("tmp");
        let mut temp_file = OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(true)
            .open(&temp_path)?;

        for record in &trimmed_records {
            let encoded = bincode::serialize(record)
                .map_err(|e| DbxError::Wal(format!("serialization failed: {}", e)))?;
            let len = (encoded.len() as u32).to_le_bytes();
            temp_file.write_all(&len)?;
            temp_file.write_all(&encoded)?;
        }

        temp_file.sync_all()?;
        drop(temp_file);

        // Replace the original WAL file with the trimmed one
        std::fs::rename(&temp_path, &self.wal_path)?;

        Ok(())
    }

    /// Returns the checkpoint interval.
    pub fn interval(&self) -> Duration {
        self.interval
    }
}

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

    #[test]
    fn checkpoint_applies_wal() {
        use std::cell::RefCell;

        let temp_file = NamedTempFile::new().unwrap();
        let wal = Arc::new(WriteAheadLog::open(temp_file.path()).unwrap());
        let checkpoint_mgr = CheckpointManager::new(wal.clone(), temp_file.path());

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

        wal.append(&record1).unwrap();
        wal.append(&record2).unwrap();
        wal.sync().unwrap();

        // Checkpoint
        let applied_records = RefCell::new(Vec::new());
        let apply_fn = |record: &WalRecord| {
            applied_records.borrow_mut().push(record.clone());
            Ok(())
        };

        let checkpoint_seq = checkpoint_mgr.checkpoint(apply_fn).unwrap();
        assert!(checkpoint_seq > 0);
        let records = applied_records.borrow();
        assert_eq!(records.len(), 2);
        assert_eq!(records[0], record1);
        assert_eq!(records[1], record2);
    }

    #[test]
    fn recover_replays_after_checkpoint() {
        use std::cell::RefCell;

        let temp_file = NamedTempFile::new().unwrap();
        let wal = Arc::new(WriteAheadLog::open(temp_file.path()).unwrap());

        // Add records before checkpoint
        let record1 = WalRecord::Insert {
            table: "users".to_string(),
            key: b"user:1".to_vec(),
            value: b"Alice".to_vec(),
            ts: 0,
        };
        wal.append(&record1).unwrap();

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

        // Add records after checkpoint
        let record2 = WalRecord::Insert {
            table: "users".to_string(),
            key: b"user:2".to_vec(),
            value: b"Bob".to_vec(),
            ts: 2, // After checkpoint
        };
        wal.append(&record2).unwrap();
        wal.sync().unwrap();

        // Recover
        let recovered_records = RefCell::new(Vec::new());
        let apply_fn = |record: &WalRecord| {
            recovered_records.borrow_mut().push(record.clone());
            Ok(())
        };

        let count = CheckpointManager::recover(temp_file.path(), apply_fn).unwrap();

        // Should only replay record2 (after checkpoint)
        assert_eq!(count, 1);
        let records = recovered_records.borrow();
        assert_eq!(records.len(), 1);
        assert_eq!(records[0], record2);
    }

    #[test]
    fn trim_removes_old_records() {
        let temp_file = NamedTempFile::new().unwrap();
        let wal = Arc::new(WriteAheadLog::open(temp_file.path()).unwrap());
        let checkpoint_mgr = CheckpointManager::new(wal.clone(), temp_file.path());

        // Add records
        let record1 = WalRecord::Insert {
            table: "users".to_string(),
            key: b"user:1".to_vec(),
            value: b"Alice".to_vec(),
            ts: 0,
        };
        wal.append(&record1).unwrap();

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

        let record2 = WalRecord::Insert {
            table: "users".to_string(),
            key: b"user:2".to_vec(),
            value: b"Bob".to_vec(),
            ts: 2,
        };
        wal.append(&record2).unwrap();
        wal.sync().unwrap();

        // Trim before sequence 1
        checkpoint_mgr.trim_before(1).unwrap();

        // Re-open and verify
        let wal2 = WriteAheadLog::open(temp_file.path()).unwrap();
        let records = wal2.replay().unwrap();

        // Should only have checkpoint and record2
        assert_eq!(records.len(), 2);
        assert!(matches!(records[0], WalRecord::Checkpoint { sequence: 1 }));
        assert_eq!(records[1], record2);
    }

    #[test]
    fn recover_empty_wal() {
        let temp_file = NamedTempFile::new().unwrap();
        std::fs::remove_file(temp_file.path()).unwrap();

        let apply_fn = |_: &WalRecord| Ok(());
        let count = CheckpointManager::recover(temp_file.path(), apply_fn).unwrap();

        assert_eq!(count, 0);
    }

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

        let checkpoint_mgr =
            CheckpointManager::new(wal, temp_file.path()).with_interval(Duration::from_secs(60));

        assert_eq!(checkpoint_mgr.interval(), Duration::from_secs(60));
    }
}