Skip to main content

wal_db/
store.rs

1//! Storage backends.
2//!
3//! A [`Wal`](crate::Wal) frames records, hands out sequence numbers, and
4//! coordinates durability; the bytes themselves live behind the [`WalStore`]
5//! trait. Every method takes `&self`, because the multi-writer append path
6//! writes from several threads at once — the store must accept concurrent,
7//! positioned writes without a lock of its own (a file does; an in-memory
8//! [`MemStore`] uses a short internal lock). The default [`FileStore`] writes to
9//! a file; a custom implementation could put the log on any byte-addressable,
10//! appendable medium.
11
12use std::{
13    fs::{File, OpenOptions},
14    io,
15    path::{Path, PathBuf},
16    sync::{
17        Mutex,
18        atomic::{AtomicBool, Ordering},
19    },
20};
21
22use crate::error::{Result, WalError};
23
24/// A byte-addressable, append-only store with an explicit durability barrier.
25///
26/// The log treats a store as a growing array of bytes. It writes framed records
27/// at reserved offsets — possibly from several threads concurrently and out of
28/// order — reads from arbitrary offsets during recovery, and occasionally
29/// truncates a torn tail. The one guarantee the log cannot provide itself — that
30/// written bytes have reached stable storage — is delegated to
31/// [`sync`](WalStore::sync).
32///
33/// # Implementing a backend
34///
35/// The contract an implementation must honour:
36///
37/// - [`write_at`](WalStore::write_at) writes `bytes` at `offset`, growing the
38///   store if `offset` is past the current end and zero-filling any gap (so a
39///   later offset written before an earlier one leaves detectable zero bytes in
40///   between, exactly as a sparse file does). Concurrent calls to disjoint
41///   ranges must not corrupt each other.
42/// - [`read_at`](WalStore::read_at) fills `buf` starting at `offset`, returning
43///   the number of bytes read. It returns fewer than `buf.len()` only when the
44///   store ends first — that short read is how recovery detects a torn tail.
45/// - [`sync`](WalStore::sync) returns only once every prior write is durable.
46/// - [`truncate`](WalStore::truncate) discards everything at or after `len`.
47///
48/// `Send + Sync` is required so the log can be shared across threads.
49///
50/// # Examples
51///
52/// ```
53/// use wal_db::{MemStore, Wal};
54///
55/// # fn main() -> Result<(), wal_db::WalError> {
56/// let wal = Wal::with_store(MemStore::new())?;
57/// wal.append(b"record")?;
58/// wal.sync()?;
59/// # Ok(())
60/// # }
61/// ```
62pub trait WalStore: Send + Sync {
63    /// Write `bytes` at byte `offset`, growing the store and zero-filling any
64    /// gap if `offset` is beyond the current end.
65    fn write_at(&self, offset: u64, bytes: &[u8]) -> Result<()>;
66
67    /// Read into `buf` starting at byte `offset`, returning the number of bytes
68    /// read.
69    ///
70    /// A return value smaller than `buf.len()` means the store ended before
71    /// `buf` could be filled.
72    fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<usize>;
73
74    /// Discard every byte at or after `len`, shrinking the store to exactly
75    /// `len` bytes.
76    fn truncate(&self, len: u64) -> Result<()>;
77
78    /// Flush every preceding [`write_at`](WalStore::write_at) to stable storage.
79    ///
80    /// Returns only once the data will survive a power loss. This is the
81    /// durability barrier the whole log rests on.
82    fn sync(&self) -> Result<()>;
83
84    /// The current size of the store in bytes.
85    fn len(&self) -> Result<u64>;
86
87    /// Whether the store holds no bytes.
88    ///
89    /// The default defers to [`len`](WalStore::len); override it only if a
90    /// backend can answer more cheaply.
91    fn is_empty(&self) -> Result<bool> {
92        Ok(self.len()? == 0)
93    }
94
95    /// The lowest offset that still holds data.
96    ///
97    /// Normally `0`. A backend that can drop a prefix (see
98    /// [`truncate_before`](WalStore::truncate_before)) reports the offset of its
99    /// first surviving byte here, so recovery knows where to begin scanning. The
100    /// default backends that cannot drop a prefix leave this at `0`.
101    fn head(&self) -> Result<u64> {
102        Ok(0)
103    }
104
105    /// Discard storage entirely below `offset`, if the backend can, returning the
106    /// new [`head`](WalStore::head).
107    ///
108    /// Offsets are preserved: dropping a prefix never renumbers what remains, so
109    /// a record keeps its byte position (its LSN) for life. A backend that cannot
110    /// remove a prefix — a single file, where the surviving bytes would have to
111    /// move — leaves the store unchanged and returns its current head. One that
112    /// can (a segmented store, by deleting whole leading segment files) removes
113    /// what it can at its own granularity and returns the resulting head, which
114    /// may be below `offset`.
115    fn truncate_before(&self, _offset: u64) -> Result<u64> {
116        self.head()
117    }
118}
119
120/// A file-backed [`WalStore`]: the default storage for [`Wal::open`](crate::Wal::open).
121///
122/// All reads and writes are positioned (`pread`/`pwrite` on Unix, `seek_read`/
123/// `seek_write` on Windows), so concurrent appenders writing to disjoint offsets
124/// never contend on a shared file cursor, and a recovery read never disturbs an
125/// append. [`sync`](WalStore::sync) issues the platform's true durability
126/// barrier: `fdatasync` on Linux, `FlushFileBuffers` on Windows, and
127/// `fcntl(F_FULLFSYNC)` on macOS — the last because macOS's `fsync` does not
128/// flush the drive's write cache.
129#[derive(Debug)]
130pub struct FileStore {
131    file: File,
132    path: PathBuf,
133    /// The directory holding the file, flushed once per open by the first
134    /// [`sync`](WalStore::sync): that is what makes a new file's name durable.
135    parent: PathBuf,
136    parent_dirty: AtomicBool,
137}
138
139impl FileStore {
140    /// Open the file at `path`, creating it if it does not exist.
141    ///
142    /// The store does not interpret the file's contents — it does not look for a
143    /// torn tail or validate records. That is [`Wal::open`](crate::Wal::open)'s
144    /// job, which scans on open and truncates any incomplete trailing record.
145    ///
146    /// # Errors
147    ///
148    /// Returns [`WalError::Io`] if the file cannot be opened (for example a
149    /// missing parent directory or insufficient permissions).
150    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
151        let path = path.as_ref().to_path_buf();
152        let file = OpenOptions::new()
153            .read(true)
154            .write(true)
155            .create(true)
156            .truncate(false)
157            .open(&path)
158            .map_err(|e| WalError::io("opening the log file", e))?;
159        let parent = parent_dir(&path);
160        Ok(FileStore {
161            file,
162            path,
163            parent,
164            parent_dirty: AtomicBool::new(true),
165        })
166    }
167
168    /// The path this store was opened from.
169    #[must_use]
170    pub fn path(&self) -> &Path {
171        &self.path
172    }
173}
174
175impl WalStore for FileStore {
176    fn write_at(&self, offset: u64, bytes: &[u8]) -> Result<()> {
177        pwrite_all(&self.file, offset, bytes).map_err(|e| WalError::io("writing a record", e))
178    }
179
180    fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<usize> {
181        pread_fill(&self.file, offset, buf).map_err(|e| WalError::io("reading from the log", e))
182    }
183
184    fn truncate(&self, len: u64) -> Result<()> {
185        self.file
186            .set_len(len)
187            .map_err(|e| WalError::io("truncating the log", e))
188    }
189
190    fn sync(&self) -> Result<()> {
191        flush_dir_if_dirty(&self.parent_dirty, &self.parent)?;
192        durable_sync(&self.file).map_err(|e| WalError::io("flushing to stable storage", e))
193    }
194
195    fn len(&self) -> Result<u64> {
196        Ok(self
197            .file
198            .metadata()
199            .map_err(|e| WalError::io("reading log file metadata", e))?
200            .len())
201    }
202}
203
204/// An in-memory [`WalStore`] backed by a `Vec<u8>` behind a short lock.
205///
206/// Everything a [`FileStore`] does, without touching the filesystem, including
207/// the sparse-file behaviour of zero-filling a gap when a higher offset is
208/// written first. [`sync`](WalStore::sync) is a no-op — memory has no separate
209/// durable tier — so a `MemStore` is for tests, examples, and benchmarking the
210/// framing path in isolation, not for durability.
211///
212/// # Examples
213///
214/// ```
215/// use wal_db::{MemStore, Wal};
216///
217/// # fn main() -> Result<(), wal_db::WalError> {
218/// let wal = Wal::with_store(MemStore::new())?;
219/// let lsn = wal.append(b"in memory")?;
220/// assert_eq!(lsn.get(), 0);
221/// # Ok(())
222/// # }
223/// ```
224#[derive(Debug, Default)]
225pub struct MemStore {
226    data: Mutex<Vec<u8>>,
227}
228
229impl MemStore {
230    /// Create an empty in-memory store.
231    #[must_use]
232    pub fn new() -> Self {
233        MemStore {
234            data: Mutex::new(Vec::new()),
235        }
236    }
237
238    /// Create an empty store that has pre-allocated room for `capacity` bytes,
239    /// to avoid reallocations during a known-size workload.
240    #[must_use]
241    pub fn with_capacity(capacity: usize) -> Self {
242        MemStore {
243            data: Mutex::new(Vec::with_capacity(capacity)),
244        }
245    }
246
247    /// Create a store preloaded with `bytes` — for example a log image captured
248    /// elsewhere, so [`Wal::with_store`](crate::Wal::with_store) can recover it.
249    #[must_use]
250    pub fn from_bytes(bytes: Vec<u8>) -> Self {
251        MemStore {
252            data: Mutex::new(bytes),
253        }
254    }
255
256    fn lock(&self) -> std::sync::MutexGuard<'_, Vec<u8>> {
257        self.data
258            .lock()
259            .unwrap_or_else(std::sync::PoisonError::into_inner)
260    }
261
262    /// A copy of the current bytes. Crate-internal, for tests that inspect or
263    /// snapshot the on-disk image.
264    #[cfg(test)]
265    pub(crate) fn snapshot(&self) -> Vec<u8> {
266        self.lock().clone()
267    }
268}
269
270impl Clone for MemStore {
271    fn clone(&self) -> Self {
272        MemStore {
273            data: Mutex::new(self.lock().clone()),
274        }
275    }
276}
277
278impl WalStore for MemStore {
279    fn write_at(&self, offset: u64, bytes: &[u8]) -> Result<()> {
280        let start = usize::try_from(offset).map_err(|_| {
281            WalError::io(
282                "writing to memory",
283                io::Error::other("offset exceeds usize"),
284            )
285        })?;
286        let end = start.checked_add(bytes.len()).ok_or_else(|| {
287            WalError::io(
288                "writing to memory",
289                io::Error::other("write overflows usize"),
290            )
291        })?;
292
293        let mut data = self.lock();
294        if data.len() < end {
295            data.resize(end, 0); // zero-fill any gap, like a sparse file
296        }
297        data[start..end].copy_from_slice(bytes);
298        Ok(())
299    }
300
301    fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<usize> {
302        let data = self.lock();
303        let start = match usize::try_from(offset) {
304            Ok(start) if start < data.len() => start,
305            _ => return Ok(0),
306        };
307        let available = &data[start..];
308        let n = available.len().min(buf.len());
309        buf[..n].copy_from_slice(&available[..n]);
310        Ok(n)
311    }
312
313    fn truncate(&self, len: u64) -> Result<()> {
314        let len = usize::try_from(len).unwrap_or(usize::MAX);
315        self.lock().truncate(len);
316        Ok(())
317    }
318
319    fn sync(&self) -> Result<()> {
320        Ok(())
321    }
322
323    fn len(&self) -> Result<u64> {
324        Ok(self.lock().len() as u64)
325    }
326}
327
328// ---------------------------------------------------------------------------
329// Platform-correct durability.
330// ---------------------------------------------------------------------------
331
332/// Flush every buffered write for `file` to stable storage.
333///
334/// On macOS this is `fcntl(F_FULLFSYNC)`. The standard library's `sync_all` and
335/// `sync_data` call `fsync(2)` there, which flushes the page cache to the device
336/// but leaves the data in the device's own write cache, where a power loss can
337/// still take it. `F_FULLFSYNC` is the documented way to force a full flush.
338#[cfg(target_os = "macos")]
339pub(crate) fn durable_sync(file: &File) -> io::Result<()> {
340    use std::os::unix::io::AsRawFd;
341
342    let fd = file.as_raw_fd();
343    // SAFETY: `fd` is a valid, open file descriptor for as long as `file` is
344    // borrowed, so it cannot be closed from under us. `F_FULLFSYNC` takes no
345    // argument pointer and neither reads nor writes any user buffer. `fcntl`
346    // reports failure by returning -1 and setting `errno`, which is checked
347    // immediately below.
348    let ret = unsafe { libc::fcntl(fd, libc::F_FULLFSYNC) };
349    if ret == -1 {
350        return Err(io::Error::last_os_error());
351    }
352    Ok(())
353}
354
355/// On Linux `sync_data` is `fdatasync`; on Windows it is `FlushFileBuffers`.
356/// Both are true durability barriers, so the standard library call is correct
357/// on every platform except macOS.
358#[cfg(not(target_os = "macos"))]
359pub(crate) fn durable_sync(file: &File) -> io::Result<()> {
360    file.sync_data()
361}
362
363/// Flush a directory, so the names created, renamed, or removed in it survive a
364/// power loss. Flushing a file does not do this on Unix.
365///
366/// A directory that cannot be opened for lack of permission, or a filesystem
367/// that does not support the flush, is skipped rather than failed: the log has
368/// no other way to do this, and refusing would stop logs that work today. A real
369/// I/O error is returned. Plain `fsync` on macOS, where `F_FULLFSYNC` is not
370/// dependable on a directory; callers flush the directory first, so the file
371/// flush that follows empties the drive's write cache behind it.
372#[cfg(unix)]
373pub(crate) fn sync_dir(dir: &Path) -> io::Result<()> {
374    let file = match File::open(dir) {
375        Ok(file) => file,
376        Err(error) if error.kind() == io::ErrorKind::PermissionDenied => return Ok(()),
377        Err(error) => return Err(error),
378    };
379    match file.sync_all() {
380        Err(error)
381            if matches!(
382                error.kind(),
383                io::ErrorKind::InvalidInput | io::ErrorKind::Unsupported
384            ) =>
385        {
386            Ok(())
387        }
388        other => other,
389    }
390}
391
392/// A no-op: a directory cannot be flushed through the standard library on
393/// Windows, and NTFS commits its metadata changes through its own journal.
394#[cfg(not(unix))]
395pub(crate) fn sync_dir(_dir: &Path) -> io::Result<()> {
396    Ok(())
397}
398
399/// Flush `dir` if `dirty` is set, clearing it. It stays set if the flush fails.
400///
401/// A store's `sync` is only ever entered by one thread at a time. A file created
402/// while the flush runs sets the flag again for the next sync, and any record
403/// that sync must cover was written, flag included, before the sync began.
404pub(crate) fn flush_dir_if_dirty(dirty: &AtomicBool, dir: &Path) -> Result<()> {
405    if dirty.load(Ordering::Acquire) && dirty.swap(false, Ordering::AcqRel) {
406        if let Err(error) = sync_dir(dir) {
407            dirty.store(true, Ordering::Release);
408            return Err(WalError::io("flushing the log directory", error));
409        }
410    }
411    Ok(())
412}
413
414/// The directory holding `path`; `.` for a bare file name.
415pub(crate) fn parent_dir(path: &Path) -> PathBuf {
416    match path.parent() {
417        Some(parent) if !parent.as_os_str().is_empty() => parent.to_path_buf(),
418        _ => PathBuf::from("."),
419    }
420}
421
422// ---------------------------------------------------------------------------
423// Positioned I/O. Reads and writes carry their own offset so they never move a
424// shared file cursor, which is what lets disjoint concurrent writes proceed
425// without a lock.
426// ---------------------------------------------------------------------------
427
428#[cfg(unix)]
429pub(crate) fn pwrite_all(file: &File, mut offset: u64, mut buf: &[u8]) -> io::Result<()> {
430    use std::os::unix::fs::FileExt;
431
432    while !buf.is_empty() {
433        match file.write_at(buf, offset) {
434            Ok(0) => {
435                return Err(io::Error::new(
436                    io::ErrorKind::WriteZero,
437                    "the store accepted zero bytes mid-record",
438                ));
439            }
440            Ok(n) => {
441                buf = &buf[n..];
442                offset += n as u64;
443            }
444            Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
445            Err(e) => return Err(e),
446        }
447    }
448    Ok(())
449}
450
451#[cfg(windows)]
452pub(crate) fn pwrite_all(file: &File, mut offset: u64, mut buf: &[u8]) -> io::Result<()> {
453    use std::os::windows::fs::FileExt;
454
455    while !buf.is_empty() {
456        match file.seek_write(buf, offset) {
457            Ok(0) => {
458                return Err(io::Error::new(
459                    io::ErrorKind::WriteZero,
460                    "the store accepted zero bytes mid-record",
461                ));
462            }
463            Ok(n) => {
464                buf = &buf[n..];
465                offset += n as u64;
466            }
467            Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
468            Err(e) => return Err(e),
469        }
470    }
471    Ok(())
472}
473
474#[cfg(unix)]
475pub(crate) fn pread_fill(file: &File, mut offset: u64, buf: &mut [u8]) -> io::Result<usize> {
476    use std::os::unix::fs::FileExt;
477
478    let mut total = 0;
479    while total < buf.len() {
480        match file.read_at(&mut buf[total..], offset) {
481            Ok(0) => break,
482            Ok(n) => {
483                total += n;
484                offset += n as u64;
485            }
486            Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
487            Err(e) => return Err(e),
488        }
489    }
490    Ok(total)
491}
492
493#[cfg(windows)]
494pub(crate) fn pread_fill(file: &File, mut offset: u64, buf: &mut [u8]) -> io::Result<usize> {
495    use std::os::windows::fs::FileExt;
496
497    let mut total = 0;
498    while total < buf.len() {
499        match file.seek_read(&mut buf[total..], offset) {
500            Ok(0) => break,
501            Ok(n) => {
502                total += n;
503                offset += n as u64;
504            }
505            Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
506            Err(e) => return Err(e),
507        }
508    }
509    Ok(total)
510}
511
512#[cfg(test)]
513#[allow(clippy::unwrap_used, clippy::expect_used)]
514mod dir_tests {
515    use super::*;
516
517    #[test]
518    fn test_parent_dir_of_a_bare_name_is_the_current_directory() {
519        assert_eq!(parent_dir(Path::new("app.wal")), PathBuf::from("."));
520        assert_eq!(parent_dir(Path::new("a/app.wal")), PathBuf::from("a"));
521    }
522
523    #[test]
524    fn test_sync_dir_flushes_a_real_directory() {
525        let dir = tempfile::tempdir().unwrap();
526        sync_dir(dir.path()).unwrap();
527    }
528
529    #[cfg(unix)]
530    #[test]
531    fn test_flush_failure_keeps_the_directory_dirty() {
532        let dir = tempfile::tempdir().unwrap();
533        let missing = dir.path().join("missing");
534        let dirty = AtomicBool::new(true);
535        assert!(flush_dir_if_dirty(&dirty, &missing).is_err());
536        assert!(dirty.load(Ordering::Acquire));
537    }
538
539    #[test]
540    fn test_clean_directory_is_not_flushed() {
541        let dir = tempfile::tempdir().unwrap();
542        let missing = dir.path().join("missing");
543        let dirty = AtomicBool::new(false);
544        // A flush would fail on Unix: the path does not exist.
545        flush_dir_if_dirty(&dirty, &missing).unwrap();
546    }
547
548    #[test]
549    fn test_file_store_flushes_its_directory_once() {
550        let dir = tempfile::tempdir().unwrap();
551        let store = FileStore::open(dir.path().join("log.wal")).unwrap();
552        assert!(store.parent_dirty.load(Ordering::Acquire));
553        store.sync().unwrap();
554        assert!(!store.parent_dirty.load(Ordering::Acquire));
555    }
556}
557
558#[cfg(test)]
559#[allow(clippy::unwrap_used, clippy::expect_used)]
560mod tests {
561    use super::*;
562
563    #[test]
564    fn test_memstore_write_at_advances_len() {
565        let store = MemStore::new();
566        assert_eq!(store.len().unwrap(), 0);
567        store.write_at(0, b"abc").unwrap();
568        assert_eq!(store.len().unwrap(), 3);
569        store.write_at(3, b"de").unwrap();
570        assert_eq!(store.len().unwrap(), 5);
571    }
572
573    #[test]
574    fn test_memstore_write_past_end_zero_fills_gap() {
575        let store = MemStore::new();
576        // Write at offset 4 while the store is empty: the gap [0,4) is zeros.
577        store.write_at(4, b"XY").unwrap();
578        assert_eq!(store.len().unwrap(), 6);
579        let mut buf = [0xFFu8; 6];
580        assert_eq!(store.read_at(0, &mut buf).unwrap(), 6);
581        assert_eq!(&buf, &[0, 0, 0, 0, b'X', b'Y']);
582    }
583
584    #[test]
585    fn test_memstore_read_past_end_is_short() {
586        let store = MemStore::new();
587        store.write_at(0, b"abc").unwrap();
588        let mut buf = [0u8; 8];
589        assert_eq!(store.read_at(1, &mut buf).unwrap(), 2);
590        assert_eq!(&buf[..2], b"bc");
591    }
592
593    #[test]
594    fn test_memstore_truncate_shrinks() {
595        let store = MemStore::new();
596        store.write_at(0, b"0123456789").unwrap();
597        store.truncate(4).unwrap();
598        assert_eq!(store.len().unwrap(), 4);
599    }
600
601    #[test]
602    fn test_filestore_roundtrip_through_disk() {
603        let dir = tempfile::tempdir().unwrap();
604        let path = dir.path().join("store.bin");
605
606        {
607            let store = FileStore::open(&path).unwrap();
608            store.write_at(0, b"hello world").unwrap();
609            store.sync().unwrap();
610            assert_eq!(store.len().unwrap(), 11);
611        }
612
613        let store = FileStore::open(&path).unwrap();
614        assert_eq!(store.len().unwrap(), 11);
615        let mut buf = [0u8; 5];
616        assert_eq!(store.read_at(6, &mut buf).unwrap(), 5);
617        assert_eq!(&buf, b"world");
618    }
619
620    #[test]
621    fn test_filestore_concurrent_disjoint_writes() {
622        use std::sync::Arc;
623        use std::thread;
624
625        let dir = tempfile::tempdir().unwrap();
626        let path = dir.path().join("concurrent.bin");
627        let store = Arc::new(FileStore::open(&path).unwrap());
628
629        let mut handles = Vec::new();
630        for i in 0..8u64 {
631            let store = Arc::clone(&store);
632            handles.push(thread::spawn(move || {
633                let byte = b'A' + i as u8;
634                store.write_at(i * 4, &[byte; 4]).unwrap();
635            }));
636        }
637        for h in handles {
638            h.join().unwrap();
639        }
640        store.sync().unwrap();
641
642        let mut buf = [0u8; 32];
643        assert_eq!(store.read_at(0, &mut buf).unwrap(), 32);
644        for i in 0..8 {
645            let expected = b'A' + i as u8;
646            assert_eq!(&buf[i * 4..i * 4 + 4], &[expected; 4]);
647        }
648    }
649
650    #[test]
651    fn test_filestore_sync_durable_across_reopen() {
652        let dir = tempfile::tempdir().unwrap();
653        let path = dir.path().join("durable.bin");
654        {
655            let store = FileStore::open(&path).unwrap();
656            store.write_at(0, b"persisted").unwrap();
657            store.sync().unwrap();
658        }
659        let store = FileStore::open(&path).unwrap();
660        let mut buf = [0u8; 9];
661        assert_eq!(store.read_at(0, &mut buf).unwrap(), 9);
662        assert_eq!(&buf, b"persisted");
663    }
664}