Skip to main content

wal_db/
segment.rs

1//! Segmented file storage.
2//!
3//! A [`SegmentedStore`] presents one continuous byte address space — the same
4//! flat space the log already uses, since an [`Lsn`](crate::Lsn) is a byte offset
5//! — striped across fixed-size segment files on disk. A write or read that
6//! crosses a segment boundary is split across the two files; a record may span
7//! boundaries freely, exactly as PostgreSQL's WAL records span its 16 MiB
8//! segments. Bounded segments keep recovery time bounded and let old, fully
9//! superseded segments be archived or pruned.
10//!
11//! Because the address space stays contiguous, the log's append, recovery, and
12//! iteration logic do not change at all: a [`Wal`](crate::Wal) over a
13//! `SegmentedStore` behaves identically to one over a single file, only with the
14//! bytes spread across `00000000000000000000.wal`, `00000000000000000001.wal`,
15//! and so on inside a directory.
16
17use std::{
18    collections::HashMap,
19    ffi::OsStr,
20    fs::{self, File, OpenOptions},
21    io,
22    path::{Path, PathBuf},
23    sync::{
24        Arc, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard,
25        atomic::{AtomicBool, AtomicU64, Ordering},
26    },
27};
28
29use crate::{
30    error::{Result, WalError},
31    store::{
32        WalStore, durable_sync, flush_dir_if_dirty, parent_dir, pread_fill, pwrite_all, sync_dir,
33    },
34};
35
36/// The fixed width of a segment file name, in zero-padded decimal digits — wide
37/// enough for any `u64` index and lexically sortable.
38const NAME_DIGITS: usize = 20;
39/// The segment file extension.
40const NAME_EXT: &str = "wal";
41/// Name of the file that records the log's head (its lowest surviving offset)
42/// after a prefix has been dropped. Absent until the first `truncate_before`.
43const HEAD_FILE: &str = "head";
44/// The marker is written here, flushed, and renamed over [`HEAD_FILE`], so a
45/// crash leaves the old marker or the new one and never a torn one.
46const HEAD_TMP_FILE: &str = "head.tmp";
47/// Size of the head marker: an 8-byte offset plus a 4-byte CRC32C of it.
48const HEAD_FILE_LEN: usize = 12;
49/// Name of the file that records the segment size the log was written with
50/// (since 1.4). Readers before 1.4 ignore it.
51const META_FILE: &str = "meta";
52/// Written here, flushed, and renamed over [`META_FILE`].
53const META_TMP_FILE: &str = "meta.tmp";
54/// The meta file's magic.
55const META_MAGIC: &[u8; 8] = b"WALSEGSZ";
56/// Size of the meta file: magic, the segment size as a u64, and a CRC32C of
57/// both.
58const META_FILE_LEN: usize = 8 + 8 + 4;
59
60/// A [`WalStore`] that stripes one flat byte space across fixed-size segment
61/// files in a directory.
62///
63/// Open one with [`SegmentedStore::open`] and hand it to
64/// [`Wal::with_store`](crate::Wal::with_store), or use the
65/// [`Wal::open_segmented`](crate::Wal::open_segmented) convenience constructor.
66/// Segments are created lazily as the log grows, and [`sync`](WalStore::sync)
67/// flushes every segment written since the last sync, not the whole history.
68///
69/// The segment size is recorded in a `meta` file next to the segments; opening
70/// with another size is refused rather than reading the bytes at the wrong
71/// offsets.
72///
73/// # Examples
74///
75/// ```
76/// use wal_db::{SegmentedStore, Wal};
77///
78/// # fn main() -> Result<(), wal_db::WalError> {
79/// # let dir = tempfile::tempdir().map_err(wal_db::WalError::from)?;
80/// // 1 MiB segments. Records larger than a segment simply span several.
81/// let store = SegmentedStore::open(dir.path(), 1024 * 1024)?;
82/// let wal = Wal::with_store(store)?;
83/// wal.append(b"spans nothing yet")?;
84/// wal.sync()?;
85/// # Ok(())
86/// # }
87/// ```
88#[derive(Debug)]
89pub struct SegmentedStore {
90    dir: PathBuf,
91    segment_size: u64,
92    segments: RwLock<HashMap<u64, Arc<Segment>>>,
93    /// Highest byte offset ever written: the logical length.
94    max_written: AtomicU64,
95    /// Lowest offset still present — the start of the lowest segment that has not
96    /// been dropped by `truncate_before`. Recovery scans from here.
97    head: AtomicU64,
98    /// A segment file was created or removed since the directory was last
99    /// flushed. Set at open too: a sync must also cover names left unflushed by
100    /// a process that stopped before flushing them.
101    dir_dirty: AtomicBool,
102    /// This store created the log directory, whose own name lives in its parent.
103    parent_dirty: AtomicBool,
104}
105
106/// One open segment file and whether it holds bytes written since its last
107/// flush.
108#[derive(Debug)]
109struct Segment {
110    file: File,
111    /// Set after every write to the segment; cleared by the sync that flushes
112    /// it. A sync flushes every segment with the flag set, so bytes written
113    /// late into an older segment (a record whose writer finished after a
114    /// later one) are flushed by the sync that covers them.
115    dirty: AtomicBool,
116}
117
118impl Segment {
119    fn new(file: File, dirty: bool) -> Arc<Segment> {
120        Arc::new(Segment {
121            file,
122            dirty: AtomicBool::new(dirty),
123        })
124    }
125}
126
127impl SegmentedStore {
128    /// Open the segmented log in `dir`, creating the directory if needed, with
129    /// segments of `segment_size` bytes.
130    ///
131    /// Existing segment files are picked up so the log can be recovered. The
132    /// store does not validate record contents — that is
133    /// [`Wal::open`](crate::Wal::open)'s recovery scan, which runs unchanged over
134    /// the flat space. Every existing segment is flushed first: a process that
135    /// stopped without syncing may have left bytes only in the page cache, and
136    /// recovery must not trust what a power loss could still take away.
137    ///
138    /// # Errors
139    ///
140    /// - [`WalError::Io`] if `segment_size` is zero, or if the directory or a
141    ///   segment cannot be created, read, or flushed.
142    /// - [`WalError::Corruption`] if the log was written with another segment
143    ///   size, or if its first segments were dropped and the head marker that
144    ///   says where it now starts is missing or damaged. Nothing is deleted.
145    pub fn open(dir: impl AsRef<Path>, segment_size: u64) -> Result<Self> {
146        if segment_size == 0 {
147            return Err(WalError::io(
148                "opening the segmented log",
149                io::Error::other("segment size must be non-zero"),
150            ));
151        }
152        let dir = dir.as_ref().to_path_buf();
153        let created = !dir.is_dir();
154        fs::create_dir_all(&dir).map_err(|e| WalError::io("creating the log directory", e))?;
155
156        // Every segment, by index, with its file length.
157        let mut found: Vec<(u64, u64)> = Vec::new();
158        for entry in fs::read_dir(&dir).map_err(|e| WalError::io("reading the log directory", e))? {
159            let entry = entry.map_err(|e| WalError::io("reading the log directory", e))?;
160            if let Some(index) = parse_segment_name(&entry.file_name()) {
161                let len = entry
162                    .metadata()
163                    .map_err(|e| WalError::io("reading segment metadata", e))?
164                    .len();
165                found.push((index, len));
166            }
167        }
168        found.sort_unstable();
169
170        check_segment_size(&dir, segment_size, &found)?;
171
172        let total_len = match found.last() {
173            Some(&(index, len)) => index.saturating_mul(segment_size).saturating_add(len),
174            None => 0,
175        };
176        // The head is the exact record boundary recorded by the last prefix
177        // truncation, or 0 for a log that has never had one. It is durable, so
178        // recovery resumes from the same place after a crash.
179        let lowest = found.first().map_or(0, |&(index, _)| index);
180        let head = match read_head_file(&dir)? {
181            Some(head) => head.min(total_len),
182            // No marker (or a damaged one) and segment 0 still here: the whole
183            // log is present and recovery reads it from the start.
184            None if lowest == 0 => 0,
185            None => {
186                return Err(WalError::corruption(
187                    lowest.saturating_mul(segment_size),
188                    "the log's first segments were dropped and its head marker is missing or damaged",
189                ));
190            }
191        };
192        if !found.is_empty() && head / segment_size < lowest {
193            return Err(WalError::corruption(
194                head,
195                "the segment holding the log's head is missing",
196            ));
197        }
198
199        // Flush every segment before recovery reads it, and keep the handles.
200        let mut segments = HashMap::with_capacity(found.len());
201        for &(index, _) in &found {
202            let file = OpenOptions::new()
203                .read(true)
204                .write(true)
205                .open(dir.join(segment_name(index)))
206                .map_err(|e| WalError::io("opening a log segment", e))?;
207            durable_sync(&file).map_err(|e| WalError::io("flushing a log segment", e))?;
208            let _ = segments.insert(index, Segment::new(file, false));
209        }
210
211        Ok(SegmentedStore {
212            dir,
213            segment_size,
214            segments: RwLock::new(segments),
215            max_written: AtomicU64::new(total_len),
216            head: AtomicU64::new(head),
217            dir_dirty: AtomicBool::new(true),
218            parent_dirty: AtomicBool::new(created),
219        })
220    }
221
222    /// The directory holding the segment files.
223    #[must_use]
224    pub fn dir(&self) -> &Path {
225        &self.dir
226    }
227
228    /// The configured segment size in bytes.
229    #[must_use]
230    pub fn segment_size(&self) -> u64 {
231        self.segment_size
232    }
233
234    fn read_map(&self) -> RwLockReadGuard<'_, HashMap<u64, Arc<Segment>>> {
235        self.segments.read().unwrap_or_else(PoisonError::into_inner)
236    }
237
238    fn write_map(&self) -> RwLockWriteGuard<'_, HashMap<u64, Arc<Segment>>> {
239        self.segments
240            .write()
241            .unwrap_or_else(PoisonError::into_inner)
242    }
243
244    /// Get segment `index`, creating the file if it does not exist yet.
245    fn segment_for_write(&self, index: u64) -> Result<Arc<Segment>> {
246        if let Some(segment) = self.read_map().get(&index) {
247            return Ok(Arc::clone(segment));
248        }
249        let mut map = self.write_map();
250        if let Some(segment) = map.get(&index) {
251            return Ok(Arc::clone(segment));
252        }
253        let path = self.dir.join(segment_name(index));
254        let file = OpenOptions::new()
255            .read(true)
256            .write(true)
257            .create(true)
258            .truncate(false)
259            .open(&path)
260            .map_err(|e| WalError::io("creating a log segment", e))?;
261        // Set before the write that follows completes, so the sync covering it
262        // flushes the new name. The append path pays one atomic store per
263        // segment; the directory flush itself happens in `sync`.
264        self.dir_dirty.store(true, Ordering::Release);
265        let segment = Segment::new(file, false);
266        let _ = map.insert(index, Arc::clone(&segment));
267        Ok(segment)
268    }
269
270    /// Get segment `index` only if it already exists, without creating it.
271    /// `None` means the log ends before this segment.
272    fn segment_for_read(&self, index: u64) -> Result<Option<Arc<Segment>>> {
273        if let Some(segment) = self.read_map().get(&index) {
274            return Ok(Some(Arc::clone(segment)));
275        }
276        let path = self.dir.join(segment_name(index));
277        match OpenOptions::new().read(true).write(true).open(&path) {
278            Ok(file) => {
279                let mut map = self.write_map();
280                if let Some(existing) = map.get(&index) {
281                    return Ok(Some(Arc::clone(existing)));
282                }
283                let segment = Segment::new(file, false);
284                let _ = map.insert(index, Arc::clone(&segment));
285                Ok(Some(segment))
286            }
287            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
288            Err(error) => Err(WalError::io("opening a log segment", error)),
289        }
290    }
291
292    /// Remove segment `index`'s file and mark the directory for a flush.
293    fn remove_segment(&self, index: u64) -> Result<()> {
294        // Drop our handle before unlinking — Windows refuses to remove a
295        // file that still has an open handle.
296        let _ = self.write_map().remove(&index);
297        fs::remove_file(self.dir.join(segment_name(index)))
298            .map_err(|e| WalError::io("removing a truncated segment", e))?;
299        self.dir_dirty.store(true, Ordering::Release);
300        #[cfg(test)]
301        steps::note(steps::Step::Removed(index));
302        Ok(())
303    }
304
305    /// Durably record `head` so a later open resumes from the same boundary.
306    ///
307    /// The marker is checksummed (`[head: u64][crc32c(head): u32]`) so a torn
308    /// write of the marker itself is detected on read rather than trusted — a
309    /// corrupt marker must never make recovery skip live records.
310    fn write_head_file(&self, head: u64) -> Result<()> {
311        let mut buf = [0u8; HEAD_FILE_LEN];
312        buf[..8].copy_from_slice(&head.to_le_bytes());
313        let crc = crate::crc::crc32c(&buf[..8]);
314        buf[8..].copy_from_slice(&crc.to_le_bytes());
315        write_small_file(&self.dir, HEAD_TMP_FILE, HEAD_FILE, &buf, "the head marker")
316    }
317}
318
319/// Write `bytes` to `dir/name` atomically and durably: through `tmp`,
320/// flushed, renamed over `name`, and the directory flushed.
321fn write_small_file(
322    dir: &Path,
323    tmp: &str,
324    name: &str,
325    bytes: &[u8],
326    what: &'static str,
327) -> Result<()> {
328    let tmp = dir.join(tmp);
329    let file = OpenOptions::new()
330        .write(true)
331        .create(true)
332        .truncate(true)
333        .open(&tmp)
334        .map_err(|e| WalError::io(what, e))?;
335    pwrite_all(&file, 0, bytes).map_err(|e| WalError::io(what, e))?;
336    durable_sync(&file).map_err(|e| WalError::io(what, e))?;
337    // Windows refuses to rename a file that still has an open handle.
338    drop(file);
339    fs::rename(&tmp, dir.join(name)).map_err(|e| WalError::io(what, e))?;
340    sync_dir(dir).map_err(|e| WalError::io("flushing the log directory", e))
341}
342
343/// Check `segment_size` against the size the log in `dir` was written with,
344/// and record it for a log that has no record of it yet.
345///
346/// A log from 1.4 on records its size in the `meta` file. For an older log
347/// the segments' lengths tell: every segment before the last one is full, so
348/// one that is longer than `segment_size`, or a set of them none of which is
349/// exactly `segment_size` long, means another size. (A segment before the
350/// last may be short only if a crash cut writes that were still in flight.)
351fn check_segment_size(dir: &Path, segment_size: u64, found: &[(u64, u64)]) -> Result<()> {
352    let mismatch = || {
353        WalError::corruption(
354            0,
355            "the log was written with another segment size: open it with that size",
356        )
357    };
358    if let Some(recorded) = read_meta_file(dir)? {
359        return if recorded == segment_size {
360            Ok(())
361        } else {
362            Err(mismatch())
363        };
364    }
365    let before_last = found.len().saturating_sub(1);
366    let full = &found[..before_last];
367    if found.iter().any(|&(_, len)| len > segment_size)
368        || (!full.is_empty() && !full.iter().any(|&(_, len)| len == segment_size))
369    {
370        return Err(mismatch());
371    }
372    let mut buf = [0u8; META_FILE_LEN];
373    buf[..8].copy_from_slice(META_MAGIC);
374    buf[8..16].copy_from_slice(&segment_size.to_le_bytes());
375    let crc = crate::crc::crc32c(&buf[..16]);
376    buf[16..].copy_from_slice(&crc.to_le_bytes());
377    write_small_file(dir, META_TMP_FILE, META_FILE, &buf, "the log's meta file")
378}
379
380/// The segment size recorded in the meta file, or `None` when there is none.
381fn read_meta_file(dir: &Path) -> Result<Option<u64>> {
382    match fs::read(dir.join(META_FILE)) {
383        Ok(bytes) => {
384            if bytes.len() != META_FILE_LEN
385                || &bytes[..8] != META_MAGIC
386                || crate::crc::crc32c(&bytes[..16])
387                    != u32::from_le_bytes([bytes[16], bytes[17], bytes[18], bytes[19]])
388            {
389                return Err(WalError::corruption(0, "the log's meta file is damaged"));
390            }
391            let mut size = [0u8; 8];
392            size.copy_from_slice(&bytes[8..16]);
393            Ok(Some(u64::from_le_bytes(size)))
394        }
395        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
396        Err(error) => Err(WalError::io("reading the log's meta file", error)),
397    }
398}
399
400/// Read the durably recorded head, or `None` if no prefix has been dropped
401/// or the marker is unreadable.
402///
403/// A marker that is absent, too short, or whose checksum does not match is
404/// `None`. The caller then reads the log from 0 only if segment 0 is still
405/// there; once a prefix has been dropped it refuses to open instead, since
406/// recovery from 0 would find nothing and cut the log.
407fn read_head_file(dir: &Path) -> Result<Option<u64>> {
408    match fs::read(dir.join(HEAD_FILE)) {
409        Ok(bytes) if bytes.len() >= HEAD_FILE_LEN => {
410            let head = u64::from_le_bytes([
411                bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
412            ]);
413            let stored = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]);
414            if crate::crc::crc32c(&bytes[..8]) == stored {
415                Ok(Some(head))
416            } else {
417                Ok(None)
418            }
419        }
420        Ok(_) => Ok(None),
421        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
422        Err(error) => Err(WalError::io("reading the head marker", error)),
423    }
424}
425
426impl WalStore for SegmentedStore {
427    fn write_at(&self, offset: u64, bytes: &[u8]) -> Result<()> {
428        let mut pos = offset;
429        let mut remaining = bytes;
430        while !remaining.is_empty() {
431            let index = pos / self.segment_size;
432            let local = pos % self.segment_size;
433            let room = (self.segment_size - local) as usize;
434            let take = remaining.len().min(room);
435
436            let segment = self.segment_for_write(index)?;
437            pwrite_all(&segment.file, local, &remaining[..take])
438                .map_err(|e| WalError::io("writing a record", e))?;
439            // After the bytes are in the file: a sync that reads the flag as set
440            // flushes them; one that cleared it just before has flushed them too.
441            segment.dirty.store(true, Ordering::Release);
442
443            pos += take as u64;
444            remaining = &remaining[take..];
445        }
446        let end = offset.saturating_add(bytes.len() as u64);
447        let _ = self.max_written.fetch_max(end, Ordering::Relaxed);
448        Ok(())
449    }
450
451    fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<usize> {
452        let mut pos = offset;
453        let mut filled = 0;
454        while filled < buf.len() {
455            let index = pos / self.segment_size;
456            let local = pos % self.segment_size;
457            let room = (self.segment_size - local) as usize;
458            let want = (buf.len() - filled).min(room);
459
460            let Some(segment) = self.segment_for_read(index)? else {
461                break; // no such segment: the log ends here
462            };
463            let got = pread_fill(&segment.file, local, &mut buf[filled..filled + want])
464                .map_err(|e| WalError::io("reading from the log", e))?;
465            filled += got;
466            pos += got as u64;
467            if got < want {
468                break; // short read within a segment: the log ends here
469            }
470        }
471        Ok(filled)
472    }
473
474    fn truncate(&self, len: u64) -> Result<()> {
475        let last_index = len / self.segment_size;
476        let last_local = len % self.segment_size;
477
478        // Walk the directory so segments not currently open are handled too.
479        let mut later: Vec<u64> = Vec::new();
480        let mut at_cut = false;
481        let entries =
482            fs::read_dir(&self.dir).map_err(|e| WalError::io("reading the log directory", e))?;
483        for entry in entries {
484            let entry = entry.map_err(|e| WalError::io("reading the log directory", e))?;
485            match parse_segment_name(&entry.file_name()) {
486                Some(index) if index > last_index => later.push(index),
487                Some(index) if index == last_index => at_cut = true,
488                _ => {}
489            }
490        }
491
492        // Segments wholly past the cut go first, the highest first, and their
493        // removal is flushed before the cut is made. A crash part-way leaves
494        // a log that ends on a whole segment somewhere between its old end
495        // and the cut; it never leaves the cut made with records still in a
496        // file after it.
497        later.sort_unstable_by(|a, b| b.cmp(a));
498        let removed_later = !later.is_empty();
499        for index in later {
500            self.remove_segment(index)?;
501        }
502        if removed_later {
503            flush_dir_if_dirty(&self.dir_dirty, &self.dir)?;
504            #[cfg(test)]
505            steps::note(steps::Step::DirectoryFlushed);
506        }
507
508        // The cut itself is a change of length in the segment it lands in,
509        // flushed at once. That holds when the cut is on a segment boundary
510        // too: the segment that starts there is emptied and flushed before it
511        // is removed. Removing a file is a change to the directory, which not
512        // every platform lets us flush (`sync_dir`), so the removal alone
513        // would leave the dropped records one power loss away from coming
514        // back at the very offsets they had. An empty file that comes back
515        // is harmless: the log ends where it starts.
516        if at_cut {
517            let segment = self.segment_for_write(last_index)?;
518            segment
519                .file
520                .set_len(last_local)
521                .map_err(|e| WalError::io("truncating a log segment", e))?;
522            durable_sync(&segment.file)
523                .map_err(|e| WalError::io("flushing a truncated segment", e))?;
524            #[cfg(test)]
525            steps::note(steps::Step::CutFlushed(last_index, last_local));
526            drop(segment);
527            if last_local == 0 {
528                self.remove_segment(last_index)?;
529            }
530        }
531
532        self.max_written.store(len, Ordering::Relaxed);
533        Ok(())
534    }
535
536    fn sync(&self) -> Result<()> {
537        // Directory first: on macOS only the file flush below empties the
538        // drive's write cache.
539        flush_dir_if_dirty(&self.dir_dirty, &self.dir)?;
540        flush_dir_if_dirty(&self.parent_dirty, &parent_dir(&self.dir))?;
541
542        // Every segment written since its last flush, whichever it is: a record
543        // whose writer finished late may have landed in an older one.
544        let dirty: Vec<Arc<Segment>> = self
545            .read_map()
546            .values()
547            .filter(|segment| segment.dirty.load(Ordering::Acquire))
548            .cloned()
549            .collect();
550        for segment in dirty {
551            if segment.dirty.swap(false, Ordering::AcqRel) {
552                if let Err(e) = durable_sync(&segment.file) {
553                    segment.dirty.store(true, Ordering::Release);
554                    return Err(WalError::io("flushing to stable storage", e));
555                }
556            }
557        }
558        Ok(())
559    }
560
561    fn len(&self) -> Result<u64> {
562        Ok(self.max_written.load(Ordering::Acquire))
563    }
564
565    fn head(&self) -> Result<u64> {
566        Ok(self.head.load(Ordering::Acquire))
567    }
568
569    fn truncate_before(&self, offset: u64) -> Result<u64> {
570        let written = self.max_written.load(Ordering::Acquire);
571        // The new head is the caller's record boundary, clamped so it never moves
572        // backwards and never past the end. It is a *record* boundary, not a
573        // segment boundary: because records span segments, the lowest surviving
574        // segment may start mid-record, so the head — and where recovery begins —
575        // must be the exact offset the caller gave.
576        let prev = self.head.load(Ordering::Acquire);
577        let new_head = offset.clamp(prev, written);
578
579        // Persist the head durably *before* deleting anything: a crash mid-delete
580        // then recovers from the right boundary, and the leftover segments below it
581        // are harmless dead space.
582        self.write_head_file(new_head)?;
583
584        // Delete every segment entirely below the one that holds the new head; that
585        // segment, and the one holding the most recent records, are always kept.
586        let last_segment = written.saturating_sub(1) / self.segment_size;
587        let keep_from = (new_head / self.segment_size).min(last_segment);
588        let entries =
589            fs::read_dir(&self.dir).map_err(|e| WalError::io("reading the log directory", e))?;
590        for entry in entries {
591            let entry = entry.map_err(|e| WalError::io("reading the log directory", e))?;
592            let Some(index) = parse_segment_name(&entry.file_name()) else {
593                continue;
594            };
595            if index < keep_from {
596                // Drop our handle before unlinking — Windows refuses to remove a
597                // file that still has an open handle.
598                let _ = self.write_map().remove(&index);
599                fs::remove_file(entry.path())
600                    .map_err(|e| WalError::io("removing a dropped segment", e))?;
601                self.dir_dirty.store(true, Ordering::Release);
602            }
603        }
604
605        self.head.store(new_head, Ordering::Release);
606        Ok(new_head)
607    }
608}
609
610/// The file name for segment `index`: zero-padded decimal, then `.wal`.
611fn segment_name(index: u64) -> String {
612    format!("{index:0NAME_DIGITS$}.{NAME_EXT}")
613}
614
615/// Parse a segment index out of a file name, or `None` if it is not a segment
616/// file. Only names of exactly the expected shape are accepted, so unrelated
617/// files in the directory are ignored.
618fn parse_segment_name(name: &OsStr) -> Option<u64> {
619    let name = name.to_str()?;
620    let stem = name.strip_suffix(&format!(".{NAME_EXT}"))?;
621    if stem.len() != NAME_DIGITS || !stem.bytes().all(|b| b.is_ascii_digit()) {
622        return None;
623    }
624    stem.parse().ok()
625}
626
627/// What a truncation did to the disk, in order, for the tests: the order is
628/// what a crash part-way through depends on.
629#[cfg(test)]
630mod steps {
631    use std::cell::RefCell;
632
633    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
634    pub(super) enum Step {
635        /// A segment file was removed.
636        Removed(u64),
637        /// The log directory was flushed.
638        DirectoryFlushed,
639        /// A segment was set to a length and flushed.
640        CutFlushed(u64, u64),
641    }
642
643    thread_local! {
644        static STEPS: RefCell<Vec<Step>> = const { RefCell::new(Vec::new()) };
645    }
646
647    pub(super) fn note(step: Step) {
648        STEPS.with(|steps| steps.borrow_mut().push(step));
649    }
650
651    /// The steps noted on this thread since the last call.
652    pub(super) fn take() -> Vec<Step> {
653        STEPS.with(|steps| std::mem::take(&mut *steps.borrow_mut()))
654    }
655}
656
657#[cfg(test)]
658#[allow(clippy::unwrap_used, clippy::expect_used)]
659mod tests {
660    use super::steps::Step;
661    use super::*;
662
663    /// A cut on a segment boundary shrinks nothing that stays, so the segment
664    /// that starts at the cut is what carries it: emptied and flushed, and
665    /// only then removed. Later segments are already gone by then, the
666    /// highest first.
667    #[test]
668    fn test_a_cut_on_a_boundary_empties_and_flushes_before_it_removes() {
669        let dir = tempfile::tempdir().unwrap();
670        let store = SegmentedStore::open(dir.path(), 16).unwrap();
671        store.write_at(0, &[1; 64]).unwrap(); // segments 0..=3
672        store.sync().unwrap();
673        let _ = steps::take();
674
675        store.truncate(32).unwrap();
676        assert_eq!(
677            steps::take(),
678            [
679                Step::Removed(3),
680                Step::DirectoryFlushed,
681                Step::CutFlushed(2, 0),
682                Step::Removed(2),
683            ]
684        );
685        assert_eq!(store.len().unwrap(), 32);
686        assert!(!dir.path().join(segment_name(2)).exists());
687    }
688
689    /// A cut inside a segment: every later segment is removed, the highest
690    /// first, and the directory flushed, before the shrink that makes the
691    /// cut. A crash in between leaves no shrunk segment with a full one
692    /// after it, which a strict open would refuse.
693    #[test]
694    fn test_later_segments_are_removed_before_the_cut_is_made() {
695        let dir = tempfile::tempdir().unwrap();
696        let store = SegmentedStore::open(dir.path(), 16).unwrap();
697        store.write_at(0, &[1; 64]).unwrap();
698        store.sync().unwrap();
699        let _ = steps::take();
700
701        store.truncate(20).unwrap();
702        assert_eq!(
703            steps::take(),
704            [
705                Step::Removed(3),
706                Step::Removed(2),
707                Step::DirectoryFlushed,
708                Step::CutFlushed(1, 4),
709            ]
710        );
711        assert_eq!(store.len().unwrap(), 20);
712    }
713
714    /// An empty last segment, as a power loss can leave after a cut on a
715    /// boundary, opens as a log that ends at that boundary, and is written
716    /// again from there.
717    #[test]
718    fn test_an_empty_last_segment_is_the_end_of_the_log() {
719        let dir = tempfile::tempdir().unwrap();
720        {
721            let store = SegmentedStore::open(dir.path(), 16).unwrap();
722            store.write_at(0, &[1; 32]).unwrap();
723            store.sync().unwrap();
724        }
725        fs::write(dir.path().join(segment_name(2)), []).unwrap();
726        let store = SegmentedStore::open(dir.path(), 16).unwrap();
727        assert_eq!(store.len().unwrap(), 32);
728        store.write_at(32, &[2; 8]).unwrap();
729        store.sync().unwrap();
730        let mut buf = [0u8; 40];
731        assert_eq!(store.read_at(0, &mut buf).unwrap(), 40);
732        assert_eq!(&buf[32..], &[2; 8]);
733    }
734
735    fn dir_dirty(store: &SegmentedStore) -> bool {
736        store.dir_dirty.load(Ordering::Acquire)
737    }
738
739    fn segment_dirty(store: &SegmentedStore, index: u64) -> bool {
740        store.read_map()[&index].dirty.load(Ordering::Acquire)
741    }
742
743    /// The order the commit layer produces when a record that straddles a
744    /// segment boundary is reserved first but written last: a later record
745    /// completes, a sync runs, then the late bytes land in the older segment.
746    /// The sync that covers them must flush that older segment (before 1.4
747    /// it flushed only from the segment of the highest write on).
748    #[test]
749    fn test_a_late_write_into_an_older_segment_is_flushed() {
750        let dir = tempfile::tempdir().unwrap();
751        let store = SegmentedStore::open(dir.path(), 64).unwrap();
752        store.write_at(0, &[1u8; 54]).unwrap();
753        store.sync().unwrap();
754        store.write_at(74, &[2u8; 30]).unwrap(); // the later record, segment 1
755        store.sync().unwrap();
756        assert!(!segment_dirty(&store, 0) && !segment_dirty(&store, 1));
757        store.write_at(54, &[3u8; 20]).unwrap(); // the late one, segments 0 and 1
758        assert!(segment_dirty(&store, 0) && segment_dirty(&store, 1));
759        store.sync().unwrap();
760        assert!(!segment_dirty(&store, 0) && !segment_dirty(&store, 1));
761    }
762
763    /// A reopened log flushes every segment before recovery trusts it: a
764    /// process that stopped without syncing may have left bytes only in the
765    /// page cache.
766    #[test]
767    fn test_open_flushes_every_existing_segment() {
768        let dir = tempfile::tempdir().unwrap();
769        {
770            let store = SegmentedStore::open(dir.path(), 64).unwrap();
771            store.write_at(0, &[1u8; 200]).unwrap(); // four segments, never synced
772        }
773        let store = SegmentedStore::open(dir.path(), 64).unwrap();
774        for index in 0..4 {
775            assert!(!segment_dirty(&store, index), "segment {index}");
776        }
777        assert_eq!(store.len().unwrap(), 200);
778    }
779
780    #[test]
781    fn test_new_segment_marks_the_directory_until_the_next_sync() {
782        let dir = tempfile::tempdir().unwrap();
783        let store = SegmentedStore::open(dir.path(), 16).unwrap();
784        assert!(dir_dirty(&store), "a fresh open has names to flush");
785
786        store.write_at(0, &[1; 8]).unwrap();
787        store.sync().unwrap();
788        assert!(!dir_dirty(&store));
789
790        // Same segment: no new name, so no directory flush.
791        store.write_at(8, &[1; 4]).unwrap();
792        assert!(!dir_dirty(&store));
793
794        // Crossing into a new segment creates a name.
795        store.write_at(12, &[1; 8]).unwrap();
796        assert!(dir_dirty(&store));
797        store.sync().unwrap();
798        assert!(!dir_dirty(&store));
799    }
800
801    #[test]
802    fn test_removing_a_segment_marks_the_directory() {
803        let dir = tempfile::tempdir().unwrap();
804        let store = SegmentedStore::open(dir.path(), 16).unwrap();
805        store.write_at(0, &[1; 40]).unwrap();
806        store.sync().unwrap();
807
808        // On a boundary the last thing removed is the emptied segment at
809        // the cut: its name is left for the next sync.
810        store.truncate(16).unwrap();
811        assert!(dir_dirty(&store));
812        store.sync().unwrap();
813        assert!(!dir_dirty(&store));
814
815        // Inside a segment the removals are flushed before the cut is made.
816        store.write_at(16, &[1; 24]).unwrap();
817        store.sync().unwrap();
818        store.truncate(8).unwrap();
819        assert!(!dir_dirty(&store));
820    }
821
822    #[test]
823    fn test_only_a_created_directory_marks_its_parent() {
824        let root = tempfile::tempdir().unwrap();
825        let path = root.path().join("log");
826
827        let store = SegmentedStore::open(&path, 16).unwrap();
828        assert!(store.parent_dirty.load(Ordering::Acquire));
829        store.sync().unwrap();
830        assert!(!store.parent_dirty.load(Ordering::Acquire));
831        drop(store);
832
833        let store = SegmentedStore::open(&path, 16).unwrap();
834        assert!(!store.parent_dirty.load(Ordering::Acquire));
835    }
836
837    #[test]
838    fn test_head_marker_replacement_leaves_no_temporary_file() {
839        let dir = tempfile::tempdir().unwrap();
840        let store = SegmentedStore::open(dir.path(), 16).unwrap();
841        store.write_head_file(1).unwrap();
842        store.write_head_file(2).unwrap();
843        assert_eq!(read_head_file(dir.path()).unwrap(), Some(2));
844        assert!(!dir.path().join(HEAD_TMP_FILE).exists());
845    }
846
847    #[test]
848    fn test_torn_temporary_marker_never_touches_the_live_one() {
849        // A crash while writing the replacement: the live marker is what counts.
850        let dir = tempfile::tempdir().unwrap();
851        let store = SegmentedStore::open(dir.path(), 16).unwrap();
852        store.write_head_file(7).unwrap();
853        fs::write(dir.path().join(HEAD_TMP_FILE), [0xAB; 3]).unwrap();
854        assert_eq!(read_head_file(dir.path()).unwrap(), Some(7));
855
856        // The next replacement overwrites the leftover.
857        store.write_head_file(9).unwrap();
858        assert_eq!(read_head_file(dir.path()).unwrap(), Some(9));
859    }
860
861    #[test]
862    fn test_segment_name_roundtrips() {
863        assert_eq!(segment_name(0), "00000000000000000000.wal");
864        assert_eq!(segment_name(42), "00000000000000000042.wal");
865        assert_eq!(
866            parse_segment_name(OsStr::new("00000000000000000042.wal")),
867            Some(42)
868        );
869        assert_eq!(parse_segment_name(OsStr::new("README.md")), None);
870        assert_eq!(parse_segment_name(OsStr::new("42.wal")), None);
871        assert_eq!(
872            parse_segment_name(OsStr::new("0000000000000000004x.wal")),
873            None
874        );
875    }
876
877    #[test]
878    fn test_write_read_within_one_segment() {
879        let dir = tempfile::tempdir().unwrap();
880        let store = SegmentedStore::open(dir.path(), 64).unwrap();
881        store.write_at(0, b"hello").unwrap();
882        store.sync().unwrap();
883
884        let mut buf = [0u8; 5];
885        assert_eq!(store.read_at(0, &mut buf).unwrap(), 5);
886        assert_eq!(&buf, b"hello");
887        assert_eq!(store.len().unwrap(), 5);
888    }
889
890    #[test]
891    fn test_write_spans_segment_boundary() {
892        let dir = tempfile::tempdir().unwrap();
893        // 8-byte segments force a 12-byte write to span two segments.
894        let store = SegmentedStore::open(dir.path(), 8).unwrap();
895        store.write_at(0, b"ABCDEFGHIJKL").unwrap(); // 12 bytes -> segments 0 and 1
896        store.sync().unwrap();
897
898        // Two segment files exist.
899        assert!(dir.path().join("00000000000000000000.wal").exists());
900        assert!(dir.path().join("00000000000000000001.wal").exists());
901
902        let mut buf = [0u8; 12];
903        assert_eq!(store.read_at(0, &mut buf).unwrap(), 12);
904        assert_eq!(&buf, b"ABCDEFGHIJKL");
905    }
906
907    #[test]
908    fn test_read_at_arbitrary_offset_across_boundary() {
909        let dir = tempfile::tempdir().unwrap();
910        let store = SegmentedStore::open(dir.path(), 4).unwrap();
911        store.write_at(0, b"0123456789").unwrap();
912        let mut buf = [0u8; 5];
913        let n = store.read_at(3, &mut buf).unwrap(); // spans segments 0,1,2
914        assert_eq!(n, 5);
915        assert_eq!(&buf, b"34567");
916    }
917
918    #[test]
919    fn test_reopen_reports_correct_length() {
920        let dir = tempfile::tempdir().unwrap();
921        {
922            let store = SegmentedStore::open(dir.path(), 8).unwrap();
923            store.write_at(0, b"ABCDEFGHIJKLM").unwrap(); // 13 bytes -> segs 0(full),1(partial)
924            store.sync().unwrap();
925            assert_eq!(store.len().unwrap(), 13);
926        }
927        let store = SegmentedStore::open(dir.path(), 8).unwrap();
928        assert_eq!(store.len().unwrap(), 13);
929        let mut buf = [0u8; 13];
930        assert_eq!(store.read_at(0, &mut buf).unwrap(), 13);
931        assert_eq!(&buf, b"ABCDEFGHIJKLM");
932    }
933
934    #[test]
935    fn test_truncate_removes_later_segments() {
936        let dir = tempfile::tempdir().unwrap();
937        let store = SegmentedStore::open(dir.path(), 8).unwrap();
938        store.write_at(0, &[0xAB; 30]).unwrap(); // segments 0..=3
939        store.sync().unwrap();
940        assert!(dir.path().join("00000000000000000003.wal").exists());
941
942        store.truncate(10).unwrap(); // keep segment 0 (full) + 2 bytes of segment 1
943        assert_eq!(store.len().unwrap(), 10);
944        assert!(dir.path().join("00000000000000000001.wal").exists());
945        assert!(!dir.path().join("00000000000000000002.wal").exists());
946        assert!(!dir.path().join("00000000000000000003.wal").exists());
947
948        let mut buf = [0u8; 16];
949        assert_eq!(store.read_at(0, &mut buf).unwrap(), 10);
950    }
951
952    #[test]
953    fn test_read_past_end_is_short() {
954        let dir = tempfile::tempdir().unwrap();
955        let store = SegmentedStore::open(dir.path(), 8).unwrap();
956        store.write_at(0, b"abc").unwrap();
957        let mut buf = [0u8; 16];
958        assert_eq!(store.read_at(0, &mut buf).unwrap(), 3);
959        assert_eq!(store.read_at(100, &mut buf).unwrap(), 0);
960    }
961}