Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down
54 changes: 54 additions & 0 deletions src/crc.rs
Original file line number Diff line number Diff line change
@@ -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);
}
}
5 changes: 5 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<T> = std::result::Result<T, Error>;
Expand All @@ -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}")
}
}
}
}
Expand All @@ -23,6 +27,7 @@ impl std::error::Error for Error {
match self {
Error::Io(err) => Some(err),
Error::InvalidArgument(_) => None,
Error::Corrupt { .. } => None,
}
}
}
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
mod crc;
mod error;
mod store;
mod wal;

pub use error::{Error, Result};
pub use store::Store;
26 changes: 20 additions & 6 deletions src/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,40 @@ 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<u8>, Vec<u8>>,
wal: Wal,
}

impl Store {
pub fn open(path: impl AsRef<Path>) -> Result<Self> {
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 {
&self.dir
}

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(())
}
Expand All @@ -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<bool> {
self.wal.append_delete(key)?;
Ok(self.mem.remove(key).is_some())
}

pub fn contains_key(&self, key: &[u8]) -> bool {
Expand Down
203 changes: 203 additions & 0 deletions src/wal.rs
Original file line number Diff line number Diff line change
@@ -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<u8>, value: Vec<u8> },
Delete { key: Vec<u8> },
}

enum ReadOutcome {
Full,
Eof,
Torn,
}

#[derive(Debug)]
pub struct Wal {
file: File,
}

impl Wal {
pub fn open(dir: &Path) -> Result<(Self, Vec<Record>)> {
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<Vec<u8>> {
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> {
u32::try_from(n).map_err(|_| Error::InvalidArgument("key or value longer than u32"))
}

fn replay(file: &mut File) -> Result<Vec<Record>> {
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<ReadOutcome> {
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<Record> {
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<u32> {
let end = i.checked_add(4)?;
let slice = buf.get(*i..end)?;
*i = end;
Some(u32_from_prefix(slice))
}
Loading
Loading