wal_db/wal.rs
1//! The log itself: [`Wal`], its recovery iterator [`WalIter`], and the
2//! [`Record`] iteration yields.
3
4use std::{fmt, io, sync::atomic::Ordering};
5
6#[cfg(not(loom))]
7use std::{cell::RefCell, path::Path};
8
9use crate::{
10 commit::Commit,
11 config::{OpenPolicy, RecoveryPolicy, WalConfig},
12 error::{Result, WalError},
13 lsn::Lsn,
14 record::{self, HEADER_LEN},
15 store::{FileStore, WalStore},
16 strict::{self, Tail},
17 sync::AtomicU64,
18};
19
20/// A cache-line-aligned wrapper, used to keep the heavily-written reservation
21/// counter off the same cache line as the rest of the log's fields so appenders
22/// hammering it do not invalidate readers' caches (false sharing).
23#[repr(align(64))]
24#[derive(Debug)]
25struct CacheAligned<T>(T);
26
27/// A durable, append-only log.
28///
29/// `Wal` is the entry point. The four calls that cover almost every use are
30/// [`open`](Wal::open), [`append`](Wal::append), [`sync`](Wal::sync), and
31/// [`iter`](Wal::iter). The type parameter `S` is the storage backend and
32/// defaults to [`FileStore`], so the plain name `Wal` is the file-backed log;
33/// custom backends are supplied through [`with_store`](Wal::with_store).
34///
35/// A `Wal` is [`Send`] and [`Sync`], and the append path is built for it: many
36/// threads can call [`append`](Wal::append) at once with no global lock. Share
37/// one behind an [`Arc`](std::sync::Arc) and write from every thread.
38///
39/// # Concurrency and durability
40///
41/// Appends are lock-free. Each one reserves its byte range with a single atomic
42/// step — the range's start offset *is* the record's [`Lsn`] — frames the record
43/// into a reused thread-local buffer, and writes it, all without blocking other
44/// appenders. [`sync`](Wal::sync) is the durability barrier; when several
45/// threads sync at once they coalesce into a single fsync (group commit), so the
46/// cost of making data durable is amortised across everyone committing together.
47///
48/// `append` returns once the record is in the OS page cache; `sync` returns once
49/// it is on stable storage. See the [crate docs](crate) for the full contract.
50///
51/// # Examples
52///
53/// ```
54/// use wal_db::Wal;
55///
56/// # fn main() -> Result<(), wal_db::WalError> {
57/// # let dir = tempfile::tempdir().map_err(wal_db::WalError::from)?;
58/// # let path = dir.path().join("log.wal");
59/// let wal = Wal::open(&path)?;
60/// let first = wal.append(b"first")?;
61/// let second = wal.append(b"second")?;
62/// wal.sync()?;
63///
64/// // LSNs are byte offsets: the first record starts at 0, the second after it.
65/// assert_eq!(first.get(), 0);
66/// assert!(second.get() > first.get());
67///
68/// let read_back: Vec<Vec<u8>> = wal
69/// .iter()?
70/// .map(|entry| entry.map(|record| record.into_data()))
71/// .collect::<Result<_, _>>()?;
72/// assert_eq!(read_back, vec![b"first".to_vec(), b"second".to_vec()]);
73/// # Ok(())
74/// # }
75/// ```
76pub struct Wal<S = FileStore> {
77 /// Next byte offset to reserve. Hammered by every appender, so kept on its
78 /// own cache line.
79 tail: CacheAligned<AtomicU64>,
80 store: S,
81 max_record_size: u32,
82 recovery_policy: RecoveryPolicy,
83 /// Lowest readable offset — `0` until a prefix is dropped by
84 /// [`truncate_before`](Wal::truncate_before).
85 head: AtomicU64,
86 commit: Commit,
87 /// Bytes the open scan cut from the end of the store.
88 truncated_on_open: u64,
89}
90
91#[cfg(not(loom))]
92impl Wal<FileStore> {
93 /// Open the log at `path`, creating it if it does not exist.
94 ///
95 /// On open the log scans its contents, stops at the first record that is
96 /// incomplete or fails its checksum, and truncates that torn tail so the
97 /// next append lands on a clean boundary. The common cause of a torn tail is
98 /// a crash partway through an earlier append; that record was never
99 /// acknowledged durable, so discarding it loses nothing the caller was
100 /// promised. Damage in the middle of the log is cut the same way, with the
101 /// intact records after it; to refuse that instead, open with
102 /// [`OpenPolicy::Strict`] through [`open_with`](Wal::open_with).
103 /// [`truncated_on_open`](Wal::truncated_on_open) reports what was cut.
104 ///
105 /// # Errors
106 ///
107 /// Returns [`WalError::Io`] if the file cannot be opened or scanned.
108 ///
109 /// # Examples
110 ///
111 /// ```
112 /// use wal_db::Wal;
113 /// # fn main() -> Result<(), wal_db::WalError> {
114 /// # let dir = tempfile::tempdir().map_err(wal_db::WalError::from)?;
115 /// # let path = dir.path().join("log.wal");
116 /// let wal = Wal::open(&path)?;
117 /// wal.append(b"hello")?;
118 /// wal.sync()?;
119 /// # Ok(())
120 /// # }
121 /// ```
122 pub fn open(path: impl AsRef<Path>) -> Result<Self> {
123 Self::open_with(path, WalConfig::new())
124 }
125
126 /// Open the log at `path` with an explicit [`WalConfig`].
127 ///
128 /// # Errors
129 ///
130 /// - [`WalError::Io`] if the file cannot be opened or scanned.
131 /// - [`WalError::Corruption`] under [`OpenPolicy::Strict`], when intact data
132 /// follows a damaged record. Nothing is cut.
133 ///
134 /// # Examples
135 ///
136 /// ```
137 /// use wal_db::{Wal, WalConfig};
138 /// # fn main() -> Result<(), wal_db::WalError> {
139 /// # let dir = tempfile::tempdir().map_err(wal_db::WalError::from)?;
140 /// # let path = dir.path().join("log.wal");
141 /// let config = WalConfig::new().with_max_record_size(1024);
142 /// let wal = Wal::open_with(&path, config)?;
143 /// # let _ = wal;
144 /// # Ok(())
145 /// # }
146 /// ```
147 pub fn open_with(path: impl AsRef<Path>, config: WalConfig) -> Result<Self> {
148 let store = FileStore::open(path)?;
149 Self::with_store_and_config(store, config)
150 }
151}
152
153#[cfg(not(loom))]
154impl Wal<crate::segment::SegmentedStore> {
155 /// Open a segmented log in directory `dir`, with segments of `segment_size`
156 /// bytes, creating the directory if needed.
157 ///
158 /// The log is one continuous byte stream striped across fixed-size files, so
159 /// it behaves exactly like a single-file log — records span segment
160 /// boundaries freely — while keeping each file bounded for recovery and
161 /// archival. Records larger than a segment simply occupy several.
162 ///
163 /// # Errors
164 ///
165 /// Returns [`WalError::Io`] if `segment_size` is zero or the directory cannot
166 /// be opened or scanned.
167 ///
168 /// # Examples
169 ///
170 /// ```
171 /// use wal_db::Wal;
172 /// # fn main() -> Result<(), wal_db::WalError> {
173 /// # let dir = tempfile::tempdir().map_err(wal_db::WalError::from)?;
174 /// let wal = Wal::open_segmented(dir.path(), 16 * 1024 * 1024)?; // 16 MiB segments
175 /// wal.append(b"record")?;
176 /// wal.sync()?;
177 /// # Ok(())
178 /// # }
179 /// ```
180 pub fn open_segmented(dir: impl AsRef<Path>, segment_size: u64) -> Result<Self> {
181 Self::open_segmented_with(dir, segment_size, WalConfig::new())
182 }
183
184 /// Open a segmented log with an explicit [`WalConfig`].
185 ///
186 /// Like [`open_segmented`](Wal::open_segmented), but applies `config` (for
187 /// example a tighter [`max_record_size`](WalConfig::max_record_size)).
188 ///
189 /// # Errors
190 ///
191 /// - [`WalError::Io`] if `segment_size` is zero or the directory cannot be
192 /// opened or scanned.
193 /// - [`WalError::Corruption`] under [`OpenPolicy::Strict`], when intact data
194 /// follows a damaged record. Nothing is cut.
195 pub fn open_segmented_with(
196 dir: impl AsRef<Path>,
197 segment_size: u64,
198 config: WalConfig,
199 ) -> Result<Self> {
200 let store = crate::segment::SegmentedStore::open(dir, segment_size)?;
201 Self::with_store_and_config(store, config)
202 }
203}
204
205impl<S: WalStore> Wal<S> {
206 /// Build a log over a custom [`WalStore`], using the default configuration.
207 ///
208 /// # Errors
209 ///
210 /// Returns an error if scanning the existing contents of the store fails.
211 ///
212 /// # Examples
213 ///
214 /// ```
215 /// use wal_db::{MemStore, Wal};
216 /// # fn main() -> Result<(), wal_db::WalError> {
217 /// let wal = Wal::with_store(MemStore::new())?;
218 /// wal.append(b"record")?;
219 /// # Ok(())
220 /// # }
221 /// ```
222 pub fn with_store(store: S) -> Result<Self> {
223 Self::with_store_and_config(store, WalConfig::new())
224 }
225
226 /// Build a log over a custom [`WalStore`] with an explicit [`WalConfig`].
227 ///
228 /// # Errors
229 ///
230 /// - Any error the store returns while its existing contents are scanned.
231 /// - [`WalError::Corruption`] under [`OpenPolicy::Strict`], when intact data
232 /// follows a damaged record. Nothing is cut.
233 ///
234 /// # Examples
235 ///
236 /// ```
237 /// use wal_db::{MemStore, Wal, WalConfig};
238 /// # fn main() -> Result<(), wal_db::WalError> {
239 /// let config = WalConfig::new().with_max_record_size(64);
240 /// let wal = Wal::with_store_and_config(MemStore::new(), config)?;
241 /// # let _ = wal;
242 /// # Ok(())
243 /// # }
244 /// ```
245 pub fn with_store_and_config(store: S, config: WalConfig) -> Result<Self> {
246 let head = store.head()?;
247 let recovered = recover(&store, &config, head)?;
248 Ok(Wal {
249 tail: CacheAligned(AtomicU64::new(recovered.end)),
250 store,
251 max_record_size: config.max_record_size(),
252 recovery_policy: config.recovery_policy(),
253 head: AtomicU64::new(head),
254 commit: Commit::new(recovered.end),
255 truncated_on_open: recovered.cut,
256 })
257 }
258
259 /// How many bytes opening the log cut from its end.
260 ///
261 /// Zero when the log opened clean. Otherwise the open scan stopped at an
262 /// incomplete or damaged record and cut it and everything after it, as the
263 /// configured [`OpenPolicy`] allowed. Under
264 /// [`OpenPolicy::Strict`] a non-zero value is only ever a torn tail. Under
265 /// the default [`OpenPolicy::TruncateTail`] it can also include intact
266 /// records that followed damage in the middle of the log; a consumer that
267 /// knows how much it last made durable can compare.
268 ///
269 /// # Examples
270 ///
271 /// ```
272 /// use std::io::Write;
273 /// use wal_db::{Wal, WalError};
274 ///
275 /// # fn main() -> Result<(), WalError> {
276 /// # let dir = tempfile::tempdir().map_err(WalError::from)?;
277 /// # let path = dir.path().join("log.wal");
278 /// let wal = Wal::open(&path)?;
279 /// assert_eq!(wal.truncated_on_open(), 0); // a new log has nothing to cut
280 /// wal.append_and_sync(b"kept")?;
281 /// drop(wal);
282 ///
283 /// // Five stray bytes after the last record: a torn tail.
284 /// let mut file = std::fs::OpenOptions::new().append(true).open(&path)?;
285 /// file.write_all(&[0xAB; 5])?;
286 /// drop(file);
287 ///
288 /// let wal = Wal::open(&path)?;
289 /// assert_eq!(wal.truncated_on_open(), 5);
290 /// assert_eq!(wal.iter()?.count(), 1);
291 /// # Ok(())
292 /// # }
293 /// ```
294 #[must_use]
295 pub fn truncated_on_open(&self) -> u64 {
296 self.truncated_on_open
297 }
298
299 /// Append `record` to the log and return the [`Lsn`] it was assigned — the
300 /// byte offset where the record begins.
301 ///
302 /// Lock-free: the byte range is reserved with one atomic step and the record
303 /// is written without blocking other appenders. Returns once the bytes are
304 /// in the operating system's page cache. It does **not** flush the disk —
305 /// call [`sync`](Wal::sync) for that. A crash between `append` and `sync` may
306 /// lose the record.
307 ///
308 /// # Errors
309 ///
310 /// - [`WalError::RecordTooLarge`] if `record` is larger than the configured
311 /// [`max_record_size`](WalConfig::max_record_size). The log is unchanged.
312 /// - [`WalError::Io`] if the write fails. The reserved range becomes a
313 /// permanent gap: the log is durable only up to that point, recovery stops
314 /// there, and later syncs covering it report the truncation.
315 ///
316 /// # Examples
317 ///
318 /// ```
319 /// use wal_db::{MemStore, Wal};
320 /// # fn main() -> Result<(), wal_db::WalError> {
321 /// let wal = Wal::with_store(MemStore::new())?;
322 /// let lsn = wal.append(b"some bytes")?;
323 /// assert_eq!(lsn.get(), 0);
324 /// # Ok(())
325 /// # }
326 /// ```
327 pub fn append(&self, record: &[u8]) -> Result<Lsn> {
328 let payload_len = record.len();
329 if payload_len > self.max_record_size as usize {
330 return Err(WalError::RecordTooLarge {
331 len: payload_len,
332 max: self.max_record_size,
333 });
334 }
335 let frame_len = record::framed_len(payload_len) as u64;
336
337 // Reserve the byte range. The returned start offset is the LSN, and
338 // because it comes from a single atomic it is unique and ordered.
339 let start = self.tail.0.fetch_add(frame_len, Ordering::Relaxed);
340 let end = match start.checked_add(frame_len) {
341 Some(end) => end,
342 None => {
343 self.commit.mark_failed(start);
344 return Err(WalError::io(
345 "reserving a record offset",
346 io::Error::other("log size exceeds u64"),
347 ));
348 }
349 };
350
351 match self.frame_and_write(start, record) {
352 Ok(()) => {
353 self.commit.mark_written(start, end);
354 Ok(Lsn::new(start))
355 }
356 Err(error) => {
357 self.commit.mark_failed(start);
358 Err(error)
359 }
360 }
361 }
362
363 /// Make every record appended before this call durable.
364 ///
365 /// Returns once the data is on stable storage, using the platform's true
366 /// durability barrier. Concurrent calls coalesce into a single fsync, so the
367 /// flush cost is shared by everyone committing at the same time.
368 ///
369 /// # Errors
370 ///
371 /// Returns [`WalError::Io`] if the flush fails, or [`WalError::Corruption`]
372 /// if an earlier append's write failed and left a gap that cannot be made
373 /// durable. A failed sync means the records are not durable, and the failure
374 /// is permanent for this handle: the operating system may have dropped the
375 /// pages it could not write, so a retry could succeed without them. Every
376 /// later sync covering anything not yet durable returns [`WalError::Io`].
377 /// Stop appending and reopen the log, so recovery decides what survived.
378 ///
379 /// # Examples
380 ///
381 /// ```
382 /// use wal_db::Wal;
383 /// # fn main() -> Result<(), wal_db::WalError> {
384 /// # let dir = tempfile::tempdir().map_err(wal_db::WalError::from)?;
385 /// # let path = dir.path().join("log.wal");
386 /// let wal = Wal::open(&path)?;
387 /// wal.append(b"durable me")?;
388 /// wal.sync()?; // now on stable storage
389 /// # Ok(())
390 /// # }
391 /// ```
392 pub fn sync(&self) -> Result<()> {
393 let target = self.tail.0.load(Ordering::Acquire);
394 if target == 0 {
395 return Ok(());
396 }
397 self.commit.sync_to(&self.store, target)
398 }
399
400 /// Append `record` and make it durable in one call, returning its [`Lsn`].
401 ///
402 /// Equivalent to [`append`](Wal::append) followed by a [`sync`](Wal::sync)
403 /// scoped to this record, but with the sync coalesced into the group commit
404 /// of any other threads syncing at the same moment. Use it when every record
405 /// must be durable before you proceed and you want the group-commit
406 /// throughput without managing the two calls yourself.
407 ///
408 /// # Errors
409 ///
410 /// The union of [`append`](Wal::append)'s and [`sync`](Wal::sync)'s errors.
411 ///
412 /// # Examples
413 ///
414 /// ```
415 /// use wal_db::Wal;
416 /// # fn main() -> Result<(), wal_db::WalError> {
417 /// # let dir = tempfile::tempdir().map_err(wal_db::WalError::from)?;
418 /// # let path = dir.path().join("log.wal");
419 /// let wal = Wal::open(&path)?;
420 /// let lsn = wal.append_and_sync(b"committed immediately")?;
421 /// # let _ = lsn;
422 /// # Ok(())
423 /// # }
424 /// ```
425 pub fn append_and_sync(&self, record: &[u8]) -> Result<Lsn> {
426 let lsn = self.append(record)?;
427 let end = lsn.get() + record::framed_len(record.len()) as u64;
428 self.commit.sync_to(&self.store, end)?;
429 Ok(lsn)
430 }
431
432 /// Serialise `value` with `pack-io` and append it, returning its [`Lsn`].
433 ///
434 /// The typed counterpart to [`append`](Wal::append): the value is encoded to
435 /// bytes and appended as one record, which [`Record::decode`] reads back.
436 /// Available with the `pack-io` feature. Like `append`, it does not sync.
437 ///
438 /// # Errors
439 ///
440 /// - [`WalError::Encoding`] if the value fails to serialise.
441 /// - Otherwise the errors of [`append`](Wal::append) ([`WalError::RecordTooLarge`],
442 /// [`WalError::Io`]).
443 ///
444 /// # Examples
445 ///
446 /// ```
447 /// use wal_db::{MemStore, Wal};
448 /// use wal_db::pack_io::{Deserialize, Serialize};
449 ///
450 /// #[derive(Serialize, Deserialize, PartialEq, Debug)]
451 /// struct Entry {
452 /// key: String,
453 /// value: u64,
454 /// }
455 ///
456 /// # fn main() -> Result<(), wal_db::WalError> {
457 /// let wal = Wal::with_store(MemStore::new())?;
458 /// wal.append_typed(&Entry { key: "balance".into(), value: 100 })?;
459 ///
460 /// let entry: Entry = wal.iter()?.next().unwrap()?.decode()?;
461 /// assert_eq!(entry.value, 100);
462 /// # Ok(())
463 /// # }
464 /// ```
465 #[cfg(feature = "pack-io")]
466 pub fn append_typed<T: pack_io::Serialize + ?Sized>(&self, value: &T) -> Result<Lsn> {
467 let bytes = pack_io::encode(value).map_err(WalError::encoding)?;
468 self.append(&bytes)
469 }
470
471 /// Serialise `value` with `pack-io` 2 and append it, returning its
472 /// [`Lsn`]. [`Record::unpack`] reads it back. Available with the
473 /// `pack-io-2` feature. Like `append`, it does not sync.
474 ///
475 /// For the values both codecs support, the bytes are the same as
476 /// [`append_typed`](Wal::append_typed) writes.
477 ///
478 /// # Errors
479 ///
480 /// - [`WalError::Encoding`] if the value fails to serialise.
481 /// - Otherwise the errors of [`append`](Wal::append).
482 ///
483 /// # Examples
484 ///
485 /// ```
486 /// use wal_db::{MemStore, Wal};
487 /// use wal_db::pack_io2::{Deserialize, Serialize};
488 ///
489 /// #[derive(Serialize, Deserialize, PartialEq, Debug)]
490 /// #[pack_io(crate = "wal_db::pack_io2")]
491 /// struct Entry {
492 /// key: String,
493 /// value: u64,
494 /// }
495 ///
496 /// # fn main() -> Result<(), wal_db::WalError> {
497 /// let wal = Wal::with_store(MemStore::new())?;
498 /// wal.append_pack(&Entry { key: "balance".into(), value: 100 })?;
499 ///
500 /// let entry: Entry = wal.iter()?.next().unwrap()?.unpack()?;
501 /// assert_eq!(entry.value, 100);
502 /// # Ok(())
503 /// # }
504 /// ```
505 #[cfg(feature = "pack-io-2")]
506 pub fn append_pack<T: pack_io2::Serialize + ?Sized>(&self, value: &T) -> Result<Lsn> {
507 let bytes = pack_io2::encode(value).map_err(WalError::encoding)?;
508 self.append(&bytes)
509 }
510
511 /// Iterate the log from the beginning, yielding each record in append order.
512 ///
513 /// The iterator walks the records that are fully written at the moment it is
514 /// created — it does not see records still being written by other threads, or
515 /// appended afterwards. Each item is a [`Result`]: a damaged record yields a
516 /// single [`WalError::Corruption`] and then the iterator stops. In a log
517 /// opened normally the torn tail has already been truncated, so iteration
518 /// runs cleanly to the end.
519 ///
520 /// # Examples
521 ///
522 /// ```
523 /// use wal_db::{MemStore, Wal};
524 /// # fn main() -> Result<(), wal_db::WalError> {
525 /// let wal = Wal::with_store(MemStore::new())?;
526 /// wal.append(b"one")?;
527 /// wal.append(b"two")?;
528 ///
529 /// let mut seen = Vec::new();
530 /// for entry in wal.iter()? {
531 /// seen.push(entry?.into_data());
532 /// }
533 /// assert_eq!(seen, vec![b"one".to_vec(), b"two".to_vec()]);
534 /// # Ok(())
535 /// # }
536 /// ```
537 pub fn iter(&self) -> Result<WalIter<'_, S>> {
538 let end = self.commit.committed();
539 Ok(WalIter {
540 wal: self,
541 offset: self.head.load(Ordering::Acquire),
542 end,
543 done: false,
544 policy: self.recovery_policy,
545 })
546 }
547
548 /// Iterate from `from` (a record's [`Lsn`]) to the end, skipping the records
549 /// before it.
550 ///
551 /// Because an LSN is a byte offset, seeking is O(1): iteration simply starts
552 /// at `from` instead of 0. Pass an [`Lsn`] that a previous
553 /// [`append`](Wal::append) or [`iter`](Wal::iter) produced — a real record
554 /// boundary. An `Lsn` that does not land on a record boundary will be read as
555 /// a malformed record and surface as [`WalError::Corruption`]; an `Lsn` past
556 /// the end yields an empty iterator.
557 ///
558 /// # Examples
559 ///
560 /// ```
561 /// use wal_db::{MemStore, Wal};
562 /// # fn main() -> Result<(), wal_db::WalError> {
563 /// let wal = Wal::with_store(MemStore::new())?;
564 /// wal.append(b"one")?;
565 /// let second = wal.append(b"two")?;
566 /// wal.append(b"three")?;
567 ///
568 /// let from_second: Vec<Vec<u8>> = wal
569 /// .iter_from(second)?
570 /// .map(|entry| entry.map(|r| r.into_data()))
571 /// .collect::<Result<_, _>>()?;
572 /// assert_eq!(from_second, vec![b"two".to_vec(), b"three".to_vec()]);
573 /// # Ok(())
574 /// # }
575 /// ```
576 pub fn iter_from(&self, from: Lsn) -> Result<WalIter<'_, S>> {
577 let end = self.commit.committed();
578 // Never read below the head: a dropped prefix is gone.
579 let start = from.get().max(self.head.load(Ordering::Acquire)).min(end);
580 Ok(WalIter {
581 wal: self,
582 offset: start,
583 end,
584 done: false,
585 policy: self.recovery_policy,
586 })
587 }
588
589 /// Drop every record after the one at `lsn`, keeping the log up to and
590 /// including it. For compaction.
591 ///
592 /// The record at `lsn` becomes the new last record; the next append lands
593 /// right after it. The truncation is made durable before returning. `lsn`
594 /// must be a real record boundary from a previous [`append`](Wal::append) or
595 /// [`iter`](Wal::iter), and the record there must be intact.
596 ///
597 /// # Exclusive access
598 ///
599 /// This mutates the log's end, so it must **not** run concurrently with
600 /// [`append`](Wal::append), [`sync`](Wal::sync), or another `truncate_after`.
601 /// The caller is responsible for quiescing writers first — the usual case for
602 /// compaction, where the engine pauses the log, truncates, and resumes.
603 ///
604 /// # Errors
605 ///
606 /// - [`WalError::Corruption`] if `lsn` does not point at an intact record.
607 /// - [`WalError::Io`] if the truncation or its sync fails.
608 ///
609 /// # Examples
610 ///
611 /// ```
612 /// use wal_db::{MemStore, Wal};
613 /// # fn main() -> Result<(), wal_db::WalError> {
614 /// let wal = Wal::with_store(MemStore::new())?;
615 /// wal.append(b"keep me")?;
616 /// let last_kept = wal.append(b"and me")?;
617 /// wal.append(b"drop me")?;
618 ///
619 /// wal.truncate_after(last_kept)?;
620 ///
621 /// let remaining: Vec<Vec<u8>> = wal
622 /// .iter()?
623 /// .map(|entry| entry.map(|r| r.into_data()))
624 /// .collect::<Result<_, _>>()?;
625 /// assert_eq!(remaining, vec![b"keep me".to_vec(), b"and me".to_vec()]);
626 /// # Ok(())
627 /// # }
628 /// ```
629 pub fn truncate_after(&self, lsn: Lsn) -> Result<()> {
630 let start = lsn.get();
631
632 // Confirm an intact record really lives at `lsn` before keeping it.
633 let mut header = [0u8; HEADER_LEN];
634 if self.store.read_at(start, &mut header)? < HEADER_LEN {
635 return Err(WalError::corruption(start, "no record at this LSN"));
636 }
637 let parsed = record::parse_header(&header);
638 if parsed.len > self.max_record_size {
639 return Err(WalError::corruption(start, "no valid record at this LSN"));
640 }
641 let payload_start = start
642 .checked_add(HEADER_LEN as u64)
643 .ok_or_else(|| WalError::corruption(start, "record offset overflow"))?;
644 let mut payload = vec![0u8; parsed.len as usize];
645 if self.store.read_at(payload_start, &mut payload)? < payload.len() {
646 return Err(WalError::corruption(start, "incomplete record at this LSN"));
647 }
648 if !record::verify(&header, &payload, parsed.crc) {
649 return Err(WalError::corruption(start, "no valid record at this LSN"));
650 }
651 let new_end = payload_start
652 .checked_add(u64::from(parsed.len))
653 .ok_or_else(|| WalError::corruption(start, "record offset overflow"))?;
654
655 self.store.truncate(new_end)?;
656 self.store.sync()?;
657 self.tail.0.store(new_end, Ordering::Release);
658 self.commit.reset(new_end);
659 Ok(())
660 }
661
662 /// Drop the records before the one at `lsn`, keeping the log from there on,
663 /// and return the new head [`Lsn`] — the lowest record still present.
664 ///
665 /// This is prefix compaction: once a consumer has durably applied (and
666 /// flushed elsewhere) everything up to a checkpoint, the old records can be
667 /// reclaimed. Offsets are preserved — surviving records keep their LSNs — so
668 /// [`iter`](Wal::iter) and [`iter_from`](Wal::iter_from) continue to work.
669 ///
670 /// Reading resumes at exactly `lsn` — the returned head is `lsn` itself
671 /// (clamped so it never moves backward or past the end). *Reclamation*,
672 /// though, is at the backend's granularity: a segmented log
673 /// ([`Wal::open_segmented`](Wal::open_segmented)) deletes whole leading segment
674 /// files below the one that holds `lsn`, so a little space just before `lsn` —
675 /// back to its segment boundary — is kept rather than reclaimed, and the
676 /// segment with the most recent records is never dropped. A single-file log
677 /// cannot reclaim a prefix without moving the surviving bytes (which would
678 /// change their LSNs), so it is left unchanged and the returned head is
679 /// `Lsn(0)`.
680 ///
681 /// # Exclusive access
682 ///
683 /// Like [`truncate_after`](Wal::truncate_after), this must **not** run
684 /// concurrently with [`append`](Wal::append), [`sync`](Wal::sync),
685 /// [`iter`](Wal::iter), or another truncation: it removes files a reader could
686 /// be holding open. Quiesce other users first.
687 ///
688 /// # Errors
689 ///
690 /// Returns [`WalError::Io`] if the removal fails.
691 ///
692 /// # Examples
693 ///
694 /// ```
695 /// use wal_db::Wal;
696 /// # fn main() -> Result<(), wal_db::WalError> {
697 /// # let dir = tempfile::tempdir().map_err(wal_db::WalError::from)?;
698 /// // 32-byte segments so a handful of records spans several files.
699 /// let wal = Wal::open_segmented(dir.path(), 32)?;
700 /// for i in 0..10 {
701 /// let _ = wal.append(format!("record {i}").as_bytes())?;
702 /// }
703 /// let checkpoint = wal.append(b"checkpoint")?;
704 /// wal.sync()?;
705 ///
706 /// // Reclaim everything before the checkpoint's segment.
707 /// let head = wal.truncate_before(checkpoint)?;
708 /// assert!(head <= checkpoint);
709 /// // Iteration now starts at (or before) the checkpoint, never at 0.
710 /// assert!(wal.iter()?.next().unwrap()?.lsn() >= head);
711 /// # Ok(())
712 /// # }
713 /// ```
714 pub fn truncate_before(&self, lsn: Lsn) -> Result<Lsn> {
715 let new_head = self.store.truncate_before(lsn.get())?;
716 self.head.store(new_head, Ordering::Release);
717 Ok(Lsn::new(new_head))
718 }
719
720 /// The logical size of the log in bytes, including record framing.
721 ///
722 /// This is the offset at which the next append will land. It counts bytes
723 /// that have been reserved, which under heavy concurrency may include a
724 /// record another thread is still writing.
725 #[must_use]
726 pub fn len(&self) -> u64 {
727 self.tail.0.load(Ordering::Acquire)
728 }
729
730 /// Whether the log holds no records.
731 #[must_use]
732 pub fn is_empty(&self) -> bool {
733 self.len() == 0
734 }
735
736 /// Frame `record` into a reused buffer and write it at `start`.
737 fn frame_and_write(&self, start: u64, record: &[u8]) -> Result<()> {
738 with_frame_buffer(|buf| {
739 record::encode(buf, record);
740 self.store.write_at(start, buf)
741 })
742 }
743
744 /// Crate-internal access to the backing store, for tests that need to read,
745 /// corrupt, or extend the on-disk image directly.
746 #[cfg(test)]
747 pub(crate) fn store(&self) -> &S {
748 &self.store
749 }
750}
751
752/// Frame a record using a reused thread-local buffer, so steady-state appends do
753/// not allocate. Under loom a fresh buffer is used, since the model checker does
754/// not need (and does not instrument) the thread-local.
755#[cfg(not(loom))]
756fn with_frame_buffer<R>(f: impl FnOnce(&mut Vec<u8>) -> R) -> R {
757 thread_local! {
758 static FRAME: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
759 }
760 FRAME.with(|cell| f(&mut cell.borrow_mut()))
761}
762
763#[cfg(loom)]
764fn with_frame_buffer<R>(f: impl FnOnce(&mut Vec<u8>) -> R) -> R {
765 let mut buf = Vec::new();
766 f(&mut buf)
767}
768
769/// What the open scan recovered.
770#[derive(Debug, Clone, Copy)]
771struct Recovered {
772 /// End offset of the last intact record: where the next append lands.
773 end: u64,
774 /// Bytes cut from the store past `end`.
775 cut: u64,
776}
777
778/// Scan a store from the head, returning the end offset of the last intact
779/// record and cutting whatever follows it, as `config`'s [`OpenPolicy`] allows.
780///
781/// Under [`OpenPolicy::Strict`] a cut is made only when nothing intact follows
782/// the damage; otherwise the store is left untouched and the damaged record's
783/// offset is returned as [`WalError::Corruption`].
784fn recover<S: WalStore>(store: &S, config: &WalConfig, head: u64) -> Result<Recovered> {
785 let max_record_size = config.max_record_size();
786 let physical = store.len()?;
787 // Scan from the head: a log whose prefix was dropped no longer starts at 0.
788 let mut offset: u64 = head;
789 let mut header = [0u8; HEADER_LEN];
790 // One reused payload buffer for the whole scan: only the checksum needs the
791 // bytes, so the buffer is refilled per record rather than reallocated.
792 let mut payload = Vec::new();
793
794 while offset < physical {
795 if store.read_at(offset, &mut header)? < HEADER_LEN {
796 break; // incomplete header: torn tail
797 }
798 let parsed = record::parse_header(&header);
799 if parsed.len > max_record_size {
800 break; // implausible length: treat the rest as a torn tail
801 }
802
803 let payload_start = match offset.checked_add(HEADER_LEN as u64) {
804 Some(start) => start,
805 None => break,
806 };
807 let len = parsed.len as usize;
808 payload.clear();
809 payload.resize(len, 0);
810 if store.read_at(payload_start, &mut payload)? < len {
811 break; // incomplete payload: torn tail
812 }
813 if !record::verify(&header, &payload, parsed.crc) {
814 break; // checksum mismatch: stop here
815 }
816
817 offset = match payload_start.checked_add(u64::from(parsed.len)) {
818 Some(end) => end,
819 None => break,
820 };
821 }
822
823 if offset < physical {
824 if config.open_policy() == OpenPolicy::Strict {
825 match strict::classify(store, max_record_size, offset, physical)? {
826 Tail::Torn => {}
827 Tail::IntactAfter => {
828 return Err(WalError::corruption(
829 offset,
830 "intact data follows a damaged record",
831 ));
832 }
833 Tail::Unreadable => {
834 return Err(WalError::corruption(
835 offset,
836 "the log cannot be read to its end after a damaged record",
837 ));
838 }
839 Tail::Oversized => {
840 return Err(WalError::corruption(
841 offset,
842 "an intact record is longer than max_record_size",
843 ));
844 }
845 }
846 }
847 store.truncate(offset)?;
848 }
849 Ok(Recovered {
850 end: offset,
851 cut: physical.saturating_sub(offset),
852 })
853}
854
855impl<S: WalStore> fmt::Debug for Wal<S> {
856 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
857 f.debug_struct("Wal")
858 .field("len", &self.tail.0.load(Ordering::Relaxed))
859 .finish_non_exhaustive()
860 }
861}
862
863/// One record read back during iteration: its [`Lsn`] and its payload bytes.
864///
865/// Yielded by [`Wal::iter`]. The payload is owned (a fresh `Vec` per record);
866/// take it without copying via [`into_data`](Record::into_data), or borrow it
867/// via [`data`](Record::data).
868#[derive(Debug, Clone, PartialEq, Eq)]
869pub struct Record {
870 lsn: Lsn,
871 data: Vec<u8>,
872}
873
874impl Record {
875 /// The sequence number this record was assigned — its byte offset in the log.
876 pub fn lsn(&self) -> Lsn {
877 self.lsn
878 }
879
880 /// The record's payload bytes.
881 #[must_use]
882 pub fn data(&self) -> &[u8] {
883 &self.data
884 }
885
886 /// The payload length in bytes.
887 #[must_use]
888 pub fn len(&self) -> usize {
889 self.data.len()
890 }
891
892 /// Whether the record's payload is empty.
893 #[must_use]
894 pub fn is_empty(&self) -> bool {
895 self.data.is_empty()
896 }
897
898 /// Consume the record and take ownership of its payload without copying.
899 #[must_use]
900 pub fn into_data(self) -> Vec<u8> {
901 self.data
902 }
903
904 /// Decode the record's payload into a typed value via `pack-io`.
905 ///
906 /// The mirror of [`Wal::append_typed`]. Available with the `pack-io` feature.
907 ///
908 /// # Untrusted bytes
909 ///
910 /// `pack-io` 1.0's decoder is not bounded on hostile input: a few crafted
911 /// bytes can make it allocate hundreds of MiB. A record's CRC32C catches
912 /// damage, not a log written by someone else. Decode only logs this
913 /// program wrote; for any other, use [`unpack`](Record::unpack) (feature
914 /// `pack-io-2`), which reads the same records with bounded allocation and
915 /// nesting.
916 ///
917 /// # Errors
918 ///
919 /// Returns [`WalError::Encoding`] if the bytes do not deserialise into `T` —
920 /// for example reading a record written as a different type.
921 ///
922 /// # Examples
923 ///
924 /// ```
925 /// use wal_db::{MemStore, Wal};
926 /// use wal_db::pack_io::{Deserialize, Serialize};
927 ///
928 /// #[derive(Serialize, Deserialize, PartialEq, Debug)]
929 /// struct Event {
930 /// id: u64,
931 /// name: String,
932 /// }
933 ///
934 /// # fn main() -> Result<(), wal_db::WalError> {
935 /// let wal = Wal::with_store(MemStore::new())?;
936 /// wal.append_typed(&Event { id: 7, name: "boot".into() })?;
937 ///
938 /// let record = wal.iter()?.next().unwrap()?;
939 /// let event: Event = record.decode()?;
940 /// assert_eq!(event, Event { id: 7, name: "boot".into() });
941 /// # Ok(())
942 /// # }
943 /// ```
944 #[cfg(feature = "pack-io")]
945 pub fn decode<T: pack_io::Deserialize>(&self) -> Result<T> {
946 pack_io::decode(&self.data).map_err(WalError::encoding)
947 }
948
949 /// Decode the record's payload with `pack-io` 2, under its default
950 /// limits: no allocation the input cannot back, at most 1 GiB for one
951 /// value, and at most 128 levels of nested types.
952 ///
953 /// The mirror of [`Wal::append_pack`]. It also reads records written by
954 /// [`Wal::append_typed`]: the same values decode from the same bytes. A
955 /// record nested deeper than 128 levels is refused; read it with
956 /// [`unpack_with`](Record::unpack_with) and a higher
957 /// [`max_depth`](pack_io2::Config::max_depth). Available with the
958 /// `pack-io-2` feature.
959 ///
960 /// # Errors
961 ///
962 /// [`WalError::Encoding`] if the bytes do not decode into `T` within the
963 /// limits.
964 ///
965 /// # Examples
966 ///
967 /// ```
968 /// use wal_db::{MemStore, Wal};
969 /// use wal_db::pack_io2::{Deserialize, Serialize};
970 ///
971 /// #[derive(Serialize, Deserialize, PartialEq, Debug)]
972 /// #[pack_io(crate = "wal_db::pack_io2")]
973 /// struct Event {
974 /// id: u64,
975 /// name: String,
976 /// }
977 ///
978 /// # fn main() -> Result<(), wal_db::WalError> {
979 /// let wal = Wal::with_store(MemStore::new())?;
980 /// wal.append_pack(&Event { id: 7, name: "boot".into() })?;
981 /// let event: Event = wal.iter()?.next().unwrap()?.unpack()?;
982 /// assert_eq!(event, Event { id: 7, name: "boot".into() });
983 /// # Ok(())
984 /// # }
985 /// ```
986 #[cfg(feature = "pack-io-2")]
987 pub fn unpack<T: pack_io2::Deserialize>(&self) -> Result<T> {
988 pack_io2::decode(&self.data).map_err(WalError::encoding)
989 }
990
991 /// [`unpack`](Record::unpack) under the limits of `config`: raise
992 /// [`max_depth`](pack_io2::Config::max_depth) to read an old record
993 /// nested more than 128 levels deep, or lower the limits for bytes from
994 /// a less trusted source. Available with the `pack-io-2` feature.
995 ///
996 /// # Errors
997 ///
998 /// [`WalError::Encoding`] if `config` is invalid or the bytes do not
999 /// decode into `T` within its limits.
1000 #[cfg(feature = "pack-io-2")]
1001 pub fn unpack_with<T: pack_io2::Deserialize>(&self, config: pack_io2::Config) -> Result<T> {
1002 pack_io2::decode_with_config(&self.data, config).map_err(WalError::encoding)
1003 }
1004}
1005
1006/// The outcome of reading one record-sized chunk at the iterator's cursor.
1007enum Step {
1008 /// A valid record, plus the offset just past it.
1009 Record(Record, u64),
1010 /// A damaged record. `skip_to` is the offset of the next record if its
1011 /// extent is known (length and payload present, only the checksum failed),
1012 /// or `None` if the damage makes the next record's position unknowable.
1013 Damaged(WalError, Option<u64>),
1014 /// A clean end: a short read, meaning the log stops here (a torn tail).
1015 End,
1016}
1017
1018/// The iterator returned by [`Wal::iter`].
1019///
1020/// Walks the records fully written when it was created, yielding
1021/// `Result<`[`Record`]`>`. Behaviour at a damaged record follows the configured
1022/// [`RecoveryPolicy`]: by default the iterator yields the damage once and stops;
1023/// under [`RecoveryPolicy::SkipBadRecords`] it yields the damage and continues
1024/// past it when the next record's position is still recoverable.
1025pub struct WalIter<'a, S: WalStore = FileStore> {
1026 wal: &'a Wal<S>,
1027 offset: u64,
1028 end: u64,
1029 done: bool,
1030 policy: RecoveryPolicy,
1031}
1032
1033impl<S: WalStore> WalIter<'_, S> {
1034 /// Read and classify the record at the current offset, without advancing.
1035 fn step(&self) -> Result<Step> {
1036 let mut header = [0u8; HEADER_LEN];
1037 if self.wal.store.read_at(self.offset, &mut header)? < HEADER_LEN {
1038 return Ok(Step::End);
1039 }
1040 let parsed = record::parse_header(&header);
1041 if parsed.len > self.wal.max_record_size {
1042 // The length is implausible, so the next record's position is
1043 // unknowable — there is nothing to skip to.
1044 return Ok(Step::Damaged(
1045 WalError::corruption(self.offset, "record length exceeds the maximum"),
1046 None,
1047 ));
1048 }
1049
1050 let payload_start = self
1051 .offset
1052 .checked_add(HEADER_LEN as u64)
1053 .ok_or_else(|| WalError::corruption(self.offset, "record offset overflow"))?;
1054 let mut payload = vec![0u8; parsed.len as usize];
1055 if self.wal.store.read_at(payload_start, &mut payload)? < payload.len() {
1056 return Ok(Step::End);
1057 }
1058 let next = payload_start
1059 .checked_add(u64::from(parsed.len))
1060 .ok_or_else(|| WalError::corruption(self.offset, "record offset overflow"))?;
1061
1062 if !record::verify(&header, &payload, parsed.crc) {
1063 // The length and payload are present, so we know where the next
1064 // record starts even though this one is corrupt.
1065 return Ok(Step::Damaged(
1066 WalError::corruption(self.offset, "checksum mismatch"),
1067 Some(next),
1068 ));
1069 }
1070
1071 Ok(Step::Record(
1072 Record {
1073 lsn: Lsn::new(self.offset),
1074 data: payload,
1075 },
1076 next,
1077 ))
1078 }
1079}
1080
1081impl<S: WalStore> Iterator for WalIter<'_, S> {
1082 type Item = Result<Record>;
1083
1084 fn next(&mut self) -> Option<Self::Item> {
1085 if self.done || self.offset >= self.end {
1086 return None;
1087 }
1088 match self.step() {
1089 Ok(Step::Record(record, next)) => {
1090 self.offset = next;
1091 Some(Ok(record))
1092 }
1093 // Skip-bad-records, and the next record is locatable: surface the
1094 // damage but continue from past it on the next call.
1095 Ok(Step::Damaged(error, Some(next)))
1096 if self.policy == RecoveryPolicy::SkipBadRecords =>
1097 {
1098 self.offset = next;
1099 Some(Err(error))
1100 }
1101 // Stop-at-first-error, or damage that makes the next position
1102 // unknowable: surface the damage and end.
1103 Ok(Step::Damaged(error, _)) => {
1104 self.done = true;
1105 Some(Err(error))
1106 }
1107 Ok(Step::End) => {
1108 self.done = true;
1109 None
1110 }
1111 Err(error) => {
1112 self.done = true;
1113 Some(Err(error))
1114 }
1115 }
1116 }
1117}
1118
1119impl<S: WalStore> fmt::Debug for WalIter<'_, S> {
1120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1121 f.debug_struct("WalIter")
1122 .field("offset", &self.offset)
1123 .field("end", &self.end)
1124 .field("done", &self.done)
1125 .finish()
1126 }
1127}
1128
1129#[cfg(all(test, not(loom)))]
1130#[allow(
1131 clippy::unwrap_used,
1132 clippy::expect_used,
1133 unused_must_use,
1134 unused_results
1135)]
1136mod tests {
1137 use std::sync::Arc;
1138 use std::thread;
1139
1140 use super::*;
1141 use crate::store::MemStore;
1142
1143 fn drain(wal: &Wal<MemStore>) -> Vec<Vec<u8>> {
1144 wal.iter()
1145 .unwrap()
1146 .map(|r| r.unwrap().into_data())
1147 .collect()
1148 }
1149
1150 fn corrupt_byte(store: &MemStore, offset: u64) {
1151 let mut byte = [0u8; 1];
1152 store.read_at(offset, &mut byte).unwrap();
1153 byte[0] ^= 0xFF;
1154 store.write_at(offset, &byte).unwrap();
1155 }
1156
1157 #[test]
1158 fn test_stop_at_first_error_stops_at_corruption() {
1159 let wal = Wal::with_store(MemStore::new()).unwrap(); // default policy
1160 wal.append(b"first").unwrap();
1161 let second = wal.append(b"second").unwrap();
1162 wal.append(b"third").unwrap();
1163 corrupt_byte(wal.store(), second.get() + HEADER_LEN as u64);
1164
1165 let items: Vec<_> = wal.iter().unwrap().collect();
1166 assert_eq!(items.len(), 2); // first ok, second damaged, then stop
1167 assert_eq!(items[0].as_ref().unwrap().data(), b"first");
1168 assert!(matches!(items[1], Err(WalError::Corruption { .. })));
1169 }
1170
1171 #[test]
1172 fn test_skip_bad_records_continues_past_corruption() {
1173 let config = WalConfig::new().with_recovery_policy(RecoveryPolicy::SkipBadRecords);
1174 let wal = Wal::with_store_and_config(MemStore::new(), config).unwrap();
1175 wal.append(b"first").unwrap();
1176 let second = wal.append(b"second").unwrap();
1177 wal.append(b"third").unwrap();
1178 // Corrupt the payload only; the length prefix stays intact, so the
1179 // record is skippable.
1180 corrupt_byte(wal.store(), second.get() + HEADER_LEN as u64);
1181
1182 let items: Vec<_> = wal.iter().unwrap().collect();
1183 assert_eq!(items.len(), 3);
1184 assert_eq!(items[0].as_ref().unwrap().data(), b"first");
1185 assert!(matches!(items[1], Err(WalError::Corruption { .. })));
1186 assert_eq!(items[2].as_ref().unwrap().data(), b"third");
1187 }
1188
1189 #[test]
1190 fn test_skip_bad_records_still_stops_on_unreadable_length() {
1191 let config = WalConfig::new()
1192 .with_max_record_size(16)
1193 .with_recovery_policy(RecoveryPolicy::SkipBadRecords);
1194 let wal = Wal::with_store_and_config(MemStore::new(), config).unwrap();
1195 wal.append(b"ok").unwrap();
1196 let second = wal.append(b"victim").unwrap();
1197 // Corrupt the length field to an implausible value: the next record's
1198 // position becomes unknowable, so even skip-mode must stop.
1199 corrupt_byte(wal.store(), second.get() + 4); // LEN_OFFSET within the header
1200
1201 let items: Vec<_> = wal.iter().unwrap().collect();
1202 assert_eq!(items.len(), 2); // first ok, then a damaged stop
1203 assert_eq!(items[0].as_ref().unwrap().data(), b"ok");
1204 assert!(matches!(items[1], Err(WalError::Corruption { .. })));
1205 }
1206
1207 #[cfg(feature = "pack-io")]
1208 #[test]
1209 fn test_typed_record_roundtrip() {
1210 use pack_io::{Deserialize, Serialize};
1211
1212 #[derive(Serialize, Deserialize, PartialEq, Debug)]
1213 struct Entry {
1214 id: u64,
1215 label: String,
1216 }
1217
1218 let wal = Wal::with_store(MemStore::new()).unwrap();
1219 wal.append_typed(&Entry {
1220 id: 9,
1221 label: "nine".into(),
1222 })
1223 .unwrap();
1224 wal.append_typed(&Entry {
1225 id: 10,
1226 label: "ten".into(),
1227 })
1228 .unwrap();
1229
1230 let decoded: Vec<Entry> = wal
1231 .iter()
1232 .unwrap()
1233 .map(|r| r.unwrap().decode().unwrap())
1234 .collect();
1235 assert_eq!(
1236 decoded[0],
1237 Entry {
1238 id: 9,
1239 label: "nine".into()
1240 }
1241 );
1242 assert_eq!(
1243 decoded[1],
1244 Entry {
1245 id: 10,
1246 label: "ten".into()
1247 }
1248 );
1249 }
1250
1251 #[cfg(feature = "pack-io")]
1252 #[test]
1253 fn test_typed_decode_wrong_type_errors() {
1254 use pack_io::{Deserialize, Serialize};
1255
1256 #[derive(Serialize)]
1257 struct Big {
1258 a: u64,
1259 b: u64,
1260 c: u64,
1261 }
1262 #[derive(Deserialize)]
1263 struct Small {
1264 _a: u8,
1265 }
1266
1267 let wal = Wal::with_store(MemStore::new()).unwrap();
1268 wal.append_typed(&Big { a: 1, b: 2, c: 3 }).unwrap();
1269 let record = wal.iter().unwrap().next().unwrap().unwrap();
1270 // Decoding 24 bytes as a 1-byte type leaves trailing bytes -> error.
1271 let result: Result<Small> = record.decode();
1272 assert!(matches!(result, Err(WalError::Encoding { .. })));
1273 }
1274
1275 #[test]
1276 fn test_append_assigns_byte_offset_lsns() {
1277 let wal = Wal::with_store(MemStore::new()).unwrap();
1278 let a = wal.append(b"abc").unwrap(); // 8 header + 3 = 11 bytes
1279 let b = wal.append(b"de").unwrap();
1280 assert_eq!(a.get(), 0);
1281 assert_eq!(b.get(), 11);
1282 }
1283
1284 #[test]
1285 fn test_iter_reads_back_all_records_in_order() {
1286 let wal = Wal::with_store(MemStore::new()).unwrap();
1287 wal.append(b"one").unwrap();
1288 wal.append(b"two").unwrap();
1289 wal.append(b"three").unwrap();
1290 assert_eq!(
1291 drain(&wal),
1292 vec![b"one".to_vec(), b"two".to_vec(), b"three".to_vec()]
1293 );
1294 }
1295
1296 #[test]
1297 fn test_empty_log_iterates_to_nothing() {
1298 let wal = Wal::with_store(MemStore::new()).unwrap();
1299 assert!(wal.is_empty());
1300 assert_eq!(drain(&wal).len(), 0);
1301 }
1302
1303 #[test]
1304 fn test_empty_record_roundtrips() {
1305 let wal = Wal::with_store(MemStore::new()).unwrap();
1306 wal.append(b"").unwrap();
1307 assert_eq!(drain(&wal), vec![Vec::<u8>::new()]);
1308 }
1309
1310 #[test]
1311 fn test_record_too_large_is_rejected() {
1312 let config = WalConfig::new().with_max_record_size(4);
1313 let wal = Wal::with_store_and_config(MemStore::new(), config).unwrap();
1314 wal.append(b"ok").unwrap();
1315 let err = wal.append(b"too long").unwrap_err();
1316 assert!(matches!(err, WalError::RecordTooLarge { len: 8, max: 4 }));
1317 // The rejected append did not advance the log.
1318 assert_eq!(drain(&wal), vec![b"ok".to_vec()]);
1319 }
1320
1321 #[test]
1322 fn test_reopen_recovers_records() {
1323 let wal = Wal::with_store(MemStore::new()).unwrap();
1324 wal.append(b"first").unwrap();
1325 wal.append(b"second").unwrap();
1326 wal.sync().unwrap();
1327 let image = wal.store().snapshot();
1328
1329 let reopened = Wal::with_store(MemStore::from_bytes(image)).unwrap();
1330 assert_eq!(
1331 drain(&reopened),
1332 vec![b"first".to_vec(), b"second".to_vec()]
1333 );
1334 // The next append continues at the recovered end: two records of
1335 // (8 + 5) and (8 + 6) bytes leave the tail at 27.
1336 assert_eq!(reopened.append(b"third").unwrap().get(), 27);
1337 }
1338
1339 #[test]
1340 fn test_recovery_truncates_torn_tail() {
1341 let wal = Wal::with_store(MemStore::new()).unwrap();
1342 wal.append(b"good record").unwrap();
1343 let clean_len = wal.len();
1344 // Append raw garbage directly to the store: a torn tail.
1345 wal.store().write_at(clean_len, &[0xAB; 5]).unwrap();
1346
1347 let reopened = Wal::with_store(MemStore::from_bytes(wal.store().snapshot())).unwrap();
1348 assert_eq!(drain(&reopened), vec![b"good record".to_vec()]);
1349 assert_eq!(reopened.len(), clean_len);
1350 }
1351
1352 #[test]
1353 fn test_corrupt_record_surfaces_error_then_stops() {
1354 let wal = Wal::with_store(MemStore::new()).unwrap();
1355 wal.append(b"intact").unwrap();
1356 let second = wal.append(b"victim").unwrap();
1357 // Flip a byte inside the second record's payload (offset + header).
1358 let payload_offset = second.get() + HEADER_LEN as u64;
1359 let mut byte = [0u8; 1];
1360 wal.store().read_at(payload_offset, &mut byte).unwrap();
1361 byte[0] ^= 0xFF;
1362 wal.store().write_at(payload_offset, &byte).unwrap();
1363
1364 let mut iter = wal.iter().unwrap();
1365 assert_eq!(iter.next().unwrap().unwrap().data(), b"intact");
1366 assert!(matches!(
1367 iter.next().unwrap(),
1368 Err(WalError::Corruption { .. })
1369 ));
1370 assert!(iter.next().is_none());
1371 }
1372
1373 #[test]
1374 fn test_append_and_sync_is_durable() {
1375 let wal = Wal::with_store(MemStore::new()).unwrap();
1376 wal.append_and_sync(b"committed").unwrap();
1377 assert_eq!(drain(&wal), vec![b"committed".to_vec()]);
1378 }
1379
1380 #[test]
1381 fn test_iter_from_seeks_to_lsn() {
1382 let wal = Wal::with_store(MemStore::new()).unwrap();
1383 wal.append(b"a").unwrap();
1384 let b = wal.append(b"b").unwrap();
1385 wal.append(b"c").unwrap();
1386
1387 let got: Vec<Vec<u8>> = wal
1388 .iter_from(b)
1389 .unwrap()
1390 .map(|r| r.unwrap().into_data())
1391 .collect();
1392 assert_eq!(got, vec![b"b".to_vec(), b"c".to_vec()]);
1393 }
1394
1395 #[test]
1396 fn test_iter_from_past_end_is_empty() {
1397 let wal = Wal::with_store(MemStore::new()).unwrap();
1398 wal.append(b"a").unwrap();
1399 assert_eq!(wal.iter_from(Lsn::new(9_999)).unwrap().count(), 0);
1400 }
1401
1402 #[test]
1403 fn test_truncate_after_drops_later_records() {
1404 let wal = Wal::with_store(MemStore::new()).unwrap();
1405 wal.append(b"first").unwrap(); // [0, 13)
1406 let keep = wal.append(b"second").unwrap(); // [13, 27)
1407 wal.append(b"third").unwrap();
1408 wal.append(b"fourth").unwrap();
1409
1410 wal.truncate_after(keep).unwrap();
1411 assert_eq!(drain(&wal), vec![b"first".to_vec(), b"second".to_vec()]);
1412 assert_eq!(wal.len(), 27);
1413
1414 // Appends resume immediately after the kept record.
1415 assert_eq!(wal.append(b"new").unwrap().get(), 27);
1416 assert_eq!(
1417 drain(&wal),
1418 vec![b"first".to_vec(), b"second".to_vec(), b"new".to_vec()]
1419 );
1420 }
1421
1422 #[test]
1423 fn test_truncate_after_keeping_last_record_is_a_no_op() {
1424 let wal = Wal::with_store(MemStore::new()).unwrap();
1425 wal.append(b"first").unwrap();
1426 let last = wal.append(b"second").unwrap();
1427 let before = wal.len();
1428
1429 wal.truncate_after(last).unwrap();
1430 assert_eq!(wal.len(), before);
1431 assert_eq!(drain(&wal), vec![b"first".to_vec(), b"second".to_vec()]);
1432 }
1433
1434 #[test]
1435 fn test_truncate_after_invalid_lsn_errors() {
1436 let config = WalConfig::new().with_max_record_size(64);
1437 let wal = Wal::with_store_and_config(MemStore::new(), config).unwrap();
1438 wal.append(b"only record").unwrap();
1439 // An LSN that does not land on a record boundary is rejected.
1440 let err = wal.truncate_after(Lsn::new(3)).unwrap_err();
1441 assert!(matches!(err, WalError::Corruption { .. }));
1442 }
1443
1444 #[test]
1445 fn test_concurrent_appends_no_overlap_all_recovered() {
1446 const THREADS: usize = 8;
1447 const PER_THREAD: usize = 200;
1448
1449 let wal = Arc::new(Wal::with_store(MemStore::new()).unwrap());
1450 let mut handles = Vec::new();
1451 for t in 0..THREADS {
1452 let wal = Arc::clone(&wal);
1453 handles.push(thread::spawn(move || {
1454 let mut lsns = Vec::with_capacity(PER_THREAD);
1455 for i in 0..PER_THREAD {
1456 let payload = format!("t{t}-r{i}").into_bytes();
1457 lsns.push(wal.append(&payload).unwrap().get());
1458 }
1459 lsns
1460 }));
1461 }
1462 let mut all_lsns = Vec::new();
1463 for h in handles {
1464 all_lsns.extend(h.join().unwrap());
1465 }
1466 wal.sync().unwrap();
1467
1468 // Every LSN is distinct (no two records shared a byte range).
1469 let mut sorted = all_lsns.clone();
1470 sorted.sort_unstable();
1471 sorted.dedup();
1472 assert_eq!(sorted.len(), THREADS * PER_THREAD);
1473
1474 // Recovery reads back exactly the records that were appended, in offset
1475 // order, with no gaps or corruption.
1476 let records = drain(&wal);
1477 assert_eq!(records.len(), THREADS * PER_THREAD);
1478
1479 // Reopening from the raw image recovers the same set.
1480 let reopened = Wal::with_store(MemStore::from_bytes(wal.store().snapshot())).unwrap();
1481 assert_eq!(reopened.iter().unwrap().count(), THREADS * PER_THREAD);
1482 }
1483
1484 #[test]
1485 fn test_concurrent_append_and_sync_all_durable() {
1486 const THREADS: usize = 8;
1487
1488 let wal = Arc::new(Wal::with_store(MemStore::new()).unwrap());
1489 let mut handles = Vec::new();
1490 for t in 0..THREADS {
1491 let wal = Arc::clone(&wal);
1492 handles.push(thread::spawn(move || {
1493 for i in 0..50 {
1494 wal.append_and_sync(format!("{t}:{i}").as_bytes()).unwrap();
1495 }
1496 }));
1497 }
1498 for h in handles {
1499 h.join().unwrap();
1500 }
1501 assert_eq!(drain(&wal).len(), THREADS * 50);
1502 }
1503}