Skip to main content

wal_db/
lib.rs

1//! # wal-db
2//!
3//! A write-ahead log primitive for Rust storage engines.
4//!
5//! A write-ahead log (WAL) is the durability substrate every database leans on:
6//! a state change is appended to a durable, append-only log *before* it is
7//! acknowledged, and that log is the source of truth used to rebuild state after
8//! a crash. `wal-db` publishes that primitive as a small, audited, benchmarked
9//! crate so the storage engines in the portfolio (`lsm-db`, `txn-db`,
10//! `raft-io`) share one well-tested implementation instead of each
11//! re-deriving the durability contract and getting it subtly wrong.
12//!
13//! ## The four-call API
14//!
15//! The common case is four calls: open, append, sync, iterate.
16//!
17//! ```
18//! use wal_db::Wal;
19//!
20//! # fn main() -> Result<(), wal_db::WalError> {
21//! # let dir = tempfile::tempdir().map_err(wal_db::WalError::from)?;
22//! # let path = dir.path().join("app.wal");
23//! // Open (or create) the log.
24//! let wal = Wal::open(&path)?;
25//!
26//! // Append a record; `append` returns once the bytes are in the kernel
27//! // page cache. It does not flush the disk. The returned LSN is the record's
28//! // byte offset — the first record starts at 0.
29//! let lsn = wal.append(b"the first record")?;
30//! assert_eq!(lsn.get(), 0);
31//!
32//! // `sync` is the durability barrier: it returns once every record appended
33//! // before it is on stable storage.
34//! wal.sync()?;
35//!
36//! // On restart, replay the log to rebuild state.
37//! for entry in wal.iter()? {
38//!     let entry = entry?;
39//!     assert_eq!(entry.data(), b"the first record");
40//! }
41//! # Ok(())
42//! # }
43//! ```
44//!
45//! ## Concurrency and group commit
46//!
47//! `Wal` is built for many writers. [`append`](Wal::append) is lock-free: each
48//! call reserves its byte range with a single atomic step — that range's start
49//! offset *is* the record's [`Lsn`] — then writes its record without blocking
50//! the others. Share one `Wal` behind an [`Arc`](std::sync::Arc) and append from
51//! every thread.
52//!
53//! Durability is where threads cooperate. When several call [`sync`](Wal::sync)
54//! at once, they coalesce into a single fsync — **group commit** — so the cost
55//! of making data durable is amortised across everyone committing together
56//! rather than paid N times. [`append_and_sync`](Wal::append_and_sync) does an
57//! append and a group-commit-aware sync in one call.
58//!
59//! ## The durability contract
60//!
61//! Two operations, two distinct guarantees. Confusing them is the single most
62//! common way to lose data with a WAL, so they are kept explicit:
63//!
64//! - [`Wal::append`] returns when the record is in the operating system's page
65//!   cache. A crash *after* `append` but *before* `sync` may lose the record.
66//! - [`Wal::sync`] returns only when every previously appended record is on
67//!   stable storage and will survive a power loss.
68//!
69//! The flush is platform-correct on each target, which is not the same call
70//! everywhere:
71//!
72//! | Platform | Durability call |
73//! |----------|-----------------|
74//! | Linux    | `fdatasync` (via [`std::fs::File::sync_data`]) |
75//! | Windows  | `FlushFileBuffers` (via [`std::fs::File::sync_data`]) |
76//! | macOS    | `fcntl(F_FULLFSYNC)` (via [`std::fs::File::sync_data`], which issues it on Apple platforms) — **not** plain `fsync`, which leaves data in the drive's write cache |
77//!
78//! ## Recovery
79//!
80//! Every record carries a CRC32C checksum over its own bytes. Recovery walks
81//! the log forward and stops at the first record whose checksum fails or whose
82//! bytes are incomplete — a torn write from a crash mid-append. Records up to
83//! that point are returned; the torn tail is discarded. Recovery never reads a
84//! partially written record as if it were complete, and a corrupt length prefix
85//! can never trigger an unbounded allocation: lengths are validated against
86//! [`WalConfig::max_record_size`] before a single byte of payload is read.
87//!
88//! By default the open scan cuts everything from the first damaged record on,
89//! which also cuts intact records that follow damage in the middle of the log.
90//! [`OpenPolicy::Strict`] refuses to open in that case instead, returning
91//! [`WalError::Corruption`] with the store untouched, and still cuts a damaged
92//! final record. [`Wal::truncated_on_open`] reports how many bytes were cut.
93//!
94//! ## Backends
95//!
96//! [`Wal::open`] uses the file-backed [`FileStore`]. Custom backends — in-memory
97//! for tests, or an alternative storage layer — implement the [`WalStore`] trait
98//! and plug in through [`Wal::with_store`]. An in-memory [`MemStore`] ships for
99//! testing and examples.
100//!
101//! ## Status
102//!
103//! Stable 1.x: lock-free multi-writer append, group commit, segmented logs,
104//! prefix and suffix truncation, and a frozen record format. The API does
105//! not change shape before 2.0. For typed records use the `pack-io-2`
106//! feature (`append_pack`, `Record::unpack`); the older `pack-io` feature's
107//! decoder is not bounded on hostile input.
108
109#![deny(warnings)]
110#![deny(missing_docs)]
111#![deny(unsafe_op_in_unsafe_fn)]
112#![deny(unused_must_use)]
113#![deny(unused_results)]
114#![deny(clippy::unwrap_used)]
115#![deny(clippy::expect_used)]
116#![deny(clippy::todo)]
117#![deny(clippy::unimplemented)]
118#![deny(clippy::print_stdout)]
119#![deny(clippy::print_stderr)]
120#![deny(clippy::dbg_macro)]
121#![deny(clippy::unreachable)]
122#![deny(clippy::undocumented_unsafe_blocks)]
123#![deny(clippy::missing_safety_doc)]
124
125mod commit;
126mod config;
127mod crc;
128mod error;
129mod lsn;
130mod record;
131mod segment;
132mod store;
133mod strict;
134mod sync;
135mod wal;
136
137pub use crate::config::{OpenPolicy, RecoveryPolicy, WalConfig};
138pub use crate::error::{Result, WalError};
139pub use crate::lsn::Lsn;
140pub use crate::segment::SegmentedStore;
141pub use crate::store::{FileStore, MemStore, WalStore};
142pub use crate::wal::{Record, Wal, WalIter};
143
144/// The `pack-io` codec, re-exported so typed-record consumers can derive
145/// `Serialize`/`Deserialize` without adding the dependency themselves.
146///
147/// Available only with the `pack-io` feature. Use it as
148/// `use wal_db::pack_io::{Serialize, Deserialize};` alongside
149/// [`Wal::append_typed`] and [`Record::decode`].
150#[cfg(feature = "pack-io")]
151pub use pack_io;
152
153/// The `pack-io` 2 codec, re-exported for [`Wal::append_pack`] and
154/// [`Record::unpack`].
155///
156/// Available only with the `pack-io-2` feature. Derived types name this path,
157/// since the derives default to a crate called `pack_io`:
158///
159/// ```
160/// # #[cfg(feature = "pack-io-2")]
161/// # {
162/// use wal_db::pack_io2::{Deserialize, Serialize};
163///
164/// #[derive(Serialize, Deserialize, PartialEq, Debug)]
165/// #[pack_io(crate = "wal_db::pack_io2")]
166/// struct Event {
167///     id: u64,
168/// }
169/// # }
170/// ```
171#[cfg(feature = "pack-io-2")]
172pub use pack_io2;
173
174/// The common imports for working with a log.
175///
176/// Glob-importing the prelude pulls in the four-call API and the types its
177/// methods return, which is enough for the great majority of uses.
178///
179/// ```
180/// use wal_db::prelude::*;
181///
182/// # fn main() -> Result<()> {
183/// # let dir = tempfile::tempdir().map_err(WalError::from)?;
184/// # let path = dir.path().join("p.wal");
185/// let wal = Wal::open(&path)?;
186/// let _lsn: Lsn = wal.append(b"record")?;
187/// wal.sync()?;
188/// # Ok(())
189/// # }
190/// ```
191pub mod prelude {
192    pub use crate::config::{OpenPolicy, RecoveryPolicy, WalConfig};
193    pub use crate::error::{Result, WalError};
194    pub use crate::lsn::Lsn;
195    pub use crate::store::WalStore;
196    pub use crate::wal::{Record, Wal};
197}