Skip to main content

fallow_types/
atomic_file.rs

1//! Atomic replacement of a cache file.
2//!
3//! The extraction cache and the graph cache both live in `.fallow/`, and more
4//! than one fallow process can write there at the same time: an editor server
5//! beside a CLI run, or a pre-commit hook beside an editor. A fixed temp name
6//! (`cache.bin.tmp`) let those writers truncate and interleave bytes in one
7//! shared file, so the renamed result could hold parts of two payloads, and a
8//! writer whose temp file another writer had already renamed failed outright.
9//! Each write here gets its own uniquely named temp file in the target
10//! directory, so the rename always moves one complete payload into place.
11
12use std::io::Write as _;
13use std::path::Path;
14
15/// The mode `File::create` requests on Unix, before the umask applies.
16#[cfg(unix)]
17const DEFAULT_FILE_MODE: u32 = 0o666;
18
19/// Replace `path` with `data` atomically, without `fsync`.
20///
21/// The data goes to a uniquely named temp file beside `path` and is then
22/// renamed over `path`. Readers see the old file or the new file, never a
23/// mix. Concurrent writers each move their own complete payload into place,
24/// and the last rename wins. A failed write removes its temp file.
25///
26/// Use this function only for a cache that fallow can build again. After a
27/// crash or a power loss, the file can be empty or cut short. The cache
28/// loaders refuse such a file when its framing or its payload does not
29/// decode. On macOS, `File::sync_all` flushes the drive cache. That flush was
30/// 60% to 90% of the parse cache save after a one-file edit. For data that
31/// fallow cannot build again, use [`write_atomic_synced`].
32///
33/// # Errors
34///
35/// Returns the IO error when `path` has no parent directory or file name, or
36/// when the temp file cannot be created, written, or renamed into place.
37pub fn write_atomic(path: &Path, data: &[u8]) -> std::io::Result<()> {
38    write_through_temp(path, data, false)
39}
40
41/// [`write_atomic`] with a best-effort `fsync` of the temp file before the
42/// rename, for data that fallow cannot build again.
43///
44/// # Errors
45///
46/// Returns the errors of [`write_atomic`].
47pub fn write_atomic_synced(path: &Path, data: &[u8]) -> std::io::Result<()> {
48    write_through_temp(path, data, true)
49}
50
51fn write_through_temp(path: &Path, data: &[u8], sync: bool) -> std::io::Result<()> {
52    let (Some(dir), Some(name)) = (path.parent(), path.file_name()) else {
53        return Err(std::io::Error::new(
54            std::io::ErrorKind::InvalidInput,
55            "cache file path has no parent directory or file name",
56        ));
57    };
58    let dir = if dir.as_os_str().is_empty() {
59        Path::new(".")
60    } else {
61        dir
62    };
63    let mut prefix = name.to_os_string();
64    prefix.push(".");
65    let mut builder = tempfile::Builder::new();
66    builder.prefix(&prefix).suffix(".tmp");
67    // A temp file is private (0600) by default. Ask for the mode that
68    // `File::create` uses, so the umask decides as before and a cache that
69    // another user or a CI container reads stays readable.
70    #[cfg(unix)]
71    {
72        use std::os::unix::fs::PermissionsExt as _;
73        builder.permissions(std::fs::Permissions::from_mode(DEFAULT_FILE_MODE));
74    }
75    let mut tmp = builder.tempfile_in(dir)?;
76    tmp.write_all(data)?;
77    if sync {
78        // Best effort: a filesystem without fsync support still gets the rename.
79        let _ = tmp.as_file().sync_all();
80    }
81    persist(tmp, path)
82}
83
84/// How often a rename over `path` is tried when another writer holds it.
85#[cfg(windows)]
86const PERSIST_ATTEMPTS: u32 = 20;
87
88/// The pause between two rename attempts.
89#[cfg(windows)]
90const PERSIST_RETRY_DELAY: std::time::Duration = std::time::Duration::from_millis(5);
91
92#[cfg(not(windows))]
93fn persist(tmp: tempfile::NamedTempFile, path: &Path) -> std::io::Result<()> {
94    tmp.persist(path).map_err(|error| error.error)?;
95    Ok(())
96}
97
98/// `ERROR_ACCESS_DENIED`: another writer replaces the target at this moment.
99#[cfg(windows)]
100const ERROR_ACCESS_DENIED: i32 = 5;
101/// `ERROR_SHARING_VIOLATION`: a reader holds the target open.
102#[cfg(windows)]
103const ERROR_SHARING_VIOLATION: i32 = 32;
104/// `ERROR_LOCK_VIOLATION`: a process holds a lock on part of the target.
105#[cfg(windows)]
106const ERROR_LOCK_VIOLATION: i32 = 33;
107
108/// Whether a failed rename is a short-lived conflict with another process.
109#[cfg(windows)]
110fn is_transient_rename_error(error: &std::io::Error) -> bool {
111    matches!(
112        error.raw_os_error(),
113        Some(ERROR_ACCESS_DENIED | ERROR_SHARING_VIOLATION | ERROR_LOCK_VIOLATION)
114    )
115}
116
117/// Windows refuses a rename over a file that another writer is replacing at
118/// the same moment (`ERROR_ACCESS_DENIED`), or that a reader or a scanner
119/// holds open. Those conflicts end within milliseconds, so a short bounded
120/// retry lets each writer move its payload into place.
121#[cfg(windows)]
122fn persist(mut tmp: tempfile::NamedTempFile, path: &Path) -> std::io::Result<()> {
123    let mut attempt = 1;
124    loop {
125        match tmp.persist(path) {
126            Ok(_) => return Ok(()),
127            Err(error) if is_transient_rename_error(&error.error) && attempt < PERSIST_ATTEMPTS => {
128                tmp = error.file;
129                attempt += 1;
130                std::thread::sleep(PERSIST_RETRY_DELAY);
131            }
132            Err(error) => return Err(error.error),
133        }
134    }
135}
136
137#[cfg(test)]
138mod tests {
139    use super::*;
140
141    fn dir_names(dir: &Path) -> Vec<String> {
142        let mut names: Vec<String> = std::fs::read_dir(dir)
143            .unwrap()
144            .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
145            .collect();
146        names.sort();
147        names
148    }
149
150    #[cfg_attr(miri, ignore = "the filesystem is blocked by Miri isolation")]
151    #[test]
152    fn write_replaces_the_file_and_leaves_no_temp_file() {
153        let dir = tempfile::tempdir().unwrap();
154        let path = dir.path().join("cache.bin");
155        write_atomic(&path, b"first").unwrap();
156        write_atomic(&path, b"second payload").unwrap();
157        assert_eq!(std::fs::read(&path).unwrap(), b"second payload");
158        assert_eq!(dir_names(dir.path()), ["cache.bin"]);
159    }
160
161    #[cfg_attr(miri, ignore = "the filesystem is blocked by Miri isolation")]
162    #[test]
163    fn concurrent_writers_each_move_one_whole_payload_into_place() {
164        const WRITERS: u8 = 8;
165        const ROUNDS: usize = 50;
166        const PAYLOAD_LEN: usize = 256 * 1024;
167        let dir = tempfile::tempdir().unwrap();
168        let path = dir.path().join("cache.bin");
169        let errors = std::sync::Mutex::new(Vec::<std::io::Error>::new());
170        std::thread::scope(|scope| {
171            for writer in 0..WRITERS {
172                let (path, errors) = (&path, &errors);
173                scope.spawn(move || {
174                    let payload = vec![writer; PAYLOAD_LEN];
175                    for _ in 0..ROUNDS {
176                        if let Err(error) = write_atomic(path, &payload) {
177                            errors.lock().unwrap().push(error);
178                        }
179                    }
180                });
181            }
182        });
183        let errors = errors.into_inner().unwrap();
184        assert!(errors.is_empty(), "writes failed: {errors:?}");
185
186        let data = std::fs::read(&path).unwrap();
187        assert_eq!(data.len(), PAYLOAD_LEN, "the file holds one whole payload");
188        assert!(
189            data.iter().all(|byte| *byte == data[0]),
190            "the file holds bytes from more than one writer"
191        );
192        assert_eq!(dir_names(dir.path()), ["cache.bin"]);
193    }
194
195    /// A cache that another user or a CI container reads must keep the mode a
196    /// plain `File::create` gives, not the private mode of a temp file.
197    #[cfg(unix)]
198    #[cfg_attr(miri, ignore = "the filesystem is blocked by Miri isolation")]
199    #[test]
200    fn the_file_gets_the_mode_that_file_create_gives() {
201        use std::os::unix::fs::PermissionsExt as _;
202        let dir = tempfile::tempdir().unwrap();
203        let reference = dir.path().join("reference");
204        std::fs::File::create(&reference).unwrap();
205        let path = dir.path().join("cache.bin");
206        write_atomic(&path, b"data").unwrap();
207        let mode = |path: &Path| std::fs::metadata(path).unwrap().permissions().mode() & 0o777;
208        assert_eq!(mode(&path), mode(&reference));
209    }
210
211    #[test]
212    fn a_path_without_a_file_name_is_refused() {
213        let error = write_atomic(Path::new("/"), b"data").unwrap_err();
214        assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
215    }
216}