91 lines
2.9 KiB
Rust
91 lines
2.9 KiB
Rust
//! Atomic save (docs/FORMAT.md, "Saving").
|
|
|
|
use crate::Error;
|
|
use std::ffi::OsString;
|
|
use std::fs::File;
|
|
use std::io::Write;
|
|
use std::path::{Path, PathBuf};
|
|
|
|
/// Where `save_atomic_crashing` stops, as if the process died there.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
pub enum CrashPoint {
|
|
MidTempWrite,
|
|
AfterTempWrite,
|
|
MidBackup,
|
|
AfterBackup,
|
|
}
|
|
|
|
/// Writes `bytes` to `path` so that a crash at any moment leaves either the previous file or the new one
|
|
/// in place, and keeps the previous version as `<path>.bak`.
|
|
pub fn save_atomic(path: &Path, bytes: &[u8]) -> Result<(), Error> {
|
|
save(path, bytes, None)
|
|
}
|
|
|
|
/// `save_atomic` that stops at `crash` with an error, for the crash tests.
|
|
#[doc(hidden)]
|
|
pub fn save_atomic_crashing(path: &Path, bytes: &[u8], crash: CrashPoint) -> Result<(), Error> {
|
|
save(path, bytes, Some(crash))
|
|
}
|
|
|
|
fn sibling(path: &Path, suffix: &str) -> PathBuf {
|
|
let mut name: OsString = path.file_name().unwrap_or_default().to_owned();
|
|
name.push(suffix);
|
|
path.with_file_name(name)
|
|
}
|
|
|
|
fn crashed(at: CrashPoint) -> Error {
|
|
Error::Io(std::io::Error::other(format!("simulated crash at {at:?}")))
|
|
}
|
|
|
|
/// Writes and fsyncs `path`; with `half`, writes only the first half and "crashes".
|
|
fn write_synced(path: &Path, bytes: &[u8], half: Option<CrashPoint>) -> Result<(), Error> {
|
|
let mut f = File::create(path)?;
|
|
if let Some(at) = half {
|
|
f.write_all(&bytes[..bytes.len() / 2])?;
|
|
return Err(crashed(at));
|
|
}
|
|
f.write_all(bytes)?;
|
|
f.sync_all()?;
|
|
Ok(())
|
|
}
|
|
|
|
/// `rename` that replaces the target. On Windows a sync client or a virus scanner can hold the target
|
|
/// open for a moment, so this retries for about two seconds before giving up.
|
|
fn replace(from: &Path, to: &Path) -> Result<(), Error> {
|
|
let mut tries = 0;
|
|
loop {
|
|
match std::fs::rename(from, to) {
|
|
Ok(()) => return Ok(()),
|
|
Err(e) if tries < 20 && e.kind() == std::io::ErrorKind::PermissionDenied => {
|
|
tries += 1;
|
|
std::thread::sleep(std::time::Duration::from_millis(100));
|
|
}
|
|
Err(e) => return Err(e.into()),
|
|
}
|
|
}
|
|
}
|
|
|
|
fn save(path: &Path, bytes: &[u8], crash: Option<CrashPoint>) -> Result<(), Error> {
|
|
let at = |p: CrashPoint| (crash == Some(p)).then_some(p);
|
|
let tmp = sibling(path, ".tmp");
|
|
write_synced(&tmp, bytes, at(CrashPoint::MidTempWrite))?;
|
|
if let Some(p) = at(CrashPoint::AfterTempWrite) {
|
|
return Err(crashed(p));
|
|
}
|
|
if path.exists() {
|
|
let old = std::fs::read(path)?;
|
|
let bak_tmp = sibling(path, ".bak.tmp");
|
|
write_synced(&bak_tmp, &old, at(CrashPoint::MidBackup))?;
|
|
replace(&bak_tmp, &sibling(path, ".bak"))?;
|
|
}
|
|
if let Some(p) = at(CrashPoint::AfterBackup) {
|
|
return Err(crashed(p));
|
|
}
|
|
replace(&tmp, path)?;
|
|
#[cfg(unix)]
|
|
if let Some(dir) = path.parent() {
|
|
File::open(dir)?.sync_all()?;
|
|
}
|
|
Ok(())
|
|
}
|