fallow_types/
atomic_file.rs1use std::io::Write as _;
13use std::path::Path;
14
15#[cfg(unix)]
17const DEFAULT_FILE_MODE: u32 = 0o666;
18
19pub fn write_atomic(path: &Path, data: &[u8]) -> std::io::Result<()> {
38 write_through_temp(path, data, false)
39}
40
41pub 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 #[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 let _ = tmp.as_file().sync_all();
80 }
81 persist(tmp, path)
82}
83
84#[cfg(windows)]
86const PERSIST_ATTEMPTS: u32 = 20;
87
88#[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#[cfg(windows)]
100const ERROR_ACCESS_DENIED: i32 = 5;
101#[cfg(windows)]
103const ERROR_SHARING_VIOLATION: i32 = 32;
104#[cfg(windows)]
106const ERROR_LOCK_VIOLATION: i32 = 33;
107
108#[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#[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 #[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}