Skip to main content

eclipse_core/
atomic.rs

1//! Write a file without ever leaving it half-written.
2//!
3//! A truncating write is two operations on disk — the size goes to zero, then the bytes arrive —
4//! and everything in between is a file a reader can open. For a settings file that means a machine
5//! whose `provider.*` silently vanished because a crash, a full disk or a `kill -9` landed in the
6//! gap; for `jobs.toml` it means a job list that no longer parses; for `state.json` it means the
7//! next tick reading a record that is not a record (`#408`).
8//!
9//! The fix is the one `rename(2)` has always offered: write a sibling and rename over the target.
10//! Rename is atomic on one filesystem, so a reader sees the old file or the new one and never a
11//! mixture, and a process that dies mid-write leaves the old file exactly as it was.
12//!
13//! Two details are load-bearing:
14//!
15//! - **The temporary name is unique per writer**, pid *and* an in-process counter. A fixed
16//!   `<path>.tmp` gives two writers one scratch file — they interleave inside it and the rename
17//!   publishes whatever the mixture was. A clock is not a source of uniqueness either: cargo runs
18//!   tests as threads of one process, and two calls inside one tick get the same name (the lesson
19//!   `tempdir_lite` and `release.rs` both learned).
20//! - **The mode is set on the temporary file, not after the rename.** A file that is created
21//!   world-readable and tightened later is world-readable in between, and `0600` here is not
22//!   decoration: this writer carries `config.toml`, `.env`, `MEMORY.md`, `jobs.toml` and the cron
23//!   state.
24//!
25//! `sync_all` before the rename is what makes the promise survive a power cut rather than only a
26//! killed process. It is the slow part, which is why it is here and not in a loop somewhere.
27
28use std::io::Write;
29use std::path::{Path, PathBuf};
30use std::sync::atomic::{AtomicU64, Ordering};
31
32/// Distinguishes two writers in one process; the pid distinguishes processes.
33static COUNTER: AtomicU64 = AtomicU64::new(0);
34
35/// The sibling to write before renaming over `path`.
36///
37/// The name keeps the original file name as a prefix (`config.toml.4711-3.tmp`) so a leftover is
38/// recognisable as ours and sits in the same directory — `rename` is only atomic within one
39/// filesystem, and a temp directory elsewhere can be another one.
40fn scratch(path: &Path, pid: u32, seq: u64) -> PathBuf {
41    let mut name = path
42        .file_name()
43        .map(|n| n.to_os_string())
44        .unwrap_or_default();
45    name.push(format!(".{pid}-{seq}.tmp"));
46    path.with_file_name(name)
47}
48
49/// Write `text` to `path` atomically, `0600`.
50///
51/// Kept infallible about the temporary file: a failure removes the scratch file and returns the
52/// error, leaving the target untouched. That "leaves the target untouched" half is the whole point
53/// and is asserted in the tests.
54pub fn write_file_atomically(path: &Path, text: &str) -> std::io::Result<()> {
55    if let Some(parent) = path.parent() {
56        std::fs::create_dir_all(parent)?;
57    }
58    let tmp = scratch(
59        path,
60        std::process::id(),
61        COUNTER.fetch_add(1, Ordering::Relaxed),
62    );
63    let mut opts = std::fs::OpenOptions::new();
64    opts.write(true).create_new(true);
65    #[cfg(unix)]
66    {
67        use std::os::unix::fs::OpenOptionsExt;
68        opts.mode(0o600);
69    }
70    let written = (|| -> std::io::Result<()> {
71        let mut file = opts.open(&tmp)?;
72        file.write_all(text.as_bytes())?;
73        // A rename that lands before the bytes reach the disk publishes an empty file after a
74        // power cut: the metadata moved, the data did not.
75        file.sync_all()?;
76        Ok(())
77    })();
78    if let Err(e) = written {
79        let _ = std::fs::remove_file(&tmp);
80        return Err(e);
81    }
82    if let Err(e) = std::fs::rename(&tmp, path) {
83        let _ = std::fs::remove_file(&tmp);
84        return Err(e);
85    }
86    Ok(())
87}
88
89#[cfg(test)]
90mod tests {
91    use super::*;
92
93    #[test]
94    fn a_write_leaves_no_scratch_file_behind() {
95        let dir = tempfile::tempdir().unwrap();
96        let path = dir.path().join("config.toml");
97        write_file_atomically(&path, "a = 1\n").unwrap();
98        assert_eq!(std::fs::read_to_string(&path).unwrap(), "a = 1\n");
99        let names: Vec<String> = std::fs::read_dir(dir.path())
100            .unwrap()
101            .flatten()
102            .map(|e| e.file_name().to_string_lossy().into_owned())
103            .collect();
104        assert_eq!(names, ["config.toml"], "the temporary file is gone");
105    }
106
107    #[test]
108    fn every_writer_gets_its_own_scratch_name() {
109        let path = Path::new("/tmp/x/config.toml");
110        let (a, b) = (scratch(path, 7, 1), scratch(path, 7, 2));
111        assert_ne!(a, b, "a counter, because two writers share one process");
112        assert_ne!(scratch(path, 7, 1), scratch(path, 8, 1), "and a pid");
113        assert_eq!(a.parent(), path.parent(), "same directory, so rename works");
114        assert_eq!(
115            a.file_name().unwrap().to_string_lossy(),
116            "config.toml.7-1.tmp"
117        );
118    }
119
120    /// The property the issue is about, driven rather than argued: a reader that opens the file in
121    /// a tight loop must never see it empty or half-written. With `File::create` + `write_all` this
122    /// fails within a few hundred iterations; with write-and-rename it cannot.
123    #[test]
124    fn a_reader_never_sees_a_half_written_file() {
125        let dir = tempfile::tempdir().unwrap();
126        let path = dir.path().join("config.toml");
127        let big_a = "a".repeat(200_000);
128        let big_b = "b".repeat(200_000);
129        write_file_atomically(&path, &big_a).unwrap();
130
131        let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
132        let expect = big_a.len();
133        let reader = {
134            let path = path.clone();
135            let stop = stop.clone();
136            std::thread::spawn(move || {
137                let mut seen = 0usize;
138                while !stop.load(std::sync::atomic::Ordering::Relaxed) {
139                    let text = std::fs::read_to_string(&path).unwrap_or_default();
140                    assert_eq!(
141                        text.len(),
142                        expect,
143                        "a reader saw a {}-byte file, not the {expect} bytes written",
144                        text.len()
145                    );
146                    seen += 1;
147                }
148                seen
149            })
150        };
151        for i in 0..200 {
152            write_file_atomically(&path, if i % 2 == 0 { &big_b } else { &big_a }).unwrap();
153        }
154        stop.store(true, std::sync::atomic::Ordering::Relaxed);
155        let seen = reader.join().unwrap();
156        assert!(seen > 0, "the reader ran at least once");
157    }
158
159    /// A write that cannot be renamed into place leaves the old file alone — the reason the
160    /// temporary file exists. `rename` over a non-empty directory fails on every Unix.
161    #[test]
162    fn a_failed_write_leaves_the_old_file_intact() {
163        let dir = tempfile::tempdir().unwrap();
164        let path = dir.path().join("jobs.toml");
165        write_file_atomically(&path, "kept\n").unwrap();
166        // Make the destination impossible without touching the file itself: a directory named like
167        // the target cannot be replaced by a rename.
168        let blocked = dir.path().join("blocked.toml");
169        std::fs::create_dir(&blocked).unwrap();
170        std::fs::write(blocked.join("inner"), "x").unwrap();
171        assert!(write_file_atomically(&blocked, "new\n").is_err());
172        assert_eq!(
173            std::fs::read_dir(&blocked).unwrap().count(),
174            1,
175            "the directory that was there is still there"
176        );
177        assert_eq!(
178            std::fs::read_to_string(&path).unwrap(),
179            "kept\n",
180            "and an unrelated file is untouched"
181        );
182    }
183}