1use std::{io, path::Path};
4
5#[derive(Debug)]
7pub struct DurableReplaceError {
8 renamed: bool,
9 source: io::Error,
10}
11
12impl DurableReplaceError {
13 pub fn renamed(&self) -> bool {
16 self.renamed
17 }
18
19 pub(crate) fn new(source: io::Error, renamed: bool) -> Self {
20 Self { renamed, source }
21 }
22}
23
24impl std::fmt::Display for DurableReplaceError {
25 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26 self.source.fmt(f)
27 }
28}
29
30impl std::error::Error for DurableReplaceError {
31 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
32 Some(&self.source)
33 }
34}
35
36impl From<DurableReplaceError> for io::Error {
37 fn from(error: DurableReplaceError) -> Self {
38 error.source
39 }
40}
41
42pub fn durable_replace(from: &Path, to: &Path) -> Result<(), DurableReplaceError> {
47 durable_replace_impl(from, to, || Ok(()))
48}
49
50#[cfg(windows)]
53pub fn durable_move_to_new_name(from: &Path, to: &Path) -> io::Result<()> {
54 windows_move_file_ex(from, to, false)
55}
56
57#[cfg(feature = "test-support")]
62pub fn durable_replace_with_rename_hook(
63 from: &Path,
64 to: &Path,
65 after_rename: impl FnOnce() -> io::Result<()>,
66) -> Result<(), DurableReplaceError> {
67 durable_replace_impl(from, to, after_rename)
68}
69
70fn durable_replace_impl(
71 from: &Path,
72 to: &Path,
73 after_rename: impl FnOnce() -> io::Result<()>,
74) -> Result<(), DurableReplaceError> {
75 #[cfg(unix)]
76 {
77 std::fs::rename(from, to).map_err(|error| DurableReplaceError::new(error, false))?;
78 after_rename().map_err(|error| DurableReplaceError::new(error, true))?;
79 let parent = to.parent().ok_or_else(|| {
80 DurableReplaceError::new(
81 io::Error::new(io::ErrorKind::InvalidInput, "destination has no parent"),
82 true,
83 )
84 })?;
85 std::fs::File::open(parent)
86 .and_then(|directory| directory.sync_all())
87 .map_err(|error| DurableReplaceError::new(error, true))
88 }
89 #[cfg(windows)]
90 {
91 windows_replace_with_operation(
92 from,
93 to,
94 || windows_move(from, to).and_then(|()| after_rename()),
95 windows_path_identity,
96 )
97 }
98 #[cfg(not(any(unix, windows)))]
99 {
100 let _ = (from, to, after_rename);
101 Err(DurableReplaceError::new(
102 io::Error::new(
103 io::ErrorKind::Unsupported,
104 "durable replacement unsupported",
105 ),
106 false,
107 ))
108 }
109}
110
111#[cfg(windows)]
112#[derive(Clone, Copy, PartialEq, Eq)]
113struct FileIdentity {
114 volume: u32,
115 index: u64,
116}
117
118#[cfg(windows)]
119fn windows_open_identity(path: &Path) -> io::Result<std::fs::File> {
120 use std::os::windows::fs::OpenOptionsExt;
121 use windows_sys::Win32::Storage::FileSystem::{
122 FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE,
123 };
124 std::fs::OpenOptions::new()
125 .access_mode(0)
126 .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)
127 .open(path)
128}
129
130#[cfg(windows)]
131#[allow(unsafe_code)]
132fn windows_file_identity(file: &std::fs::File) -> io::Result<FileIdentity> {
133 use std::os::windows::io::AsRawHandle;
134 use windows_sys::Win32::Storage::FileSystem::{
135 GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION,
136 };
137 let mut information: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
139 if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut information) } == 0 {
142 return Err(io::Error::last_os_error());
143 }
144 Ok(FileIdentity {
145 volume: information.dwVolumeSerialNumber,
146 index: (u64::from(information.nFileIndexHigh) << 32) | u64::from(information.nFileIndexLow),
147 })
148}
149
150#[cfg(windows)]
151fn windows_path_identity(path: &Path) -> io::Result<Option<FileIdentity>> {
152 match windows_open_identity(path) {
153 Ok(file) => windows_file_identity(&file).map(Some),
154 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
155 Err(error) => Err(error),
156 }
157}
158
159#[cfg(windows)]
160fn windows_replace_with_operation(
161 from: &Path,
162 to: &Path,
163 operation: impl FnOnce() -> io::Result<()>,
164 inspect: impl Fn(&Path) -> io::Result<Option<FileIdentity>>,
165) -> Result<(), DurableReplaceError> {
166 let source =
167 windows_open_identity(from).map_err(|error| DurableReplaceError::new(error, false))?;
168 let identity =
169 windows_file_identity(&source).map_err(|error| DurableReplaceError::new(error, false))?;
170 let result = operation().map_err(|error| {
171 let renamed = match (inspect(from), inspect(to)) {
172 (Ok(None), Ok(Some(destination))) if destination == identity => true,
173 (Ok(Some(original)), Ok(_)) if original == identity => false,
174 _ => true,
179 };
180 DurableReplaceError::new(error, renamed)
181 });
182 drop(source);
185 result
186}
187
188#[cfg(windows)]
189fn windows_move(from: &Path, to: &Path) -> io::Result<()> {
190 if windows_posix_move(from, to)? {
191 Ok(())
192 } else {
193 windows_legacy_move(from, to)
197 }
198}
199
200#[cfg(windows)]
201fn windows_wide(path: &Path) -> io::Result<Vec<u16>> {
202 use std::os::windows::ffi::OsStrExt;
203 let mut result: Vec<_> = path.as_os_str().encode_wide().collect();
204 if result.contains(&0) {
205 return Err(io::Error::new(io::ErrorKind::InvalidInput, "NUL in path"));
206 }
207 result.push(0);
208 Ok(result)
209}
210
211#[cfg(windows)]
212#[allow(unsafe_code)]
213fn windows_posix_move(from: &Path, to: &Path) -> io::Result<bool> {
214 use std::{
215 mem::{offset_of, size_of},
216 os::windows::{fs::OpenOptionsExt, io::AsRawHandle},
217 };
218 use windows_sys::Win32::{
219 Foundation::{ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED, GENERIC_WRITE},
220 Storage::FileSystem::{
221 FileRenameInfoEx, SetFileInformationByHandle, DELETE, FILE_FLAG_WRITE_THROUGH,
222 FILE_RENAME_INFO, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE,
223 },
224 System::WindowsProgramming::{
225 FILE_RENAME_FLAG_POSIX_SEMANTICS, FILE_RENAME_FLAG_REPLACE_IF_EXISTS,
226 },
227 };
228 let destination = windows_wide(&std::path::absolute(to)?)?;
229 let name_bytes = (destination.len() - 1) * size_of::<u16>();
230 let buffer_bytes =
231 offset_of!(FILE_RENAME_INFO, FileName) + destination.len() * size_of::<u16>();
232 let length = u32::try_from(buffer_bytes)
233 .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "rename path too long"))?;
234 let mut buffer = vec![0usize; buffer_bytes.div_ceil(size_of::<usize>())];
237 let information = buffer.as_mut_ptr().cast::<FILE_RENAME_INFO>();
238 unsafe {
241 (*information).Anonymous.Flags =
242 FILE_RENAME_FLAG_REPLACE_IF_EXISTS | FILE_RENAME_FLAG_POSIX_SEMANTICS;
243 (*information).FileNameLength = name_bytes as u32;
244 std::ptr::copy_nonoverlapping(
245 destination.as_ptr(),
246 (*information).FileName.as_mut_ptr(),
247 destination.len(),
248 );
249 }
250 let file = std::fs::OpenOptions::new()
251 .access_mode(DELETE | GENERIC_WRITE)
252 .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)
253 .custom_flags(FILE_FLAG_WRITE_THROUGH)
254 .open(from)?;
255 if unsafe {
261 SetFileInformationByHandle(
262 file.as_raw_handle(),
263 FileRenameInfoEx,
264 information.cast(),
265 length,
266 )
267 } == 0
268 {
269 let error = io::Error::last_os_error();
270 if matches!(
271 error.raw_os_error().map(|code| code as u32),
272 Some(ERROR_INVALID_PARAMETER | ERROR_NOT_SUPPORTED)
273 ) {
274 return Ok(false);
278 }
279 return Err(error);
280 }
281 file.sync_all()?;
285 Ok(true)
286}
287
288#[cfg(windows)]
289fn windows_legacy_move(from: &Path, to: &Path) -> io::Result<()> {
290 windows_move_file_ex(from, to, true)
291}
292
293#[cfg(windows)]
294#[allow(unsafe_code)]
295fn windows_move_file_ex(from: &Path, to: &Path, replace: bool) -> io::Result<()> {
296 use windows_sys::Win32::Storage::FileSystem::{
297 MoveFileExW, MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH,
298 };
299 let from = windows_wide(from)?;
300 let to = windows_wide(to)?;
301 let flags = MOVEFILE_WRITE_THROUGH
306 | if replace {
307 MOVEFILE_REPLACE_EXISTING
308 } else {
309 0
310 };
311 if unsafe { MoveFileExW(from.as_ptr(), to.as_ptr(), flags) } == 0 {
312 return Err(io::Error::last_os_error());
313 }
314 Ok(())
315}
316
317#[cfg(test)]
318mod tests {
319 use super::*;
320 use std::{fs, io::Write};
321 fn root() -> cortexkit_test_support::ScratchDir {
322 cortexkit_test_support::ScratchDir::new("subc-durable-replace")
323 }
324 #[test]
325 fn durable_replace_replaces_existing_file() {
326 let root = root();
327 let from = root.join("stage");
328 let to = root.join("store");
329 fs::write(&to, b"previous").unwrap();
330 let mut file = fs::File::create(&from).unwrap();
331 file.write_all(b"next").unwrap();
332 file.sync_all().unwrap();
333 drop(file);
334 durable_replace(&from, &to).unwrap();
335 assert_eq!(fs::read(&to).unwrap(), b"next");
336 assert!(!from.exists());
337 }
338
339 #[cfg(windows)]
340 #[test]
341 fn durable_replace_windows_replaces_destination_with_readers_open() {
342 use std::{io::Read, os::windows::fs::OpenOptionsExt};
343 use windows_sys::Win32::Storage::FileSystem::{
344 FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE,
345 };
346 let root = root();
347 let (from, to) = replacement_files(&root);
348 let mut reader = fs::OpenOptions::new()
349 .read(true)
350 .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)
351 .open(&to)
352 .unwrap();
353 let captured = crate::open_regular_nofollow(&to).unwrap();
354 durable_replace(&from, &to).unwrap();
355 assert_eq!(fs::read(&to).unwrap(), b"next");
356 assert!(!from.exists());
357 let mut previous = Vec::new();
358 reader.read_to_end(&mut previous).unwrap();
359 assert_eq!(previous, b"previous");
360 assert_ne!(
361 crate::retained_file_identity(&captured).unwrap(),
362 crate::retained_file_identity(&fs::File::open(&to).unwrap()).unwrap()
363 );
364 }
365 #[test]
366 fn durable_replace_missing_source_is_error() {
367 let root = root();
368 let to = root.join("store");
369 fs::write(&to, b"previous").unwrap();
370 assert!(!durable_replace(&root.join("absent"), &to)
371 .unwrap_err()
372 .renamed());
373 assert_eq!(fs::read(&to).unwrap(), b"previous");
374 }
375
376 fn replacement_files(root: &Path) -> (std::path::PathBuf, std::path::PathBuf) {
377 let from = root.join("stage");
378 let to = root.join("store");
379 let mut file = fs::File::create(&from).unwrap();
380 file.write_all(b"next").unwrap();
381 file.sync_all().unwrap();
382 drop(file);
383 fs::write(&to, b"previous").unwrap();
384 (from, to)
385 }
386
387 #[cfg(unix)]
388 #[test]
389 fn durable_replace_sync_error_after_rename_retains_publication_witness() {
390 let root = root();
391 let (from, to) = replacement_files(&root);
392 let error = durable_replace_impl(&from, &to, || {
393 Err(io::Error::other("injected directory sync failure"))
394 })
395 .unwrap_err();
396 assert!(error.renamed(), "{error}");
397 assert_eq!(error.to_string(), "injected directory sync failure");
398 assert_eq!(fs::read(to).unwrap(), b"next");
399 assert!(!from.exists());
400 }
401
402 #[cfg(windows)]
403 #[test]
404 fn durable_replace_windows_error_after_real_move_reports_renamed() {
405 let root = root();
406 let (from, to) = replacement_files(&root);
407 let error = durable_replace_impl(&from, &to, || {
408 Err(io::Error::other("injected write-through failure"))
409 })
410 .unwrap_err();
411 assert!(error.renamed(), "{error}");
412 assert_eq!(error.to_string(), "injected write-through failure");
413 assert_eq!(fs::read(to).unwrap(), b"next");
414 assert!(!from.exists());
415 }
416
417 #[cfg(windows)]
418 #[test]
419 fn durable_replace_windows_error_without_move_reports_not_renamed() {
420 let root = root();
421 let (from, to) = replacement_files(&root);
422 let error = windows_replace_with_operation(
423 &from,
424 &to,
425 || Err(io::Error::other("injected pre-move failure")),
426 windows_path_identity,
427 )
428 .unwrap_err();
429 assert!(!error.renamed(), "{error}");
430 assert_eq!(fs::read(to).unwrap(), b"previous");
431 assert_eq!(fs::read(from).unwrap(), b"next");
432 }
433
434 #[cfg(windows)]
435 #[test]
436 fn durable_replace_windows_inspection_failure_advances_conservatively() {
437 let root = root();
438 let (from, to) = replacement_files(&root);
439 let error = windows_replace_with_operation(
440 &from,
441 &to,
442 || Err(io::Error::other("injected move failure")),
443 |path| {
444 if path == from {
445 windows_path_identity(path)
446 } else {
447 Err(io::Error::other("injected destination inspection failure"))
448 }
449 },
450 )
451 .unwrap_err();
452 assert!(
453 error.renamed(),
454 "uncertainty must retain the witness: {error}"
455 );
456 assert_eq!(error.to_string(), "injected move failure");
457 assert_eq!(fs::read(to).unwrap(), b"previous");
458 assert_eq!(fs::read(from).unwrap(), b"next");
459 }
460}