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