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