Skip to main content

subc_os/
durable_replace.rs

1//! Namespace durability for an already-synced, same-directory staging file.
2
3use std::{io, path::Path};
4
5/// A replacement can be visible even when flushing its publication fails.
6#[derive(Debug)]
7pub struct DurableReplaceError {
8    renamed: bool,
9    source: io::Error,
10}
11
12impl DurableReplaceError {
13    /// Whether the replacement happened, or may have happened when Windows
14    /// cannot establish the namespace state after an operating-system error.
15    pub fn renamed(&self) -> bool {
16        self.renamed
17    }
18
19    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
42/// Atomically replace `to`, then flush the publication before returning. The
43/// caller must sync the source file's contents first. Neither path may be on a
44/// different filesystem; there is deliberately no copy/delete fallback.
45/// An error retains whether publication occurred before durability failed.
46pub fn durable_replace(from: &Path, to: &Path) -> Result<(), DurableReplaceError> {
47    durable_replace_impl(from, to, || Ok(()))
48}
49
50/// Inject a failure after a real rename. Unix runs the hook before syncing the
51/// directory; Windows preserves its write-through move and classifies the error
52/// from retained file identity, just as it does a failed operating-system call.
53#[cfg(feature = "test-support")]
54pub fn durable_replace_with_rename_hook(
55    from: &Path,
56    to: &Path,
57    after_rename: impl FnOnce() -> io::Result<()>,
58) -> Result<(), DurableReplaceError> {
59    durable_replace_impl(from, to, after_rename)
60}
61
62fn durable_replace_impl(
63    from: &Path,
64    to: &Path,
65    after_rename: impl FnOnce() -> io::Result<()>,
66) -> Result<(), DurableReplaceError> {
67    #[cfg(unix)]
68    {
69        std::fs::rename(from, to).map_err(|error| DurableReplaceError::new(error, false))?;
70        after_rename().map_err(|error| DurableReplaceError::new(error, true))?;
71        let parent = to.parent().ok_or_else(|| {
72            DurableReplaceError::new(
73                io::Error::new(io::ErrorKind::InvalidInput, "destination has no parent"),
74                true,
75            )
76        })?;
77        std::fs::File::open(parent)
78            .and_then(|directory| directory.sync_all())
79            .map_err(|error| DurableReplaceError::new(error, true))
80    }
81    #[cfg(windows)]
82    {
83        windows_replace_with_operation(
84            from,
85            to,
86            || windows_move(from, to).and_then(|()| after_rename()),
87            windows_path_identity,
88        )
89    }
90    #[cfg(not(any(unix, windows)))]
91    {
92        let _ = (from, to, after_rename);
93        Err(DurableReplaceError::new(
94            io::Error::new(
95                io::ErrorKind::Unsupported,
96                "durable replacement unsupported",
97            ),
98            false,
99        ))
100    }
101}
102
103#[cfg(windows)]
104#[derive(Clone, Copy, PartialEq, Eq)]
105struct FileIdentity {
106    volume: u32,
107    index: u64,
108}
109
110#[cfg(windows)]
111fn windows_open_identity(path: &Path) -> io::Result<std::fs::File> {
112    use std::os::windows::fs::OpenOptionsExt;
113    use windows_sys::Win32::Storage::FileSystem::{
114        FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE,
115    };
116    std::fs::OpenOptions::new()
117        .access_mode(0)
118        .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)
119        .open(path)
120}
121
122#[cfg(windows)]
123#[allow(unsafe_code)]
124fn windows_file_identity(file: &std::fs::File) -> io::Result<FileIdentity> {
125    use std::os::windows::io::AsRawHandle;
126    use windows_sys::Win32::Storage::FileSystem::{
127        GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION,
128    };
129    // SAFETY: Every member of this Win32 output structure accepts zero bits.
130    let mut information: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
131    // SAFETY: The handle is borrowed from a live file and the output structure
132    // remains writable for the call. A failed call never reads its contents.
133    if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut information) } == 0 {
134        return Err(io::Error::last_os_error());
135    }
136    Ok(FileIdentity {
137        volume: information.dwVolumeSerialNumber,
138        index: (u64::from(information.nFileIndexHigh) << 32) | u64::from(information.nFileIndexLow),
139    })
140}
141
142#[cfg(windows)]
143fn windows_path_identity(path: &Path) -> io::Result<Option<FileIdentity>> {
144    match windows_open_identity(path) {
145        Ok(file) => windows_file_identity(&file).map(Some),
146        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
147        Err(error) => Err(error),
148    }
149}
150
151#[cfg(windows)]
152fn windows_replace_with_operation(
153    from: &Path,
154    to: &Path,
155    operation: impl FnOnce() -> io::Result<()>,
156    inspect: impl Fn(&Path) -> io::Result<Option<FileIdentity>>,
157) -> Result<(), DurableReplaceError> {
158    let source =
159        windows_open_identity(from).map_err(|error| DurableReplaceError::new(error, false))?;
160    let identity =
161        windows_file_identity(&source).map_err(|error| DurableReplaceError::new(error, false))?;
162    let result = operation().map_err(|error| {
163        let renamed = match (inspect(from), inspect(to)) {
164            (Ok(None), Ok(Some(destination))) if destination == identity => true,
165            (Ok(Some(original)), Ok(_)) if original == identity => false,
166            // Treat an ambiguous outcome as a rename. An unnecessary publication
167            // sequence increment only forces re-verification after a durability
168            // error; a missed increment would let replacement bytes retain an
169            // older approval's authority.
170            _ => true,
171        };
172        DurableReplaceError::new(error, renamed)
173    });
174    // Retain the original handle until inspection ends so its identity cannot
175    // be recycled after the source name disappears.
176    drop(source);
177    result
178}
179
180#[cfg(windows)]
181#[allow(unsafe_code)]
182fn windows_move(from: &Path, to: &Path) -> io::Result<()> {
183    use std::os::windows::ffi::OsStrExt;
184    use windows_sys::Win32::Storage::FileSystem::{
185        MoveFileExW, MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH,
186    };
187    fn wide(path: &Path) -> io::Result<Vec<u16>> {
188        let mut result: Vec<_> = path.as_os_str().encode_wide().collect();
189        if result.contains(&0) {
190            return Err(io::Error::new(io::ErrorKind::InvalidInput, "NUL in path"));
191        }
192        result.push(0);
193        Ok(result)
194    }
195    let from = wide(from)?;
196    let to = wide(to)?;
197    // SAFETY: Both paths are NUL-terminated and live through the call. There
198    // are no borrowed handles. WRITE_THROUGH returns only once the move is
199    // flushed; Windows has no directory fsync. Failure is never retried using
200    // a weaker rename that could report an approval before publication flush.
201    if unsafe {
202        MoveFileExW(
203            from.as_ptr(),
204            to.as_ptr(),
205            MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH,
206        )
207    } == 0
208    {
209        return Err(io::Error::last_os_error());
210    }
211    Ok(())
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217    use std::{fs, io::Write};
218    fn root() -> cortexkit_test_support::ScratchDir {
219        cortexkit_test_support::ScratchDir::new("subc-durable-replace")
220    }
221    #[test]
222    fn durable_replace_replaces_existing_file() {
223        let root = root();
224        let from = root.join("stage");
225        let to = root.join("store");
226        fs::write(&to, b"previous").unwrap();
227        let mut file = fs::File::create(&from).unwrap();
228        file.write_all(b"next").unwrap();
229        file.sync_all().unwrap();
230        drop(file);
231        durable_replace(&from, &to).unwrap();
232        assert_eq!(fs::read(&to).unwrap(), b"next");
233        assert!(!from.exists());
234    }
235    #[test]
236    fn durable_replace_missing_source_is_error() {
237        let root = root();
238        let to = root.join("store");
239        fs::write(&to, b"previous").unwrap();
240        assert!(!durable_replace(&root.join("absent"), &to)
241            .unwrap_err()
242            .renamed());
243        assert_eq!(fs::read(&to).unwrap(), b"previous");
244    }
245
246    fn replacement_files(root: &Path) -> (std::path::PathBuf, std::path::PathBuf) {
247        let from = root.join("stage");
248        let to = root.join("store");
249        let mut file = fs::File::create(&from).unwrap();
250        file.write_all(b"next").unwrap();
251        file.sync_all().unwrap();
252        drop(file);
253        fs::write(&to, b"previous").unwrap();
254        (from, to)
255    }
256
257    #[cfg(unix)]
258    #[test]
259    fn durable_replace_sync_error_after_rename_retains_publication_witness() {
260        let root = root();
261        let (from, to) = replacement_files(&root);
262        let error = durable_replace_impl(&from, &to, || {
263            Err(io::Error::other("injected directory sync failure"))
264        })
265        .unwrap_err();
266        assert!(error.renamed(), "{error}");
267        assert_eq!(error.to_string(), "injected directory sync failure");
268        assert_eq!(fs::read(to).unwrap(), b"next");
269        assert!(!from.exists());
270    }
271
272    #[cfg(windows)]
273    #[test]
274    fn durable_replace_windows_error_after_real_move_reports_renamed() {
275        let root = root();
276        let (from, to) = replacement_files(&root);
277        let error = durable_replace_impl(&from, &to, || {
278            Err(io::Error::other("injected write-through failure"))
279        })
280        .unwrap_err();
281        assert!(error.renamed(), "{error}");
282        assert_eq!(error.to_string(), "injected write-through failure");
283        assert_eq!(fs::read(to).unwrap(), b"next");
284        assert!(!from.exists());
285    }
286
287    #[cfg(windows)]
288    #[test]
289    fn durable_replace_windows_error_without_move_reports_not_renamed() {
290        let root = root();
291        let (from, to) = replacement_files(&root);
292        let error = windows_replace_with_operation(
293            &from,
294            &to,
295            || Err(io::Error::other("injected pre-move failure")),
296            windows_path_identity,
297        )
298        .unwrap_err();
299        assert!(!error.renamed(), "{error}");
300        assert_eq!(fs::read(to).unwrap(), b"previous");
301        assert_eq!(fs::read(from).unwrap(), b"next");
302    }
303
304    #[cfg(windows)]
305    #[test]
306    fn durable_replace_windows_inspection_failure_advances_conservatively() {
307        let root = root();
308        let (from, to) = replacement_files(&root);
309        let error = windows_replace_with_operation(
310            &from,
311            &to,
312            || Err(io::Error::other("injected move failure")),
313            |path| {
314                if path == from {
315                    windows_path_identity(path)
316                } else {
317                    Err(io::Error::other("injected destination inspection failure"))
318                }
319            },
320        )
321        .unwrap_err();
322        assert!(
323            error.renamed(),
324            "uncertainty must retain the witness: {error}"
325        );
326        assert_eq!(error.to_string(), "injected move failure");
327        assert_eq!(fs::read(to).unwrap(), b"previous");
328        assert_eq!(fs::read(from).unwrap(), b"next");
329    }
330}