Skip to main content

wal_db/
config.rs

1//! Log configuration.
2
3/// The default maximum record size: 64 MiB.
4///
5/// Generous enough for any realistic single record, small enough that a
6/// corrupt length prefix cannot request a wild allocation.
7const DEFAULT_MAX_RECORD_SIZE: u32 = 64 * 1024 * 1024;
8
9/// How [`Wal::iter`](crate::Wal::iter) reacts to a damaged record.
10///
11/// This governs *iteration*, not what [`Wal::open`](crate::Wal::open) does with
12/// damage it finds while opening; that is [`OpenPolicy`]. It matters when a
13/// record in the middle of an already-recovered log is damaged — bit rot, say —
14/// and you are reading the log back.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16#[non_exhaustive]
17pub enum RecoveryPolicy {
18    /// Stop at the first damaged record: yield it as a single
19    /// [`WalError::Corruption`](crate::WalError::Corruption), then end.
20    ///
21    /// The default, and the right choice for an append-only log, where a damaged
22    /// record means everything after it is untrustworthy.
23    StopAtFirstError,
24
25    /// Skip past a damaged record and keep going, for forensic or partial
26    /// recovery.
27    ///
28    /// Each damaged record is still yielded as a
29    /// [`WalError::Corruption`](crate::WalError::Corruption) — the loss is never
30    /// silent — but iteration then resumes at the next record. This is only
31    /// possible while a damaged record's length prefix is intact enough to locate
32    /// the next one; a record whose length itself is unreadable (a short read, or
33    /// a length past the maximum) still stops iteration, because there is no way
34    /// to know where the following record begins.
35    SkipBadRecords,
36}
37
38/// What opening a log does when its scan stops before the end of the store.
39///
40/// Opening a log scans it from the head and stops at the first record that is
41/// incomplete or fails its checksum. Nothing from that point on is part of the
42/// recovered log. The policy decides whether those bytes may be cut.
43///
44/// The common cause is a torn tail: a crash partway through an append, leaving
45/// a final record that was never acknowledged durable. Cutting it loses nothing
46/// the caller was promised. The other cause is damage in the middle of the log
47/// (bit rot, a bad sector, a missing segment file), where the records after the
48/// damage are intact and were acknowledged. Cutting those loses committed data.
49/// [`TruncateTail`](OpenPolicy::TruncateTail) cuts in both cases;
50/// [`Strict`](OpenPolicy::Strict) cuts only in the first.
51///
52/// Set it with [`WalConfig::with_open_policy`]. Under either policy,
53/// [`Wal::truncated_on_open`](crate::Wal::truncated_on_open) reports how many
54/// bytes were cut.
55///
56/// # Examples
57///
58/// ```
59/// use wal_db::{OpenPolicy, Wal, WalConfig, WalError};
60///
61/// # fn main() -> Result<(), WalError> {
62/// # let dir = tempfile::tempdir().map_err(WalError::from)?;
63/// # let path = dir.path().join("log.wal");
64/// // Two records, then damage in the first one's payload.
65/// let wal = Wal::open(&path)?;
66/// wal.append(b"first")?;
67/// wal.append(b"second")?;
68/// wal.sync()?;
69/// drop(wal);
70/// let mut bytes = std::fs::read(&path).map_err(WalError::from)?;
71/// bytes[8] ^= 0xFF;
72/// std::fs::write(&path, &bytes).map_err(WalError::from)?;
73///
74/// // Strict open refuses, because an intact record follows the damage, and
75/// // leaves the file as it was.
76/// let strict = WalConfig::new().with_open_policy(OpenPolicy::Strict);
77/// let refused = Wal::open_with(&path, strict);
78/// assert!(matches!(refused, Err(WalError::Corruption { offset: 0, .. })));
79/// assert_eq!(std::fs::read(&path).map_err(WalError::from)?, bytes);
80///
81/// // The default cuts the log at the damage, intact second record included.
82/// let wal = Wal::open(&path)?;
83/// assert_eq!(wal.truncated_on_open(), 27);
84/// assert!(wal.is_empty());
85/// # Ok(())
86/// # }
87/// ```
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89#[non_exhaustive]
90pub enum OpenPolicy {
91    /// Cut everything from the first damaged record to the end, then open.
92    ///
93    /// The default, and the behaviour of every 1.0 release. A torn tail is cut
94    /// and the log opens with a clean append boundary. Damage in the middle of
95    /// the log is cut the same way, together with every intact record after it.
96    TruncateTail,
97
98    /// Cut a damaged final record, but refuse to open if intact data follows the
99    /// damage.
100    ///
101    /// When the scan stops at a damaged record, every byte offset after it is
102    /// checked for the start of an intact record: a full header, a length within
103    /// [`WalConfig::max_record_size`], the whole payload present, and a matching
104    /// checksum. Every offset is tried because the damage may be in the length
105    /// field, which leaves the next record's position unknown. If none is found,
106    /// the damage is a torn tail and is cut as under
107    /// [`TruncateTail`](OpenPolicy::TruncateTail). If one is found, or the store
108    /// cannot read back bytes it reports holding (a missing segment file, say),
109    /// opening fails with [`WalError::Corruption`](crate::WalError::Corruption)
110    /// at the damaged record's offset and the store is not modified.
111    ///
112    /// A record rejected only because its length is above
113    /// [`WalConfig::max_record_size`] (a log written with a larger limit) is also
114    /// refused when the rest of it is intact, last record or not, rather than
115    /// cut as a torn tail. Checking it costs one read of that record.
116    ///
117    /// # When it refuses a log that was only torn
118    ///
119    /// The check cannot tell damage from a crash that left a later record
120    /// complete behind an incomplete earlier one. That happens when several
121    /// appends are in flight together and the process stops before they all
122    /// finish: concurrent appenders, or several appends before one sync with
123    /// write-back persisting them out of order. None of those records was
124    /// acknowledged durable, but strict open refuses anyway. It is exact for a
125    /// log written one record at a time, each made durable
126    /// ([`append_and_sync`](crate::Wal::append_and_sync), or `append` then
127    /// `sync`) before the next is appended. Two rarer cases also refuse: a torn
128    /// record whose payload itself contains a framed record, and random bytes
129    /// matching a checksum by chance (about one in 2^32 per offset whose length
130    /// field is plausible). Every refusal fails closed: nothing is cut, and
131    /// reopening with [`TruncateTail`](OpenPolicy::TruncateTail) after
132    /// inspection cuts as before.
133    ///
134    /// # Cost
135    ///
136    /// Nothing on a log that opens clean. When there is damage, one pass over
137    /// the bytes after it: a few nanoseconds per byte, plus a checksum for each
138    /// offset whose length field is plausible. A candidate that fits in the
139    /// 64 KiB read window is checksummed from it; a longer one is checked from
140    /// prefix checksums kept every 4 KiB, so its cost does not grow with its
141    /// length. Memory: the window, plus 4 bytes per 4 KiB scanned.
142    Strict,
143}
144
145/// Tunable parameters for a [`Wal`](crate::Wal).
146///
147/// `WalConfig` is a builder. Construct it with [`WalConfig::new`] (or
148/// [`Default`]), set the parameters you care about with the `with_*` methods,
149/// and pass it to [`Wal::open_with`](crate::Wal::open_with) or
150/// [`Wal::with_store_and_config`](crate::Wal::with_store_and_config). The
151/// builder methods take and return `self`, so they chain.
152///
153/// New parameters are added here as later milestones land (segment size, sync
154/// policy, group-commit window). The builder shape means those additions do not
155/// break existing call sites.
156///
157/// # Examples
158///
159/// ```
160/// use wal_db::WalConfig;
161///
162/// // Cap records at 1 MiB instead of the 64 MiB default.
163/// let config = WalConfig::new().with_max_record_size(1024 * 1024);
164/// assert_eq!(config.max_record_size(), 1024 * 1024);
165/// ```
166#[derive(Debug, Clone, Copy, PartialEq, Eq)]
167pub struct WalConfig {
168    max_record_size: u32,
169    recovery_policy: RecoveryPolicy,
170    open_policy: OpenPolicy,
171}
172
173impl WalConfig {
174    /// Start from the defaults.
175    ///
176    /// The only default that matters today is a 64 MiB maximum record size.
177    ///
178    /// ```
179    /// use wal_db::WalConfig;
180    /// let config = WalConfig::new();
181    /// assert_eq!(config.max_record_size(), 64 * 1024 * 1024);
182    /// ```
183    #[must_use]
184    pub const fn new() -> Self {
185        WalConfig {
186            max_record_size: DEFAULT_MAX_RECORD_SIZE,
187            recovery_policy: RecoveryPolicy::StopAtFirstError,
188            open_policy: OpenPolicy::TruncateTail,
189        }
190    }
191
192    /// Set the largest record the log will accept, in bytes.
193    ///
194    /// [`Wal::append`](crate::Wal::append) rejects any record larger than this
195    /// with [`WalError::RecordTooLarge`](crate::WalError::RecordTooLarge), and
196    /// recovery rejects any on-disk length prefix that claims to be larger
197    /// before reading the payload. That second use is the security-relevant one:
198    /// it bounds the allocation a corrupt or hostile log can request.
199    ///
200    /// ```
201    /// use wal_db::WalConfig;
202    /// let config = WalConfig::new().with_max_record_size(4096);
203    /// assert_eq!(config.max_record_size(), 4096);
204    /// ```
205    #[must_use]
206    pub const fn with_max_record_size(mut self, bytes: u32) -> Self {
207        self.max_record_size = bytes;
208        self
209    }
210
211    /// The configured maximum record size, in bytes.
212    #[must_use]
213    pub const fn max_record_size(self) -> u32 {
214        self.max_record_size
215    }
216
217    /// Set how iteration reacts to a damaged record.
218    ///
219    /// Defaults to [`RecoveryPolicy::StopAtFirstError`].
220    ///
221    /// ```
222    /// use wal_db::{RecoveryPolicy, WalConfig};
223    /// let config = WalConfig::new().with_recovery_policy(RecoveryPolicy::SkipBadRecords);
224    /// assert_eq!(config.recovery_policy(), RecoveryPolicy::SkipBadRecords);
225    /// ```
226    #[must_use]
227    pub const fn with_recovery_policy(mut self, policy: RecoveryPolicy) -> Self {
228        self.recovery_policy = policy;
229        self
230    }
231
232    /// The configured recovery policy.
233    #[must_use]
234    pub const fn recovery_policy(self) -> RecoveryPolicy {
235        self.recovery_policy
236    }
237
238    /// Set what opening the log does with damage it finds.
239    ///
240    /// Defaults to [`OpenPolicy::TruncateTail`]. Use [`OpenPolicy::Strict`]
241    /// when a damaged record in the middle of the log must stop the open
242    /// instead of cutting the intact records after it.
243    ///
244    /// ```
245    /// use wal_db::{OpenPolicy, WalConfig};
246    /// let config = WalConfig::new().with_open_policy(OpenPolicy::Strict);
247    /// assert_eq!(config.open_policy(), OpenPolicy::Strict);
248    /// ```
249    #[must_use]
250    pub const fn with_open_policy(mut self, policy: OpenPolicy) -> Self {
251        self.open_policy = policy;
252        self
253    }
254
255    /// The configured open policy.
256    #[must_use]
257    pub const fn open_policy(self) -> OpenPolicy {
258        self.open_policy
259    }
260}
261
262impl Default for WalConfig {
263    fn default() -> Self {
264        Self::new()
265    }
266}
267
268#[cfg(test)]
269mod tests {
270    use super::*;
271
272    #[test]
273    fn test_default_max_record_size_is_64_mib() {
274        assert_eq!(WalConfig::new().max_record_size(), 64 * 1024 * 1024);
275        assert_eq!(WalConfig::default().max_record_size(), 64 * 1024 * 1024);
276    }
277
278    #[test]
279    fn test_with_max_record_size_overrides_default() {
280        let config = WalConfig::new().with_max_record_size(123);
281        assert_eq!(config.max_record_size(), 123);
282    }
283
284    #[test]
285    fn test_default_open_policy_truncates_the_tail() {
286        assert_eq!(WalConfig::new().open_policy(), OpenPolicy::TruncateTail);
287        assert_eq!(WalConfig::default().open_policy(), OpenPolicy::TruncateTail);
288    }
289
290    #[test]
291    fn test_with_open_policy_leaves_other_settings_alone() {
292        let config = WalConfig::new().with_open_policy(OpenPolicy::Strict);
293        assert_eq!(config.open_policy(), OpenPolicy::Strict);
294        assert_eq!(config.recovery_policy(), RecoveryPolicy::StopAtFirstError);
295        assert_eq!(config.max_record_size(), 64 * 1024 * 1024);
296    }
297
298    #[test]
299    fn test_config_is_copy_and_eq() {
300        let a = WalConfig::new().with_max_record_size(10);
301        let b = a;
302        assert_eq!(a, b);
303    }
304}