link-cli 3.2.1

A CLI tool and reusable library for links manipulation backed by a LiNo-notation doublet storage engine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! Storage backends for the transitions log.
//!
//! The transactions layer only needs three things from its log: append
//! one entry, read every entry back in write order, and make what has
//! been appended durable. [`TransitionLogStore`] captures exactly that,
//! so a consumer can plug in whichever log it already has.
//!
//! Two implementations ship with the library:
//!
//! * [`NamedTypesDecorator`] — the original sidecar *links* log, where
//!   each entry is the name of a freshly created link. Keeps the log in
//!   the same format the C# port uses.
//! * [`FileTransitionLog`] — a plain append-only text file, one entry
//!   per line, `fsync`ed on every append by default. Cheaper than a
//!   links database. An incomplete final line, or trailing lines with a
//!   NUL byte that power loss left, is discarded on open or before reusing
//!   a writer after an I/O error.
//!
//! Reading takes `&mut self` because the links-backed log resolves
//! names through [`NamedTypes::get_name`], which needs mutable access
//! to its own caches.

use std::fs::{File, OpenOptions};
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};

use crate::error::LinkError;
use crate::named_types::{NamedTypes, NamedTypesDecorator};

/// Append-only store of serialized transitions and recovery markers.
pub trait TransitionLogStore {
    /// Appends one entry. Entries never contain newlines.
    fn append_log_entry(&mut self, entry: &str) -> Result<(), LinkError>;

    /// Reads every entry back, oldest first.
    fn read_log_entries(&mut self) -> Result<Vec<String>, LinkError>;

    /// Makes every appended entry durable.
    fn flush_log(&mut self) -> Result<(), LinkError>;

    /// Whether flush requests persistent storage. Custom/volatile logs default
    /// to false; this describes an adapter, not the reliability of its hardware.
    fn supports_durable_flush(&self) -> bool {
        false
    }

    /// Whether [`compact_log_entries`](Self::compact_log_entries) can rewrite
    /// the durable journal. Retention uses it to bound the journal on disk;
    /// logs without it keep every entry, as before.
    fn supports_compaction(&self) -> bool {
        false
    }

    /// Atomically and durably replaces every entry with `entries`, the
    /// retained journal. After a crash the log holds either the old or the
    /// new journal, never a mixture. Called only between transactions and
    /// only when [`supports_compaction`](Self::supports_compaction) is true.
    fn compact_log_entries(&mut self, entries: &[String]) -> Result<(), LinkError> {
        let _ = entries;
        Err(LinkError::StorageError(
            "this transitions log does not support compaction".into(),
        ))
    }
}

/// Optional replacement of a complete ordered journal under the same exclusive
/// owner. Success publishes all records atomically and durably when advertised.
/// An uncertain failure fences the implementation until actual reopening.
pub trait ReplaceableTransitionLogStore: TransitionLogStore {
    /// Dynamic adapters can expose the capability only when their inner log can.
    fn supports_replacement(&self) -> bool {
        true
    }
    /// Returns false when an identical committed journal needs no replacement.
    /// Pending unflushed records must be rejected before changing durable state.
    fn replace_log_entries(&mut self, entries: &[String]) -> Result<bool, LinkError>;
}

fn storage_error(error: anyhow::Error) -> LinkError {
    LinkError::StorageError(format!("{error:#}"))
}

impl TransitionLogStore for NamedTypesDecorator {
    fn supports_durable_flush(&self) -> bool {
        !self.links().database_path().as_os_str().is_empty()
    }
    fn append_log_entry(&mut self, entry: &str) -> Result<(), LinkError> {
        // Always allocate a fresh link so entries never overwrite one
        // another (mirrors C# `CreateAndUpdate(Null, Null)`).
        let link = self.create(0, 0);
        self.set_name(link, entry).map_err(storage_error)?;
        Ok(())
    }

    fn read_log_entries(&mut self) -> Result<Vec<String>, LinkError> {
        let mut addresses: Vec<u32> = self.all().into_iter().map(|link| link.index).collect();
        addresses.sort_unstable();
        let mut entries = Vec::with_capacity(addresses.len());
        for address in addresses {
            if let Some(name) = NamedTypes::get_name(self, address).map_err(storage_error)? {
                entries.push(name);
            }
        }
        Ok(entries)
    }

    fn flush_log(&mut self) -> Result<(), LinkError> {
        crate::LinksStorage::flush(self)
    }
}

/// Append-only, line-oriented transitions log backed by a single file.
///
/// Appending costs one write and one `fsync` regardless of how many
/// entries the log already holds. Retention policies compact it through
/// [`compact_log_entries`](TransitionLogStore::compact_log_entries), which
/// writes the retained entries to `<path>.compact`, syncs it and renames it
/// over the log, so the journal on disk stays bounded (issue #195).
///
/// # Durability
///
/// With `sync_on_append` enabled (the default) every
/// [`append_log_entry`](TransitionLogStore::append_log_entry) returns
/// only after the entry has reached stable storage, which is what makes
/// the write-ahead ordering of the transactions layer meaningful: a
/// transition is always durable before the data-store write it
/// describes is reported as committed. Disabling it trades that
/// guarantee for throughput — the log is then durable only as far as
/// the last [`flush_log`](TransitionLogStore::flush_log).
///
/// An interrupted append can leave a partial final line. Opening the log,
/// or reading, appending or flushing after a writer I/O error, repairs that
/// suffix before proceeding. A failed repair is retried on the next operation.
/// Complete records remain intact, including records written before an error
/// was returned; callers must discover an uncertain transaction's outcome
/// rather than blindly retry it. Repair scans backwards with an 8 KiB buffer;
/// successful operations do not rescan. This framing protocol assumes storage
/// honors flush and does not prove device-sector atomicity after power loss.
#[derive(Debug)]
pub struct FileTransitionLog {
    path: PathBuf,
    file: File,
    sync_on_append: bool,
    tail_may_be_torn: bool,
    _lock: Option<crate::FileLock>,
}

impl FileTransitionLog {
    /// Opens (creating if needed) the log at `path`, discarding a
    /// trailing entry left half-written by a crash.
    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, LinkError> {
        let path = path.as_ref().to_path_buf();
        if let Some(parent) = path.parent() {
            if !parent.as_os_str().is_empty() && !parent.exists() {
                std::fs::create_dir_all(parent)?;
            }
        }
        // A compaction interrupted before its rename leaves only a stale
        // copy; the log itself still holds the complete previous journal.
        match std::fs::remove_file(compaction_path(&path)) {
            Err(error) if error.kind() != std::io::ErrorKind::NotFound => return Err(error.into()),
            _ => {}
        }
        // The torn tail is trimmed through a dedicated read/write handle:
        // Windows grants an append-only handle `FILE_APPEND_DATA` without
        // `FILE_WRITE_DATA`, so `set_len` on it fails with `ERROR_ACCESS_DENIED`.
        let repair = OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(false)
            .open(&path)?;
        truncate_torn_tail(&repair)?;
        drop(repair);
        let file = OpenOptions::new().read(true).append(true).open(&path)?;
        sync_parent_directory(&path)?;
        Ok(Self {
            path,
            file,
            sync_on_append: true,
            tail_may_be_torn: false,
            _lock: None,
        })
    }

    /// Holds the conventional sidecar lock until drop. Contention fails fast;
    /// all writers must follow the same advisory locking convention.
    pub fn open_exclusive<P: AsRef<Path>>(path: P) -> Result<Self, LinkError> {
        let lock =
            crate::FileLock::try_acquire(crate::lock_file_path(&path), crate::LockMode::Exclusive)?
                .ok_or_else(|| LinkError::Lock("journal writer is busy".into()))?;
        let mut log = Self::open(path)?;
        log._lock = Some(lock);
        Ok(log)
    }

    // An error may follow successful short writes. Keep the flag until both
    // truncation and its durable flush succeed, so repeated I/O faults retry.
    fn repair_if_needed(&mut self) -> Result<(), LinkError> {
        if self.tail_may_be_torn {
            let repair = OpenOptions::new().read(true).write(true).open(&self.path)?;
            truncate_torn_tail(&repair)?;
            // A previous failed repair may already have changed the length.
            repair.sync_all()?;
            // A failed compaction may have left the writer on a replaced file.
            self.file = OpenOptions::new()
                .read(true)
                .append(true)
                .open(&self.path)?;
            self.tail_may_be_torn = false;
        }
        Ok(())
    }

    /// Path of the backing file.
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Whether every append is `fsync`ed. Enabled by default.
    pub fn sync_on_append(&self) -> bool {
        self.sync_on_append
    }

    /// Turns per-append `fsync` on or off — see the durability notes.
    pub fn set_sync_on_append(&mut self, value: bool) {
        self.sync_on_append = value;
    }
}

impl TransitionLogStore for FileTransitionLog {
    fn supports_durable_flush(&self) -> bool {
        true
    }
    fn supports_compaction(&self) -> bool {
        true
    }
    fn compact_log_entries(&mut self, entries: &[String]) -> Result<(), LinkError> {
        if entries
            .iter()
            .any(|entry| entry.is_empty() || entry.contains(['\n', '\r', '\0']))
        {
            return Err(LinkError::InvalidFormat(
                "transition log entries must be non-empty single lines without NUL".to_string(),
            ));
        }
        self.repair_if_needed()?;
        let temporary = compaction_path(&self.path);
        let mut contents = String::with_capacity(entries.iter().map(|e| e.len() + 1).sum());
        for entry in entries {
            contents.push_str(entry);
            contents.push('\n');
        }
        let written = (|| -> Result<File, LinkError> {
            let mut file = OpenOptions::new()
                .write(true)
                .create(true)
                .truncate(true)
                .open(&temporary)?;
            file.write_all(contents.as_bytes())?;
            file.sync_all()?;
            Ok(file)
        })();
        let file = match written {
            Ok(file) => file,
            Err(error) => {
                let _ = std::fs::remove_file(&temporary);
                return Err(error);
            }
        };
        // Release the old handle first: Windows refuses to replace a file
        // that is still open. The rename publishes either the whole new
        // journal or nothing; both leave a complete journal behind.
        // Until the append handle is reopened, repair reopens it first.
        self.file = file;
        self.tail_may_be_torn = true;
        if let Err(error) = std::fs::rename(&temporary, &self.path) {
            let _ = std::fs::remove_file(&temporary);
            return Err(error.into());
        }
        sync_parent_directory(&self.path)?;
        self.repair_if_needed()
    }

    fn append_log_entry(&mut self, entry: &str) -> Result<(), LinkError> {
        if entry.contains(['\n', '\r', '\0']) {
            return Err(LinkError::InvalidFormat(
                "transition log entries must not contain line breaks or NUL".to_string(),
            ));
        }
        self.repair_if_needed()?;
        self.tail_may_be_torn = true;
        writeln!(self.file, "{entry}")?;
        self.file.flush()?;
        if self.sync_on_append {
            self.file.sync_data()?;
        }
        self.tail_may_be_torn = false;
        Ok(())
    }

    fn read_log_entries(&mut self) -> Result<Vec<String>, LinkError> {
        self.repair_if_needed()?;
        let mut contents = String::new();
        File::open(&self.path)?.read_to_string(&mut contents)?;
        // Only newline-terminated lines were fully written; a trailing
        // fragment is the torn tail of a crashed append.
        Ok(contents
            .lines()
            .take(contents.matches('\n').count())
            .filter(|line| !line.is_empty())
            .map(|line| line.to_string())
            .collect())
    }

    fn flush_log(&mut self) -> Result<(), LinkError> {
        self.repair_if_needed()?;
        self.tail_may_be_torn = true;
        self.file.flush()?;
        self.file.sync_data()?;
        self.tail_may_be_torn = false;
        Ok(())
    }
}

impl ReplaceableTransitionLogStore for FileTransitionLog {
    fn replace_log_entries(&mut self, entries: &[String]) -> Result<bool, LinkError> {
        if self.read_log_entries()? == entries {
            return Ok(false);
        }
        self.compact_log_entries(entries)?;
        Ok(true)
    }
}

/// Temporary file a compaction writes before renaming it over the log.
fn compaction_path(path: &Path) -> PathBuf {
    let mut name = path.as_os_str().to_os_string();
    name.push(".compact");
    PathBuf::from(name)
}

/// Makes a created or renamed directory entry durable (no-op off Unix,
/// where directories cannot be opened for syncing).
fn sync_parent_directory(path: &Path) -> Result<(), LinkError> {
    #[cfg(unix)]
    File::open(
        path.parent()
            .filter(|p| !p.as_os_str().is_empty())
            .unwrap_or(Path::new(".")),
    )?
    .sync_all()?;
    #[cfg(not(unix))]
    let _ = path;
    Ok(())
}

/// Shrinks `file` to its last complete (newline-terminated) line that holds no
/// NUL byte.
///
/// A crash can leave the log ending in a fragment of an entry. Appending
/// after that fragment would concatenate the next entry onto it, turning
/// one lost transition into two, so the fragment is dropped when the log
/// is opened or its live writer recovers from an I/O error.
///
/// Power loss can also keep the newline of an entry that was never flushed
/// while a sector before it was never written: a disk may reorder writes no
/// flush ordered, and an unwritten sector reads back as zeros. Entries never
/// contain NUL (appends refuse it), so trailing lines holding one are torn
/// as well, as etcd's WAL treats a last record with a zeroed sector. A NUL
/// before an intact line is damage; opening refuses it and repair decides.
fn truncate_torn_tail(file: &File) -> Result<(), LinkError> {
    let len = file.metadata()?.len();
    if len == 0 {
        return Ok(());
    }
    let mut file = file;
    let mut end = len;
    // End of the line being scanned, just past its newline; None while still
    // in the fragment after the last newline. Blank lines are skipped, as
    // reading skips them.
    let mut complete: Option<u64> = None;
    let mut newer_newline = len;
    let mut zeroed = false;
    let mut buffer = [0u8; 8192];
    let keep = 'scan: loop {
        if end == 0 {
            // The first line of the file is reached.
            break 'scan if zeroed { 0 } else { complete.unwrap_or(0) };
        }
        let chunk = std::cmp::min(end, buffer.len() as u64);
        let start = end - chunk;
        file.seek(SeekFrom::Start(start))?;
        let slice = &mut buffer[..chunk as usize];
        file.read_exact(slice)?;
        for (offset, byte) in slice.iter().enumerate().rev() {
            let position = start + offset as u64;
            match (*byte, complete) {
                (b'\n', None) => complete = Some(position + 1),
                (b'\n', Some(_)) if newer_newline == position + 1 => {}
                (b'\n', Some(line_end)) => {
                    if !zeroed {
                        break 'scan line_end;
                    }
                    complete = Some(position + 1);
                    zeroed = false;
                }
                (0, Some(_)) => zeroed = true,
                _ => {}
            }
            if *byte == b'\n' {
                newer_newline = position;
            }
        }
        end = start;
    };
    if keep != len {
        file.set_len(keep)?;
        file.sync_all()?;
    }
    Ok(())
}