use std::io::Write;
use std::path::Path;
use thiserror::Error;
#[derive(Debug, Clone, Error)]
pub enum AtomicWriteError {
#[error("io: {0}")]
Io(String),
}
crate::impl_error_kind! {
AtomicWriteError {
(Io(_)) => "io",
}
}
pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), AtomicWriteError> {
write_atomic_with(path, bytes, None)
}
pub fn write_atomic_mode(path: &Path, bytes: &[u8], mode: u32) -> Result<(), AtomicWriteError> {
write_atomic_with(path, bytes, Some(mode))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[must_use]
pub enum WriteOnce {
Created,
AlreadyExisted,
}
pub fn write_new_atomic_mode(
path: &Path,
bytes: &[u8],
mode: u32,
) -> Result<WriteOnce, AtomicWriteError> {
let tmp = write_temp(path, bytes, Some(mode))?;
match std::fs::hard_link(tmp.path(), path) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
return Ok(WriteOnce::AlreadyExisted);
}
Err(e) => {
return Err(AtomicWriteError::Io(format!(
"link {}: {e}",
path.display()
)));
}
}
if let Some(parent) = path.parent()
&& !parent.as_os_str().is_empty()
{
std::fs::File::open(parent)
.and_then(|dir| dir.sync_all())
.map_err(|e| AtomicWriteError::Io(format!("fsync {}: {e}", parent.display())))?;
}
Ok(WriteOnce::Created)
}
fn write_atomic_with(path: &Path, bytes: &[u8], mode: Option<u32>) -> Result<(), AtomicWriteError> {
write_temp(path, bytes, mode)?.publish(path)
}
fn write_temp(path: &Path, bytes: &[u8], mode: Option<u32>) -> Result<TempPath, AtomicWriteError> {
if let Some(parent) = path.parent()
&& !parent.as_os_str().is_empty()
{
std::fs::create_dir_all(parent)
.map_err(|e| AtomicWriteError::Io(format!("mkdir {}: {e}", parent.display())))?;
}
let tmp = TempPath::mint(path);
{
let mut options = std::fs::OpenOptions::new();
options.write(true).create(true).truncate(true);
#[cfg(unix)]
if let Some(mode) = mode {
use std::os::unix::fs::OpenOptionsExt;
options.mode(mode);
}
let mut f = options
.open(tmp.path())
.map_err(|e| AtomicWriteError::Io(format!("create {}: {e}", tmp.path().display())))?;
#[cfg(unix)]
if let Some(mode) = mode {
use std::os::unix::fs::PermissionsExt;
f.set_permissions(std::fs::Permissions::from_mode(mode))
.map_err(|e| {
AtomicWriteError::Io(format!("chmod {}: {e}", tmp.path().display()))
})?;
}
#[cfg(not(unix))]
let _ = mode;
f.write_all(bytes)
.map_err(|e| AtomicWriteError::Io(format!("write {}: {e}", tmp.path().display())))?;
f.sync_all()
.map_err(|e| AtomicWriteError::Io(format!("fsync {}: {e}", tmp.path().display())))?;
}
Ok(tmp)
}
#[derive(Debug)]
pub struct TempPath {
path: std::path::PathBuf,
published: bool,
}
impl TempPath {
fn mint(target: &Path) -> Self {
use std::fmt::Write as _;
static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let mut suffix = String::new();
let _ = write!(suffix, ".{}.{seq}.tmp", std::process::id());
let mut s: std::ffi::OsString = target.as_os_str().to_os_string();
s.push(suffix);
Self {
path: s.into(),
published: false,
}
}
#[must_use]
pub fn path(&self) -> &Path {
&self.path
}
pub fn publish(mut self, target: &Path) -> Result<(), AtomicWriteError> {
std::fs::rename(&self.path, target).map_err(|e| {
AtomicWriteError::Io(
[
"rename ",
&self.path.display().to_string(),
" → ",
&target.display().to_string(),
": ",
&e.to_string(),
]
.concat(),
)
})?;
self.published = true;
Ok(())
}
}
impl Drop for TempPath {
fn drop(&mut self) {
if !self.published {
let _ = std::fs::remove_file(&self.path);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn temp_path(suffix: &str) -> std::path::PathBuf {
std::env::temp_dir().join(format!(
"engenho-substrate-atomic-{}-{suffix}",
std::process::id()
))
}
#[test]
fn write_once_never_replaces_an_existing_file() {
let path = temp_path("write-once");
let _ = std::fs::remove_file(&path);
assert_eq!(
write_new_atomic_mode(&path, b"first", 0o600).unwrap(),
WriteOnce::Created
);
assert_eq!(
write_new_atomic_mode(&path, b"second", 0o600).unwrap(),
WriteOnce::AlreadyExisted
);
assert_eq!(std::fs::read(&path).unwrap(), b"first");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
}
let _ = std::fs::remove_file(&path);
}
#[test]
fn writes_bytes_to_path() {
let path = temp_path("basic");
let _ = std::fs::remove_file(&path);
write_atomic(&path, b"hello").unwrap();
let read = std::fs::read(&path).unwrap();
assert_eq!(read, b"hello");
let _ = std::fs::remove_file(&path);
}
#[test]
fn creates_parent_directory_if_missing() {
let nested = temp_path("nested").join("a/b/c/file.bin");
let _ = std::fs::remove_dir_all(nested.parent().unwrap());
write_atomic(&nested, b"abc").unwrap();
assert!(nested.exists());
let _ = std::fs::remove_dir_all(temp_path("nested"));
}
#[test]
fn overwrites_existing_file_atomically() {
let path = temp_path("overwrite");
write_atomic(&path, b"v1").unwrap();
write_atomic(&path, b"v2").unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"v2");
let _ = std::fs::remove_file(&path);
}
#[test]
fn cleans_up_tmp_after_successful_rename() {
let path = temp_path("tmpcleanup");
let _ = std::fs::remove_file(&path);
write_atomic(&path, b"x").unwrap();
assert!(path.exists(), "final path exists");
let dir = path.parent().expect("parent");
let stem = path
.file_name()
.expect("name")
.to_string_lossy()
.into_owned();
let strays: Vec<_> = std::fs::read_dir(dir)
.expect("read_dir")
.filter_map(Result::ok)
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|n| n.starts_with(&stem) && n.ends_with(".tmp"))
.collect();
assert!(strays.is_empty(), "temp files left behind: {strays:?}");
let _ = std::fs::remove_file(&path);
}
#[test]
fn an_unpublished_temp_file_is_cleaned_up_on_drop() {
let target = temp_path("dropme");
let stray = {
let t = TempPath::mint(&target);
std::fs::write(t.path(), b"partial").expect("write");
assert!(t.path().exists());
t.path().to_path_buf()
};
assert!(
!stray.exists(),
"a temp that was never published must not survive its owner"
);
}
const _PUBLISH_CONSUMES: () = ();
#[test]
fn two_calls_never_return_the_same_temp_path() {
let p = std::path::PathBuf::from("/tmp/x.bin");
let a = TempPath::mint(&p);
let b = TempPath::mint(&p);
assert_ne!(
a.path(),
b.path(),
"a deterministic temp path is a lost-update race"
);
}
#[test]
fn concurrent_writers_to_one_path_all_succeed() {
let path = temp_path("concurrent");
let _ = std::fs::remove_file(&path);
let mut handles = Vec::new();
for i in 0..16u8 {
let p = path.clone();
handles.push(std::thread::spawn(move || write_atomic(&p, &[i; 64])));
}
for h in handles {
h.join()
.expect("thread")
.expect("every atomic write must succeed");
}
let got = std::fs::read(&path).expect("read back");
assert_eq!(got.len(), 64, "a torn write would not be 64 bytes");
assert!(
got.iter().all(|b| *b == got[0]),
"the published file must be exactly ONE writer's bytes, not a mix"
);
let _ = std::fs::remove_file(&path);
}
#[test]
fn tmp_path_for_is_a_sibling_ending_in_dot_tmp() {
let p = std::path::PathBuf::from("/tmp/x.bin");
let minted = TempPath::mint(&p);
let t = minted.path().to_path_buf();
assert_eq!(t.parent(), p.parent());
let name = t.to_string_lossy().into_owned();
assert!(name.starts_with("/tmp/x.bin."), "{name}");
assert!(name.ends_with(".tmp"), "{name}");
}
#[cfg(unix)]
#[test]
fn a_mode_is_the_files_from_the_start() {
use std::os::unix::fs::PermissionsExt;
let path = temp_path("mode");
let _ = std::fs::remove_file(&path);
write_atomic_mode(&path, b"secret", 0o600).unwrap();
let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
write_atomic_mode(&path, b"secret2", 0o600).unwrap();
let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
assert_eq!(std::fs::read(&path).unwrap(), b"secret2");
let _ = std::fs::remove_file(&path);
}
#[test]
fn error_kind_is_stable() {
assert_eq!(AtomicWriteError::Io("x".into()).kind(), "io");
}
#[test]
fn write_to_directory_returns_io_error() {
let dir = std::env::temp_dir();
let err = write_atomic(&dir, b"x").unwrap_err();
assert_eq!(err.kind(), "io");
}
}