use std::fmt;
use std::io::{self, Write as _};
use std::path::{Path, PathBuf};
use std::sync::Arc;
#[derive(Clone)]
pub struct Durability(Arc<Hooks>);
struct Hooks {
flush: Box<dyn Fn() + Send + Sync>,
ended_synced: Box<dyn Fn(&str) -> bool + Send + Sync>,
}
impl Durability {
pub fn new(
flush: impl Fn() + Send + Sync + 'static,
ended_synced: impl Fn(&str) -> bool + Send + Sync + 'static,
) -> Durability {
Durability(Arc::new(Hooks {
flush: Box::new(flush),
ended_synced: Box::new(ended_synced),
}))
}
pub fn host() -> Durability {
Durability::new(rustix::fs::sync, crate::boots::ended_synced)
}
}
impl fmt::Debug for Durability {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Durability")
}
}
#[derive(Debug)]
pub(crate) struct Unsynced {
file: PathBuf,
boot_id: PathBuf,
durability: Durability,
state: Owed,
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Owed {
Synced,
Since { boot: String },
Torn { refusals: u32, held: Vec<String> },
}
pub(crate) const REFUSALS: u32 = 5;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Recovered {
Unchanged,
ShutDownInOrder,
Torn,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum AfterRefusal {
Again { tries: u32 },
GiveUp,
}
const TORN: &str = "torn";
const SINCE: &str = "since ";
impl Unsynced {
pub(crate) fn open(file: PathBuf, proc: &Path, durability: Durability) -> Unsynced {
let state = match std::fs::read_to_string(&file) {
Err(error) if error.kind() == io::ErrorKind::NotFound => Owed::Synced,
Err(_) => Owed::Torn {
refusals: 0,
held: Vec::new(),
},
Ok(text) => match text.trim_end().strip_prefix(SINCE) {
Some(boot) if !boot.is_empty() => Owed::Since {
boot: boot.to_owned(),
},
_ => Owed::Torn {
refusals: 0,
held: Vec::new(),
},
},
};
Unsynced {
file,
boot_id: proc.join("sys/kernel/random/boot_id"),
durability,
state,
}
}
fn boot(&self) -> Option<String> {
let boot = std::fs::read_to_string(&self.boot_id).ok()?;
let boot = boot.trim();
(!boot.is_empty()).then(|| boot.to_owned())
}
pub(crate) fn recovered(&mut self) -> io::Result<Recovered> {
let Owed::Since { boot } = &self.state else {
return Ok(Recovered::Unchanged);
};
if self.boot().as_deref() == Some(boot.as_str()) {
return Ok(Recovered::Unchanged);
}
if (self.durability.0.ended_synced)(boot) {
self.settle()?;
return Ok(Recovered::ShutDownInOrder);
}
self.state = Owed::Torn {
refusals: 0,
held: Vec::new(),
};
write(&self.file, TORN)?;
Ok(Recovered::Torn)
}
pub(crate) fn is_torn(&self) -> bool {
matches!(self.state, Owed::Torn { .. })
}
pub(crate) fn torn(&self) -> Option<&[String]> {
match &self.state {
Owed::Torn { held, .. } => Some(held),
Owed::Synced | Owed::Since { .. } => None,
}
}
pub(crate) fn runner_skips(&mut self) -> bool {
let Some(boot) = self.boot() else {
return false;
};
match &self.state {
Owed::Torn { .. } => false,
Owed::Since { boot: since } if *since == boot => true,
Owed::Synced | Owed::Since { .. } => {
if write(&self.file, &format!("{SINCE}{boot}")).is_err() {
return false;
}
self.state = Owed::Since { boot };
true
}
}
}
pub(crate) fn emptied(&mut self) -> io::Result<()> {
if !self.is_torn() {
return Ok(());
}
self.settle()
}
pub(crate) fn refused(&mut self, volumes: Vec<String>) -> AfterRefusal {
let Owed::Torn { refusals, held } = &mut self.state else {
return AfterRefusal::GiveUp;
};
*refusals = refusals.saturating_add(1);
*held = volumes;
let tries = *refusals;
if tries < REFUSALS {
return AfterRefusal::Again { tries };
}
AfterRefusal::GiveUp
}
pub(crate) fn gave_up(&mut self) -> io::Result<()> {
if !self.is_torn() {
return Ok(());
}
self.settle()
}
pub(crate) fn stopped_clean(&mut self) -> io::Result<()> {
if !matches!(self.state, Owed::Since { .. }) {
return Ok(());
}
self.settle()
}
fn settle(&mut self) -> io::Result<()> {
(self.durability.0.flush)();
match std::fs::remove_file(&self.file) {
Err(error) if error.kind() != io::ErrorKind::NotFound => return Err(error),
_ => {}
}
sync_parent(&self.file)?;
self.state = Owed::Synced;
Ok(())
}
}
fn write(file: &Path, text: &str) -> io::Result<()> {
let temporary = file.with_extension("new");
{
let mut out = std::fs::File::create(&temporary)?;
out.write_all(text.as_bytes())?;
out.write_all(b"\n")?;
out.sync_all()?;
}
std::fs::rename(&temporary, file)?;
sync_parent(file)
}
fn sync_parent(file: &Path) -> io::Result<()> {
match file.parent() {
Some(dir) if !dir.as_os_str().is_empty() => std::fs::File::open(dir)?.sync_all(),
_ => Ok(()),
}
}