From afc3477b5c10460352cf1f6b27c1548d561e40a1 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 19:57:06 +0100 Subject: [PATCH] [control] Atomic writes: a temporary name unique per write (pid, counter, random), so two writers of one file never collide; same for edge's epoch floor --- crates/control/src/util.rs | 27 ++++++++++++++++++++++++++- crates/edge/src/shared.rs | 8 +++++++- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/crates/control/src/util.rs b/crates/control/src/util.rs index 2ecff64..12759c1 100644 --- a/crates/control/src/util.rs +++ b/crates/control/src/util.rs @@ -62,7 +62,12 @@ pub fn write_atomic(path: &Path, data: &[u8], mode: u32) -> std::io::Result<()> .unwrap_or(Path::new(".")); std::fs::create_dir_all(dir)?; let mut name = path.file_name().unwrap_or_default().to_os_string(); - name.push(format!(".tmp-{}", std::process::id())); + // Unique per write (process, counter, random), so two writers of the same file never + // share a temporary file. + static WRITES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = WRITES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let r = random::<4>().map(|b| hex(&b))?; + name.push(format!(".tmp-{}-{n}-{r}", std::process::id())); let tmp = dir.join(name); { let mut opts = std::fs::OpenOptions::new(); @@ -133,6 +138,26 @@ mod tests { assert!(!ct_eq(b"abc", b"ab")); } + #[test] + fn concurrent_atomic_writes_of_one_file_all_succeed() { + let d = std::env::temp_dir().join(format!("ianitor-util-c-{}", std::process::id())); + let p = d.join("paused.json"); + let threads: Vec<_> = (0..16) + .map(|i| { + let p = p.clone(); + std::thread::spawn(move || { + (0..50).all(|_| write_atomic(&p, format!("{i}").as_bytes(), 0o600).is_ok()) + }) + }) + .collect(); + for t in threads { + assert!(t.join().unwrap(), "a write failed"); + } + let left: Vec<_> = std::fs::read_dir(&d).unwrap().collect(); + assert_eq!(left.len(), 1, "no temporary files left"); + let _ = std::fs::remove_dir_all(&d); + } + #[test] fn atomic_write_replaces() { let d = std::env::temp_dir().join(format!("ianitor-util-{}", std::process::id())); diff --git a/crates/edge/src/shared.rs b/crates/edge/src/shared.rs index 7839e2f..9fc6d19 100644 --- a/crates/edge/src/shared.rs +++ b/crates/edge/src/shared.rs @@ -463,7 +463,13 @@ fn write_epoch_floor(rt: &Runtime, epoch: u32) -> std::io::Result<()> { if let Some(dir) = path.parent() { std::fs::create_dir_all(dir)?; } - let tmp = path.with_extension("tmp"); + // Unique per write: the admin socket and the poller can both reload the revocations. + static WRITES: AtomicU64 = AtomicU64::new(0); + let tmp = path.with_extension(format!( + "tmp-{}-{}", + std::process::id(), + WRITES.fetch_add(1, Ordering::Relaxed) + )); { use std::io::Write; let mut f = std::fs::File::create(&tmp)?;