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 checked_next(self) -> Option<Self> {
59 self.0.checked_add(1).map(Self)
60 }
61
62 pub fn next(self) -> Self {
63 self.checked_next().unwrap_or(self)
64 }
65
66 /// Predecessor id, saturating at zero. Used for the "active and
67 /// the segment immediately preceding it" tombstone-retention rule
68 /// in [`crate::wal::Wal::truncate_up_to`].
69 pub fn saturating_prev(self) -> Self {
70 Self(self.0.saturating_sub(1))
71 }
72}
73
74impl fmt::Display for SegmentId {
75 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76 write!(f, "{}", self.0)
77 }
78}
79
80/// A `(SegmentId, PathBuf)` pair. Returned by [`SegmentDir::list`] so
81/// callers can iterate once and not have to parse the id back out of
82/// the path themselves.
83#[derive(Debug, Clone)]
84pub struct SegmentEntry {
85 pub id: SegmentId,
86 pub path: PathBuf,
87}
88
89/// Owns the canonical naming scheme for a WAL directory and the
90/// operations that depend on it. Cheap to construct (`Clone` is a
91/// `PathBuf` clone) — the type is just a typed wrapper over a
92/// directory path.
93#[derive(Debug, Clone)]
94pub struct SegmentDir {
95 root: PathBuf,
96}
97
98impl SegmentDir {
99 pub fn new(root: impl Into<PathBuf>) -> Self {
100 Self { root: root.into() }
101 }
102
103 pub fn root(&self) -> &Path {
104 &self.root
105 }
106
107 /// Best-effort portability boundary for directory-entry durability. Native
108 /// Unix targets fsync directories directly; platforms without that concept
109 /// (including wasm) intentionally degrade to a no-op.
110 pub fn sync_dir(&self) -> Result<(), WalError> {
111 sync_dir(&self.root)?;
112 Ok(())
113 }
114
115 /// Canonical path for the segment with id `id`.
116 pub fn path_for(&self, id: SegmentId) -> PathBuf {
117 self.root
118 .join(format!("{:0width$}.wal", id.0, width = SEGMENT_ID_WIDTH))
119 }
120
121 /// Parse a `<NNNNNNNNNN>.wal` path back into a [`SegmentId`].
122 /// Returns `None` if the file name does not match the canonical
123 /// pattern (e.g. a leftover `.tmp` or a non-numeric stem).
124 pub fn id_of(path: &Path) -> Option<SegmentId> {
125 path.extension()
126 .and_then(|s| s.to_str())
127 .filter(|ext| *ext == "wal")?;
128 path.file_stem()
129 .and_then(|s| s.to_str())
130 .and_then(|s| s.parse::<u64>().ok())
131 .map(SegmentId)
132 }
133
134 /// List every `*.wal` file in the directory in ascending id order.
135 /// Files whose names do not match the canonical pattern are ignored
136 /// so a stray `.tmp` does not block boot. Directory entry I/O errors
137 /// still abort the listing rather than risking an incomplete replay.
138 pub fn list(&self) -> Result<Vec<SegmentEntry>, WalError> {
139 let mut out = Vec::new();
140 for entry in fs::read_dir(&self.root)? {
141 let path = entry?.path();
142 if let Some(id) = Self::id_of(&path) {
143 out.push(SegmentEntry { id, path });
144 }
145 }
146 out.sort_by_key(|e| e.id);
147 Ok(out)
148 }
149
150 /// `base_lsn` recorded in `segment`'s header. Used by
151 /// `truncate_up_to` to compute the LSN range each sealed segment
152 /// covers without re-walking its records.
153 pub fn base_lsn(segment: &Path) -> Result<Lsn, WalError> {
154 // `SegmentReader::open` already validates the magic, format,
155 // and header CRC — no point re-implementing the layout here
156 // just to skip a few bytes.
157 let reader = SegmentReader::open(segment)?;
158 Ok(reader.header().base_lsn)
159 }
160}
161
162#[cfg(test)]
163mod tests {
164 use super::*;
165
166 #[test]
167 fn segment_id_path_round_trip() {
168 let dir = SegmentDir::new("/tmp");
169 let id = SegmentId::new(42);
170 let path = dir.path_for(id);
171 assert_eq!(path.to_str().unwrap(), "/tmp/0000000042.wal");
172 assert_eq!(SegmentDir::id_of(&path), Some(id));
173 }
174
175 #[test]
176 fn id_of_rejects_non_wal_files() {
177 assert_eq!(SegmentDir::id_of(Path::new("/tmp/0000000001.txt")), None);
178 assert_eq!(SegmentDir::id_of(Path::new("/tmp/notanumber.wal")), None);
179 assert_eq!(SegmentDir::id_of(Path::new("/tmp/CURRENT")), None);
180 }
181
182 #[test]
183 fn saturating_prev_does_not_underflow() {
184 assert_eq!(SegmentId::new(0).saturating_prev(), SegmentId::new(0));
185 assert_eq!(SegmentId::new(1).saturating_prev(), SegmentId::new(0));
186 assert_eq!(SegmentId::new(7).saturating_prev(), SegmentId::new(6));
187 }
188}