Skip to main content

lora_wal/
dir.rs

1//! Segment-directory helpers.
2//!
3//! `Wal::open`, `replay_dir`, and `Wal::truncate_up_to` all need to:
4//!
5//! - turn a [`SegmentId`] into the canonical `<NNNNNNNNNN>.wal` path,
6//! - parse a path back into a [`SegmentId`],
7//! - list every well-formed segment file in a directory in ascending
8//!   id order,
9//! - read just the `base_lsn` of a segment without paying for a full
10//!   record walk.
11//!
12//! The same operations were inlined in two places before the refactor.
13//! Pulling them behind a single `SegmentDir` and a `SegmentId` newtype
14//! removes the duplication and makes the magic number "10 zero-padded
15//! digits" live in exactly one location.
16//!
17//! `SegmentDir` does not hold an open `DirHandle`. Every call hits the
18//! filesystem fresh — segment listings happen at open time and at
19//! truncate time, neither of which is in any hot path, so caching is
20//! not worth the invalidation work.
21
22use std::fmt;
23use std::fs;
24use std::path::{Path, PathBuf};
25
26use crate::errors::WalError;
27use crate::io::sync_dir;
28use crate::lsn::Lsn;
29use crate::segment::SegmentReader;
30
31/// Width of the zero-padded segment id in file names. 10 digits is
32/// enough for ~10 billion segments, which at the default 8 MiB target
33/// is ~80 EiB of log. Plenty.
34const SEGMENT_ID_WIDTH: usize = 10;
35
36/// Monotonic identifier for a WAL segment file.
37///
38/// Allocation policy: ids start at 1 (`SegmentId(0)` is reserved as a
39/// "no segment" sentinel that callers should never encounter for a
40/// live WAL), and rotation simply does `id + 1`. Ids are stable: a
41/// truncated segment retains its id even after every preceding segment
42/// has been deleted.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
44#[repr(transparent)]
45pub struct SegmentId(u64);
46
47impl SegmentId {
48    pub const FIRST: SegmentId = SegmentId(1);
49
50    pub const fn new(value: u64) -> Self {
51        Self(value)
52    }
53
54    pub const fn raw(self) -> u64 {
55        self.0
56    }
57
58    pub fn next(self) -> Self {
59        Self(self.0 + 1)
60    }
61
62    /// Predecessor id, saturating at zero. Used for the "active and
63    /// the segment immediately preceding it" tombstone-retention rule
64    /// in [`crate::wal::Wal::truncate_up_to`].
65    pub fn saturating_prev(self) -> Self {
66        Self(self.0.saturating_sub(1))
67    }
68}
69
70impl fmt::Display for SegmentId {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        write!(f, "{}", self.0)
73    }
74}
75
76/// A `(SegmentId, PathBuf)` pair. Returned by [`SegmentDir::list`] so
77/// callers can iterate once and not have to parse the id back out of
78/// the path themselves.
79#[derive(Debug, Clone)]
80pub struct SegmentEntry {
81    pub id: SegmentId,
82    pub path: PathBuf,
83}
84
85/// Owns the canonical naming scheme for a WAL directory and the
86/// operations that depend on it. Cheap to construct (`Clone` is a
87/// `PathBuf` clone) — the type is just a typed wrapper over a
88/// directory path.
89#[derive(Debug, Clone)]
90pub struct SegmentDir {
91    root: PathBuf,
92}
93
94impl SegmentDir {
95    pub fn new(root: impl Into<PathBuf>) -> Self {
96        Self { root: root.into() }
97    }
98
99    pub fn root(&self) -> &Path {
100        &self.root
101    }
102
103    /// Best-effort portability boundary for directory-entry durability. Native
104    /// Unix targets fsync directories directly; platforms without that concept
105    /// (including wasm) intentionally degrade to a no-op.
106    pub fn sync_dir(&self) -> Result<(), WalError> {
107        sync_dir(&self.root)?;
108        Ok(())
109    }
110
111    /// Canonical path for the segment with id `id`.
112    pub fn path_for(&self, id: SegmentId) -> PathBuf {
113        self.root
114            .join(format!("{:0width$}.wal", id.0, width = SEGMENT_ID_WIDTH))
115    }
116
117    /// Parse a `<NNNNNNNNNN>.wal` path back into a [`SegmentId`].
118    /// Returns `None` if the file name does not match the canonical
119    /// pattern (e.g. a leftover `.tmp` or a non-numeric stem).
120    pub fn id_of(path: &Path) -> Option<SegmentId> {
121        path.extension()
122            .and_then(|s| s.to_str())
123            .filter(|ext| *ext == "wal")?;
124        path.file_stem()
125            .and_then(|s| s.to_str())
126            .and_then(|s| s.parse::<u64>().ok())
127            .map(SegmentId)
128    }
129
130    /// List every `*.wal` file in the directory in ascending id order.
131    /// Files whose names do not match the canonical pattern are ignored
132    /// so a stray `.tmp` does not block boot. Directory entry I/O errors
133    /// still abort the listing rather than risking an incomplete replay.
134    pub fn list(&self) -> Result<Vec<SegmentEntry>, WalError> {
135        let mut out = Vec::new();
136        for entry in fs::read_dir(&self.root)? {
137            let path = entry?.path();
138            if let Some(id) = Self::id_of(&path) {
139                out.push(SegmentEntry { id, path });
140            }
141        }
142        out.sort_by_key(|e| e.id);
143        Ok(out)
144    }
145
146    /// `base_lsn` recorded in `segment`'s header. Used by
147    /// `truncate_up_to` to compute the LSN range each sealed segment
148    /// covers without re-walking its records.
149    pub fn base_lsn(segment: &Path) -> Result<Lsn, WalError> {
150        // `SegmentReader::open` already validates the magic, format,
151        // and header CRC — no point re-implementing the layout here
152        // just to skip a few bytes.
153        let reader = SegmentReader::open(segment)?;
154        Ok(reader.header().base_lsn)
155    }
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161
162    #[test]
163    fn segment_id_path_round_trip() {
164        let dir = SegmentDir::new("/tmp");
165        let id = SegmentId::new(42);
166        let path = dir.path_for(id);
167        assert_eq!(path.to_str().unwrap(), "/tmp/0000000042.wal");
168        assert_eq!(SegmentDir::id_of(&path), Some(id));
169    }
170
171    #[test]
172    fn id_of_rejects_non_wal_files() {
173        assert_eq!(SegmentDir::id_of(Path::new("/tmp/0000000001.txt")), None);
174        assert_eq!(SegmentDir::id_of(Path::new("/tmp/notanumber.wal")), None);
175        assert_eq!(SegmentDir::id_of(Path::new("/tmp/CURRENT")), None);
176    }
177
178    #[test]
179    fn saturating_prev_does_not_underflow() {
180        assert_eq!(SegmentId::new(0).saturating_prev(), SegmentId::new(0));
181        assert_eq!(SegmentId::new(1).saturating_prev(), SegmentId::new(0));
182        assert_eq!(SegmentId::new(7).saturating_prev(), SegmentId::new(6));
183    }
184}