Skip to main content

aft_base/
cross_volume.rs

1//! Moves between storage folders that may sit on different volumes.
2//!
3//! The rebuildable cache folders under the storage root (views, blobs,
4//! callgraph, semantic, index, symbols, inspect) can be placed on a separate
5//! volume, as a mount point or through a symlink. A `rename(2)` from one
6//! volume to another fails with `EXDEV` (`ERROR_NOT_SAME_DEVICE` on Windows),
7//! so a move whose source and destination folders can differ in volume goes
8//! through [`move_path`], which falls back to a copy that is published by a
9//! same-folder, no-replace rename in the destination and only then removes the
10//! source. Filesystems without no-replace support prefer an atomic hard link
11//! for regular files. Directories, and files where hard links are unsupported,
12//! use a non-atomic existence check before renaming.
13//!
14//! [`rename`] also refuses to replace an existing destination. Tests make it
15//! report the cross-device error for folders registered with
16//! `crate::walk_boundary::simulated_volumes`, because CI has no second volume.
17
18use std::fs;
19use std::io;
20use std::path::{Path, PathBuf};
21
22/// True when `error` is the operating system's "cannot move across volumes"
23/// error.
24pub(crate) fn is_cross_device(error: &io::Error) -> bool {
25    #[cfg(unix)]
26    if error.raw_os_error() == Some(libc::EXDEV) {
27        return true;
28    }
29    // ERROR_NOT_SAME_DEVICE
30    #[cfg(windows)]
31    if error.raw_os_error() == Some(17) {
32        return true;
33    }
34    error.kind() == io::ErrorKind::CrossesDevices
35}
36
37#[cfg(any(test, feature = "test-support"))]
38fn cross_device_error() -> io::Error {
39    #[cfg(unix)]
40    return io::Error::from_raw_os_error(libc::EXDEV);
41    #[cfg(windows)]
42    return io::Error::from_raw_os_error(17);
43    #[cfg(not(any(unix, windows)))]
44    return io::Error::from(io::ErrorKind::CrossesDevices);
45}
46
47/// Rename without replacing a destination, including an empty directory.
48/// When the filesystem lacks no-replace support, directories and files without
49/// hard-link support use a non-atomic existence check and rename. Each fallback
50/// reason produces one process-wide warning.
51// Cache retirement now uses directory-handle-relative renames. Keep this
52// pathname helper for the cross-volume fallback fixtures and other move users.
53#[allow(dead_code)]
54pub(crate) fn rename(from: &Path, to: &Path) -> io::Result<()> {
55    if let Some(error) = publish_no_replace(from, to)? {
56        Moved::PublishedWithWarning(error).warn_if_incomplete(from, to);
57    }
58    Ok(())
59}
60
61/// A warning means publication succeeded, but the hard-link fallback could
62/// not unlink its source. Never turn that into a pre-publication failure.
63fn publish_no_replace(from: &Path, to: &Path) -> io::Result<Option<io::Error>> {
64    #[cfg(any(test, feature = "test-support"))]
65    {
66        use crate::walk_boundary::simulated_volumes::device_of;
67        let source = device_of(from);
68        let destination = to.parent().and_then(device_of);
69        if (source.is_some() || destination.is_some()) && source != destination {
70            return Err(cross_device_error());
71        }
72    }
73    native_publish_no_replace(from, to)
74}
75
76#[cfg(any(target_os = "linux", target_os = "macos"))]
77fn native_publish_no_replace(from: &Path, to: &Path) -> io::Result<Option<io::Error>> {
78    let result = flagged_rename(from, to);
79    rename_or_fallback(from, to, result)
80}
81
82#[cfg(any(target_os = "linux", target_os = "macos"))]
83fn flagged_rename(from: &Path, to: &Path) -> io::Result<()> {
84    #[cfg(any(test, feature = "test-support"))]
85    if let Some(errno) = UNSUPPORTED_RENAME.with(|slot| slot.take()) {
86        return Err(io::Error::from_raw_os_error(errno));
87    }
88    use std::ffi::CString;
89    use std::os::unix::ffi::OsStrExt;
90    let source = CString::new(from.as_os_str().as_bytes())?;
91    let destination = CString::new(to.as_os_str().as_bytes())?;
92    // SAFETY: both paths are NUL-terminated and live through the syscall.
93    #[cfg(target_os = "macos")]
94    let result =
95        unsafe { libc::renamex_np(source.as_ptr(), destination.as_ptr(), libc::RENAME_EXCL) };
96    #[cfg(target_os = "linux")]
97    let result = unsafe {
98        libc::syscall(
99            libc::SYS_renameat2,
100            libc::AT_FDCWD,
101            source.as_ptr(),
102            libc::AT_FDCWD,
103            destination.as_ptr(),
104            libc::RENAME_NOREPLACE,
105        )
106    };
107    if result == 0 {
108        Ok(())
109    } else {
110        Err(io::Error::last_os_error())
111    }
112}
113
114#[cfg(any(target_os = "linux", target_os = "macos"))]
115fn rename_or_fallback(
116    from: &Path,
117    to: &Path,
118    result: io::Result<()>,
119) -> io::Result<Option<io::Error>> {
120    match result {
121        Ok(()) => Ok(None),
122        Err(error) if no_replace_unsupported(&error) => {
123            let metadata = fs::symlink_metadata(from)?;
124            if metadata.is_dir() {
125                return checked_rename(from, to, CheckedRenameReason::DirectoryWithoutNoReplace);
126            }
127            // Hard links still publish regular files atomically when native
128            // no-replace flags are unavailable. Other entry types are refused.
129            if !metadata.is_file() {
130                return Err(error);
131            }
132            match hard_link_for_publication(from, to) {
133                Ok(()) => {}
134                Err(error) if hard_link_unsupported(&error) => {
135                    return checked_rename(from, to, CheckedRenameReason::FileWithoutHardLinks);
136                }
137                Err(error) => return Err(error),
138            }
139            Ok(fs::remove_file(from).err().map(|error| {
140                io::Error::new(
141                    error.kind(),
142                    format!(
143                        "could not unlink published source {}: {error}",
144                        from.display()
145                    ),
146                )
147            }))
148        }
149        Err(error) => Err(error),
150    }
151}
152
153#[cfg(any(target_os = "linux", target_os = "macos"))]
154enum CheckedRenameReason {
155    DirectoryWithoutNoReplace,
156    FileWithoutHardLinks,
157}
158
159#[cfg(any(target_os = "linux", target_os = "macos"))]
160fn checked_rename(
161    from: &Path,
162    to: &Path,
163    reason: CheckedRenameReason,
164) -> io::Result<Option<io::Error>> {
165    // Some external/network filesystems support neither native no-replace nor
166    // hard links. Preserve moves there with the old rename behavior, but check
167    // first. Another process can still create a destination between this check
168    // and rename, and that destination can be replaced. The race is confined
169    // to filesystems where atomic publication is unavailable for this entry.
170    static DIRECTORY_WARN: std::sync::Once = std::sync::Once::new();
171    static FILE_WARN: std::sync::Once = std::sync::Once::new();
172    let (warning, reason) = match reason {
173        CheckedRenameReason::DirectoryWithoutNoReplace => (
174            &DIRECTORY_WARN,
175            "atomic no-replace rename is unavailable for directories",
176        ),
177        CheckedRenameReason::FileWithoutHardLinks => (
178            &FILE_WARN,
179            "atomic no-replace rename and hard links are unavailable for files",
180        ),
181    };
182    warning.call_once(|| {
183        crate::slog_warn!(
184            "{reason} at {}; using a non-atomic existence check before rename, which can race with destination creation",
185            to.display()
186        );
187    });
188    match fs::symlink_metadata(to) {
189        Ok(_) => return Err(io::Error::from(io::ErrorKind::AlreadyExists)),
190        Err(error) if error.kind() == io::ErrorKind::NotFound => {}
191        Err(error) => return Err(error),
192    }
193    fs::rename(from, to).map(|()| None)
194}
195
196#[cfg(any(target_os = "linux", target_os = "macos"))]
197fn hard_link_unsupported(error: &io::Error) -> bool {
198    // macOS msdos/exFAT reports EPERM for unsupported hard links. A link-count
199    // limit (EMLINK) or another permission/I/O failure must remain a refusal.
200    #[cfg(target_os = "macos")]
201    if error.raw_os_error() == Some(libc::EPERM) {
202        return true;
203    }
204    error
205        .raw_os_error()
206        .is_some_and(|errno| errno == libc::ENOTSUP || errno == libc::EOPNOTSUPP)
207}
208
209#[cfg(any(target_os = "linux", target_os = "macos"))]
210fn hard_link_for_publication(from: &Path, to: &Path) -> io::Result<()> {
211    #[cfg(any(test, feature = "test-support"))]
212    if let Some(errno) = UNSUPPORTED_LINK.with(|slot| slot.take()) {
213        return Err(io::Error::from_raw_os_error(errno));
214    }
215    fs::hard_link(from, to)
216}
217
218#[cfg(any(target_os = "linux", target_os = "macos"))]
219fn no_replace_unsupported(error: &io::Error) -> bool {
220    #[cfg(target_os = "macos")]
221    return error.raw_os_error() == Some(libc::ENOTSUP);
222    #[cfg(target_os = "linux")]
223    matches!(
224        error.raw_os_error(),
225        Some(libc::EINVAL | libc::ENOSYS | libc::ENOTSUP)
226    )
227}
228
229#[cfg(windows)]
230fn native_publish_no_replace(from: &Path, to: &Path) -> io::Result<Option<io::Error>> {
231    use std::os::windows::ffi::OsStrExt;
232    use windows_sys::Win32::Storage::FileSystem::MoveFileExW;
233    fn wide(path: &Path) -> io::Result<Vec<u16>> {
234        let mut wide: Vec<u16> = path.as_os_str().encode_wide().collect();
235        if wide.contains(&0) {
236            return Err(io::Error::new(io::ErrorKind::InvalidInput, "NUL in path"));
237        }
238        wide.push(0);
239        Ok(wide)
240    }
241    let source = wide(from)?;
242    let destination = wide(to)?;
243    // SAFETY: valid, NUL-terminated paths. No REPLACE_EXISTING or COPY_ALLOWED:
244    // collisions must be refused and cross-volume moves must use our staging.
245    if unsafe { MoveFileExW(source.as_ptr(), destination.as_ptr(), 0) } != 0 {
246        Ok(None)
247    } else {
248        let error = io::Error::last_os_error();
249        // Windows may report ACCESS_DENIED for an existing directory. Check
250        // only after the atomic refusal; this check never authorizes replacement.
251        if error.kind() == io::ErrorKind::PermissionDenied && fs::symlink_metadata(to).is_ok() {
252            Err(io::Error::new(io::ErrorKind::AlreadyExists, error))
253        } else {
254            Err(error)
255        }
256    }
257}
258
259#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
260fn native_publish_no_replace(_from: &Path, _to: &Path) -> io::Result<Option<io::Error>> {
261    Err(io::Error::new(
262        io::ErrorKind::Unsupported,
263        "atomic no-replace publication is unavailable on this platform",
264    ))
265}
266
267/// A successful result always makes the destination authoritative, even when
268/// finalization fails and a stale source copy remains.
269#[derive(Debug)]
270#[must_use = "report any move finalization warning before using the destination"]
271pub enum Moved {
272    /// One rename: source and destination are on the same volume.
273    Renamed,
274    /// The volumes differ: the source was copied, published under the
275    /// destination name, and then removed.
276    Copied,
277    /// The destination was published, but directory sync or source cleanup
278    /// failed. Callers must use the destination, not a leftover source copy.
279    PublishedWithWarning(io::Error),
280}
281
282impl Moved {
283    pub fn warn_if_incomplete(self, from: &Path, to: &Path) {
284        if let Self::PublishedWithWarning(error) = self {
285            crate::slog_warn!(
286                "moved {} to {}, but finalization failed; using the destination: {error}",
287                from.display(),
288                to.display()
289            );
290        }
291    }
292}
293
294/// A collision leaves the source untouched and belongs to the caller's policy:
295/// state repair adopts the winner, while data migrations retain their source.
296#[derive(Debug)]
297pub enum MoveError {
298    AlreadyPublished { cleanup_warning: Option<io::Error> },
299    Failed(io::Error),
300}
301
302impl MoveError {
303    #[cfg(any(test, feature = "test-support"))]
304    #[cfg_attr(not(test), allow(dead_code))]
305    pub(crate) fn kind(&self) -> io::ErrorKind {
306        match self {
307            Self::AlreadyPublished { .. } => io::ErrorKind::AlreadyExists,
308            Self::Failed(error) => error.kind(),
309        }
310    }
311
312    pub fn warn_if_incomplete(&self, to: &Path) {
313        if let Self::AlreadyPublished {
314            cleanup_warning: Some(error),
315        } = self
316        {
317            crate::slog_warn!("using already-published {}: {error}", to.display());
318        }
319    }
320}
321
322impl std::fmt::Display for MoveError {
323    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
324        match self {
325            Self::AlreadyPublished { cleanup_warning } => {
326                write!(f, "destination already published; source left in place")?;
327                if let Some(warning) = cleanup_warning {
328                    write!(f, "; {warning}")?;
329                }
330                Ok(())
331            }
332            Self::Failed(error) => error.fmt(f),
333        }
334    }
335}
336
337impl std::error::Error for MoveError {}
338
339impl From<io::Error> for MoveError {
340    fn from(error: io::Error) -> Self {
341        Self::Failed(error)
342    }
343}
344
345/// Move the file or directory `from` to `to`, which must not exist.
346///
347/// A same-volume move is one rename. A cross-volume move copies `from` into a
348/// staging name inside `to`'s own folder, syncs every copied file and folder,
349/// publishes the staging copy without replacement, and removes `from` last. If
350/// the copy fails, staging cleanup is attempted and `from` is left untouched.
351/// The source is authoritative unless [`MoveError::AlreadyPublished`]
352/// identifies a destination won by another mover. That outcome never removes
353/// the source and carries any staging-cleanup warning for the caller to report.
354/// Directories and linkless files on filesystems without native no-replace
355/// support use the checked, non-atomic fallback described by [`rename`].
356/// Once published, directory sync or source removal failures return
357/// [`Moved::PublishedWithWarning`]: callers must report the warning and use `to`.
358pub fn move_path(from: &Path, to: &Path) -> Result<Moved, MoveError> {
359    let parent = to
360        .parent()
361        .filter(|parent| !parent.as_os_str().is_empty())
362        .unwrap_or(Path::new("."));
363    let error = match publish_no_replace(from, to) {
364        Ok(warning) => {
365            return Ok(finish_publication(warning, parent, Moved::Renamed));
366        }
367        Err(error) => error,
368    };
369    if error.kind() == io::ErrorKind::AlreadyExists {
370        return Err(MoveError::AlreadyPublished {
371            cleanup_warning: None,
372        });
373    }
374    if !is_cross_device(&error) {
375        return Err(error.into());
376    }
377    if fs::symlink_metadata(to).is_ok() {
378        return Err(MoveError::AlreadyPublished {
379            cleanup_warning: None,
380        });
381    }
382    let staging = staging_path(parent, to)?;
383    let mut publishing = false;
384    let publication = copy_tree(from, &staging).and_then(|()| {
385        #[cfg(any(test, feature = "test-support"))]
386        before_publish()?;
387        publishing = true;
388        publish_no_replace(&staging, to)
389    });
390    let warning = match publication {
391        Ok(warning) => warning,
392        Err(error) => {
393            let cleanup_warning = cleanup_staging(&staging).err();
394            if publishing && error.kind() == io::ErrorKind::AlreadyExists {
395                return Err(MoveError::AlreadyPublished { cleanup_warning });
396            }
397            let cleanup = cleanup_warning
398                .map(|warning| format!("; {warning}"))
399                .unwrap_or_default();
400            let message = format!(
401                    "cannot move {} across volumes to {}: {error}; the source was left in place{cleanup}",
402                    from.display(), to.display(),
403                );
404            return Err(io::Error::new(error.kind(), message).into());
405        }
406    };
407    // Publication has committed the destination's authority. Keep the source
408    // until that directory entry is synced, but never select it for new writes.
409    if let Moved::PublishedWithWarning(error) = finish_publication(warning, parent, Moved::Copied) {
410        return Ok(Moved::PublishedWithWarning(error));
411    }
412    if let Err(error) = remove_path(from) {
413        return Ok(Moved::PublishedWithWarning(io::Error::new(
414            error.kind(),
415            format!("could not remove the source: {error}"),
416        )));
417    }
418    Ok(Moved::Copied)
419}
420
421fn finish_publication(warning: Option<io::Error>, parent: &Path, success: Moved) -> Moved {
422    let sync_error = crate::durability::sync_dir(parent).err();
423    match (warning, sync_error) {
424        (None, None) => success,
425        (Some(error), None) | (None, Some(error)) => Moved::PublishedWithWarning(error),
426        (Some(error), Some(sync)) => Moved::PublishedWithWarning(io::Error::new(
427            error.kind(),
428            format!("{error}; directory sync failed: {sync}"),
429        )),
430    }
431}
432
433fn cleanup_staging(path: &Path) -> io::Result<()> {
434    let cleanup = || {
435        #[cfg(windows)]
436        clear_staging_readonly(path)?;
437        #[cfg(any(test, feature = "test-support"))]
438        before_staging_removal(path);
439        remove_path(path)
440    };
441    cleanup().map_err(|error| {
442        io::Error::new(
443            error.kind(),
444            format!("could not remove staging copy {}: {error}", path.display()),
445        )
446    })
447}
448
449#[cfg(windows)]
450fn clear_staging_readonly(path: &Path) -> io::Result<()> {
451    let metadata = match fs::symlink_metadata(path) {
452        Ok(metadata) => metadata,
453        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
454        Err(error) => return Err(error),
455    };
456    // Only unpublished copies are made writable. Never follow a link into
457    // source data, or change permissions on a published destination.
458    if metadata.is_symlink() {
459        return Ok(());
460    }
461    if metadata.permissions().readonly() {
462        let mut permissions = metadata.permissions();
463        permissions.set_readonly(false);
464        fs::set_permissions(path, permissions)?;
465    }
466    if metadata.is_dir() {
467        for entry in fs::read_dir(path)? {
468            clear_staging_readonly(&entry?.path())?;
469        }
470    }
471    Ok(())
472}
473
474fn staging_path(parent: &Path, to: &Path) -> io::Result<PathBuf> {
475    let mut nonce = [0_u8; 8];
476    getrandom::fill(&mut nonce).map_err(io::Error::other)?;
477    Ok(parent.join(format!(
478        ".{}.aft-move-{}-{:016x}",
479        to.file_name().unwrap_or_default().to_string_lossy(),
480        std::process::id(),
481        u64::from_le_bytes(nonce)
482    )))
483}
484
485/// Copy `from` to the new path `to`, keeping permissions, and sync it.
486/// Symlinks are recreated as links (never followed); any other special file
487/// is refused rather than silently skipped.
488fn copy_tree(from: &Path, to: &Path) -> io::Result<()> {
489    let metadata = fs::symlink_metadata(from)?;
490    let kind = metadata.file_type();
491    if kind.is_symlink() {
492        #[cfg(unix)]
493        return std::os::unix::fs::symlink(fs::read_link(from)?, to);
494        #[cfg(not(unix))]
495        return Err(io::Error::new(
496            io::ErrorKind::Unsupported,
497            format!("cannot copy symlink {} across volumes", from.display()),
498        ));
499    }
500    if kind.is_file() {
501        fs::copy(from, to)?;
502        #[cfg(not(windows))]
503        aft_store::sync::sync_all(&fs::File::open(to)?, to)?;
504        #[cfg(windows)]
505        {
506            // FlushFileBuffers requires a writable handle. fs::copy preserves
507            // the readonly attribute, so clear it on the unpublished copy only
508            // and restore it even if opening or syncing the file fails.
509            let permissions = fs::metadata(to)?.permissions();
510            if permissions.readonly() {
511                let mut writable = permissions.clone();
512                writable.set_readonly(false);
513                fs::set_permissions(to, writable)?;
514            }
515            let synced = fs::OpenOptions::new()
516                .write(true)
517                .open(to)
518                .and_then(|file| aft_store::sync::sync_all(&file, to));
519            if permissions.readonly() {
520                fs::set_permissions(to, permissions)?;
521            }
522            synced?;
523        }
524        return Ok(());
525    }
526    if !kind.is_dir() {
527        return Err(io::Error::new(
528            io::ErrorKind::Unsupported,
529            format!("cannot copy special file {} across volumes", from.display()),
530        ));
531    }
532    fs::create_dir(to)?;
533    for entry in fs::read_dir(from)? {
534        let entry = entry?;
535        copy_tree(&entry.path(), &to.join(entry.file_name()))?;
536    }
537    fs::set_permissions(to, metadata.permissions())?;
538    crate::durability::sync_dir(to)
539}
540
541#[cfg(any(test, feature = "test-support"))]
542thread_local! {
543    #[cfg(any(target_os = "linux", target_os = "macos"))]
544    static UNSUPPORTED_RENAME: std::cell::Cell<Option<i32>> = const { std::cell::Cell::new(None) };
545    #[cfg(any(target_os = "linux", target_os = "macos"))]
546    static UNSUPPORTED_LINK: std::cell::Cell<Option<i32>> = const { std::cell::Cell::new(None) };
547    pub static BEFORE_PUBLISH: std::cell::RefCell<Option<Box<dyn FnOnce() -> io::Result<()>>>> = const {
548        std::cell::RefCell::new(None)
549    };
550    static BEFORE_STAGING_REMOVAL: std::cell::RefCell<Option<Box<dyn FnOnce(&Path)>>> = const {
551        std::cell::RefCell::new(None)
552    };
553    static FAIL_SOURCE_REMOVAL: std::cell::RefCell<Option<PathBuf>> = const {
554        std::cell::RefCell::new(None)
555    };
556}
557
558#[cfg(any(test, feature = "test-support"))]
559fn before_publish() -> io::Result<()> {
560    let hook = BEFORE_PUBLISH.with(|slot| slot.borrow_mut().take());
561    hook.map_or(Ok(()), |hook| hook())
562}
563
564#[cfg(any(test, feature = "test-support"))]
565fn before_staging_removal(path: &Path) {
566    let hook = BEFORE_STAGING_REMOVAL.with(|slot| slot.borrow_mut().take());
567    if let Some(hook) = hook {
568        hook(path);
569    }
570}
571
572fn remove_path(path: &Path) -> io::Result<()> {
573    #[cfg(any(test, feature = "test-support"))]
574    if FAIL_SOURCE_REMOVAL.with(|slot| {
575        let mut slot = slot.borrow_mut();
576        if slot.as_deref() == Some(path) {
577            slot.take();
578            true
579        } else {
580            false
581        }
582    }) {
583        return Err(io::Error::other("injected source removal failure"));
584    }
585    match fs::symlink_metadata(path) {
586        Ok(metadata) if metadata.is_dir() => fs::remove_dir_all(path),
587        Ok(_) => fs::remove_file(path),
588        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
589        Err(error) => Err(error),
590    }
591}
592
593#[cfg(test)]
594mod tests {
595    use super::*;
596    use crate::walk_boundary::simulated_volumes::simulate;
597
598    #[cfg(any(target_os = "linux", target_os = "macos"))]
599    #[test]
600    fn unsupported_flag_file_fallback_moves_without_replacing_an_existing_destination() {
601        unsupported_flag_fallback(false, None);
602    }
603
604    #[cfg(any(target_os = "linux", target_os = "macos"))]
605    #[test]
606    fn unsupported_flag_directory_fallback_moves_without_replacing_an_existing_destination() {
607        unsupported_flag_fallback(true, None);
608    }
609
610    #[cfg(any(target_os = "linux", target_os = "macos"))]
611    #[test]
612    fn linkless_file_fallback_moves_without_replacing_an_existing_destination() {
613        #[cfg(target_os = "linux")]
614        let errors = [libc::ENOTSUP, libc::EOPNOTSUPP];
615        #[cfg(target_os = "macos")]
616        let errors = [libc::ENOTSUP, libc::EOPNOTSUPP, libc::EPERM];
617        for errno in errors {
618            unsupported_flag_fallback(false, Some(errno));
619        }
620    }
621
622    #[cfg(any(target_os = "linux", target_os = "macos"))]
623    #[test]
624    fn link_limit_and_permission_errors_do_not_use_checked_rename() {
625        #[cfg(target_os = "linux")]
626        let errors = [libc::EMLINK, libc::EACCES, libc::EPERM];
627        #[cfg(target_os = "macos")]
628        let errors = [libc::EMLINK, libc::EACCES];
629        for errno in errors {
630            let temp = tempfile::tempdir().unwrap();
631            let source = temp.path().join("source");
632            let destination = temp.path().join("destination");
633            fs::write(&source, b"old").unwrap();
634            UNSUPPORTED_RENAME.with(|slot| slot.set(Some(libc::ENOTSUP)));
635            UNSUPPORTED_LINK.with(|slot| slot.set(Some(errno)));
636            let result = move_path(&source, &destination);
637            assert!(UNSUPPORTED_RENAME.with(|slot| slot.take()).is_none());
638            assert!(UNSUPPORTED_LINK.with(|slot| slot.take()).is_none());
639            assert!(
640                matches!(result, Err(MoveError::Failed(ref error)) if error.raw_os_error() == Some(errno)),
641                "{result:?}"
642            );
643            assert_eq!(fs::read(&source).unwrap(), b"old");
644            assert!(!destination.exists());
645        }
646    }
647
648    #[cfg(any(target_os = "linux", target_os = "macos"))]
649    fn unsupported_flag_fallback(directory: bool, link_error: Option<i32>) {
650        #[cfg(target_os = "linux")]
651        let errors = [libc::EINVAL, libc::ENOSYS, libc::ENOTSUP];
652        #[cfg(target_os = "macos")]
653        let errors = [libc::ENOTSUP];
654        for errno in errors {
655            for cross_volume in [false, true] {
656                let temp = tempfile::tempdir().unwrap();
657                let source = temp.path().join("source");
658                let other = temp.path().join("destination-volume");
659                fs::create_dir(&other).unwrap();
660                let _volume = cross_volume.then(|| simulate(&other, u64::MAX - 14));
661                let destination = other.join("destination");
662                let create_source = || {
663                    if directory {
664                        fs::create_dir(&source).unwrap();
665                        fs::write(source.join("state.json"), b"old").unwrap();
666                    } else {
667                        fs::write(&source, b"old").unwrap();
668                    }
669                };
670                create_source();
671                UNSUPPORTED_RENAME.with(|slot| slot.set(Some(errno)));
672                UNSUPPORTED_LINK.with(|slot| slot.set(link_error));
673                let result = move_path(&source, &destination);
674                assert!(
675                    UNSUPPORTED_RENAME.with(|slot| slot.take()).is_none(),
676                    "the unsupported syscall seam must execute"
677                );
678                assert!(
679                    UNSUPPORTED_LINK.with(|slot| slot.take()).is_none(),
680                    "the injected link error must execute"
681                );
682                assert!(result.is_ok(), "fallback must move the source: {result:?}");
683                assert!(!source.exists());
684                let saved = if directory {
685                    destination.join("state.json")
686                } else {
687                    destination.clone()
688                };
689                assert_eq!(fs::read(&saved).unwrap(), b"old");
690
691                if cross_volume {
692                    continue;
693                }
694                create_source();
695                fs::write(&saved, b"new").unwrap();
696                if directory {
697                    // Empty destinations are replaceable by POSIX rename, so
698                    // the fallback's existence check must protect them too.
699                    fs::remove_file(&saved).unwrap();
700                }
701                UNSUPPORTED_RENAME.with(|slot| slot.set(Some(errno)));
702                UNSUPPORTED_LINK.with(|slot| slot.set(link_error));
703                let result = move_path(&source, &destination);
704                assert!(
705                    UNSUPPORTED_RENAME.with(|slot| slot.take()).is_none(),
706                    "the collision must reach the unsupported syscall seam"
707                );
708                assert!(
709                    UNSUPPORTED_LINK.with(|slot| slot.take()).is_none(),
710                    "the collision must reach the injected link error"
711                );
712                assert!(
713                    matches!(
714                        result,
715                        Err(MoveError::AlreadyPublished {
716                            cleanup_warning: None
717                        })
718                    ),
719                    "{result:?}"
720                );
721                assert!(source.exists(), "collision must keep the source");
722                if directory {
723                    assert_eq!(fs::read_dir(&destination).unwrap().count(), 0);
724                    assert_eq!(fs::read(source.join("state.json")).unwrap(), b"old");
725                } else {
726                    assert_eq!(fs::read(&saved).unwrap(), b"new");
727                    assert_eq!(fs::read(&source).unwrap(), b"old");
728                }
729            }
730        }
731    }
732
733    #[test]
734    fn cross_volume_racing_file_publish_keeps_the_winners_new_value() {
735        let temp = tempfile::tempdir().unwrap();
736        let source = temp.path().join("state.json");
737        fs::write(&source, b"old").unwrap();
738        let other = temp.path().join("other-volume");
739        fs::create_dir(&other).unwrap();
740        let _volume = simulate(&other, u64::MAX - 10);
741        let destination = other.join("state.json");
742        let source_clone = source.clone();
743        let destination_clone = destination.clone();
744        BEFORE_PUBLISH.with(|slot| {
745            *slot.borrow_mut() = Some(Box::new(move || {
746                // The outer copier has staged the old bytes. A second process
747                // stages the same bytes, publishes first, and then saves state.
748                assert!(matches!(
749                    move_path(&source_clone, &destination_clone).unwrap(),
750                    Moved::Copied
751                ));
752                fs::write(destination_clone, b"new")
753            }));
754        });
755
756        let result = move_path(&source, &destination);
757        assert_eq!(fs::read(&destination).unwrap(), b"new");
758        assert!(matches!(
759            result,
760            Err(MoveError::AlreadyPublished {
761                cleanup_warning: None
762            })
763        ));
764        assert_eq!(fs::read_dir(other).unwrap().count(), 1);
765    }
766
767    #[test]
768    fn cross_volume_racing_directory_publish_preserves_the_winner() {
769        let temp = tempfile::tempdir().unwrap();
770        let source = temp.path().join("source");
771        fs::create_dir(&source).unwrap();
772        let other = temp.path().join("other-volume");
773        fs::create_dir(&other).unwrap();
774        let _volume = simulate(&other, u64::MAX - 11);
775        let destination = other.join("directory");
776        let source_clone = source.clone();
777        let destination_clone = destination.clone();
778        BEFORE_PUBLISH.with(|slot| {
779            *slot.borrow_mut() = Some(Box::new(move || {
780                assert!(matches!(
781                    move_path(&source_clone, &destination_clone).unwrap(),
782                    Moved::Copied
783                ));
784                // Leave the winner empty: POSIX rename can replace an empty
785                // directory too, even though it refuses a nonempty directory.
786                Ok(())
787            }));
788        });
789
790        let result = move_path(&source, &destination);
791        assert!(
792            matches!(
793                result,
794                Err(MoveError::AlreadyPublished {
795                    cleanup_warning: None
796                })
797            ),
798            "the losing directory publisher must refuse: {result:?}"
799        );
800        assert!(destination.is_dir());
801        assert_eq!(fs::read_dir(other).unwrap().count(), 1);
802    }
803
804    #[test]
805    fn same_volume_move_never_replaces_a_file_or_empty_directory() {
806        for directory in [false, true] {
807            let temp = tempfile::tempdir().unwrap();
808            let source = temp.path().join("source");
809            let destination = temp.path().join("destination");
810            if directory {
811                fs::create_dir(&source).unwrap();
812                fs::create_dir(&destination).unwrap();
813            } else {
814                fs::write(&source, b"old").unwrap();
815                fs::write(&destination, b"new").unwrap();
816            }
817            assert!(matches!(
818                move_path(&source, &destination),
819                Err(MoveError::AlreadyPublished {
820                    cleanup_warning: None
821                })
822            ));
823            assert!(source.exists());
824            if !directory {
825                assert_eq!(fs::read(&destination).unwrap(), b"new");
826                assert_eq!(fs::read(&source).unwrap(), b"old");
827            }
828        }
829    }
830
831    #[test]
832    fn failed_move_carries_staging_cleanup_failure_with_its_path() {
833        for collision in [false, true] {
834            let temp = tempfile::tempdir().unwrap();
835            let source = temp.path().join("source");
836            fs::write(&source, b"old").unwrap();
837            let other = temp.path().join("other-volume");
838            fs::create_dir(&other).unwrap();
839            let _volume = simulate(&other, u64::MAX - 13);
840            let destination = other.join("destination");
841            let destination_clone = destination.clone();
842            BEFORE_PUBLISH.with(|slot| {
843                *slot.borrow_mut() = Some(Box::new(move || {
844                    if collision {
845                        fs::write(destination_clone, b"new")
846                    } else {
847                        Err(io::Error::other("injected publication failure"))
848                    }
849                }));
850            });
851            BEFORE_STAGING_REMOVAL.with(|slot| {
852                *slot.borrow_mut() = Some(Box::new(|staging| {
853                    FAIL_SOURCE_REMOVAL
854                        .with(|slot| *slot.borrow_mut() = Some(staging.to_path_buf()));
855                }));
856            });
857            let error = move_path(&source, &destination).unwrap_err();
858            let message = error.to_string();
859            assert!(
860                message.contains("could not remove staging copy"),
861                "{message}"
862            );
863            assert!(message.contains(".destination.aft-move-"), "{message}");
864            assert!(
865                message.contains("injected source removal failure"),
866                "{message}"
867            );
868            assert_eq!(
869                matches!(
870                    error,
871                    MoveError::AlreadyPublished {
872                        cleanup_warning: Some(_)
873                    }
874                ),
875                collision
876            );
877            assert_eq!(fs::read(&source).unwrap(), b"old");
878            if collision {
879                assert_eq!(fs::read(&destination).unwrap(), b"new");
880            }
881        }
882    }
883
884    #[cfg(windows)]
885    #[test]
886    fn cross_volume_failed_publish_cleans_readonly_staging() {
887        for directory in [false, true] {
888            let temp = tempfile::tempdir().unwrap();
889            let source = temp.path().join("source");
890            let file = if directory {
891                fs::create_dir_all(source.join("nested")).unwrap();
892                source.join("nested/state.json")
893            } else {
894                source.clone()
895            };
896            fs::write(&file, b"old").unwrap();
897            let mut permissions = fs::metadata(&file).unwrap().permissions();
898            permissions.set_readonly(true);
899            fs::set_permissions(&file, permissions).unwrap();
900            let other = temp.path().join("other-volume");
901            fs::create_dir(&other).unwrap();
902            let _volume = simulate(&other, u64::MAX - 12);
903            BEFORE_PUBLISH.with(|slot| {
904                *slot.borrow_mut() = Some(Box::new(|| {
905                    Err(io::Error::other("injected publication failure"))
906                }));
907            });
908            BEFORE_STAGING_REMOVAL.with(|slot| {
909                *slot.borrow_mut() = Some(Box::new(|staging| {
910                    fn assert_writable(path: &Path) {
911                        let metadata = fs::symlink_metadata(path).unwrap();
912                        assert!(
913                            !metadata.permissions().readonly(),
914                            "staging must be writable before unlink: {}",
915                            path.display()
916                        );
917                        if metadata.is_dir() {
918                            for entry in fs::read_dir(path).unwrap() {
919                                assert_writable(&entry.unwrap().path());
920                            }
921                        }
922                    }
923                    // Newer Windows versions can ignore readonly during unlink.
924                    // Check the actual attributes too, so older hosts stay safe.
925                    assert_writable(staging);
926                }));
927            });
928
929            let error = move_path(&source, &other.join("destination")).unwrap_err();
930            let leftovers = fs::read_dir(&other).unwrap().count();
931            let source_readonly = fs::metadata(&file).unwrap().permissions().readonly();
932            let mut permissions = fs::metadata(&file).unwrap().permissions();
933            permissions.set_readonly(false);
934            fs::set_permissions(&file, permissions).unwrap();
935            assert!(error.to_string().contains("injected publication failure"));
936            assert_eq!(leftovers, 0, "readonly staging must be removed");
937            assert!(source_readonly, "cleanup must not change the source");
938        }
939    }
940
941    #[test]
942    fn cross_volume_move_copies_publishes_and_removes_the_source() {
943        let temp = tempfile::tempdir().unwrap();
944        let source = temp.path().join("source");
945        fs::create_dir_all(source.join("nested")).unwrap();
946        fs::write(source.join("a.json"), b"first").unwrap();
947        fs::write(source.join("nested/b.bin"), b"second").unwrap();
948        let other = temp.path().join("other-volume");
949        fs::create_dir(&other).unwrap();
950        let _volume = simulate(&other, u64::MAX - 1);
951        let destination = other.join("moved");
952
953        assert!(
954            is_cross_device(&rename(&source, &destination).unwrap_err()),
955            "the seam must reproduce the kernel's cross-volume refusal"
956        );
957        assert!(matches!(
958            move_path(&source, &destination).unwrap(),
959            Moved::Copied
960        ));
961
962        assert!(!source.exists(), "the source is removed after the copy");
963        assert_eq!(fs::read(destination.join("a.json")).unwrap(), b"first");
964        assert_eq!(
965            fs::read(destination.join("nested/b.bin")).unwrap(),
966            b"second"
967        );
968        let leftovers = fs::read_dir(&other)
969            .unwrap()
970            .map(|entry| entry.unwrap().file_name())
971            .collect::<Vec<_>>();
972        assert_eq!(leftovers, vec![std::ffi::OsString::from("moved")]);
973    }
974
975    #[test]
976    fn same_volume_move_is_one_rename() {
977        let temp = tempfile::tempdir().unwrap();
978        let source = temp.path().join("file");
979        fs::write(&source, b"x").unwrap();
980        let destination = temp.path().join("renamed");
981        assert!(matches!(
982            move_path(&source, &destination).unwrap(),
983            Moved::Renamed
984        ));
985        assert_eq!(fs::read(destination).unwrap(), b"x");
986    }
987
988    #[test]
989    fn copied_readonly_file_is_synced_and_keeps_its_permissions() {
990        let temp = tempfile::tempdir().unwrap();
991        let source = temp.path().join("readonly.json");
992        fs::write(&source, b"keep").unwrap();
993        let original_permissions = fs::metadata(&source).unwrap().permissions();
994        let mut readonly = original_permissions.clone();
995        readonly.set_readonly(true);
996        fs::set_permissions(&source, readonly).unwrap();
997        let destination = temp.path().join("staging.json");
998
999        let copied = copy_tree(&source, &destination);
1000        let source_readonly = fs::metadata(&source).unwrap().permissions().readonly();
1001        let destination_readonly = fs::metadata(&destination).unwrap().permissions().readonly();
1002        // Restore writable permissions before asserting so Windows can clean
1003        // up the fixture even when the copy or permission assertion fails.
1004        fs::set_permissions(&source, original_permissions.clone()).unwrap();
1005        fs::set_permissions(&destination, original_permissions).unwrap();
1006
1007        copied.unwrap();
1008        assert!(source_readonly, "the source permissions must not change");
1009        assert!(destination_readonly, "the copy must keep its permissions");
1010        assert_eq!(fs::read(&destination).unwrap(), b"keep");
1011    }
1012
1013    #[test]
1014    fn cross_volume_move_refuses_an_existing_destination_and_keeps_the_source() {
1015        let temp = tempfile::tempdir().unwrap();
1016        let source = temp.path().join("state.json");
1017        fs::write(&source, b"keep").unwrap();
1018        let other = temp.path().join("other-volume");
1019        fs::create_dir(&other).unwrap();
1020        let _volume = simulate(&other, u64::MAX - 2);
1021        let destination = other.join("state.json");
1022        fs::write(&destination, b"existing").unwrap();
1023
1024        let error = move_path(&source, &destination).unwrap_err();
1025        assert_eq!(error.kind(), io::ErrorKind::AlreadyExists);
1026        assert_eq!(fs::read(&source).unwrap(), b"keep");
1027        assert_eq!(fs::read(&destination).unwrap(), b"existing");
1028    }
1029
1030    #[test]
1031    fn cross_volume_published_copy_reports_directory_sync_failure() {
1032        let temp = tempfile::tempdir().unwrap();
1033        let source = temp.path().join("state.json");
1034        fs::write(&source, b"old").unwrap();
1035        let other = temp.path().join("other-volume");
1036        fs::create_dir(&other).unwrap();
1037        let _volume = simulate(&other, u64::MAX - 5);
1038        let destination = other.join("state.json");
1039        crate::durability::FAIL_DIRECTORY_SYNC.with(|slot| {
1040            *slot.borrow_mut() = Some(other.clone());
1041        });
1042
1043        let Moved::PublishedWithWarning(error) = move_path(&source, &destination).unwrap() else {
1044            panic!("the destination is published but its directory sync failed");
1045        };
1046        assert_eq!(error.to_string(), "injected directory sync failure");
1047        assert_eq!(fs::read(&destination).unwrap(), b"old");
1048        assert_eq!(fs::read(&source).unwrap(), b"old");
1049    }
1050
1051    #[test]
1052    fn cross_volume_published_copy_reports_source_removal_failure() {
1053        let temp = tempfile::tempdir().unwrap();
1054        let source = temp.path().join("state.json");
1055        fs::write(&source, b"old").unwrap();
1056        let other = temp.path().join("other-volume");
1057        fs::create_dir(&other).unwrap();
1058        let _volume = simulate(&other, u64::MAX - 6);
1059        let destination = other.join("state.json");
1060        FAIL_SOURCE_REMOVAL.with(|slot| {
1061            *slot.borrow_mut() = Some(source.clone());
1062        });
1063
1064        let Moved::PublishedWithWarning(error) = move_path(&source, &destination).unwrap() else {
1065            panic!("the destination is published but source cleanup failed");
1066        };
1067        assert_eq!(
1068            error.to_string(),
1069            "could not remove the source: injected source removal failure"
1070        );
1071        assert_eq!(fs::read(&destination).unwrap(), b"old");
1072        assert_eq!(fs::read(&source).unwrap(), b"old");
1073    }
1074
1075    #[test]
1076    fn same_volume_published_rename_reports_directory_sync_failure() {
1077        let temp = tempfile::tempdir().unwrap();
1078        let source = temp.path().join("state.json");
1079        fs::write(&source, b"old").unwrap();
1080        let destination = temp.path().join("renamed.json");
1081        crate::durability::FAIL_DIRECTORY_SYNC.with(|slot| {
1082            *slot.borrow_mut() = Some(temp.path().to_path_buf());
1083        });
1084
1085        let Moved::PublishedWithWarning(error) = move_path(&source, &destination).unwrap() else {
1086            panic!("the destination is published but its directory sync failed");
1087        };
1088        assert_eq!(error.to_string(), "injected directory sync failure");
1089        assert_eq!(fs::read(&destination).unwrap(), b"old");
1090        assert!(!source.exists());
1091    }
1092}