Skip to main content

link_cli/transactions/
journal_file.rs

1//! The append-only journal file `clink` keeps next to its database
2//! (issue #195), and the one-time import of the older links-backed journal.
3//!
4//! Older versions stored each journal entry as the name of a fresh link in
5//! `<db>.transitions.links` (plus `<db>.transitions.names.links`). Every
6//! invocation re-read that whole store and rewrote it on save, so each write
7//! got slower as the history grew. The journal is now a plain text file,
8//! `<db>.transitions.log`, that a write appends to.
9//!
10//! Opening the journal imports a legacy store once: its entries are written
11//! to a temporary file that is synced and renamed into place before the
12//! legacy files are removed, so a crash leaves either the legacy store or a
13//! complete journal. An explicit `--transactions-file` that still holds a
14//! links store is converted in place the same way.
15
16use std::fs::{File, OpenOptions};
17use std::io::{Read, Write};
18use std::path::{Path, PathBuf};
19
20use crate::error::LinkError;
21use crate::named_types::NamedTypesDecorator;
22
23use super::log::{FileTransitionLog, TransitionLogStore};
24
25/// Every journal entry starts with this, so a journal file does too.
26const ENTRY_PREFIX: &[u8] = b"__transactions:";
27
28/// Conventional journal path: `<stem>.transitions.log` next to `database`.
29pub fn make_transitions_log_filename<P: AsRef<Path>>(database_filename: P) -> PathBuf {
30    sibling(database_filename.as_ref(), "transitions.log")
31}
32
33/// Path of the links-backed journal older versions kept:
34/// `<stem>.transitions.links`.
35pub fn make_legacy_transitions_filename<P: AsRef<Path>>(database_filename: P) -> PathBuf {
36    sibling(database_filename.as_ref(), "transitions.links")
37}
38
39fn sibling(path: &Path, suffix: &str) -> PathBuf {
40    let stem = path
41        .file_stem()
42        .and_then(|s| s.to_str())
43        .unwrap_or_default();
44    let name = format!("{stem}.{suffix}");
45    match path.parent() {
46        Some(parent) if !parent.as_os_str().is_empty() => parent.join(name),
47        _ => PathBuf::from(name),
48    }
49}
50
51/// Opens the journal of `database`: `explicit` when given, the conventional
52/// `<stem>.transitions.log` otherwise, importing a legacy links-backed
53/// journal first (see the module documentation).
54pub fn open_transitions_journal(
55    database: &Path,
56    explicit: Option<&Path>,
57    trace: bool,
58) -> Result<FileTransitionLog, LinkError> {
59    let path = match explicit {
60        Some(path) => {
61            if is_links_journal(path)? {
62                import_links_journal(path, path, trace)?;
63            }
64            path.to_path_buf()
65        }
66        None => {
67            let path = make_transitions_log_filename(database);
68            let legacy = make_legacy_transitions_filename(database);
69            if legacy.exists() {
70                import_links_journal(&legacy, &path, trace)?;
71            }
72            path
73        }
74    };
75    FileTransitionLog::open(path)
76}
77
78/// Whether `path` holds something other than a text journal: a non-empty
79/// file whose first bytes are not (a prefix of) the journal entry prefix.
80pub fn is_links_journal(path: &Path) -> Result<bool, LinkError> {
81    let mut head = Vec::with_capacity(ENTRY_PREFIX.len());
82    match File::open(path) {
83        Ok(file) => {
84            file.take(ENTRY_PREFIX.len() as u64)
85                .read_to_end(&mut head)?;
86        }
87        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
88        Err(error) => return Err(error.into()),
89    }
90    Ok(!head.is_empty() && !ENTRY_PREFIX.starts_with(&head))
91}
92
93/// Copies every entry of the links-backed journal at `legacy` into the text
94/// journal at `target`, then removes the legacy store. Returns whether
95/// anything was imported.
96///
97/// When `target` already exists (a crash after publishing it), the legacy
98/// store is removed only if each of its entries is already in `target`.
99pub fn import_links_journal(legacy: &Path, target: &Path, trace: bool) -> Result<bool, LinkError> {
100    let names = NamedTypesDecorator::make_names_database_filename(legacy);
101    let entries = {
102        let mut store = NamedTypesDecorator::with_names_database_path(legacy, &names, false)
103            .map_err(|error| LinkError::StorageError(format!("{error:#}")))?
104            .with_indexed_lookups();
105        store.read_log_entries()?
106    };
107    let in_place = legacy == target;
108    if !in_place && target.exists() {
109        let mut existing = FileTransitionLog::open(target)?;
110        let present: std::collections::HashSet<String> =
111            existing.read_log_entries()?.into_iter().collect();
112        if entries.iter().all(|entry| present.contains(entry)) {
113            remove_legacy(legacy, &names)?;
114        } else if trace {
115            crate::diagnostics::stderr!(
116                "[Transactions] Kept legacy journal {}: {} already exists.",
117                legacy.display(),
118                target.display()
119            );
120        }
121        return Ok(false);
122    }
123    let mut temporary = target.as_os_str().to_os_string();
124    temporary.push(".import");
125    let temporary = PathBuf::from(temporary);
126    {
127        let mut file = OpenOptions::new()
128            .write(true)
129            .create(true)
130            .truncate(true)
131            .open(&temporary)?;
132        for entry in &entries {
133            writeln!(file, "{entry}")?;
134        }
135        file.sync_all()?;
136    }
137    std::fs::rename(&temporary, target)?;
138    if !in_place {
139        remove_legacy(legacy, &names)?;
140    } else {
141        remove_if_exists(&names)?;
142    }
143    FileTransitionLog::open(target)?; // syncs the directory entries
144    if trace {
145        crate::diagnostics::stderr!(
146            "[Transactions] Imported {} entries from legacy journal {} into {}.",
147            entries.len(),
148            legacy.display(),
149            target.display()
150        );
151    }
152    Ok(true)
153}
154
155fn remove_legacy(legacy: &Path, names: &Path) -> Result<(), LinkError> {
156    remove_if_exists(legacy)?;
157    remove_if_exists(names)
158}
159
160fn remove_if_exists(path: &Path) -> Result<(), LinkError> {
161    match std::fs::remove_file(path) {
162        Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error.into()),
163        _ => Ok(()),
164    }
165}