Skip to main content

coqui_peer/
file.rs

1//! Whole-file writes that a crash or a concurrent writer cannot leave half done: the contents
2//! go to a temporary file beside the target, are synced, and only then take the target's name.
3
4use std::fs::{self, OpenOptions};
5use std::io::{self, Write};
6use std::path::{Path, PathBuf};
7use std::time::{SystemTime, UNIX_EPOCH};
8
9/// Who may read a file written here.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
11#[non_exhaustive]
12pub enum Access {
13    /// What the process's defaults give a new file.
14    #[default]
15    Default,
16    /// The owner alone: mode `0600` on Unix. On Windows the file inherits its directory's
17    /// access control list, as with `Default`.
18    OwnerOnly,
19}
20
21/// Writes `contents` to `path` unless a file is there, atomically: a hard link from a synced
22/// temporary file, which fails when `path` exists, so an existing file is never replaced and
23/// of two concurrent writers exactly one wins. Parent directories are created.
24///
25/// # Errors
26///
27/// `AlreadyExists` when `path` exists; otherwise the filesystem's error. The temporary file
28/// is removed either way.
29pub fn write_new(path: &Path, contents: &[u8], access: Access) -> io::Result<()> {
30    let temporary = written(path, contents, access)?;
31    let result = retried(|| fs::hard_link(&temporary, path));
32    let _ = fs::remove_file(&temporary);
33    result
34}
35
36/// Writes `contents` to `path`, replacing any file there, atomically: a rename of a synced
37/// temporary file, so a reader sees the old contents or the new, never part of either. Parent
38/// directories are created.
39///
40/// # Errors
41///
42/// The filesystem's error; the temporary file is removed then.
43pub fn replace(path: &Path, contents: &[u8], access: Access) -> io::Result<()> {
44    let temporary = written(path, contents, access)?;
45    let result = retried(|| fs::rename(&temporary, path));
46    if result.is_err() {
47        let _ = fs::remove_file(&temporary);
48    }
49    result
50}
51
52/// Runs `operation`, and on Windows runs it again while it fails with `PermissionDenied`, for
53/// up to about a second: a file another handle holds open without delete sharing (a scanner
54/// that opens a file just written, a concurrent rename of it) cannot be renamed, linked or
55/// removed meanwhile, and the call fails with `ERROR_ACCESS_DENIED`.
56pub(crate) fn retried(mut operation: impl FnMut() -> io::Result<()>) -> io::Result<()> {
57    let mut wait = core::time::Duration::from_millis(2);
58    loop {
59        match operation() {
60            Err(error)
61                if cfg!(windows)
62                    && error.kind() == io::ErrorKind::PermissionDenied
63                    && wait <= core::time::Duration::from_millis(512) =>
64            {
65                std::thread::sleep(wait);
66                wait *= 2;
67            }
68            result => return result,
69        }
70    }
71}
72
73/// A synced temporary file beside `path` holding `contents`.
74fn written(path: &Path, contents: &[u8], access: Access) -> io::Result<PathBuf> {
75    let parent = path
76        .parent()
77        .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput))?;
78    if !parent.as_os_str().is_empty() {
79        fs::create_dir_all(parent)?;
80    }
81    let temporary = temporary_path(path);
82    let mut options = OpenOptions::new();
83    options.write(true).create_new(true);
84    #[cfg(unix)]
85    if access == Access::OwnerOnly {
86        use std::os::unix::fs::OpenOptionsExt;
87        options.mode(0o600);
88    }
89    #[cfg(not(unix))]
90    let _ = access;
91    let mut file = options.open(&temporary)?;
92    let result = file.write_all(contents).and_then(|()| file.sync_all());
93    drop(file);
94    match result {
95        Ok(()) => Ok(temporary),
96        Err(error) => {
97            let _ = fs::remove_file(&temporary);
98            Err(error)
99        }
100    }
101}
102
103/// A name beside `path` that no other call of this process uses, and that another process is
104/// unlikely to: the process id, the time and a counter.
105pub(crate) fn temporary_path(path: &Path) -> PathBuf {
106    static NEXT: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0);
107    let count = NEXT.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
108    let nonce = SystemTime::now()
109        .duration_since(UNIX_EPOCH)
110        .map_or(0, |elapsed| elapsed.as_nanos());
111    let mut name = path.file_name().unwrap_or_default().to_os_string();
112    name.push(format!(".{}.{}.{}.tmp", std::process::id(), nonce, count));
113    path.with_file_name(name)
114}