link_cli/transactions/log.rs
1//! Storage backends for the transitions log.
2//!
3//! The transactions layer only needs three things from its log: append
4//! one entry, read every entry back in write order, and make what has
5//! been appended durable. [`TransitionLogStore`] captures exactly that,
6//! so a consumer can plug in whichever log it already has.
7//!
8//! Two implementations ship with the library:
9//!
10//! * [`NamedTypesDecorator`] — the original sidecar *links* log, where
11//! each entry is the name of a freshly created link. Keeps the log in
12//! the same format the C# port uses.
13//! * [`FileTransitionLog`] — a plain append-only text file, one entry
14//! per line, `fsync`ed on every append by default. Cheaper than a
15//! links database. An incomplete final line, or trailing lines with a
16//! NUL byte that power loss left, is discarded on open or before reusing
17//! a writer after an I/O error.
18//!
19//! Reading takes `&mut self` because the links-backed log resolves
20//! names through [`NamedTypes::get_name`], which needs mutable access
21//! to its own caches.
22
23use std::fs::{File, OpenOptions};
24use std::io::{Read, Seek, SeekFrom, Write};
25use std::path::{Path, PathBuf};
26
27use crate::error::LinkError;
28use crate::named_types::{NamedTypes, NamedTypesDecorator};
29
30/// Append-only store of serialized transitions and recovery markers.
31pub trait TransitionLogStore {
32 /// Appends one entry. Entries never contain newlines.
33 fn append_log_entry(&mut self, entry: &str) -> Result<(), LinkError>;
34
35 /// Reads every entry back, oldest first.
36 fn read_log_entries(&mut self) -> Result<Vec<String>, LinkError>;
37
38 /// Makes every appended entry durable.
39 fn flush_log(&mut self) -> Result<(), LinkError>;
40
41 /// Whether flush requests persistent storage. Custom/volatile logs default
42 /// to false; this describes an adapter, not the reliability of its hardware.
43 fn supports_durable_flush(&self) -> bool {
44 false
45 }
46}
47
48/// Optional replacement of a complete ordered journal under the same exclusive
49/// owner. Success publishes all records atomically and durably when advertised.
50/// An uncertain failure fences the implementation until actual reopening.
51pub trait ReplaceableTransitionLogStore: TransitionLogStore {
52 /// Dynamic adapters can expose the capability only when their inner log can.
53 fn supports_replacement(&self) -> bool {
54 true
55 }
56 /// Returns false when an identical committed journal needs no replacement.
57 /// Pending unflushed records must be rejected before changing durable state.
58 fn replace_log_entries(&mut self, entries: &[String]) -> Result<bool, LinkError>;
59}
60
61fn storage_error(error: anyhow::Error) -> LinkError {
62 LinkError::StorageError(format!("{error:#}"))
63}
64
65impl TransitionLogStore for NamedTypesDecorator {
66 fn supports_durable_flush(&self) -> bool {
67 !self.links().database_path().as_os_str().is_empty()
68 }
69 fn append_log_entry(&mut self, entry: &str) -> Result<(), LinkError> {
70 // Always allocate a fresh link so entries never overwrite one
71 // another (mirrors C# `CreateAndUpdate(Null, Null)`).
72 let link = self.create(0, 0);
73 self.set_name(link, entry).map_err(storage_error)?;
74 Ok(())
75 }
76
77 fn read_log_entries(&mut self) -> Result<Vec<String>, LinkError> {
78 let mut addresses: Vec<u32> = self.all().into_iter().map(|link| link.index).collect();
79 addresses.sort_unstable();
80 let mut entries = Vec::with_capacity(addresses.len());
81 for address in addresses {
82 if let Some(name) = NamedTypes::get_name(self, address).map_err(storage_error)? {
83 entries.push(name);
84 }
85 }
86 Ok(entries)
87 }
88
89 fn flush_log(&mut self) -> Result<(), LinkError> {
90 crate::LinksStorage::flush(self)
91 }
92}
93
94/// Append-only, line-oriented transitions log backed by a single file.
95///
96/// # Durability
97///
98/// With `sync_on_append` enabled (the default) every
99/// [`append_log_entry`](TransitionLogStore::append_log_entry) returns
100/// only after the entry has reached stable storage, which is what makes
101/// the write-ahead ordering of the transactions layer meaningful: a
102/// transition is always durable before the data-store write it
103/// describes is reported as committed. Disabling it trades that
104/// guarantee for throughput — the log is then durable only as far as
105/// the last [`flush_log`](TransitionLogStore::flush_log).
106///
107/// An interrupted append can leave a partial final line. Opening the log,
108/// or reading, appending or flushing after a writer I/O error, repairs that
109/// suffix before proceeding. A failed repair is retried on the next operation.
110/// Complete records remain intact, including records written before an error
111/// was returned; callers must discover an uncertain transaction's outcome
112/// rather than blindly retry it. Repair scans backwards with an 8 KiB buffer;
113/// successful operations do not rescan. This framing protocol assumes storage
114/// honors flush and does not prove device-sector atomicity after power loss.
115#[derive(Debug)]
116pub struct FileTransitionLog {
117 path: PathBuf,
118 file: File,
119 sync_on_append: bool,
120 tail_may_be_torn: bool,
121 _lock: Option<crate::FileLock>,
122}
123
124impl FileTransitionLog {
125 /// Opens (creating if needed) the log at `path`, discarding a
126 /// trailing entry left half-written by a crash.
127 pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, LinkError> {
128 let path = path.as_ref().to_path_buf();
129 if let Some(parent) = path.parent() {
130 if !parent.as_os_str().is_empty() && !parent.exists() {
131 std::fs::create_dir_all(parent)?;
132 }
133 }
134 // The torn tail is trimmed through a dedicated read/write handle:
135 // Windows grants an append-only handle `FILE_APPEND_DATA` without
136 // `FILE_WRITE_DATA`, so `set_len` on it fails with `ERROR_ACCESS_DENIED`.
137 let repair = OpenOptions::new()
138 .read(true)
139 .write(true)
140 .create(true)
141 .truncate(false)
142 .open(&path)?;
143 truncate_torn_tail(&repair)?;
144 drop(repair);
145 let file = OpenOptions::new().read(true).append(true).open(&path)?;
146 #[cfg(unix)]
147 File::open(
148 path.parent()
149 .filter(|p| !p.as_os_str().is_empty())
150 .unwrap_or(Path::new(".")),
151 )?
152 .sync_all()?;
153 Ok(Self {
154 path,
155 file,
156 sync_on_append: true,
157 tail_may_be_torn: false,
158 _lock: None,
159 })
160 }
161
162 /// Holds the conventional sidecar lock until drop. Contention fails fast;
163 /// all writers must follow the same advisory locking convention.
164 pub fn open_exclusive<P: AsRef<Path>>(path: P) -> Result<Self, LinkError> {
165 let lock =
166 crate::FileLock::try_acquire(crate::lock_file_path(&path), crate::LockMode::Exclusive)?
167 .ok_or_else(|| LinkError::Lock("journal writer is busy".into()))?;
168 let mut log = Self::open(path)?;
169 log._lock = Some(lock);
170 Ok(log)
171 }
172
173 // An error may follow successful short writes. Keep the flag until both
174 // truncation and its durable flush succeed, so repeated I/O faults retry.
175 fn repair_if_needed(&mut self) -> Result<(), LinkError> {
176 if self.tail_may_be_torn {
177 let repair = OpenOptions::new().read(true).write(true).open(&self.path)?;
178 truncate_torn_tail(&repair)?;
179 // A previous failed repair may already have changed the length.
180 repair.sync_all()?;
181 self.tail_may_be_torn = false;
182 }
183 Ok(())
184 }
185
186 /// Path of the backing file.
187 pub fn path(&self) -> &Path {
188 &self.path
189 }
190
191 /// Whether every append is `fsync`ed. Enabled by default.
192 pub fn sync_on_append(&self) -> bool {
193 self.sync_on_append
194 }
195
196 /// Turns per-append `fsync` on or off — see the durability notes.
197 pub fn set_sync_on_append(&mut self, value: bool) {
198 self.sync_on_append = value;
199 }
200}
201
202impl TransitionLogStore for FileTransitionLog {
203 fn supports_durable_flush(&self) -> bool {
204 true
205 }
206 fn append_log_entry(&mut self, entry: &str) -> Result<(), LinkError> {
207 if entry.contains(['\n', '\r', '\0']) {
208 return Err(LinkError::InvalidFormat(
209 "transition log entries must not contain line breaks or NUL".to_string(),
210 ));
211 }
212 self.repair_if_needed()?;
213 self.tail_may_be_torn = true;
214 writeln!(self.file, "{entry}")?;
215 self.file.flush()?;
216 if self.sync_on_append {
217 self.file.sync_data()?;
218 }
219 self.tail_may_be_torn = false;
220 Ok(())
221 }
222
223 fn read_log_entries(&mut self) -> Result<Vec<String>, LinkError> {
224 self.repair_if_needed()?;
225 let mut contents = String::new();
226 File::open(&self.path)?.read_to_string(&mut contents)?;
227 // Only newline-terminated lines were fully written; a trailing
228 // fragment is the torn tail of a crashed append.
229 Ok(contents
230 .lines()
231 .take(contents.matches('\n').count())
232 .filter(|line| !line.is_empty())
233 .map(|line| line.to_string())
234 .collect())
235 }
236
237 fn flush_log(&mut self) -> Result<(), LinkError> {
238 self.repair_if_needed()?;
239 self.tail_may_be_torn = true;
240 self.file.flush()?;
241 self.file.sync_data()?;
242 self.tail_may_be_torn = false;
243 Ok(())
244 }
245}
246
247/// Shrinks `file` to its last complete (newline-terminated) line that holds no
248/// NUL byte.
249///
250/// A crash can leave the log ending in a fragment of an entry. Appending
251/// after that fragment would concatenate the next entry onto it, turning
252/// one lost transition into two, so the fragment is dropped when the log
253/// is opened or its live writer recovers from an I/O error.
254///
255/// Power loss can also keep the newline of an entry that was never flushed
256/// while a sector before it was never written: a disk may reorder writes no
257/// flush ordered, and an unwritten sector reads back as zeros. Entries never
258/// contain NUL (appends refuse it), so trailing lines holding one are torn
259/// as well, as etcd's WAL treats a last record with a zeroed sector. A NUL
260/// before an intact line is damage; opening refuses it and repair decides.
261fn truncate_torn_tail(file: &File) -> Result<(), LinkError> {
262 let len = file.metadata()?.len();
263 if len == 0 {
264 return Ok(());
265 }
266 let mut file = file;
267 let mut end = len;
268 // End of the line being scanned, just past its newline; None while still
269 // in the fragment after the last newline. Blank lines are skipped, as
270 // reading skips them.
271 let mut complete: Option<u64> = None;
272 let mut newer_newline = len;
273 let mut zeroed = false;
274 let mut buffer = [0u8; 8192];
275 let keep = 'scan: loop {
276 if end == 0 {
277 // The first line of the file is reached.
278 break 'scan if zeroed { 0 } else { complete.unwrap_or(0) };
279 }
280 let chunk = std::cmp::min(end, buffer.len() as u64);
281 let start = end - chunk;
282 file.seek(SeekFrom::Start(start))?;
283 let slice = &mut buffer[..chunk as usize];
284 file.read_exact(slice)?;
285 for (offset, byte) in slice.iter().enumerate().rev() {
286 let position = start + offset as u64;
287 match (*byte, complete) {
288 (b'\n', None) => complete = Some(position + 1),
289 (b'\n', Some(_)) if newer_newline == position + 1 => {}
290 (b'\n', Some(line_end)) => {
291 if !zeroed {
292 break 'scan line_end;
293 }
294 complete = Some(position + 1);
295 zeroed = false;
296 }
297 (0, Some(_)) => zeroed = true,
298 _ => {}
299 }
300 if *byte == b'\n' {
301 newer_newline = position;
302 }
303 }
304 end = start;
305 };
306 if keep != len {
307 file.set_len(keep)?;
308 file.sync_all()?;
309 }
310 Ok(())
311}