Skip to main content

pb_mapper_core/
durable_file.rs

1//! Atomic replace and parent-directory durability.
2//!
3//! These are general file primitives, not credential ones — they lived in the
4//! auth persistence layer only because that is where the first caller was.
5//! [`replace_contents`] is the whole sequence for a state file; [`replace_file`]
6//! and [`sync_parent_directory`] are its last two steps, for callers that write
7//! their new file some other way. Those two report `io::Result` and leave it to
8//! the caller to map into its own error type.
9
10use std::fs::{File, OpenOptions};
11use std::io::Write;
12use std::path::{Path, PathBuf};
13
14use rand::TryRng;
15use rand::rngs::SysRng;
16use snafu::Snafu;
17
18/// The permissions [`replace_contents`] gives the new file on unix. Ignored
19/// elsewhere, where the new file takes the platform's default.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum NewFileMode {
22    /// What creating a file gives it: `0o666` less the umask.
23    Default,
24    /// Exactly this mode. The file is created with it, so it is never more
25    /// open than this, and set to it before its first byte is written, so
26    /// the umask takes nothing away either.
27    Exactly(u32),
28    /// The replaced file's permissions, or [`Self::Default`]'s when there is
29    /// no file to replace.
30    KeepExisting,
31}
32
33/// The step of [`replace_contents`] that failed.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum ReplaceStep {
36    /// Creating the temporary file beside the target.
37    Create,
38    /// Giving the temporary file its [`NewFileMode`].
39    SetPermissions,
40    /// Writing the temporary file and syncing it.
41    Write,
42    /// Renaming the temporary file over the target.
43    Replace,
44    /// Syncing the directory that holds the target.
45    SyncParent,
46}
47
48impl ReplaceStep {
49    fn verb(self) -> &'static str {
50        match self {
51            Self::Create => "create",
52            Self::SetPermissions => "set the permissions of",
53            Self::Write => "write",
54            Self::Replace => "replace",
55            Self::SyncParent => "sync the directory of",
56        }
57    }
58}
59
60/// A [`replace_contents`] failure: the step, the file it touched and the cause.
61#[derive(Debug, Snafu)]
62#[snafu(display("failed to {} `{}`", step.verb(), path.display()))]
63pub struct ReplaceError {
64    pub step: ReplaceStep,
65    /// The temporary file for [`ReplaceStep::Create`],
66    /// [`ReplaceStep::SetPermissions`] and [`ReplaceStep::Write`]; the target
67    /// for [`ReplaceStep::Replace`] and [`ReplaceStep::SyncParent`], and for a
68    /// [`ReplaceStep::Create`] that failed before the temporary had a name.
69    pub path: PathBuf,
70    source: std::io::Error,
71}
72
73impl ReplaceError {
74    /// The underlying failure, for callers that word their own message.
75    pub fn io(&self) -> &std::io::Error {
76        &self.source
77    }
78}
79
80impl From<ReplaceError> for std::io::Error {
81    /// The underlying failure, kind and text unchanged, for `io::Result` callers.
82    fn from(error: ReplaceError) -> Self {
83        error.source
84    }
85}
86
87/// Replaces `path` with `bytes` all at once, so a crash leaves the old file or
88/// the new one, never a torn one.
89///
90/// The bytes go to a new file beside `path`, named
91/// `.{file name}.tmp-{pid}-{16 random hex digits}`, opened with `create_new`
92/// and given `mode` before its first byte. The digits come from the operating
93/// system's random source; when that fails, so does the create step. That
94/// file is synced, renamed over `path` with [`replace_file`], and the
95/// directory synced.
96/// On failure the temporary file is removed and `path` is left as it was —
97/// unless only the final directory sync failed, by which time it is replaced.
98///
99/// The directory must exist: each caller creates it with its own wording for
100/// that failure. The directory synced is the one [`sync_parent_directory`]
101/// syncs, so a bare file name, whose parent is the empty path, fails that last
102/// step; join it to `.` to mean the current directory.
103pub fn replace_contents(path: &Path, bytes: &[u8], mode: NewFileMode) -> Result<(), ReplaceError> {
104    let Some(file_name) = path.file_name() else {
105        return Err(ReplaceError {
106            step: ReplaceStep::Create,
107            path: path.to_path_buf(),
108            source: std::io::Error::new(std::io::ErrorKind::InvalidInput, "no file name"),
109        });
110    };
111    // Straight from the operating system, which can fail where the thread RNG
112    // would panic.
113    let suffix = SysRng.try_next_u64().map_err(|error| ReplaceError {
114        step: ReplaceStep::Create,
115        path: path.to_path_buf(),
116        source: std::io::Error::other(error),
117    })?;
118    let temporary = path.with_file_name(format!(
119        ".{}.tmp-{}-{suffix:016x}",
120        file_name.to_string_lossy(),
121        std::process::id()
122    ));
123    let mut options = OpenOptions::new();
124    options.write(true).create_new(true);
125    create_with_mode(&mut options, mode);
126    let file = options.open(&temporary).map_err(|source| ReplaceError {
127        step: ReplaceStep::Create,
128        path: temporary.clone(),
129        source,
130    })?;
131    let result = write_and_replace(file, &temporary, path, bytes, mode);
132    if result.is_err() {
133        // Best effort: after a rename this names nothing, and either way no
134        // later call would clean it up.
135        let _ = std::fs::remove_file(&temporary);
136    }
137    result
138}
139
140fn write_and_replace(
141    mut file: File,
142    temporary: &Path,
143    path: &Path,
144    bytes: &[u8],
145    mode: NewFileMode,
146) -> Result<(), ReplaceError> {
147    let failed = |step, at: &Path| {
148        let path = at.to_path_buf();
149        move |source| ReplaceError { step, path, source }
150    };
151    set_mode(&file, path, mode).map_err(failed(ReplaceStep::SetPermissions, temporary))?;
152    file.write_all(bytes)
153        .and_then(|()| file.sync_all())
154        .map_err(failed(ReplaceStep::Write, temporary))?;
155    drop(file);
156    replace_file(temporary, path).map_err(failed(ReplaceStep::Replace, path))?;
157    sync_parent_directory(path).map_err(failed(ReplaceStep::SyncParent, path))
158}
159
160#[cfg(unix)]
161fn create_with_mode(options: &mut OpenOptions, mode: NewFileMode) {
162    use std::os::unix::fs::OpenOptionsExt;
163    if let NewFileMode::Exactly(mode) = mode {
164        options.mode(mode);
165    }
166}
167
168#[cfg(not(unix))]
169fn create_with_mode(_: &mut OpenOptions, _: NewFileMode) {}
170
171#[cfg(unix)]
172fn set_mode(file: &File, target: &Path, mode: NewFileMode) -> std::io::Result<()> {
173    use std::os::unix::fs::PermissionsExt;
174    let permissions = match mode {
175        NewFileMode::Default => return Ok(()),
176        NewFileMode::Exactly(mode) => std::fs::Permissions::from_mode(mode),
177        NewFileMode::KeepExisting => match std::fs::metadata(target) {
178            Ok(metadata) => metadata.permissions(),
179            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
180            Err(error) => return Err(error),
181        },
182    };
183    file.set_permissions(permissions)
184}
185
186#[cfg(not(unix))]
187fn set_mode(_: &File, _: &Path, _: NewFileMode) -> std::io::Result<()> {
188    Ok(())
189}
190
191/// Replaces `to` with `from`, atomically where the platform allows it.
192///
193/// This is `std::fs::rename` everywhere. On Windows, std tries `MoveFileExW` and,
194/// when that is refused with `ERROR_ACCESS_DENIED` — as it is while any handle
195/// is open on `to` — retries through `FileRenameInfoEx` with POSIX semantics,
196/// which replace `to` regardless (Windows 10 1607 and later, on a file system
197/// that supports it). A bare `MoveFileExW` stops at the refusal.
198///
199/// The rename is not durable on its own on any platform: callers follow it
200/// with [`sync_parent_directory`]. They rename from the same directory, so the
201/// `MOVEFILE_WRITE_THROUGH` flag std does not pass would add nothing — it only
202/// flushes a move that crosses volumes.
203pub fn replace_file(from: &Path, to: &Path) -> std::io::Result<()> {
204    std::fs::rename(from, to)
205}
206
207/// Fsyncs the directory holding `path`, so a rename into it survives a crash.
208///
209/// A path with no parent is a no-op rather than an error. A bare file name's
210/// parent is the empty path, which fails to open, so its sync fails; join it
211/// to `.` to sync the current directory.
212pub fn sync_parent_directory(path: &Path) -> std::io::Result<()> {
213    let Some(parent) = path.parent() else {
214        return Ok(());
215    };
216    sync_directory(parent)
217}
218
219fn sync_directory(directory: &Path) -> std::io::Result<()> {
220    open_directory_for_sync(directory).and_then(|directory| directory.sync_all())
221}
222
223fn open_directory_for_sync(path: &Path) -> std::io::Result<File> {
224    #[cfg(windows)]
225    {
226        use std::os::windows::fs::OpenOptionsExt;
227        const GENERIC_READ: u32 = 0x8000_0000;
228        const GENERIC_WRITE: u32 = 0x4000_0000;
229        const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
230        OpenOptions::new()
231            .access_mode(GENERIC_READ | GENERIC_WRITE)
232            .custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
233            .open(path)
234    }
235    #[cfg(not(windows))]
236    File::open(path)
237}
238
239#[cfg(test)]
240mod tests {
241    use super::*;
242    use crate::test_support::TempPath;
243
244    /// A directory of its own for one test, created.
245    fn scratch(label: &str) -> TempPath {
246        let directory = TempPath::new(label);
247        std::fs::create_dir(&directory).unwrap();
248        directory
249    }
250
251    /// The names directly inside `directory`, sorted.
252    fn entries(directory: &Path) -> Vec<std::ffi::OsString> {
253        let mut names = std::fs::read_dir(directory)
254            .unwrap()
255            .map(|entry| entry.unwrap().file_name())
256            .collect::<Vec<_>>();
257        names.sort();
258        names
259    }
260
261    #[test]
262    fn replace_contents_creates_then_replaces_and_leaves_only_the_target() {
263        let scratch = scratch("replace");
264        let path = scratch.join("state.json");
265
266        replace_contents(&path, b"first", NewFileMode::Default).unwrap();
267        assert_eq!(std::fs::read(&path).unwrap(), b"first");
268        replace_contents(&path, b"second", NewFileMode::KeepExisting).unwrap();
269        assert_eq!(std::fs::read(&path).unwrap(), b"second");
270        assert_eq!(entries(&scratch), ["state.json"]);
271    }
272
273    /// A failed replace names its step, keeps the target and removes the
274    /// temporary file it wrote.
275    #[test]
276    fn a_failed_replace_reports_its_step_and_removes_the_temporary() {
277        let scratch = scratch("replace-fails");
278        let path = scratch.join("occupied");
279        std::fs::create_dir(&path).unwrap();
280        std::fs::write(path.join("kept"), b"kept").unwrap();
281
282        let error = replace_contents(&path, b"new", NewFileMode::Default).unwrap_err();
283        assert_eq!(error.step, ReplaceStep::Replace);
284        assert_eq!(error.path, path);
285        assert_eq!(entries(&scratch), ["occupied"]);
286        assert_eq!(std::fs::read(path.join("kept")).unwrap(), b"kept");
287    }
288
289    /// Syncing a directory opens it, which Windows allows only with backup
290    /// semantics.
291    #[test]
292    fn sync_parent_directory_succeeds_for_a_local_file() {
293        let scratch = scratch("dirsync");
294        let path = scratch.join("probe");
295        std::fs::write(&path, b"x").unwrap();
296        sync_parent_directory(&path).unwrap();
297    }
298
299    #[cfg(unix)]
300    #[test]
301    fn replace_contents_sets_the_requested_mode() {
302        use std::os::unix::fs::PermissionsExt;
303        let scratch = scratch("replace-mode");
304        let path = scratch.join("secret");
305        let mode = |path: &Path| std::fs::metadata(path).unwrap().permissions().mode() & 0o777;
306
307        replace_contents(&path, b"key", NewFileMode::Exactly(0o600)).unwrap();
308        assert_eq!(mode(&path), 0o600);
309        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o640)).unwrap();
310        replace_contents(&path, b"key", NewFileMode::KeepExisting).unwrap();
311        assert_eq!(mode(&path), 0o640);
312    }
313}