[save] Atomic save: temp + flush + rename, .bak first, kill tests
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
[package]
|
||||
name = "pictor-save"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
thiserror.workspace = true
|
||||
tempfile.workspace = true
|
||||
@@ -0,0 +1,106 @@
|
||||
//! Safe saving for Pictor: a file on disk is either the old version or the new one, never half of each.
|
||||
//!
|
||||
//! - [`save_new`] writes a new file and refuses to replace an existing one (the default: `<name>-edited.pdf`).
|
||||
//! - [`save_overwrite`] replaces a file, first keeping the current version as `<file>.bak`.
|
||||
//!
|
||||
//! Both write to a temporary file in the target's folder, flush it to disk, and then rename it into place, so a
|
||||
//! crash, a kill or a full disk at any moment leaves the original as it was. The `.bak` is written the same way, so
|
||||
//! it is always either the previous backup or a full copy of the original.
|
||||
use std::fs::File;
|
||||
use std::io::{self, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum SaveError {
|
||||
#[error("A file named {0} already exists.")]
|
||||
Exists(String),
|
||||
#[error("Pictor could not save {path}: {source}")]
|
||||
Io { path: String, source: io::Error },
|
||||
}
|
||||
|
||||
fn io_err(path: &Path) -> impl FnOnce(io::Error) -> SaveError + '_ {
|
||||
move |source| SaveError::Io { path: path.display().to_string(), source }
|
||||
}
|
||||
|
||||
/// The default name for an edited copy: `report.pdf` → `report-edited.pdf`, then `report-edited-2.pdf`, …
|
||||
/// (the first one that does not exist yet).
|
||||
pub fn edited_path(original: &Path) -> PathBuf {
|
||||
let dir = original.parent().unwrap_or(Path::new("."));
|
||||
let stem = original.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let ext = original.extension().map(|e| format!(".{}", e.to_string_lossy())).unwrap_or_default();
|
||||
let mut n = 1u32;
|
||||
loop {
|
||||
let name = if n == 1 { format!("{stem}-edited{ext}") } else { format!("{stem}-edited-{n}{ext}") };
|
||||
let candidate = dir.join(name);
|
||||
if !candidate.exists() {
|
||||
return candidate;
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// The backup path of `target`: `doc.pdf` → `doc.pdf.bak`.
|
||||
pub fn bak_path(target: &Path) -> PathBuf {
|
||||
let mut name = target.file_name().unwrap_or_default().to_os_string();
|
||||
name.push(".bak");
|
||||
target.with_file_name(name)
|
||||
}
|
||||
|
||||
fn temp_in(dir: &Path) -> Result<tempfile::NamedTempFile, SaveError> {
|
||||
tempfile::Builder::new().prefix(".pictor-").suffix(".tmp").tempfile_in(dir).map_err(io_err(dir))
|
||||
}
|
||||
|
||||
fn parent(target: &Path) -> &Path {
|
||||
match target.parent() {
|
||||
Some(p) if !p.as_os_str().is_empty() => p,
|
||||
_ => Path::new("."),
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes `bytes` to a new file at `target`; fails with [`SaveError::Exists`] if something is already there.
|
||||
pub fn save_new(target: &Path, bytes: &[u8]) -> Result<(), SaveError> {
|
||||
let mut tmp = temp_in(parent(target))?;
|
||||
tmp.write_all(bytes).map_err(io_err(target))?;
|
||||
tmp.as_file().sync_all().map_err(io_err(target))?;
|
||||
tmp.persist_noclobber(target).map_err(|e| {
|
||||
if e.error.kind() == io::ErrorKind::AlreadyExists || target.exists() {
|
||||
SaveError::Exists(target.file_name().unwrap_or_default().to_string_lossy().into_owned())
|
||||
} else {
|
||||
SaveError::Io { path: target.display().to_string(), source: e.error }
|
||||
}
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Replaces `target` with `bytes`, keeping the current version as `<target>.bak` first. Returns the `.bak` path
|
||||
/// (which does not exist if `target` did not exist).
|
||||
pub fn save_overwrite(target: &Path, bytes: &[u8]) -> Result<PathBuf, SaveError> {
|
||||
save_overwrite_hooked(target, |f| f.write_all(bytes), || {})
|
||||
}
|
||||
|
||||
/// [`save_overwrite`] with the content written by `write` and a hook called just before the `.bak` is renamed into
|
||||
/// place. Only the save-safety tests use the hooks (they stop the process inside a save and kill it).
|
||||
#[doc(hidden)]
|
||||
pub fn save_overwrite_hooked(
|
||||
target: &Path,
|
||||
write: impl FnOnce(&mut File) -> io::Result<()>,
|
||||
before_bak_rename: impl FnOnce(),
|
||||
) -> Result<PathBuf, SaveError> {
|
||||
let dir = parent(target);
|
||||
let bak = bak_path(target);
|
||||
// 1. The backup: a full copy written beside the target, flushed, then renamed over any older .bak.
|
||||
if target.exists() {
|
||||
let mut tmp = temp_in(dir)?;
|
||||
let mut src = File::open(target).map_err(io_err(target))?;
|
||||
io::copy(&mut src, tmp.as_file_mut()).map_err(io_err(&bak))?;
|
||||
tmp.as_file().sync_all().map_err(io_err(&bak))?;
|
||||
before_bak_rename();
|
||||
tmp.persist(&bak).map_err(|e| SaveError::Io { path: bak.display().to_string(), source: e.error })?;
|
||||
}
|
||||
// 2. The new content, flushed, then renamed over the target in one step.
|
||||
let mut tmp = temp_in(dir)?;
|
||||
write(tmp.as_file_mut()).map_err(io_err(target))?;
|
||||
tmp.as_file().sync_all().map_err(io_err(target))?;
|
||||
tmp.persist(target).map_err(|e| SaveError::Io { path: target.display().to_string(), source: e.error })?;
|
||||
Ok(bak)
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
//! Mandatory test 5 (save safety): a write killed mid-way leaves the original intact and the .bak valid.
|
||||
//! The test binary re-runs itself as the child (PICTOR_SAVE_CHILD set), which stops inside a save and is killed.
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const ORIGINAL: &[u8] = b"%PDF-1.7 original content that must survive";
|
||||
const OLD_BAK: &[u8] = b"%PDF-1.7 the previous backup";
|
||||
|
||||
fn new_content() -> Vec<u8> {
|
||||
let mut v = b"%PDF-1.7 new content ".to_vec();
|
||||
v.resize(4 << 20, b'x');
|
||||
v
|
||||
}
|
||||
|
||||
/// The child half: started by `run_child`, never run directly (it waits forever inside the save).
|
||||
#[test]
|
||||
fn child() {
|
||||
let Ok(dir) = std::env::var("PICTOR_SAVE_CHILD") else { return };
|
||||
let stage = std::env::var("PICTOR_SAVE_STAGE").unwrap();
|
||||
let dir = PathBuf::from(dir);
|
||||
let target = dir.join("doc.pdf");
|
||||
let ready = dir.join("ready");
|
||||
let stop = || {
|
||||
std::fs::write(&ready, b"1").unwrap();
|
||||
loop {
|
||||
std::thread::sleep(Duration::from_secs(60));
|
||||
}
|
||||
};
|
||||
let content = new_content();
|
||||
let _ = pictor_save::save_overwrite_hooked(
|
||||
&target,
|
||||
|f| {
|
||||
use std::io::Write;
|
||||
f.write_all(&content[..content.len() / 2])?;
|
||||
f.flush()?;
|
||||
if stage == "content" {
|
||||
stop();
|
||||
}
|
||||
f.write_all(&content[content.len() / 2..])
|
||||
},
|
||||
|| {
|
||||
if stage == "bak" {
|
||||
stop();
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn run_child(dir: &Path, stage: &str) {
|
||||
let exe = std::env::current_exe().unwrap();
|
||||
let mut child = Command::new(exe)
|
||||
.args(["--exact", "child", "--nocapture", "--test-threads=1"])
|
||||
.env("PICTOR_SAVE_CHILD", dir)
|
||||
.env("PICTOR_SAVE_STAGE", stage)
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let started = Instant::now();
|
||||
while !dir.join("ready").exists() {
|
||||
assert!(started.elapsed() < Duration::from_secs(30), "child never reached the stage");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
child.kill().unwrap();
|
||||
child.wait().unwrap();
|
||||
}
|
||||
|
||||
fn setup(with_old_bak: bool) -> tempfile::TempDir {
|
||||
let dir = tempfile::tempdir_in(env!("CARGO_TARGET_TMPDIR")).unwrap();
|
||||
std::fs::write(dir.path().join("doc.pdf"), ORIGINAL).unwrap();
|
||||
if with_old_bak {
|
||||
std::fs::write(dir.path().join("doc.pdf.bak"), OLD_BAK).unwrap();
|
||||
}
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn killed_while_writing_new_content_keeps_original_and_bak() {
|
||||
let dir = setup(false);
|
||||
run_child(dir.path(), "content");
|
||||
assert_eq!(std::fs::read(dir.path().join("doc.pdf")).unwrap(), ORIGINAL, "original changed");
|
||||
assert_eq!(std::fs::read(dir.path().join("doc.pdf.bak")).unwrap(), ORIGINAL, ".bak is not the original");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn killed_while_writing_bak_keeps_original_and_old_bak() {
|
||||
let dir = setup(true);
|
||||
run_child(dir.path(), "bak");
|
||||
assert_eq!(std::fs::read(dir.path().join("doc.pdf")).unwrap(), ORIGINAL, "original changed");
|
||||
let bak = std::fs::read(dir.path().join("doc.pdf.bak")).unwrap();
|
||||
assert!(bak == OLD_BAK || bak == ORIGINAL, ".bak is neither the old backup nor the original");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_finished_overwrite_replaces_the_file_and_keeps_a_bak() {
|
||||
let dir = setup(true);
|
||||
let target = dir.path().join("doc.pdf");
|
||||
let content = new_content();
|
||||
let bak = pictor_save::save_overwrite(&target, &content).unwrap();
|
||||
assert_eq!(std::fs::read(&target).unwrap(), content);
|
||||
assert_eq!(bak, dir.path().join("doc.pdf.bak"));
|
||||
assert_eq!(std::fs::read(&bak).unwrap(), ORIGINAL);
|
||||
let leftovers: Vec<_> = std::fs::read_dir(dir.path())
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().file_name().into_string().unwrap())
|
||||
.filter(|n| n != "doc.pdf" && n != "doc.pdf.bak")
|
||||
.collect();
|
||||
assert!(leftovers.is_empty(), "temporary files left behind: {leftovers:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_new_never_overwrites_and_names_the_copy() {
|
||||
let dir = setup(false);
|
||||
let target = dir.path().join("doc.pdf");
|
||||
let first = pictor_save::edited_path(&target);
|
||||
assert_eq!(first, dir.path().join("doc-edited.pdf"));
|
||||
pictor_save::save_new(&first, b"one").unwrap();
|
||||
assert!(pictor_save::save_new(&first, b"two").is_err(), "save_new clobbered an existing file");
|
||||
assert_eq!(std::fs::read(&first).unwrap(), b"one");
|
||||
assert_eq!(pictor_save::edited_path(&target), dir.path().join("doc-edited-2.pdf"));
|
||||
assert_eq!(std::fs::read(&target).unwrap(), ORIGINAL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overwrite_of_a_missing_file_makes_no_bak() {
|
||||
let dir = tempfile::tempdir_in(env!("CARGO_TARGET_TMPDIR")).unwrap();
|
||||
let target = dir.path().join("fresh.png");
|
||||
let bak = pictor_save::save_overwrite(&target, b"png").unwrap();
|
||||
assert_eq!(std::fs::read(&target).unwrap(), b"png");
|
||||
assert!(!bak.exists());
|
||||
}
|
||||
Reference in New Issue
Block a user