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 (macOS's `fsync` does not flush the drive's
128/// write cache), all through [`File::sync_data`].
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/// [`File::sync_data`] is the platform's true durability barrier: `fdatasync`
335/// on Linux, `FlushFileBuffers` on Windows, and `fcntl(F_FULLFSYNC)` on macOS
336/// and the other Apple platforms, where plain `fsync` leaves data in the
337/// drive's own write cache. The standard library has issued `F_FULLFSYNC`
338/// there for both `sync_all` and `sync_data` since before this crate's MSRV
339/// (`library/std/src/sys/pal/unix/fs.rs`, `os_datasync`, in 1.85), so the
340/// direct `libc` call wal-db 1.0 and 1.1 made duplicated it.
341pub(crate) fn durable_sync(file: &File) -> io::Result<()> {
342 file.sync_data()
343}
344
345/// Flush a directory, so the names created, renamed, or removed in it survive a
346/// power loss. Flushing a file does not do this on Unix.
347///
348/// A directory that cannot be opened for lack of permission, or a filesystem
349/// that does not support the flush, is skipped rather than failed: the log has
350/// no other way to do this, and refusing would stop logs that work today. A real
351/// I/O error is returned. Plain `fsync` on macOS, where `F_FULLFSYNC` is not
352/// dependable on a directory; callers flush the directory first, so the file
353/// flush that follows empties the drive's write cache behind it.
354#[cfg(unix)]
355pub(crate) fn sync_dir(dir: &Path) -> io::Result<()> {
356 let file = match File::open(dir) {
357 Ok(file) => file,
358 Err(error) if error.kind() == io::ErrorKind::PermissionDenied => return Ok(()),
359 Err(error) => return Err(error),
360 };
361 match file.sync_all() {
362 Err(error)
363 if matches!(
364 error.kind(),
365 io::ErrorKind::InvalidInput | io::ErrorKind::Unsupported
366 ) =>
367 {
368 Ok(())
369 }
370 other => other,
371 }
372}
373
374/// A no-op on Windows. NTFS writes name changes to its own journal and puts
375/// the journal on disk in its own time, so a file created, renamed, or removed
376/// is not durable the moment the call returns. Nothing may rest on such a
377/// change alone: whatever has to survive a power loss is carried by the flush
378/// of a file (see `SegmentedStore::truncate`).
379#[cfg(not(unix))]
380pub(crate) fn sync_dir(_dir: &Path) -> io::Result<()> {
381 Ok(())
382}
383
384/// Flush `dir` if `dirty` is set, clearing it. It stays set if the flush fails.
385///
386/// A store's `sync` is only ever entered by one thread at a time. A file created
387/// while the flush runs sets the flag again for the next sync, and any record
388/// that sync must cover was written, flag included, before the sync began.
389pub(crate) fn flush_dir_if_dirty(dirty: &AtomicBool, dir: &Path) -> Result<()> {
390 if dirty.load(Ordering::Acquire) && dirty.swap(false, Ordering::AcqRel) {
391 if let Err(error) = sync_dir(dir) {
392 dirty.store(true, Ordering::Release);
393 return Err(WalError::io("flushing the log directory", error));
394 }
395 }
396 Ok(())
397}
398
399/// The directory holding `path`; `.` for a bare file name.
400pub(crate) fn parent_dir(path: &Path) -> PathBuf {
401 match path.parent() {
402 Some(parent) if !parent.as_os_str().is_empty() => parent.to_path_buf(),
403 _ => PathBuf::from("."),
404 }
405}
406
407// ---------------------------------------------------------------------------
408// Positioned I/O. Reads and writes carry their own offset so they never move a
409// shared file cursor, which is what lets disjoint concurrent writes proceed
410// without a lock.
411// ---------------------------------------------------------------------------
412
413#[cfg(unix)]
414pub(crate) fn pwrite_all(file: &File, mut offset: u64, mut buf: &[u8]) -> io::Result<()> {
415 use std::os::unix::fs::FileExt;
416
417 while !buf.is_empty() {
418 match file.write_at(buf, offset) {
419 Ok(0) => {
420 return Err(io::Error::new(
421 io::ErrorKind::WriteZero,
422 "the store accepted zero bytes mid-record",
423 ));
424 }
425 Ok(n) => {
426 buf = &buf[n..];
427 offset += n as u64;
428 }
429 Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
430 Err(e) => return Err(e),
431 }
432 }
433 Ok(())
434}
435
436#[cfg(windows)]
437pub(crate) fn pwrite_all(file: &File, mut offset: u64, mut buf: &[u8]) -> io::Result<()> {
438 use std::os::windows::fs::FileExt;
439
440 while !buf.is_empty() {
441 match file.seek_write(buf, offset) {
442 Ok(0) => {
443 return Err(io::Error::new(
444 io::ErrorKind::WriteZero,
445 "the store accepted zero bytes mid-record",
446 ));
447 }
448 Ok(n) => {
449 buf = &buf[n..];
450 offset += n as u64;
451 }
452 Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
453 Err(e) => return Err(e),
454 }
455 }
456 Ok(())
457}
458
459#[cfg(unix)]
460pub(crate) fn pread_fill(file: &File, mut offset: u64, buf: &mut [u8]) -> io::Result<usize> {
461 use std::os::unix::fs::FileExt;
462
463 let mut total = 0;
464 while total < buf.len() {
465 match file.read_at(&mut buf[total..], offset) {
466 Ok(0) => break,
467 Ok(n) => {
468 total += n;
469 offset += n as u64;
470 }
471 Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
472 Err(e) => return Err(e),
473 }
474 }
475 Ok(total)
476}
477
478#[cfg(windows)]
479pub(crate) fn pread_fill(file: &File, mut offset: u64, buf: &mut [u8]) -> io::Result<usize> {
480 use std::os::windows::fs::FileExt;
481
482 let mut total = 0;
483 while total < buf.len() {
484 match file.seek_read(&mut buf[total..], offset) {
485 Ok(0) => break,
486 Ok(n) => {
487 total += n;
488 offset += n as u64;
489 }
490 Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
491 Err(e) => return Err(e),
492 }
493 }
494 Ok(total)
495}
496
497#[cfg(test)]
498#[allow(clippy::unwrap_used, clippy::expect_used)]
499mod dir_tests {
500 use super::*;
501
502 #[test]
503 fn test_parent_dir_of_a_bare_name_is_the_current_directory() {
504 assert_eq!(parent_dir(Path::new("app.wal")), PathBuf::from("."));
505 assert_eq!(parent_dir(Path::new("a/app.wal")), PathBuf::from("a"));
506 }
507
508 #[test]
509 fn test_sync_dir_flushes_a_real_directory() {
510 let dir = tempfile::tempdir().unwrap();
511 sync_dir(dir.path()).unwrap();
512 }
513
514 #[cfg(unix)]
515 #[test]
516 fn test_flush_failure_keeps_the_directory_dirty() {
517 let dir = tempfile::tempdir().unwrap();
518 let missing = dir.path().join("missing");
519 let dirty = AtomicBool::new(true);
520 assert!(flush_dir_if_dirty(&dirty, &missing).is_err());
521 assert!(dirty.load(Ordering::Acquire));
522 }
523
524 #[test]
525 fn test_clean_directory_is_not_flushed() {
526 let dir = tempfile::tempdir().unwrap();
527 let missing = dir.path().join("missing");
528 let dirty = AtomicBool::new(false);
529 // A flush would fail on Unix: the path does not exist.
530 flush_dir_if_dirty(&dirty, &missing).unwrap();
531 }
532
533 #[test]
534 fn test_file_store_flushes_its_directory_once() {
535 let dir = tempfile::tempdir().unwrap();
536 let store = FileStore::open(dir.path().join("log.wal")).unwrap();
537 assert!(store.parent_dirty.load(Ordering::Acquire));
538 store.sync().unwrap();
539 assert!(!store.parent_dirty.load(Ordering::Acquire));
540 }
541}
542
543#[cfg(test)]
544#[allow(clippy::unwrap_used, clippy::expect_used)]
545mod tests {
546 use super::*;
547
548 #[test]
549 fn test_memstore_write_at_advances_len() {
550 let store = MemStore::new();
551 assert_eq!(store.len().unwrap(), 0);
552 store.write_at(0, b"abc").unwrap();
553 assert_eq!(store.len().unwrap(), 3);
554 store.write_at(3, b"de").unwrap();
555 assert_eq!(store.len().unwrap(), 5);
556 }
557
558 #[test]
559 fn test_memstore_write_past_end_zero_fills_gap() {
560 let store = MemStore::new();
561 // Write at offset 4 while the store is empty: the gap [0,4) is zeros.
562 store.write_at(4, b"XY").unwrap();
563 assert_eq!(store.len().unwrap(), 6);
564 let mut buf = [0xFFu8; 6];
565 assert_eq!(store.read_at(0, &mut buf).unwrap(), 6);
566 assert_eq!(&buf, &[0, 0, 0, 0, b'X', b'Y']);
567 }
568
569 #[test]
570 fn test_memstore_read_past_end_is_short() {
571 let store = MemStore::new();
572 store.write_at(0, b"abc").unwrap();
573 let mut buf = [0u8; 8];
574 assert_eq!(store.read_at(1, &mut buf).unwrap(), 2);
575 assert_eq!(&buf[..2], b"bc");
576 }
577
578 #[test]
579 fn test_memstore_truncate_shrinks() {
580 let store = MemStore::new();
581 store.write_at(0, b"0123456789").unwrap();
582 store.truncate(4).unwrap();
583 assert_eq!(store.len().unwrap(), 4);
584 }
585
586 #[test]
587 fn test_filestore_roundtrip_through_disk() {
588 let dir = tempfile::tempdir().unwrap();
589 let path = dir.path().join("store.bin");
590
591 {
592 let store = FileStore::open(&path).unwrap();
593 store.write_at(0, b"hello world").unwrap();
594 store.sync().unwrap();
595 assert_eq!(store.len().unwrap(), 11);
596 }
597
598 let store = FileStore::open(&path).unwrap();
599 assert_eq!(store.len().unwrap(), 11);
600 let mut buf = [0u8; 5];
601 assert_eq!(store.read_at(6, &mut buf).unwrap(), 5);
602 assert_eq!(&buf, b"world");
603 }
604
605 #[test]
606 fn test_filestore_concurrent_disjoint_writes() {
607 use std::sync::Arc;
608 use std::thread;
609
610 let dir = tempfile::tempdir().unwrap();
611 let path = dir.path().join("concurrent.bin");
612 let store = Arc::new(FileStore::open(&path).unwrap());
613
614 let mut handles = Vec::new();
615 for i in 0..8u64 {
616 let store = Arc::clone(&store);
617 handles.push(thread::spawn(move || {
618 let byte = b'A' + i as u8;
619 store.write_at(i * 4, &[byte; 4]).unwrap();
620 }));
621 }
622 for h in handles {
623 h.join().unwrap();
624 }
625 store.sync().unwrap();
626
627 let mut buf = [0u8; 32];
628 assert_eq!(store.read_at(0, &mut buf).unwrap(), 32);
629 for i in 0..8 {
630 let expected = b'A' + i as u8;
631 assert_eq!(&buf[i * 4..i * 4 + 4], &[expected; 4]);
632 }
633 }
634
635 #[test]
636 fn test_filestore_sync_durable_across_reopen() {
637 let dir = tempfile::tempdir().unwrap();
638 let path = dir.path().join("durable.bin");
639 {
640 let store = FileStore::open(&path).unwrap();
641 store.write_at(0, b"persisted").unwrap();
642 store.sync().unwrap();
643 }
644 let store = FileStore::open(&path).unwrap();
645 let mut buf = [0u8; 9];
646 assert_eq!(store.read_at(0, &mut buf).unwrap(), 9);
647 assert_eq!(&buf, b"persisted");
648 }
649}