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 /// Whether [`compact_log_entries`](Self::compact_log_entries) can rewrite
48 /// the durable journal. Retention uses it to bound the journal on disk;
49 /// logs without it keep every entry, as before.
50 fn supports_compaction(&self) -> bool {
51 false
52 }
53
54 /// Atomically and durably replaces every entry with `entries`, the
55 /// retained journal. After a crash the log holds either the old or the
56 /// new journal, never a mixture. Called only between transactions and
57 /// only when [`supports_compaction`](Self::supports_compaction) is true.
58 fn compact_log_entries(&mut self, entries: &[String]) -> Result<(), LinkError> {
59 let _ = entries;
60 Err(LinkError::StorageError(
61 "this transitions log does not support compaction".into(),
62 ))
63 }
64}
65
66/// Optional replacement of a complete ordered journal under the same exclusive
67/// owner. Success publishes all records atomically and durably when advertised.
68/// An uncertain failure fences the implementation until actual reopening.
69pub trait ReplaceableTransitionLogStore: TransitionLogStore {
70 /// Dynamic adapters can expose the capability only when their inner log can.
71 fn supports_replacement(&self) -> bool {
72 true
73 }
74 /// Returns false when an identical committed journal needs no replacement.
75 /// Pending unflushed records must be rejected before changing durable state.
76 fn replace_log_entries(&mut self, entries: &[String]) -> Result<bool, LinkError>;
77}
78
79fn storage_error(error: anyhow::Error) -> LinkError {
80 LinkError::StorageError(format!("{error:#}"))
81}
82
83impl TransitionLogStore for NamedTypesDecorator {
84 fn supports_durable_flush(&self) -> bool {
85 !self.links().database_path().as_os_str().is_empty()
86 }
87 fn append_log_entry(&mut self, entry: &str) -> Result<(), LinkError> {
88 // Always allocate a fresh link so entries never overwrite one
89 // another (mirrors C# `CreateAndUpdate(Null, Null)`).
90 let link = self.create(0, 0);
91 self.set_name(link, entry).map_err(storage_error)?;
92 Ok(())
93 }
94
95 fn read_log_entries(&mut self) -> Result<Vec<String>, LinkError> {
96 let mut addresses: Vec<u32> = self.all().into_iter().map(|link| link.index).collect();
97 addresses.sort_unstable();
98 let mut entries = Vec::with_capacity(addresses.len());
99 for address in addresses {
100 if let Some(name) = NamedTypes::get_name(self, address).map_err(storage_error)? {
101 entries.push(name);
102 }
103 }
104 Ok(entries)
105 }
106
107 fn flush_log(&mut self) -> Result<(), LinkError> {
108 crate::LinksStorage::flush(self)
109 }
110}
111
112/// Append-only, line-oriented transitions log backed by a single file.
113///
114/// Appending costs one write and one `fsync` regardless of how many
115/// entries the log already holds. Retention policies compact it through
116/// [`compact_log_entries`](TransitionLogStore::compact_log_entries), which
117/// writes the retained entries to `<path>.compact`, syncs it and renames it
118/// over the log, so the journal on disk stays bounded (issue #195).
119///
120/// # Durability
121///
122/// With `sync_on_append` enabled (the default) every
123/// [`append_log_entry`](TransitionLogStore::append_log_entry) returns
124/// only after the entry has reached stable storage, which is what makes
125/// the write-ahead ordering of the transactions layer meaningful: a
126/// transition is always durable before the data-store write it
127/// describes is reported as committed. Disabling it trades that
128/// guarantee for throughput — the log is then durable only as far as
129/// the last [`flush_log`](TransitionLogStore::flush_log).
130///
131/// An interrupted append can leave a partial final line. Opening the log,
132/// or reading, appending or flushing after a writer I/O error, repairs that
133/// suffix before proceeding. A failed repair is retried on the next operation.
134/// Complete records remain intact, including records written before an error
135/// was returned; callers must discover an uncertain transaction's outcome
136/// rather than blindly retry it. Repair scans backwards with an 8 KiB buffer;
137/// successful operations do not rescan. This framing protocol assumes storage
138/// honors flush and does not prove device-sector atomicity after power loss.
139#[derive(Debug)]
140pub struct FileTransitionLog {
141 path: PathBuf,
142 file: File,
143 sync_on_append: bool,
144 tail_may_be_torn: bool,
145 _lock: Option<crate::FileLock>,
146}
147
148impl FileTransitionLog {
149 /// Opens (creating if needed) the log at `path`, discarding a
150 /// trailing entry left half-written by a crash.
151 pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, LinkError> {
152 let path = path.as_ref().to_path_buf();
153 if let Some(parent) = path.parent() {
154 if !parent.as_os_str().is_empty() && !parent.exists() {
155 std::fs::create_dir_all(parent)?;
156 }
157 }
158 // A compaction interrupted before its rename leaves only a stale
159 // copy; the log itself still holds the complete previous journal.
160 match std::fs::remove_file(compaction_path(&path)) {
161 Err(error) if error.kind() != std::io::ErrorKind::NotFound => return Err(error.into()),
162 _ => {}
163 }
164 // The torn tail is trimmed through a dedicated read/write handle:
165 // Windows grants an append-only handle `FILE_APPEND_DATA` without
166 // `FILE_WRITE_DATA`, so `set_len` on it fails with `ERROR_ACCESS_DENIED`.
167 let repair = OpenOptions::new()
168 .read(true)
169 .write(true)
170 .create(true)
171 .truncate(false)
172 .open(&path)?;
173 truncate_torn_tail(&repair)?;
174 drop(repair);
175 let file = OpenOptions::new().read(true).append(true).open(&path)?;
176 sync_parent_directory(&path)?;
177 Ok(Self {
178 path,
179 file,
180 sync_on_append: true,
181 tail_may_be_torn: false,
182 _lock: None,
183 })
184 }
185
186 /// Holds the conventional sidecar lock until drop. Contention fails fast;
187 /// all writers must follow the same advisory locking convention.
188 pub fn open_exclusive<P: AsRef<Path>>(path: P) -> Result<Self, LinkError> {
189 let lock =
190 crate::FileLock::try_acquire(crate::lock_file_path(&path), crate::LockMode::Exclusive)?
191 .ok_or_else(|| LinkError::Lock("journal writer is busy".into()))?;
192 let mut log = Self::open(path)?;
193 log._lock = Some(lock);
194 Ok(log)
195 }
196
197 // An error may follow successful short writes. Keep the flag until both
198 // truncation and its durable flush succeed, so repeated I/O faults retry.
199 fn repair_if_needed(&mut self) -> Result<(), LinkError> {
200 if self.tail_may_be_torn {
201 let repair = OpenOptions::new().read(true).write(true).open(&self.path)?;
202 truncate_torn_tail(&repair)?;
203 // A previous failed repair may already have changed the length.
204 repair.sync_all()?;
205 // A failed compaction may have left the writer on a replaced file.
206 self.file = OpenOptions::new()
207 .read(true)
208 .append(true)
209 .open(&self.path)?;
210 self.tail_may_be_torn = false;
211 }
212 Ok(())
213 }
214
215 /// Path of the backing file.
216 pub fn path(&self) -> &Path {
217 &self.path
218 }
219
220 /// Whether every append is `fsync`ed. Enabled by default.
221 pub fn sync_on_append(&self) -> bool {
222 self.sync_on_append
223 }
224
225 /// Turns per-append `fsync` on or off — see the durability notes.
226 pub fn set_sync_on_append(&mut self, value: bool) {
227 self.sync_on_append = value;
228 }
229}
230
231impl TransitionLogStore for FileTransitionLog {
232 fn supports_durable_flush(&self) -> bool {
233 true
234 }
235 fn supports_compaction(&self) -> bool {
236 true
237 }
238 fn compact_log_entries(&mut self, entries: &[String]) -> Result<(), LinkError> {
239 if entries
240 .iter()
241 .any(|entry| entry.is_empty() || entry.contains(['\n', '\r', '\0']))
242 {
243 return Err(LinkError::InvalidFormat(
244 "transition log entries must be non-empty single lines without NUL".to_string(),
245 ));
246 }
247 self.repair_if_needed()?;
248 let temporary = compaction_path(&self.path);
249 let mut contents = String::with_capacity(entries.iter().map(|e| e.len() + 1).sum());
250 for entry in entries {
251 contents.push_str(entry);
252 contents.push('\n');
253 }
254 let written = (|| -> Result<File, LinkError> {
255 let mut file = OpenOptions::new()
256 .write(true)
257 .create(true)
258 .truncate(true)
259 .open(&temporary)?;
260 file.write_all(contents.as_bytes())?;
261 file.sync_all()?;
262 Ok(file)
263 })();
264 let file = match written {
265 Ok(file) => file,
266 Err(error) => {
267 let _ = std::fs::remove_file(&temporary);
268 return Err(error);
269 }
270 };
271 // Release the old handle first: Windows refuses to replace a file
272 // that is still open. The rename publishes either the whole new
273 // journal or nothing; both leave a complete journal behind.
274 // Until the append handle is reopened, repair reopens it first.
275 self.file = file;
276 self.tail_may_be_torn = true;
277 if let Err(error) = std::fs::rename(&temporary, &self.path) {
278 let _ = std::fs::remove_file(&temporary);
279 return Err(error.into());
280 }
281 sync_parent_directory(&self.path)?;
282 self.repair_if_needed()
283 }
284
285 fn append_log_entry(&mut self, entry: &str) -> Result<(), LinkError> {
286 if entry.contains(['\n', '\r', '\0']) {
287 return Err(LinkError::InvalidFormat(
288 "transition log entries must not contain line breaks or NUL".to_string(),
289 ));
290 }
291 self.repair_if_needed()?;
292 self.tail_may_be_torn = true;
293 writeln!(self.file, "{entry}")?;
294 self.file.flush()?;
295 if self.sync_on_append {
296 self.file.sync_data()?;
297 }
298 self.tail_may_be_torn = false;
299 Ok(())
300 }
301
302 fn read_log_entries(&mut self) -> Result<Vec<String>, LinkError> {
303 self.repair_if_needed()?;
304 let mut contents = String::new();
305 File::open(&self.path)?.read_to_string(&mut contents)?;
306 // Only newline-terminated lines were fully written; a trailing
307 // fragment is the torn tail of a crashed append.
308 Ok(contents
309 .lines()
310 .take(contents.matches('\n').count())
311 .filter(|line| !line.is_empty())
312 .map(|line| line.to_string())
313 .collect())
314 }
315
316 fn flush_log(&mut self) -> Result<(), LinkError> {
317 self.repair_if_needed()?;
318 self.tail_may_be_torn = true;
319 self.file.flush()?;
320 self.file.sync_data()?;
321 self.tail_may_be_torn = false;
322 Ok(())
323 }
324}
325
326impl ReplaceableTransitionLogStore for FileTransitionLog {
327 fn replace_log_entries(&mut self, entries: &[String]) -> Result<bool, LinkError> {
328 if self.read_log_entries()? == entries {
329 return Ok(false);
330 }
331 self.compact_log_entries(entries)?;
332 Ok(true)
333 }
334}
335
336/// Temporary file a compaction writes before renaming it over the log.
337fn compaction_path(path: &Path) -> PathBuf {
338 let mut name = path.as_os_str().to_os_string();
339 name.push(".compact");
340 PathBuf::from(name)
341}
342
343/// Makes a created or renamed directory entry durable (no-op off Unix,
344/// where directories cannot be opened for syncing).
345fn sync_parent_directory(path: &Path) -> Result<(), LinkError> {
346 #[cfg(unix)]
347 File::open(
348 path.parent()
349 .filter(|p| !p.as_os_str().is_empty())
350 .unwrap_or(Path::new(".")),
351 )?
352 .sync_all()?;
353 #[cfg(not(unix))]
354 let _ = path;
355 Ok(())
356}
357
358/// Shrinks `file` to its last complete (newline-terminated) line that holds no
359/// NUL byte.
360///
361/// A crash can leave the log ending in a fragment of an entry. Appending
362/// after that fragment would concatenate the next entry onto it, turning
363/// one lost transition into two, so the fragment is dropped when the log
364/// is opened or its live writer recovers from an I/O error.
365///
366/// Power loss can also keep the newline of an entry that was never flushed
367/// while a sector before it was never written: a disk may reorder writes no
368/// flush ordered, and an unwritten sector reads back as zeros. Entries never
369/// contain NUL (appends refuse it), so trailing lines holding one are torn
370/// as well, as etcd's WAL treats a last record with a zeroed sector. A NUL
371/// before an intact line is damage; opening refuses it and repair decides.
372fn truncate_torn_tail(file: &File) -> Result<(), LinkError> {
373 let len = file.metadata()?.len();
374 if len == 0 {
375 return Ok(());
376 }
377 let mut file = file;
378 let mut end = len;
379 // End of the line being scanned, just past its newline; None while still
380 // in the fragment after the last newline. Blank lines are skipped, as
381 // reading skips them.
382 let mut complete: Option<u64> = None;
383 let mut newer_newline = len;
384 let mut zeroed = false;
385 let mut buffer = [0u8; 8192];
386 let keep = 'scan: loop {
387 if end == 0 {
388 // The first line of the file is reached.
389 break 'scan if zeroed { 0 } else { complete.unwrap_or(0) };
390 }
391 let chunk = std::cmp::min(end, buffer.len() as u64);
392 let start = end - chunk;
393 file.seek(SeekFrom::Start(start))?;
394 let slice = &mut buffer[..chunk as usize];
395 file.read_exact(slice)?;
396 for (offset, byte) in slice.iter().enumerate().rev() {
397 let position = start + offset as u64;
398 match (*byte, complete) {
399 (b'\n', None) => complete = Some(position + 1),
400 (b'\n', Some(_)) if newer_newline == position + 1 => {}
401 (b'\n', Some(line_end)) => {
402 if !zeroed {
403 break 'scan line_end;
404 }
405 complete = Some(position + 1);
406 zeroed = false;
407 }
408 (0, Some(_)) => zeroed = true,
409 _ => {}
410 }
411 if *byte == b'\n' {
412 newer_newline = position;
413 }
414 }
415 end = start;
416 };
417 if keep != len {
418 file.set_len(keep)?;
419 file.sync_all()?;
420 }
421 Ok(())
422}