Skip to main content

strata_storage/
bitcask.rs

1//! Pure-Rust Bitcask Append-Only WAL Storage Engine (Zero External Dependencies).
2
3use crate::crc32::crc32;
4use std::collections::HashMap;
5use std::fs::{File, OpenOptions};
6use std::io::{self, Read, Seek, SeekFrom, Write};
7use std::path::{Path, PathBuf};
8use std::time::{SystemTime, UNIX_EPOCH};
9
10pub const TOMBSTONE_VAL_LEN: u32 = 0xFFFF_FFFF;
11pub const MAX_KEY_SIZE: usize = 65535;
12pub const MAX_RECORD_SIZE: usize = 64 * 1024 * 1024; // 64 MB limit protecting against OOM bombs
13
14/// In-memory index entry pointing to the location of a value on disk.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub struct KeyDirEntry {
17    pub value_pos: u64,
18    pub value_size: u32,
19    pub timestamp: u64,
20}
21
22#[cfg(unix)]
23fn try_lock_exclusive(file: &File) -> io::Result<()> {
24    use std::os::unix::io::AsRawFd;
25    extern "C" {
26        fn flock(fd: i32, operation: i32) -> i32;
27    }
28    const LOCK_EX: i32 = 2;
29    const LOCK_NB: i32 = 4;
30
31    let res = unsafe { flock(file.as_raw_fd(), LOCK_EX | LOCK_NB) };
32    if res != 0 {
33        let err = io::Error::last_os_error();
34        if err.kind() == io::ErrorKind::WouldBlock || err.raw_os_error() == Some(11) {
35            Err(io::Error::new(
36                io::ErrorKind::WouldBlock,
37                "Bitcask WAL is locked by another process",
38            ))
39        } else {
40            Err(err)
41        }
42    } else {
43        Ok(())
44    }
45}
46
47#[cfg(unix)]
48fn unlock_file(file: &File) -> io::Result<()> {
49    use std::os::unix::io::AsRawFd;
50    extern "C" {
51        fn flock(fd: i32, operation: i32) -> i32;
52    }
53    const LOCK_UN: i32 = 8;
54    let res = unsafe { flock(file.as_raw_fd(), LOCK_UN) };
55    if res != 0 {
56        Err(io::Error::last_os_error())
57    } else {
58        Ok(())
59    }
60}
61
62#[cfg(windows)]
63fn try_lock_exclusive(file: &File) -> io::Result<()> {
64    use std::os::windows::io::AsRawHandle;
65    extern "system" {
66        fn LockFileEx(
67            h_file: *mut std::ffi::c_void,
68            dw_flags: u32,
69            dw_reserved: u32,
70            n_number_of_bytes_to_lock_low: u32,
71            n_number_of_bytes_to_lock_high: u32,
72            lp_overlapped: *mut std::ffi::c_void,
73        ) -> i32;
74    }
75    const LOCKFILE_EXCLUSIVE_LOCK: u32 = 0x0000_0002;
76    const LOCKFILE_FAIL_IMMEDIATELY: u32 = 0x0000_0001;
77
78    #[repr(C)]
79    struct WinOverlapped([usize; 4]);
80    let mut overlapped = WinOverlapped([0; 4]);
81    let res = unsafe {
82        LockFileEx(
83            file.as_raw_handle() as *mut _,
84            LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY,
85            0,
86            1,
87            0,
88            (&mut overlapped as *mut WinOverlapped).cast(),
89        )
90    };
91    if res == 0 {
92        let err = io::Error::last_os_error();
93        if err.raw_os_error() == Some(33) {
94            Err(io::Error::new(
95                io::ErrorKind::WouldBlock,
96                "Bitcask WAL is locked by another process",
97            ))
98        } else {
99            Err(err)
100        }
101    } else {
102        Ok(())
103    }
104}
105
106#[cfg(windows)]
107fn unlock_file(file: &File) -> io::Result<()> {
108    use std::os::windows::io::AsRawHandle;
109    extern "system" {
110        fn UnlockFile(
111            h_file: *mut std::ffi::c_void,
112            dw_file_offset_low: u32,
113            dw_file_offset_high: u32,
114            n_number_of_bytes_to_unlock_low: u32,
115            n_number_of_bytes_to_unlock_high: u32,
116        ) -> i32;
117    }
118    let res = unsafe { UnlockFile(file.as_raw_handle() as *mut _, 0, 0, 1, 0) };
119    if res == 0 {
120        Err(io::Error::last_os_error())
121    } else {
122        Ok(())
123    }
124}
125
126#[cfg(not(any(unix, windows)))]
127fn try_lock_exclusive(_file: &File) -> io::Result<()> {
128    Ok(())
129}
130
131#[cfg(not(any(unix, windows)))]
132fn unlock_file(_file: &File) -> io::Result<()> {
133    Ok(())
134}
135
136/// Pure-Rust Bitcask key-value store with append-only WAL.
137pub struct StrataKV {
138    wal_path: PathBuf,
139    wal_file: File,
140    key_dir: HashMap<String, KeyDirEntry>,
141}
142
143impl StrataKV {
144    /// Opens or creates a StrataKV database at the specified WAL file path.
145    pub fn open(wal_path: impl AsRef<Path>) -> io::Result<Self> {
146        let path = wal_path.as_ref().to_path_buf();
147        if let Some(parent) = path.parent() {
148            std::fs::create_dir_all(parent)?;
149        }
150
151        let mut file = OpenOptions::new()
152            .read(true)
153            .write(true)
154            .create(true)
155            .truncate(false)
156            .open(&path)?;
157
158        try_lock_exclusive(&file)?;
159
160        let mut key_dir = HashMap::new();
161        let valid_offset = Self::replay_wal(&mut file, &mut key_dir)?;
162        let file_len = file.metadata()?.len();
163        if valid_offset < file_len {
164            file.set_len(valid_offset)?;
165            file.sync_all()?;
166        }
167
168        // Ensure file cursor is at the very end for subsequent appends
169        file.seek(SeekFrom::Start(valid_offset))?;
170
171        Ok(Self {
172            wal_path: path,
173            wal_file: file,
174            key_dir,
175        })
176    }
177
178    /// Replays the WAL from start to end, verifying CRC32 checksums and indexing active keys.
179    /// Returns the last confirmed valid byte offset, allowing recovery and truncation of torn writes.
180    fn replay_wal(file: &mut File, key_dir: &mut HashMap<String, KeyDirEntry>) -> io::Result<u64> {
181        let file_len = file.metadata()?.len();
182        file.seek(SeekFrom::Start(0))?;
183        let mut header_buf = [0u8; 18]; // 4 (crc) + 8 (ts) + 2 (klen) + 4 (vlen)
184        let mut last_valid_offset = 0u64;
185
186        loop {
187            let offset = file.stream_position()?;
188            match file.read_exact(&mut header_buf) {
189                Ok(()) => {}
190                Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => break,
191                Err(e) => return Err(e),
192            }
193
194            let expected_crc = u32::from_le_bytes(header_buf[0..4].try_into().unwrap());
195            let timestamp = u64::from_le_bytes(header_buf[4..12].try_into().unwrap());
196            let key_len = u16::from_le_bytes(header_buf[12..14].try_into().unwrap()) as usize;
197            let val_len_raw = u32::from_le_bytes(header_buf[14..18].try_into().unwrap());
198
199            let is_tombstone = val_len_raw == TOMBSTONE_VAL_LEN;
200            let val_len = if is_tombstone {
201                0
202            } else {
203                val_len_raw as usize
204            };
205
206            // Reject pre-allocation OOM bomb: validate bounds against max record size and remaining file size
207            if val_len > MAX_RECORD_SIZE {
208                break;
209            }
210
211            let total_payload_len = key_len + val_len;
212            let remaining_file_bytes = file_len.saturating_sub(offset + 18);
213            if (total_payload_len as u64) > remaining_file_bytes {
214                break;
215            }
216
217            let mut payload = vec![0u8; total_payload_len];
218            file.read_exact(&mut payload)?;
219
220            // Verify checksum over timestamp + key_len + val_len + payload
221            let mut crc_check_data = Vec::with_capacity(14 + payload.len());
222            crc_check_data.extend_from_slice(&header_buf[4..18]);
223            crc_check_data.extend_from_slice(&payload);
224            let actual_crc = crc32(&crc_check_data);
225
226            if actual_crc != expected_crc {
227                // Detected corrupted record, stop replay at last valid offset
228                break;
229            }
230
231            let key_str = match String::from_utf8(payload[0..key_len].to_vec()) {
232                Ok(k) => k,
233                Err(_) => continue,
234            };
235
236            if is_tombstone {
237                key_dir.remove(&key_str);
238            } else {
239                let value_pos = offset + 18 + (key_len as u64);
240                key_dir.insert(
241                    key_str,
242                    KeyDirEntry {
243                        value_pos,
244                        value_size: val_len_raw,
245                        timestamp,
246                    },
247                );
248            }
249
250            last_valid_offset = file.stream_position()?;
251        }
252
253        Ok(last_valid_offset)
254    }
255
256    /// Retrieves a value by key.
257    pub fn get(&mut self, key: &str) -> io::Result<Option<Vec<u8>>> {
258        let entry = match self.key_dir.get(key) {
259            Some(e) => *e,
260            None => return Ok(None),
261        };
262
263        if entry.value_size as usize > MAX_RECORD_SIZE {
264            return Err(io::Error::new(
265                io::ErrorKind::InvalidData,
266                "Record exceeds MAX_RECORD_SIZE",
267            ));
268        }
269
270        let file_len = self.wal_file.metadata()?.len();
271        if entry.value_pos.saturating_add(entry.value_size as u64) > file_len {
272            return Err(io::Error::new(
273                io::ErrorKind::UnexpectedEof,
274                "Record exceeds WAL file length",
275            ));
276        }
277
278        self.wal_file.seek(SeekFrom::Start(entry.value_pos))?;
279        let mut buf = vec![0u8; entry.value_size as usize];
280        self.wal_file.read_exact(&mut buf)?;
281        Ok(Some(buf))
282    }
283
284    /// Stores a key-value pair, appending to the WAL and updating the in-memory index.
285    pub fn put(&mut self, key: &str, val: &[u8]) -> io::Result<()> {
286        if val.len() > MAX_RECORD_SIZE {
287            return Err(io::Error::new(
288                io::ErrorKind::InvalidInput,
289                "Value exceeds MAX_RECORD_SIZE",
290            ));
291        }
292
293        let ts = SystemTime::now()
294            .duration_since(UNIX_EPOCH)
295            .map(|d| d.as_millis() as u64)
296            .unwrap_or(0);
297
298        let key_bytes = key.as_bytes();
299        let key_len = key_bytes.len() as u16;
300        let val_len = val.len() as u32;
301
302        let mut crc_data = Vec::with_capacity(14 + key_bytes.len() + val.len());
303        crc_data.extend_from_slice(&ts.to_le_bytes());
304        crc_data.extend_from_slice(&key_len.to_le_bytes());
305        crc_data.extend_from_slice(&val_len.to_le_bytes());
306        crc_data.extend_from_slice(key_bytes);
307        crc_data.extend_from_slice(val);
308        let crc = crc32(&crc_data);
309
310        // Append to WAL
311        let record_pos = self.wal_file.seek(SeekFrom::End(0))?;
312        self.wal_file.write_all(&crc.to_le_bytes())?;
313        self.wal_file.write_all(&crc_data)?;
314        self.wal_file.flush()?;
315
316        let value_pos = record_pos + 18 + (key_len as u64);
317        self.key_dir.insert(
318            key.to_string(),
319            KeyDirEntry {
320                value_pos,
321                value_size: val_len,
322                timestamp: ts,
323            },
324        );
325
326        Ok(())
327    }
328
329    /// Deletes a key by appending a tombstone record.
330    pub fn delete(&mut self, key: &str) -> io::Result<bool> {
331        if !self.key_dir.contains_key(key) {
332            return Ok(false);
333        }
334
335        let ts = SystemTime::now()
336            .duration_since(UNIX_EPOCH)
337            .map(|d| d.as_millis() as u64)
338            .unwrap_or(0);
339
340        let key_bytes = key.as_bytes();
341        let key_len = key_bytes.len() as u16;
342        let val_len = TOMBSTONE_VAL_LEN;
343
344        let mut crc_data = Vec::with_capacity(14 + key_bytes.len());
345        crc_data.extend_from_slice(&ts.to_le_bytes());
346        crc_data.extend_from_slice(&key_len.to_le_bytes());
347        crc_data.extend_from_slice(&val_len.to_le_bytes());
348        crc_data.extend_from_slice(key_bytes);
349        let crc = crc32(&crc_data);
350
351        self.wal_file.seek(SeekFrom::End(0))?;
352        self.wal_file.write_all(&crc.to_le_bytes())?;
353        self.wal_file.write_all(&crc_data)?;
354        self.wal_file.flush()?;
355
356        self.key_dir.remove(key);
357        Ok(true)
358    }
359
360    /// Number of active non-deleted keys.
361    pub fn len(&self) -> usize {
362        self.key_dir.len()
363    }
364
365    /// Whether the database is empty.
366    pub fn is_empty(&self) -> bool {
367        self.key_dir.is_empty()
368    }
369
370    /// Returns a list of all active keys.
371    pub fn keys(&self) -> Vec<String> {
372        self.key_dir.keys().cloned().collect()
373    }
374
375    /// Returns total file size on disk in bytes.
376    pub fn total_bytes(&self) -> io::Result<u64> {
377        self.wal_file.metadata().map(|m| m.len())
378    }
379
380    /// Returns the sum of bytes utilized by all live keys, values, and frame headers.
381    pub fn live_data_bytes(&self) -> u64 {
382        self.key_dir
383            .iter()
384            .map(|(k, entry)| 18 + k.len() as u64 + entry.value_size as u64)
385            .sum()
386    }
387
388    /// Ratio of dead/reclaimable bytes in the WAL (0.0 to 1.0).
389    pub fn dead_bytes_ratio(&self) -> io::Result<f64> {
390        let total = self.total_bytes()?;
391        if total == 0 {
392            return Ok(0.0);
393        }
394        let live = self.live_data_bytes();
395        let dead = total.saturating_sub(live);
396        Ok(dead as f64 / total as f64)
397    }
398
399    /// Compacts the log if the dead bytes ratio exceeds the specified threshold.
400    pub fn maybe_compact(&mut self, threshold: f64) -> io::Result<bool> {
401        if self.dead_bytes_ratio()? >= threshold {
402            self.compact()?;
403            Ok(true)
404        } else {
405            Ok(false)
406        }
407    }
408
409    /// Compacts the log by writing all current active entries into a fresh compacted file.
410    pub fn compact(&mut self) -> io::Result<()> {
411        let compact_path = self.wal_path.with_extension("compact");
412        let mut compact_file = OpenOptions::new()
413            .read(true)
414            .write(true)
415            .create(true)
416            .truncate(true)
417            .open(&compact_path)?;
418
419        let mut new_key_dir = HashMap::new();
420
421        // Read each live entry from current file and append to compact file
422        for (key, entry) in &self.key_dir {
423            self.wal_file.seek(SeekFrom::Start(entry.value_pos))?;
424            let mut val_buf = vec![0u8; entry.value_size as usize];
425            self.wal_file.read_exact(&mut val_buf)?;
426
427            let key_bytes = key.as_bytes();
428            let key_len = key_bytes.len() as u16;
429            let val_len = val_buf.len() as u32;
430
431            let mut crc_data = Vec::with_capacity(14 + key_bytes.len() + val_buf.len());
432            crc_data.extend_from_slice(&entry.timestamp.to_le_bytes());
433            crc_data.extend_from_slice(&key_len.to_le_bytes());
434            crc_data.extend_from_slice(&val_len.to_le_bytes());
435            crc_data.extend_from_slice(key_bytes);
436            crc_data.extend_from_slice(&val_buf);
437            let crc = crc32(&crc_data);
438
439            let record_pos = compact_file.seek(SeekFrom::End(0))?;
440            compact_file.write_all(&crc.to_le_bytes())?;
441            compact_file.write_all(&crc_data)?;
442
443            let value_pos = record_pos + 18 + (key_len as u64);
444            new_key_dir.insert(
445                key.clone(),
446                KeyDirEntry {
447                    value_pos,
448                    value_size: val_len,
449                    timestamp: entry.timestamp,
450                },
451            );
452        }
453
454        compact_file.flush()?;
455        drop(compact_file);
456
457        // Replace old WAL with compacted WAL safely across operating systems:
458        // On Windows, renaming fails if either the source or target file is open.
459        // We unlock and drop the existing WAL handle first by swapping with an ephemeral file.
460        let swap_path = self.wal_path.with_extension("swap");
461        let swap_file = OpenOptions::new()
462            .read(true)
463            .write(true)
464            .create(true)
465            .truncate(true)
466            .open(&swap_path)?;
467
468        let old_file = std::mem::replace(&mut self.wal_file, swap_file);
469        let _ = unlock_file(&old_file);
470        drop(old_file);
471
472        std::fs::rename(&compact_path, &self.wal_path)?;
473
474        let mut reloaded = OpenOptions::new()
475            .read(true)
476            .write(true)
477            .open(&self.wal_path)?;
478        try_lock_exclusive(&reloaded)?;
479        reloaded.seek(SeekFrom::End(0))?;
480        self.wal_file = reloaded;
481        // Now the ephemeral swap_file handle has been dropped, so removal succeeds on Windows too.
482        let _ = std::fs::remove_file(&swap_path);
483
484        self.key_dir = new_key_dir;
485        Ok(())
486    }
487
488    /// Flushes and syncs WAL file data to underlying physical storage for durability guarantees.
489    pub fn sync(&mut self) -> io::Result<()> {
490        self.wal_file.flush()?;
491        self.wal_file.sync_data()?;
492        Ok(())
493    }
494
495    /// Verifies the integrity of the WAL file, checking CRC checksums for each frame.
496    /// Returns the number of valid records and the valid byte offset, allowing detection and recovery of torn writes.
497    pub fn verify_wal_integrity(wal_path: impl AsRef<Path>) -> io::Result<(usize, u64)> {
498        let mut file = OpenOptions::new().read(true).open(wal_path)?;
499        let mut key_dir = HashMap::new();
500        let valid_offset = Self::replay_wal(&mut file, &mut key_dir)?;
501        Ok((key_dir.len(), valid_offset))
502    }
503}
504
505impl Drop for StrataKV {
506    fn drop(&mut self) {
507        let _ = unlock_file(&self.wal_file);
508    }
509}