use super::{EngineOptions, State};
use crate::LinkError;
use doublets::data::LinkReference;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct JournalDamage {
pub record: usize,
pub reason: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct JournalCheck {
pub valid_records: usize,
pub total_records: usize,
pub revision: u64,
pub damage: Option<JournalDamage>,
}
impl JournalCheck {
pub fn is_intact(&self) -> bool {
self.damage.is_none()
}
pub fn discarded_records(&self) -> usize {
self.total_records - self.valid_records
}
}
pub fn check_journal<T: LinkReference>(
entries: &[String],
options: &EngineOptions,
) -> JournalCheck {
let mut state = State::<T, ()>::empty((), options.clone());
for (index, entry) in entries.iter().enumerate() {
if let Err(error) = state.replay(index, entry) {
return JournalCheck {
valid_records: index,
total_records: entries.len(),
revision: state.current.revision,
damage: Some(JournalDamage {
record: index,
reason: error.to_string(),
}),
};
}
}
JournalCheck {
valid_records: entries.len(),
total_records: entries.len(),
revision: state.current.revision,
damage: None,
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct JournalRecovery {
pub entries: Vec<String>,
pub source: usize,
pub revision: u64,
pub checks: Vec<JournalCheck>,
}
pub fn recover_journal<T: LinkReference>(
copies: &[Vec<String>],
options: &EngineOptions,
) -> Result<JournalRecovery, LinkError> {
if copies.is_empty() {
return Err(LinkError::Transaction(
"journal recovery needs at least one copy".into(),
));
}
let checks = copies
.iter()
.map(|copy| check_journal::<T>(copy, options))
.collect::<Vec<_>>();
let mut source = 0;
for (index, check) in checks.iter().enumerate() {
if check.valid_records > checks[source].valid_records {
source = index;
}
}
let chosen = &copies[source][..checks[source].valid_records];
for (index, check) in checks.iter().enumerate() {
if copies[index][..check.valid_records] != chosen[..check.valid_records] {
return Err(LinkError::Transaction(format!(
"journal copies {source} and {index} diverge; choose one explicitly"
)));
}
}
Ok(JournalRecovery {
entries: chosen.to_vec(),
source,
revision: checks[source].revision,
checks,
})
}
#[cfg(not(target_arch = "wasm32"))]
pub use file::{read_journal_file_lossy, repair_journal_file, JournalRepair};
#[cfg(not(target_arch = "wasm32"))]
mod file {
use super::{recover_journal, JournalRecovery};
use crate::engine::EngineOptions;
use crate::LinkError;
use doublets::data::LinkReference;
use std::fs::{File, OpenOptions};
use std::io::{ErrorKind, Read, Write};
use std::path::{Path, PathBuf};
pub fn read_journal_file_lossy(path: &Path) -> Result<Vec<String>, LinkError> {
Ok(lines(&read_bytes(path)?))
}
fn read_bytes(path: &Path) -> Result<Vec<u8>, LinkError> {
let mut bytes = Vec::new();
match File::open(path) {
Ok(mut file) => {
file.read_to_end(&mut bytes)?;
}
Err(error) if error.kind() == ErrorKind::NotFound => {}
Err(error) => return Err(error.into()),
}
Ok(bytes)
}
fn lines(bytes: &[u8]) -> Vec<String> {
let complete = bytes
.iter()
.rposition(|byte| *byte == b'\n')
.map_or(0, |end| end + 1);
let mut lines: Vec<&[u8]> = bytes[..complete]
.split(|byte| *byte == b'\n')
.filter(|line| !line.is_empty())
.collect();
while lines.last().is_some_and(|line| line.contains(&0)) {
lines.pop();
}
lines
.into_iter()
.map(|line| String::from_utf8_lossy(line).into_owned())
.collect()
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct JournalRepair {
pub recovery: JournalRecovery,
pub changed: bool,
pub preserved: Option<PathBuf>,
}
pub fn repair_journal_file<T: LinkReference>(
path: &Path,
copies: &[&Path],
options: &EngineOptions,
) -> Result<JournalRepair, 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 original = read_bytes(path)?;
let mut sources = vec![lines(&original)];
for copy in copies {
sources.push(read_journal_file_lossy(copy)?);
}
let recovery = recover_journal::<T>(&sources, options)?;
let mut repaired = Vec::new();
for entry in &recovery.entries {
repaired.extend_from_slice(entry.as_bytes());
repaired.push(b'\n');
}
if repaired == original {
return Ok(JournalRepair {
recovery,
changed: false,
preserved: None,
});
}
let preserved = if original.is_empty() {
None
} else {
Some(preserve(path, &original)?)
};
let temporary = sibling(path, ".repair");
{
let mut file = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(&temporary)?;
file.write_all(&repaired)?;
file.sync_all()?;
}
std::fs::rename(&temporary, path)?;
sync_directory(path)?;
Ok(JournalRepair {
recovery,
changed: true,
preserved,
})
}
fn sibling(path: &Path, suffix: &str) -> PathBuf {
let mut name = path.as_os_str().to_owned();
name.push(suffix);
PathBuf::from(name)
}
fn preserve(path: &Path, bytes: &[u8]) -> Result<PathBuf, LinkError> {
for attempt in 1u32.. {
let target = sibling(path, &format!(".damaged-{attempt}"));
match OpenOptions::new()
.write(true)
.create_new(true)
.open(&target)
{
Ok(mut file) => {
file.write_all(bytes)?;
file.sync_all()?;
return Ok(target);
}
Err(error) if error.kind() == ErrorKind::AlreadyExists => continue,
Err(error) => return Err(error.into()),
}
}
unreachable!("u32 attempts exhausted")
}
#[cfg(unix)]
fn sync_directory(path: &Path) -> Result<(), LinkError> {
let parent = path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or(Path::new("."));
File::open(parent)?.sync_all()?;
Ok(())
}
#[cfg(not(unix))]
fn sync_directory(_: &Path) -> Result<(), LinkError> {
Ok(())
}
}