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