Sync All Before Rename
Stage a write with write_all, force it to disk with sync_all, then publish with fs::rename so a crash never leaves a half-written live file.
Code
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
// 写暂存文件 -> sync_all 落盘 -> 原子改名发布
fn publish(dir: &Path, payload: &[u8]) -> std::io::Result<PathBuf> {
let staged = dir.join("config.json.new");
let live = dir.join("config.json");
let mut file = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(&staged)?;
file.write_all(payload)?;
file.sync_all()?; // 数据与元数据一起压到磁盘,再谈发布
fs::rename(&staged, &live)?; // 同一文件系统内改名原子生效
Ok(live)
}
fn main() -> std::io::Result<()> {
let dir = std::env::temp_dir().join("sync_all_demo");
fs::create_dir_all(&dir)?;
let live = publish(&dir, br#"{"retries": 3}"#)?;
println!("published: {}", fs::read_to_string(&live)?);
fs::remove_file(&live).ok();
fs::remove_dir_all(&dir).ok();
Ok(())
}What the code does
Sync All Before Rename is built around the functions publish and main.
Fallible operations return Result, and the ? operator short-circuits errors up to the caller.
What to watch for
- Everything it calls is documented as part of the language core.
- Errors travel through
Result; if you drop the?operators while adapting, each call site needs its ownmatch.
Using it
Signature: fn publish(dir: &Path, payload: &[u8]) -> std::io::Result<PathBuf>
Output arrives labeled — published: — when the file runs.
Launch the file; main takes over and steps through publish.
Key statements
let live = publish(&dir, br#"{"retries": 3}"#)?;
fs::rename(&staged, &live)?; // 同一文件系统内改名原子生效
Ok(live)
}
fs::create_dir_all(&dir)?;
Interactive Tools for This Topic
FAQ
- How do errors reach the caller?
- Through the type system: failures are `Result` variants the caller must consume.
- What does Sync All Before Rename print when run?
- Invoke the file as-is — the `published:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.