diff --git a/README.md b/README.md index d55e837..753f295 100644 --- a/README.md +++ b/README.md @@ -4,19 +4,25 @@ An embedded key-value storage engine in Rust, built toward an LSM-tree (memtable ## What this demonstrates -Production stores such as RocksDB, LevelDB, and Bitcask separate an in-memory write path from durable on-disk structures. This crate starts with that split: a `Store` that owns a sorted memtable, exposes a small embedded KV API (`put` / `get` / `delete`), and returns borrowed slices for in-memory reads so callers do not copy bytes they only need to inspect. Later work adds a WAL, SSTable flush, and compaction. +Production stores such as RocksDB, LevelDB, and Bitcask separate an in-memory write path from durable on-disk structures. This crate starts with that split: a `Store` that owns a sorted memtable, logs every mutation to a length-prefixed WAL with a CRC-32 checksum, and returns borrowed slices for in-memory reads so callers do not copy bytes they only need to inspect. Later work adds SSTable flush and compaction. ## Concepts demonstrated - Embedded key-value API (byte keys and values, last-write-wins) - Memtable as an ordered `BTreeMap` (the in-process stand-in for a skiplist) - Ownership: the store owns buffers; `get` borrows them (zero-copy in-memory reads) -- Directory-backed open path, ready for WAL and SSTable files +- Write-ahead logging: log the mutation, `fsync`, then apply to the memtable +- Length-prefixed record framing (`crc32` + `len` + payload) +- CRC-32/ISO-HDLC checksums over the payload +- Torn-write detection: a short tail or a bad checksum on the last record is discarded and the file is truncated to the last good offset +- Mid-log checksum failure is corruption, not a torn write +- Crash recovery by replaying the WAL on `Store::open` - Rust crate layout, `cargo test`, Clippy `-D warnings`, GitHub Actions CI ## What's implemented - Cargo scaffold, the embedded KV API, CI (`cargo test` + `clippy`) +- Write-ahead log with CRC-32 framing, `fsync` on each mutation, and crash recovery on open ## Usage @@ -26,7 +32,10 @@ use ferro_store::Store; let mut store = Store::open("/tmp/ferro-demo")?; store.put(b"user:1", b"ada")?; assert_eq!(store.get(b"user:1"), Some(b"ada".as_slice())); -store.delete(b"user:1"); +drop(store); + +let store = Store::open("/tmp/ferro-demo")?; +assert_eq!(store.get(b"user:1"), Some(b"ada".as_slice())); ``` ## Tests diff --git a/src/crc.rs b/src/crc.rs new file mode 100644 index 0000000..ff3fae2 --- /dev/null +++ b/src/crc.rs @@ -0,0 +1,54 @@ +const POLY: u32 = 0xEDB88320; + +const fn make_table() -> [u32; 256] { + let mut table = [0u32; 256]; + let mut i = 0; + while i < 256 { + let mut crc = i as u32; + let mut bit = 0; + while bit < 8 { + crc = if crc & 1 != 0 { + (crc >> 1) ^ POLY + } else { + crc >> 1 + }; + bit += 1; + } + table[i] = crc; + i += 1; + } + table +} + +const TABLE: [u32; 256] = make_table(); + +pub fn crc32(data: &[u8]) -> u32 { + let mut crc = 0xFFFF_FFFFu32; + for &byte in data { + let idx = ((crc ^ byte as u32) & 0xFF) as usize; + crc = TABLE[idx] ^ (crc >> 8); + } + !crc +} + +#[cfg(test)] +mod tests { + use super::crc32; + + #[test] + fn iso_hdlc_empty() { + assert_eq!(crc32(b""), 0); + } + + #[test] + fn iso_hdlc_123456789() { + assert_eq!(crc32(b"123456789"), 0xCBF4_3926); + } + + #[test] + fn detects_bit_flip() { + let a = crc32(b"ferro-store"); + let b = crc32(b"ferro-storf"); + assert_ne!(a, b); + } +} diff --git a/src/error.rs b/src/error.rs index 57be7ca..95ed4f0 100644 --- a/src/error.rs +++ b/src/error.rs @@ -5,6 +5,7 @@ use std::io; pub enum Error { Io(io::Error), InvalidArgument(&'static str), + Corrupt { offset: u64, reason: &'static str }, } pub type Result = std::result::Result; @@ -14,6 +15,9 @@ impl fmt::Display for Error { match self { Error::Io(err) => write!(f, "io error: {err}"), Error::InvalidArgument(msg) => write!(f, "invalid argument: {msg}"), + Error::Corrupt { offset, reason } => { + write!(f, "corrupt wal at offset {offset}: {reason}") + } } } } @@ -23,6 +27,7 @@ impl std::error::Error for Error { match self { Error::Io(err) => Some(err), Error::InvalidArgument(_) => None, + Error::Corrupt { .. } => None, } } } diff --git a/src/lib.rs b/src/lib.rs index e9b931c..8162af1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,7 @@ +mod crc; mod error; mod store; +mod wal; pub use error::{Error, Result}; pub use store::Store; diff --git a/src/store.rs b/src/store.rs index 7d3f80a..36081e1 100644 --- a/src/store.rs +++ b/src/store.rs @@ -3,20 +3,32 @@ use std::fs; use std::path::{Path, PathBuf}; use crate::error::Result; +use crate::wal::{Record, Wal}; +#[derive(Debug)] pub struct Store { dir: PathBuf, mem: BTreeMap, Vec>, + wal: Wal, } impl Store { pub fn open(path: impl AsRef) -> Result { let dir = path.as_ref().to_path_buf(); fs::create_dir_all(&dir)?; - Ok(Self { - dir, - mem: BTreeMap::new(), - }) + let (wal, records) = Wal::open(&dir)?; + let mut mem = BTreeMap::new(); + for rec in records { + match rec { + Record::Put { key, value } => { + mem.insert(key, value); + } + Record::Delete { key } => { + mem.remove(&key); + } + } + } + Ok(Self { dir, mem, wal }) } pub fn path(&self) -> &Path { @@ -24,6 +36,7 @@ impl Store { } pub fn put(&mut self, key: &[u8], value: &[u8]) -> Result<()> { + self.wal.append_put(key, value)?; self.mem.insert(key.to_vec(), value.to_vec()); Ok(()) } @@ -32,8 +45,9 @@ impl Store { self.mem.get(key).map(Vec::as_slice) } - pub fn delete(&mut self, key: &[u8]) -> bool { - self.mem.remove(key).is_some() + pub fn delete(&mut self, key: &[u8]) -> Result { + self.wal.append_delete(key)?; + Ok(self.mem.remove(key).is_some()) } pub fn contains_key(&self, key: &[u8]) -> bool { diff --git a/src/wal.rs b/src/wal.rs new file mode 100644 index 0000000..2dcf883 --- /dev/null +++ b/src/wal.rs @@ -0,0 +1,203 @@ +use std::fs::{File, OpenOptions}; +use std::io::{Read, Seek, SeekFrom, Write}; +use std::path::Path; + +use crate::crc::crc32; +use crate::error::{Error, Result}; + +const OP_PUT: u8 = 1; +const OP_DELETE: u8 = 2; +const HEADER_LEN: usize = 8; +const MAX_PAYLOAD: u32 = 16 * 1024 * 1024; + +const WAL_FILE: &str = "wal.log"; + +#[derive(Debug)] +pub enum Record { + Put { key: Vec, value: Vec }, + Delete { key: Vec }, +} + +enum ReadOutcome { + Full, + Eof, + Torn, +} + +#[derive(Debug)] +pub struct Wal { + file: File, +} + +impl Wal { + pub fn open(dir: &Path) -> Result<(Self, Vec)> { + let path = dir.join(WAL_FILE); + let mut file = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(&path)?; + let records = replay(&mut file)?; + Ok((Self { file }, records)) + } + + pub fn append_put(&mut self, key: &[u8], value: &[u8]) -> Result<()> { + self.append(&encode(OP_PUT, key, Some(value))?) + } + + pub fn append_delete(&mut self, key: &[u8]) -> Result<()> { + self.append(&encode(OP_DELETE, key, None)?) + } + + fn append(&mut self, bytes: &[u8]) -> Result<()> { + self.file.write_all(bytes)?; + // each mutation is durable on return; group commit can wait + self.file.sync_all()?; + Ok(()) + } +} + +fn encode(op: u8, key: &[u8], value: Option<&[u8]>) -> Result> { + let key_len = u32_len(key.len())?; + let mut payload = Vec::new(); + payload.push(op); + payload.extend_from_slice(&key_len.to_le_bytes()); + payload.extend_from_slice(key); + if let Some(val) = value { + let value_len = u32_len(val.len())?; + payload.extend_from_slice(&value_len.to_le_bytes()); + payload.extend_from_slice(val); + } + if payload.len() > MAX_PAYLOAD as usize { + return Err(Error::InvalidArgument("record exceeds max payload")); + } + let crc = crc32(&payload); + let mut rec = Vec::with_capacity(HEADER_LEN + payload.len()); + rec.extend_from_slice(&crc.to_le_bytes()); + rec.extend_from_slice(&(payload.len() as u32).to_le_bytes()); + rec.extend_from_slice(&payload); + Ok(rec) +} + +fn u32_len(n: usize) -> Result { + u32::try_from(n).map_err(|_| Error::InvalidArgument("key or value longer than u32")) +} + +fn replay(file: &mut File) -> Result> { + file.seek(SeekFrom::Start(0))?; + let mut records = Vec::new(); + loop { + let pos = file.stream_position()?; + let mut header = [0u8; HEADER_LEN]; + match read_exact_or_torn(file, &mut header)? { + ReadOutcome::Eof => break, + ReadOutcome::Torn => { + truncate_torn(file, pos)?; + break; + } + ReadOutcome::Full => {} + } + let crc = u32_from_prefix(&header[0..4]); + let len = u32_from_prefix(&header[4..8]); + let remaining = file.metadata()?.len().saturating_sub(pos); + let claimed = HEADER_LEN as u64 + u64::from(len); + if claimed > remaining { + truncate_torn(file, pos)?; + break; + } + if len > MAX_PAYLOAD { + return Err(Error::Corrupt { + offset: pos, + reason: "payload too large", + }); + } + let mut payload = vec![0u8; len as usize]; + match read_exact_or_torn(file, &mut payload)? { + ReadOutcome::Eof | ReadOutcome::Torn => { + truncate_torn(file, pos)?; + break; + } + ReadOutcome::Full => {} + } + if crc32(&payload) != crc { + let end = file.stream_position()?; + let file_len = file.metadata()?.len(); + // checksum fail at EOF is a torn write, not a corrupt log + if end == file_len { + truncate_torn(file, pos)?; + break; + } + return Err(Error::Corrupt { + offset: pos, + reason: "checksum mismatch", + }); + } + let rec = decode(&payload).ok_or(Error::Corrupt { + offset: pos, + reason: "malformed payload", + })?; + records.push(rec); + } + file.seek(SeekFrom::End(0))?; + Ok(records) +} + +fn truncate_torn(file: &mut File, pos: u64) -> Result<()> { + file.set_len(pos)?; + // durable size before later appends, or a crash can restore the old tail + file.sync_all()?; + Ok(()) +} + +fn read_exact_or_torn(file: &mut File, buf: &mut [u8]) -> Result { + let mut got = 0; + while got < buf.len() { + match file.read(&mut buf[got..])? { + 0 if got == 0 => return Ok(ReadOutcome::Eof), + 0 => return Ok(ReadOutcome::Torn), + n => got += n, + } + } + Ok(ReadOutcome::Full) +} + +fn u32_from_prefix(slice: &[u8]) -> u32 { + let mut bytes = [0u8; 4]; + bytes.copy_from_slice(slice); + u32::from_le_bytes(bytes) +} + +fn decode(payload: &[u8]) -> Option { + let mut i = 0usize; + let op = *payload.get(i)?; + i += 1; + let key_len = take_u32(payload, &mut i)? as usize; + let key = payload.get(i..i.checked_add(key_len)?)?.to_vec(); + i += key_len; + match op { + OP_PUT => { + let value_len = take_u32(payload, &mut i)? as usize; + let value = payload.get(i..i.checked_add(value_len)?)?.to_vec(); + i += value_len; + if i != payload.len() { + return None; + } + Some(Record::Put { key, value }) + } + OP_DELETE => { + if i != payload.len() { + return None; + } + Some(Record::Delete { key }) + } + _ => None, + } +} + +fn take_u32(buf: &[u8], i: &mut usize) -> Option { + let end = i.checked_add(4)?; + let slice = buf.get(*i..end)?; + *i = end; + Some(u32_from_prefix(slice)) +} diff --git a/tests/store.rs b/tests/store.rs index cb27209..1aac3f4 100644 --- a/tests/store.rs +++ b/tests/store.rs @@ -76,9 +76,9 @@ fn overwrite_last_write_wins() { fn delete_existing_and_missing() { let (mut store, _g) = open(); store.put(b"k", b"v").unwrap(); - assert!(store.delete(b"k")); + assert!(store.delete(b"k").unwrap()); assert_eq!(store.get(b"k"), None); - assert!(!store.delete(b"k")); + assert!(!store.delete(b"k").unwrap()); } #[test] diff --git a/tests/wal.rs b/tests/wal.rs new file mode 100644 index 0000000..6b7274e --- /dev/null +++ b/tests/wal.rs @@ -0,0 +1,222 @@ +use std::fs::{self, OpenOptions}; +use std::io::Write; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use ferro_store::{Error, Store}; + +static NEXT: AtomicU64 = AtomicU64::new(0); + +fn scratch() -> PathBuf { + let n = NEXT.fetch_add(1, Ordering::Relaxed); + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("clock") + .as_nanos(); + let dir = + std::env::temp_dir().join(format!("ferro-wal-{}-{}-{}", std::process::id(), nanos, n)); + let _ = fs::remove_dir_all(&dir); + dir +} + +struct Guard(PathBuf); + +impl Drop for Guard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn wal_path(dir: &std::path::Path) -> PathBuf { + dir.join("wal.log") +} + +#[test] +fn reopen_replays_puts_and_deletes() { + let dir = scratch(); + let _g = Guard(dir.clone()); + { + let mut store = Store::open(&dir).unwrap(); + store.put(b"a", b"1").unwrap(); + store.put(b"b", b"2").unwrap(); + store.delete(b"a").unwrap(); + store.put(b"c", b"3").unwrap(); + store.put(b"", b"empty-key").unwrap(); + } + let store = Store::open(&dir).unwrap(); + assert_eq!(store.get(b"a"), None); + assert_eq!(store.get(b"b"), Some(b"2".as_slice())); + assert_eq!(store.get(b"c"), Some(b"3".as_slice())); + assert_eq!(store.get(b""), Some(b"empty-key".as_slice())); + assert_eq!(store.len(), 3); +} + +#[test] +fn last_write_wins_across_reopen() { + let dir = scratch(); + let _g = Guard(dir.clone()); + { + let mut store = Store::open(&dir).unwrap(); + store.put(b"k", b"v1").unwrap(); + store.put(b"k", b"v2").unwrap(); + } + let store = Store::open(&dir).unwrap(); + assert_eq!(store.get(b"k"), Some(b"v2".as_slice())); +} + +#[test] +fn torn_tail_is_discarded_then_appends_resume() { + let dir = scratch(); + let _g = Guard(dir.clone()); + { + let mut store = Store::open(&dir).unwrap(); + store.put(b"keep", b"yes").unwrap(); + store.put(b"lost", b"no").unwrap(); + } + let path = wal_path(&dir); + let len = fs::metadata(&path).unwrap().len(); + assert!(len > 3); + OpenOptions::new() + .write(true) + .open(&path) + .unwrap() + .set_len(len - 3) + .unwrap(); + + let store = Store::open(&dir).unwrap(); + assert_eq!(store.get(b"keep"), Some(b"yes".as_slice())); + assert_eq!(store.get(b"lost"), None); + + { + let mut store = Store::open(&dir).unwrap(); + store.put(b"after", b"ok").unwrap(); + } + let store = Store::open(&dir).unwrap(); + assert_eq!(store.get(b"keep"), Some(b"yes".as_slice())); + assert_eq!(store.get(b"after"), Some(b"ok".as_slice())); + assert_eq!(store.get(b"lost"), None); +} + +#[test] +fn last_record_length_past_eof_is_torn() { + let dir = scratch(); + let _g = Guard(dir.clone()); + { + let mut store = Store::open(&dir).unwrap(); + store.put(b"keep", b"yes").unwrap(); + store.put(b"lost", b"no").unwrap(); + } + let path = wal_path(&dir); + let mut bytes = fs::read(&path).unwrap(); + let at = last_record_len_offset(&bytes); + bytes[at..at + 4].copy_from_slice(&20_000_000u32.to_le_bytes()); + fs::write(&path, &bytes).unwrap(); + + let store = Store::open(&dir).unwrap(); + assert_eq!(store.get(b"keep"), Some(b"yes".as_slice())); + assert_eq!(store.get(b"lost"), None); +} + +fn last_record_len_offset(bytes: &[u8]) -> usize { + let mut i = 0usize; + let mut last = None; + while i + 8 <= bytes.len() { + let rec_len = u32::from_le_bytes(bytes[i + 4..i + 8].try_into().unwrap()) as usize; + last = Some(i + 4); + match i.checked_add(8).and_then(|n| n.checked_add(rec_len)) { + Some(next) if next <= bytes.len() => i = next, + _ => break, + } + } + last.expect("wal has a framed record") +} + +#[test] +fn checksum_mismatch_on_last_record_is_torn() { + let dir = scratch(); + let _g = Guard(dir.clone()); + { + let mut store = Store::open(&dir).unwrap(); + store.put(b"only", b"one").unwrap(); + } + let path = wal_path(&dir); + let mut bytes = fs::read(&path).unwrap(); + let last = bytes.len() - 1; + bytes[last] ^= 0xFF; + fs::write(&path, &bytes).unwrap(); + + let store = Store::open(&dir).unwrap(); + assert_eq!(store.get(b"only"), None); + assert!(store.is_empty()); +} + +#[test] +fn checksum_mismatch_in_middle_is_corrupt() { + let dir = scratch(); + let _g = Guard(dir.clone()); + { + let mut store = Store::open(&dir).unwrap(); + store.put(b"first", b"1").unwrap(); + store.put(b"second", b"2").unwrap(); + } + let path = wal_path(&dir); + let mut bytes = fs::read(&path).unwrap(); + bytes[12] ^= 0xFF; + fs::write(&path, &bytes).unwrap(); + + let err = Store::open(&dir).unwrap_err(); + assert!( + matches!( + err, + Error::Corrupt { + reason: "checksum mismatch", + .. + } + ), + "{err:?}" + ); +} + +#[test] +fn empty_wal_opens_empty_store() { + let dir = scratch(); + let _g = Guard(dir.clone()); + let store = Store::open(&dir).unwrap(); + assert!(store.is_empty()); + assert!(wal_path(&dir).is_file()); +} + +#[test] +fn binary_payload_survives_reopen() { + let dir = scratch(); + let _g = Guard(dir.clone()); + let key = [0u8, 255, 1, 2]; + let val = vec![0u8; 1024]; + { + let mut store = Store::open(&dir).unwrap(); + store.put(&key, &val).unwrap(); + } + let store = Store::open(&dir).unwrap(); + assert_eq!(store.get(&key), Some(val.as_slice())); +} + +#[test] +fn header_only_torn_write_is_ignored() { + let dir = scratch(); + let _g = Guard(dir.clone()); + { + let mut store = Store::open(&dir).unwrap(); + store.put(b"keep", b"yes").unwrap(); + } + let mut file = OpenOptions::new() + .append(true) + .open(wal_path(&dir)) + .unwrap(); + file.write_all(&[0x11, 0x22, 0x33]).unwrap(); + file.sync_all().unwrap(); + drop(file); + + let store = Store::open(&dir).unwrap(); + assert_eq!(store.get(b"keep"), Some(b"yes".as_slice())); +}