Skip to main content

aft_base/
atomic_replace.rs

1//! Atomic publication through a pinned directory with explicit durability.
2
3use crate::pinned_dir::{random_temp_name, validate_regular_handle, PinnedDir};
4#[cfg(windows)]
5use crate::pinned_dir::{
6    validate_directory_handle, FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT,
7};
8use std::ffi::OsStr;
9use std::fs::File;
10#[cfg(windows)]
11use std::fs::OpenOptions;
12use std::io::{self, Write};
13#[cfg(windows)]
14use std::os::windows::fs::OpenOptionsExt;
15use std::path::Path;
16
17/// How much of an atomic file replacement is synced to disk.
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19pub enum ReplaceSync {
20    /// Nothing is synced. The rename still protects readers from a partly
21    /// written file after a process kill, but not after a power loss.
22    None,
23    /// The new file's contents are synced before the rename; the directory
24    /// entry is not synced after it.
25    File,
26    /// The new file is synced before the rename and its directory after it,
27    /// so the replacement itself survives a power loss.
28    FileAndDirectory,
29}
30
31/// Sync and crash/fault instrumentation supplied by the artifact owner.
32pub trait ReplaceHooks {
33    fn sync_file(&mut self, file: &File, path: &Path) -> io::Result<()>;
34    fn before_rename(&mut self);
35    fn after_rename(&mut self);
36}
37
38/// Normal syncing with no crash or fault injection.
39pub struct NoReplaceHooks;
40
41impl ReplaceHooks for NoReplaceHooks {
42    fn sync_file(&mut self, file: &File, path: &Path) -> io::Result<()> {
43        aft_store::sync::sync_all(file, path)
44    }
45    fn before_rename(&mut self) {}
46    fn after_rename(&mut self) {}
47}
48
49pub fn sync_directory_with_hooks(dir: &PinnedDir, hooks: &mut impl ReplaceHooks) -> io::Result<()> {
50    #[cfg(unix)]
51    {
52        hooks.sync_file(&dir.file, &dir.path)
53    }
54    #[cfg(windows)]
55    {
56        // FlushFileBuffers requires GENERIC_WRITE even for a directory. Keep
57        // ordinary pinned opens read-only; acquire write access only to flush,
58        // and verify that the reopened handle still names the pinned folder.
59        let writable = PinnedDir::from_open_file(
60            OpenOptions::new()
61                .read(true)
62                .write(true)
63                .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS)
64                .open(&dir.path)?,
65            dir.path.clone(),
66            {
67                #[cfg(any(test, feature = "test-support"))]
68                {
69                    dir.cache_device_override
70                }
71                #[cfg(not(any(test, feature = "test-support")))]
72                {
73                    None
74                }
75            },
76        );
77        validate_directory_handle(&writable.file)?;
78        if !dir.same_identity(&writable)? {
79            return Err(io::Error::new(
80                io::ErrorKind::PermissionDenied,
81                "pinned directory path identity changed",
82            ));
83        }
84        hooks.sync_file(&writable.file, &dir.path)?;
85        dir.ensure_current_identity()
86    }
87}
88
89pub fn atomic_replace_with_hooks(
90    dir: &PinnedDir,
91    name: &OsStr,
92    content: &[u8],
93    sync: ReplaceSync,
94    hooks: &mut impl ReplaceHooks,
95) -> io::Result<()> {
96    for _ in 0..32 {
97        let temporary = random_temp_name()?;
98        let mut file = match dir.open_new_file(&temporary) {
99            Ok(file) => file,
100            Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
101            Err(error) => return Err(error),
102        };
103        let result = (|| {
104            file.write_all(content)?;
105            if sync != ReplaceSync::None {
106                hooks.sync_file(&file, &dir.path.join(&temporary))?;
107            }
108            // Rename protects readers from partial bytes after a process kill;
109            // the explicit sync policy separately governs power-loss durability.
110            validate_regular_handle(&file)?;
111            hooks.before_rename();
112            dir.rename(&temporary, name)?;
113            hooks.after_rename();
114            if sync == ReplaceSync::FileAndDirectory {
115                sync_directory_with_hooks(dir, hooks)?;
116            }
117            Ok(())
118        })();
119        if result.is_err() {
120            let _ = dir.remove_file(&temporary);
121        }
122        return result;
123    }
124    Err(io::Error::new(
125        io::ErrorKind::AlreadyExists,
126        "failed to allocate a randomized atomic-write name",
127    ))
128}