Skip to main content

link_cli/engine/
recovery.rs

1//! Check and repair a damaged engine journal. `Engine::open` refuses a journal
2//! with any bad record; these functions apply the same rules to report the
3//! longest prefix that still replays, and to rebuild a journal from it or from
4//! an intact copy. See `docs/ENGINE-RECOVERY.md` for what each step can and
5//! cannot get back.
6use super::{EngineOptions, State};
7use crate::LinkError;
8use doublets::data::LinkReference;
9
10/// The first record that does not replay, and why.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct JournalDamage {
13    /// Zero-based index of the record.
14    pub record: usize,
15    pub reason: String,
16}
17
18/// What `Engine::open` would make of a journal.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct JournalCheck {
21    /// Records that replay, counted from the first. They form the valid prefix.
22    pub valid_records: usize,
23    pub total_records: usize,
24    /// Revision after the valid prefix; zero when nothing replays.
25    pub revision: u64,
26    /// `None` when every record replays.
27    pub damage: Option<JournalDamage>,
28}
29
30impl JournalCheck {
31    pub fn is_intact(&self) -> bool {
32        self.damage.is_none()
33    }
34    /// Records after the valid prefix that a repair from this copy drops.
35    pub fn discarded_records(&self) -> usize {
36        self.total_records - self.valid_records
37    }
38}
39
40/// Replay `entries` with the checksum, format, revision, allocator and
41/// selected constraint rules of `Engine::open`. Never fails: damage is part of
42/// the report. Costs the same O(N) replay as opening, without a log.
43pub fn check_journal<T: LinkReference>(
44    entries: &[String],
45    options: &EngineOptions,
46) -> JournalCheck {
47    let mut state = State::<T, ()>::empty((), options.clone());
48    for (index, entry) in entries.iter().enumerate() {
49        if let Err(error) = state.replay(index, entry) {
50            return JournalCheck {
51                valid_records: index,
52                total_records: entries.len(),
53                revision: state.current.revision,
54                damage: Some(JournalDamage {
55                    record: index,
56                    reason: error.to_string(),
57                }),
58            };
59        }
60    }
61    JournalCheck {
62        valid_records: entries.len(),
63        total_records: entries.len(),
64        revision: state.current.revision,
65        damage: None,
66    }
67}
68
69/// The journal a repair keeps, and where it came from.
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct JournalRecovery {
72    /// The longest valid prefix among the copies.
73    pub entries: Vec<String>,
74    /// Index of the copy that supplied `entries`; the first wins a tie.
75    pub source: usize,
76    /// Revision after `entries`.
77    pub revision: u64,
78    /// One check per copy, in the order given.
79    pub checks: Vec<JournalCheck>,
80}
81
82/// Pick the longest valid prefix among copies of one journal: the damaged
83/// primary first, then replicas, mirrors or a restored backup. Every other
84/// copy's valid prefix must be a prefix of the chosen one. Copies that disagree
85/// are refused rather than guessed between, because each may hold commits the
86/// other lacks; choose one explicitly. A copy compacted into an engine3
87/// checkpoint disagrees with an uncompacted copy of the same history.
88pub fn recover_journal<T: LinkReference>(
89    copies: &[Vec<String>],
90    options: &EngineOptions,
91) -> Result<JournalRecovery, LinkError> {
92    if copies.is_empty() {
93        return Err(LinkError::Transaction(
94            "journal recovery needs at least one copy".into(),
95        ));
96    }
97    let checks = copies
98        .iter()
99        .map(|copy| check_journal::<T>(copy, options))
100        .collect::<Vec<_>>();
101    let mut source = 0;
102    for (index, check) in checks.iter().enumerate() {
103        if check.valid_records > checks[source].valid_records {
104            source = index;
105        }
106    }
107    let chosen = &copies[source][..checks[source].valid_records];
108    for (index, check) in checks.iter().enumerate() {
109        if copies[index][..check.valid_records] != chosen[..check.valid_records] {
110            return Err(LinkError::Transaction(format!(
111                "journal copies {source} and {index} diverge; choose one explicitly"
112            )));
113        }
114    }
115    Ok(JournalRecovery {
116        entries: chosen.to_vec(),
117        source,
118        revision: checks[source].revision,
119        checks,
120    })
121}
122
123#[cfg(not(target_arch = "wasm32"))]
124pub use file::{read_journal_file_lossy, repair_journal_file, JournalRepair};
125
126#[cfg(not(target_arch = "wasm32"))]
127mod file {
128    use super::{recover_journal, JournalRecovery};
129    use crate::engine::EngineOptions;
130    use crate::LinkError;
131    use doublets::data::LinkReference;
132    use std::fs::{File, OpenOptions};
133    use std::io::{ErrorKind, Read, Write};
134    use std::path::{Path, PathBuf};
135
136    /// Complete lines of a file journal, in the form `FileTransitionLog` reads
137    /// them, but tolerating damage it would reject: invalid UTF-8 becomes U+FFFD
138    /// (so the checksum flags that record) and a missing file is empty.
139    pub fn read_journal_file_lossy(path: &Path) -> Result<Vec<String>, LinkError> {
140        Ok(lines(&read_bytes(path)?))
141    }
142
143    fn read_bytes(path: &Path) -> Result<Vec<u8>, LinkError> {
144        let mut bytes = Vec::new();
145        match File::open(path) {
146            Ok(mut file) => {
147                file.read_to_end(&mut bytes)?;
148            }
149            Err(error) if error.kind() == ErrorKind::NotFound => {}
150            Err(error) => return Err(error.into()),
151        }
152        Ok(bytes)
153    }
154
155    fn lines(bytes: &[u8]) -> Vec<String> {
156        let complete = bytes
157            .iter()
158            .rposition(|byte| *byte == b'\n')
159            .map_or(0, |end| end + 1);
160        let mut lines: Vec<&[u8]> = bytes[..complete]
161            .split(|byte| *byte == b'\n')
162            .filter(|line| !line.is_empty())
163            .collect();
164        // Trailing lines with a NUL byte are torn by power loss, as
165        // `FileTransitionLog` drops them; one further back is damage.
166        while lines.last().is_some_and(|line| line.contains(&0)) {
167            lines.pop();
168        }
169        lines
170            .into_iter()
171            .map(|line| String::from_utf8_lossy(line).into_owned())
172            .collect()
173    }
174
175    /// Outcome of `repair_journal_file`.
176    #[derive(Debug, Clone, PartialEq, Eq)]
177    pub struct JournalRepair {
178        pub recovery: JournalRecovery,
179        /// False when the file already held exactly the recovered journal.
180        pub changed: bool,
181        /// Where the original bytes were kept before the file was replaced.
182        pub preserved: Option<PathBuf>,
183    }
184
185    /// Rebuild the journal at `path` from the longest valid prefix among it and
186    /// `copies` (see `recover_journal`). The original bytes are first copied to
187    /// `<path>.damaged-<n>`; the replacement is flushed, then renamed over
188    /// `path`. Holds the writer lock that `FileTransitionLog::open_exclusive`
189    /// takes, so it fails while an engine owns the journal. Copies are only
190    /// read; their owners must not be writing them.
191    pub fn repair_journal_file<T: LinkReference>(
192        path: &Path,
193        copies: &[&Path],
194        options: &EngineOptions,
195    ) -> Result<JournalRepair, LinkError> {
196        let _lock =
197            crate::FileLock::try_acquire(crate::lock_file_path(path), crate::LockMode::Exclusive)?
198                .ok_or_else(|| LinkError::Lock("journal writer is busy".into()))?;
199        let original = read_bytes(path)?;
200        let mut sources = vec![lines(&original)];
201        for copy in copies {
202            sources.push(read_journal_file_lossy(copy)?);
203        }
204        let recovery = recover_journal::<T>(&sources, options)?;
205        let mut repaired = Vec::new();
206        for entry in &recovery.entries {
207            repaired.extend_from_slice(entry.as_bytes());
208            repaired.push(b'\n');
209        }
210        if repaired == original {
211            return Ok(JournalRepair {
212                recovery,
213                changed: false,
214                preserved: None,
215            });
216        }
217        let preserved = if original.is_empty() {
218            None
219        } else {
220            Some(preserve(path, &original)?)
221        };
222        let temporary = sibling(path, ".repair");
223        {
224            let mut file = OpenOptions::new()
225                .write(true)
226                .create(true)
227                .truncate(true)
228                .open(&temporary)?;
229            file.write_all(&repaired)?;
230            file.sync_all()?;
231        }
232        std::fs::rename(&temporary, path)?;
233        sync_directory(path)?;
234        Ok(JournalRepair {
235            recovery,
236            changed: true,
237            preserved,
238        })
239    }
240
241    fn sibling(path: &Path, suffix: &str) -> PathBuf {
242        let mut name = path.as_os_str().to_owned();
243        name.push(suffix);
244        PathBuf::from(name)
245    }
246
247    /// Claim the first free `<path>.damaged-<n>` so no earlier evidence is lost.
248    fn preserve(path: &Path, bytes: &[u8]) -> Result<PathBuf, LinkError> {
249        for attempt in 1u32.. {
250            let target = sibling(path, &format!(".damaged-{attempt}"));
251            match OpenOptions::new()
252                .write(true)
253                .create_new(true)
254                .open(&target)
255            {
256                Ok(mut file) => {
257                    file.write_all(bytes)?;
258                    file.sync_all()?;
259                    return Ok(target);
260                }
261                Err(error) if error.kind() == ErrorKind::AlreadyExists => continue,
262                Err(error) => return Err(error.into()),
263            }
264        }
265        unreachable!("u32 attempts exhausted")
266    }
267
268    #[cfg(unix)]
269    fn sync_directory(path: &Path) -> Result<(), LinkError> {
270        let parent = path
271            .parent()
272            .filter(|parent| !parent.as_os_str().is_empty())
273            .unwrap_or(Path::new("."));
274        File::open(parent)?.sync_all()?;
275        Ok(())
276    }
277
278    #[cfg(not(unix))]
279    fn sync_directory(_: &Path) -> Result<(), LinkError> {
280        Ok(())
281    }
282}