eclipse-core 0.13.3

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
//! Write a file without ever leaving it half-written.
//!
//! A truncating write is two operations on disk — the size goes to zero, then the bytes arrive —
//! and everything in between is a file a reader can open. For a settings file that means a machine
//! whose `provider.*` silently vanished because a crash, a full disk or a `kill -9` landed in the
//! gap; for `jobs.toml` it means a job list that no longer parses; for `state.json` it means the
//! next tick reading a record that is not a record (`#408`).
//!
//! The fix is the one `rename(2)` has always offered: write a sibling and rename over the target.
//! Rename is atomic on one filesystem, so a reader sees the old file or the new one and never a
//! mixture, and a process that dies mid-write leaves the old file exactly as it was.
//!
//! Two details are load-bearing:
//!
//! - **The temporary name is unique per writer**, pid *and* an in-process counter. A fixed
//!   `<path>.tmp` gives two writers one scratch file — they interleave inside it and the rename
//!   publishes whatever the mixture was. A clock is not a source of uniqueness either: cargo runs
//!   tests as threads of one process, and two calls inside one tick get the same name (the lesson
//!   `tempdir_lite` and `release.rs` both learned).
//! - **The mode is set on the temporary file, not after the rename.** A file that is created
//!   world-readable and tightened later is world-readable in between, and `0600` here is not
//!   decoration: this writer carries `config.toml`, `.env`, `MEMORY.md`, `jobs.toml` and the cron
//!   state.
//!
//! `sync_all` before the rename is what makes the promise survive a power cut rather than only a
//! killed process. It is the slow part, which is why it is here and not in a loop somewhere.

use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};

/// Distinguishes two writers in one process; the pid distinguishes processes.
static COUNTER: AtomicU64 = AtomicU64::new(0);

/// The sibling to write before renaming over `path`.
///
/// The name keeps the original file name as a prefix (`config.toml.4711-3.tmp`) so a leftover is
/// recognisable as ours and sits in the same directory — `rename` is only atomic within one
/// filesystem, and a temp directory elsewhere can be another one.
fn scratch(path: &Path, pid: u32, seq: u64) -> PathBuf {
    let mut name = path
        .file_name()
        .map(|n| n.to_os_string())
        .unwrap_or_default();
    name.push(format!(".{pid}-{seq}.tmp"));
    path.with_file_name(name)
}

/// Write `text` to `path` atomically, `0600`.
///
/// Kept infallible about the temporary file: a failure removes the scratch file and returns the
/// error, leaving the target untouched. That "leaves the target untouched" half is the whole point
/// and is asserted in the tests.
pub fn write_file_atomically(path: &Path, text: &str) -> std::io::Result<()> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let tmp = scratch(
        path,
        std::process::id(),
        COUNTER.fetch_add(1, Ordering::Relaxed),
    );
    let mut opts = std::fs::OpenOptions::new();
    opts.write(true).create_new(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        opts.mode(0o600);
    }
    let written = (|| -> std::io::Result<()> {
        let mut file = opts.open(&tmp)?;
        file.write_all(text.as_bytes())?;
        // A rename that lands before the bytes reach the disk publishes an empty file after a
        // power cut: the metadata moved, the data did not.
        file.sync_all()?;
        Ok(())
    })();
    if let Err(e) = written {
        let _ = std::fs::remove_file(&tmp);
        return Err(e);
    }
    if let Err(e) = std::fs::rename(&tmp, path) {
        let _ = std::fs::remove_file(&tmp);
        return Err(e);
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_write_leaves_no_scratch_file_behind() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        write_file_atomically(&path, "a = 1\n").unwrap();
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "a = 1\n");
        let names: Vec<String> = std::fs::read_dir(dir.path())
            .unwrap()
            .flatten()
            .map(|e| e.file_name().to_string_lossy().into_owned())
            .collect();
        assert_eq!(names, ["config.toml"], "the temporary file is gone");
    }

    #[test]
    fn every_writer_gets_its_own_scratch_name() {
        let path = Path::new("/tmp/x/config.toml");
        let (a, b) = (scratch(path, 7, 1), scratch(path, 7, 2));
        assert_ne!(a, b, "a counter, because two writers share one process");
        assert_ne!(scratch(path, 7, 1), scratch(path, 8, 1), "and a pid");
        assert_eq!(a.parent(), path.parent(), "same directory, so rename works");
        assert_eq!(
            a.file_name().unwrap().to_string_lossy(),
            "config.toml.7-1.tmp"
        );
    }

    /// The property the issue is about, driven rather than argued: a reader that opens the file in
    /// a tight loop must never see it empty or half-written. With `File::create` + `write_all` this
    /// fails within a few hundred iterations; with write-and-rename it cannot.
    #[test]
    fn a_reader_never_sees_a_half_written_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        let big_a = "a".repeat(200_000);
        let big_b = "b".repeat(200_000);
        write_file_atomically(&path, &big_a).unwrap();

        let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let expect = big_a.len();
        let reader = {
            let path = path.clone();
            let stop = stop.clone();
            std::thread::spawn(move || {
                let mut seen = 0usize;
                while !stop.load(std::sync::atomic::Ordering::Relaxed) {
                    let text = std::fs::read_to_string(&path).unwrap_or_default();
                    assert_eq!(
                        text.len(),
                        expect,
                        "a reader saw a {}-byte file, not the {expect} bytes written",
                        text.len()
                    );
                    seen += 1;
                }
                seen
            })
        };
        for i in 0..200 {
            write_file_atomically(&path, if i % 2 == 0 { &big_b } else { &big_a }).unwrap();
        }
        stop.store(true, std::sync::atomic::Ordering::Relaxed);
        let seen = reader.join().unwrap();
        assert!(seen > 0, "the reader ran at least once");
    }

    /// A write that cannot be renamed into place leaves the old file alone — the reason the
    /// temporary file exists. `rename` over a non-empty directory fails on every Unix.
    #[test]
    fn a_failed_write_leaves_the_old_file_intact() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("jobs.toml");
        write_file_atomically(&path, "kept\n").unwrap();
        // Make the destination impossible without touching the file itself: a directory named like
        // the target cannot be replaced by a rename.
        let blocked = dir.path().join("blocked.toml");
        std::fs::create_dir(&blocked).unwrap();
        std::fs::write(blocked.join("inner"), "x").unwrap();
        assert!(write_file_atomically(&blocked, "new\n").is_err());
        assert_eq!(
            std::fs::read_dir(&blocked).unwrap().count(),
            1,
            "the directory that was there is still there"
        );
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "kept\n",
            "and an unrelated file is untouched"
        );
    }
}