1use super::{EngineOptions, State};
7use crate::LinkError;
8use doublets::data::LinkReference;
9
10#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct JournalDamage {
13 pub record: usize,
15 pub reason: String,
16}
17
18#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct JournalCheck {
21 pub valid_records: usize,
23 pub total_records: usize,
24 pub revision: u64,
26 pub damage: Option<JournalDamage>,
28}
29
30impl JournalCheck {
31 pub fn is_intact(&self) -> bool {
32 self.damage.is_none()
33 }
34 pub fn discarded_records(&self) -> usize {
36 self.total_records - self.valid_records
37 }
38}
39
40pub 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#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct JournalRecovery {
72 pub entries: Vec<String>,
74 pub source: usize,
76 pub revision: u64,
78 pub checks: Vec<JournalCheck>,
80}
81
82pub 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 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 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 #[derive(Debug, Clone, PartialEq, Eq)]
177 pub struct JournalRepair {
178 pub recovery: JournalRecovery,
179 pub changed: bool,
181 pub preserved: Option<PathBuf>,
183 }
184
185 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 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}