use std::fs::{self, File, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
pub(crate) fn atomic_write<F>(dest: &Path, f: F) -> Result<()>
where
F: FnOnce(&mut dyn Write) -> Result<()>,
{
let dir = parent_dir(dest);
fs::create_dir_all(&dir)
.with_context(|| format!("creating directory {:?} for atomic write", dir))?;
let (mut file, tmp_path) = create_temp_in(&dir)?;
let write_result = (|| -> Result<()> {
{
let mut buf = std::io::BufWriter::new(&mut file);
f(&mut buf)?;
buf.flush()?;
}
file.sync_all()
.with_context(|| format!("syncing temp file {:?}", tmp_path))?;
Ok(())
})();
if let Err(e) = write_result {
drop(file);
let _ = fs::remove_file(&tmp_path);
return Err(e);
}
drop(file);
fs::rename(&tmp_path, dest).with_context(|| {
format!(
"atomically publishing {:?} (temp file {:?})",
dest, tmp_path
)
})?;
sync_dir(&dir);
Ok(())
}
pub(crate) fn atomic_write_bytes(dest: &Path, bytes: &[u8]) -> Result<()> {
atomic_write(dest, |w| {
w.write_all(bytes)?;
Ok(())
})
}
pub(crate) fn publish_bytes_nosync(dest: &Path, bytes: &[u8]) -> Result<()> {
let dir = parent_dir(dest);
let (mut file, tmp_path) = create_temp_in(&dir)?;
if let Err(e) = file.write_all(bytes) {
drop(file);
let _ = fs::remove_file(&tmp_path);
return Err(e).with_context(|| format!("writing temp file {:?}", tmp_path));
}
drop(file);
fs::rename(&tmp_path, dest).with_context(|| {
format!("publishing {:?} (temp file {:?})", dest, tmp_path)
})?;
Ok(())
}
fn parent_dir(dest: &Path) -> PathBuf {
match dest.parent().filter(|p| !p.as_os_str().is_empty()) {
Some(p) => p.to_path_buf(),
None => PathBuf::from("."),
}
}
fn create_temp_in(dir: &Path) -> Result<(File, PathBuf)> {
let pid = std::process::id();
for attempt in 0..1024u32 {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
let candidate = dir.join(format!(".rgstore.tmp.{}.{}.{}", pid, nanos, attempt));
match OpenOptions::new()
.write(true)
.create_new(true)
.open(&candidate)
{
Ok(f) => return Ok((f, candidate)),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(e) => {
return Err(e).with_context(|| format!("creating temp file in {:?}", dir));
}
}
}
anyhow::bail!("could not create a temp file in {:?} after 1024 attempts", dir)
}
fn sync_dir(dir: &Path) {
if let Ok(handle) = File::open(dir) {
let _ = handle.sync_all();
}
}
pub fn is_transient_store_file(name: &str) -> bool {
name.starts_with(".rgstore.tmp.")
|| name == ".rgstore.lock"
|| name == ".rgstore.lock.break"
|| name.starts_with(".rgstore.lock.stale.")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn publishes_full_contents() {
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("out.txt");
atomic_write(&dest, |w| {
w.write_all(b"hello")?;
Ok(())
})
.unwrap();
assert_eq!(fs::read_to_string(&dest).unwrap(), "hello");
}
#[test]
fn failed_write_leaves_destination_untouched_and_no_temp() {
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("out.txt");
atomic_write_bytes(&dest, b"original").unwrap();
let err = atomic_write(&dest, |w| {
w.write_all(b"partial")?;
anyhow::bail!("boom")
});
assert!(err.is_err());
assert_eq!(fs::read_to_string(&dest).unwrap(), "original");
let leftovers: Vec<_> = fs::read_dir(dir.path())
.unwrap()
.filter_map(|e| e.ok())
.filter(|e| {
e.file_name()
.to_str()
.map_or(false, |n| n.starts_with(".rgstore.tmp."))
})
.collect();
assert!(leftovers.is_empty(), "temp file was not cleaned up");
}
#[test]
fn creates_missing_parent_directory() {
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("nested/deeper/out.txt");
atomic_write_bytes(&dest, b"x").unwrap();
assert_eq!(fs::read_to_string(&dest).unwrap(), "x");
}
#[test]
fn transient_file_detection() {
assert!(is_transient_store_file(".rgstore.lock"));
assert!(is_transient_store_file(".rgstore.lock.stale.123.456"));
assert!(is_transient_store_file(".rgstore.tmp.1.2.0"));
assert!(!is_transient_store_file("rgstore.json"));
assert!(!is_transient_store_file("sequences.rgsi"));
}
}