//! Atomic file writes: write to a sibling temp file, then `rename` over the //! target. Matters here specifically for the instance JSON file, which the //! supervisor rewrites on every state change while it may be alive for //! months; a reader (`status`/`list`) must never observe a half-written //! file, and a crash mid-write must never corrupt the last-known-good state. use std::io::Write; use std::path::Path; pub fn write(path: &Path, contents: &[u8]) -> std::io::Result<()> { let tmp = path.with_extension(format!( "{}.tmp.{}", path.extension().and_then(|e| e.to_str()).unwrap_or(""), std::process::id() )); { let mut f = std::fs::File::create(&tmp)?; f.write_all(contents)?; f.sync_all()?; } std::fs::rename(&tmp, path) }