link-cli 3.0.0

A CLI tool and reusable library for links manipulation backed by a LiNo-notation doublet storage engine.
Documentation
//! 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
    }
}

/// 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.
///
/// # 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)?;
            }
        }
        // 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)?;
        #[cfg(unix)]
        File::open(
            path.parent()
                .filter(|p| !p.as_os_str().is_empty())
                .unwrap_or(Path::new(".")),
        )?
        .sync_all()?;
        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()?;
            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 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(())
    }
}

/// 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(())
}