Skip to main content

aft_base/
durability.rs

1//! Durable file commits use the platform's full sync, including F_FULLFSYNC on
2//! macOS, or fsync when the mount does not support it. Rebuildable and
3//! process-lifetime stores deliberately do not call these sync helpers.
4//! Atomic writes select their durability explicitly. The test
5//! ledger observes the real calls, never substitutes for them.
6
7use std::fs::{self, File};
8use std::io::{self, Write};
9use std::path::{Path, PathBuf};
10
11#[cfg(unix)]
12#[derive(Default)]
13struct PendingSyncs {
14    devices: std::collections::BTreeMap<u64, (File, PathBuf)>,
15}
16
17#[cfg(unix)]
18thread_local! {
19    static SYNC_GROUP: std::cell::RefCell<Option<PendingSyncs>> = const { std::cell::RefCell::new(None) };
20}
21
22/// Keep file and directory fsync ordering, but flush the device cache once per
23/// device at commit. In particular, macOS F_FULLFSYNC need not flush the same
24/// device after every file. The caller must finish the group before unlinking
25/// any source or acknowledging a durable backup. Dropping an unfinished group
26/// abandons its device barriers; it is only safe when no source was removed.
27///
28/// A group opened while another is open on the same thread joins it: its syncs
29/// wait for the enclosing group's commit, and its own `finish` flushes
30/// nothing. An `aft_delete` snapshots every entry inside one group, and each
31/// snapshot opens a group of its own for its metadata; joining keeps that to
32/// one device flush before the first unlink, and none when the delete gives
33/// up and drops its group.
34pub struct SyncGroup {
35    /// Whether this group opened the thread's pending set and so flushes it,
36    /// rather than joining an enclosing group's.
37    #[cfg(unix)]
38    owner: bool,
39    _thread: std::marker::PhantomData<std::rc::Rc<()>>,
40}
41
42impl SyncGroup {
43    pub fn new() -> Self {
44        Self {
45            #[cfg(unix)]
46            owner: SYNC_GROUP.with(|group| {
47                let mut group = group.borrow_mut();
48                if group.is_some() {
49                    return false;
50                }
51                *group = Some(PendingSyncs::default());
52                true
53            }),
54            _thread: std::marker::PhantomData,
55        }
56    }
57
58    #[cfg(unix)]
59    fn detach(&mut self) -> PendingSyncs {
60        self.owner = false;
61        SYNC_GROUP.with(|group| group.take().expect("active sync group"))
62    }
63
64    pub fn finish(mut self) -> io::Result<()> {
65        #[cfg(unix)]
66        if self.owner {
67            for (_, (file, path)) in self.detach().devices {
68                #[cfg(any(test, feature = "test-support"))]
69                if FAIL_GROUP_SYNC.with(|fail| fail.replace(false)) {
70                    return Err(io::Error::other("injected backup group sync failure"));
71                }
72                full_sync(&file, &path)?;
73            }
74        }
75        #[cfg(not(unix))]
76        let _ = &mut self;
77        Ok(())
78    }
79}
80
81impl Drop for SyncGroup {
82    fn drop(&mut self) {
83        #[cfg(unix)]
84        if self.owner {
85            self.detach();
86        }
87    }
88}
89
90fn full_sync(file: &File, path: &Path) -> io::Result<()> {
91    aft_store::sync::sync_all(file, path)?;
92    #[cfg(any(test, feature = "test-support"))]
93    FULL_SYNCS.with(|syncs| syncs.borrow_mut().push(path.to_path_buf()));
94    Ok(())
95}
96
97fn ordered_sync(file: &File, path: &Path) -> io::Result<()> {
98    #[cfg(unix)]
99    if SYNC_GROUP.with(|group| group.borrow().is_some()) {
100        use std::os::fd::AsRawFd;
101        use std::os::unix::fs::MetadataExt;
102        // fsync submits each file's data and metadata in publication order.
103        // The group's final full sync makes those submissions survive loss of
104        // the device's volatile write cache before deletion may begin.
105        loop {
106            // SAFETY: the borrowed File keeps this descriptor open for fsync.
107            if unsafe { libc::fsync(file.as_raw_fd()) } == 0 {
108                break;
109            }
110            let error = io::Error::last_os_error();
111            if error.kind() != io::ErrorKind::Interrupted {
112                return Err(error);
113            }
114        }
115        let device = file.metadata()?.dev();
116        return SYNC_GROUP.with(|group| {
117            let mut group = group.borrow_mut();
118            let devices = &mut group.as_mut().expect("active sync group").devices;
119            if let std::collections::btree_map::Entry::Vacant(entry) = devices.entry(device) {
120                entry.insert((file.try_clone()?, path.to_path_buf()));
121            }
122            Ok(())
123        });
124    }
125    full_sync(file, path)
126}
127
128// Some binaries do not use every atomic-write durability option. Callers choose
129// whether private state needs no sync, file sync, or file plus directory sync.
130#[derive(Clone, Copy)]
131pub enum AtomicWriteDurability {
132    None,
133    // Callers publishing several files sync the directory once after the batch.
134    File,
135    FileAndDirectory,
136}
137
138/// Publish private state without leaving a partial destination or a failed temp.
139/// Authorization and directory creation remain the caller's responsibility.
140pub fn atomic_write(
141    path: &Path,
142    bytes: &[u8],
143    durability: AtomicWriteDurability,
144) -> io::Result<()> {
145    let parent = path
146        .parent()
147        .filter(|p| !p.as_os_str().is_empty())
148        .unwrap_or(Path::new("."));
149    let mut random = [0_u8; 16];
150    getrandom::fill(&mut random).map_err(io::Error::other)?;
151    let temporary = parent.join(format!(".aft-{:032x}.tmp", u128::from_ne_bytes(random)));
152    #[cfg(any(test, feature = "test-support"))]
153    before_temp_create(&temporary);
154    let file = crate::private_storage::options()
155        .write(true)
156        .create_new(true)
157        .open(&temporary)?;
158    let mut cleanup = TempCleanup(Some(temporary.clone()));
159    // Close before replacing so Windows does not retain an open temp handle.
160    (move || -> io::Result<()> {
161        let mut file = file;
162        #[cfg(unix)]
163        {
164            use std::os::unix::fs::PermissionsExt;
165            if file.metadata()?.permissions().mode() & 0o777 != crate::private_storage::FILE_MODE {
166                file.set_permissions(fs::Permissions::from_mode(
167                    crate::private_storage::FILE_MODE,
168                ))?;
169            }
170        }
171        file.write_all(bytes)?;
172        if !matches!(durability, AtomicWriteDurability::None) {
173            sync_file(&file, path)?;
174        }
175        Ok(())
176    })()?;
177    crate::fs_lock::rename_over(&temporary, path)?;
178    cleanup.0 = None;
179    record(EventKind::AtomicReplace, path);
180    if matches!(durability, AtomicWriteDurability::FileAndDirectory) {
181        sync_dir(parent)?;
182    }
183    Ok(())
184}
185
186struct TempCleanup(Option<PathBuf>);
187
188impl Drop for TempCleanup {
189    fn drop(&mut self) {
190        if let Some(path) = &self.0 {
191            let _ = fs::remove_file(path);
192        }
193    }
194}
195
196#[cfg(any(test, feature = "test-support"))]
197type BeforeTempCreate = Box<dyn FnOnce(&Path)>;
198#[cfg(any(test, feature = "test-support"))]
199thread_local! {
200    pub static BEFORE_TEMP_CREATE: std::cell::RefCell<Option<BeforeTempCreate>> = const { std::cell::RefCell::new(None) };
201}
202
203#[cfg(any(test, feature = "test-support"))]
204pub(crate) fn before_temp_create(path: &Path) {
205    let hook = BEFORE_TEMP_CREATE.with(|slot| slot.borrow_mut().take());
206    if let Some(hook) = hook {
207        hook(path);
208    }
209}
210
211pub fn sync_file(file: &File, path: &Path) -> io::Result<()> {
212    ordered_sync(file, path)?;
213    record(EventKind::FileSync, path);
214    Ok(())
215}
216
217pub fn sync_dir(path: &Path) -> io::Result<()> {
218    #[cfg(any(test, feature = "test-support"))]
219    if FAIL_DIRECTORY_SYNC.with(|slot| {
220        let mut slot = slot.borrow_mut();
221        if slot.as_deref() == Some(path) {
222            slot.take();
223            true
224        } else {
225            false
226        }
227    }) {
228        return Err(FAIL_DIRECTORY_SYNC_ERRNO.with(|errno| {
229            errno.take().map_or_else(
230                || io::Error::other("injected directory sync failure"),
231                io::Error::from_raw_os_error,
232            )
233        }));
234    }
235    #[cfg(unix)]
236    {
237        ordered_sync(&File::open(path)?, path)?;
238        record(EventKind::DirectorySync, path);
239    }
240    // Windows cannot open a directory as a regular File. Its rename uses
241    // MoveFileExW write-through semantics; data files are synced before rename.
242    #[cfg(not(unix))]
243    let _ = path;
244    Ok(())
245}
246
247#[derive(Clone, Copy, Debug, PartialEq, Eq)]
248pub enum EventKind {
249    FileSync,
250    #[cfg_attr(not(unix), allow(dead_code))]
251    DirectorySync,
252    DirectoryCreated,
253    AtomicReplace,
254    CorruptCheckpointSkipped,
255}
256
257#[cfg(any(test, feature = "test-support"))]
258thread_local! {
259    #[cfg(unix)]
260    pub static FAIL_GROUP_SYNC: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
261    static FULL_SYNCS: std::cell::RefCell<Vec<PathBuf>> = const { std::cell::RefCell::new(Vec::new()) };
262    pub static FAIL_DIRECTORY_SYNC: std::cell::RefCell<Option<PathBuf>> = const {
263        std::cell::RefCell::new(None)
264    };
265    // Optional errno for FAIL_DIRECTORY_SYNC; leaving it unset injects the
266    // existing generic I/O error, so path-only callers need no change.
267    pub static FAIL_DIRECTORY_SYNC_ERRNO: std::cell::Cell<Option<i32>> = const {
268        std::cell::Cell::new(None)
269    };
270    static EVENTS: std::cell::RefCell<Vec<(EventKind, std::path::PathBuf)>> = const {
271        std::cell::RefCell::new(Vec::new())
272    };
273}
274
275#[cfg(any(test, feature = "test-support"))]
276pub fn take_full_syncs() -> Vec<PathBuf> {
277    FULL_SYNCS.with(|syncs| std::mem::take(&mut *syncs.borrow_mut()))
278}
279
280#[inline]
281pub fn record(kind: EventKind, path: &Path) {
282    #[cfg(any(test, feature = "test-support"))]
283    EVENTS.with(|events| events.borrow_mut().push((kind, path.to_path_buf())));
284    #[cfg(not(any(test, feature = "test-support")))]
285    let _ = (kind, path);
286}
287
288#[cfg(any(test, feature = "test-support"))]
289pub fn take() -> Vec<(EventKind, std::path::PathBuf)> {
290    EVENTS.with(|events| std::mem::take(&mut *events.borrow_mut()))
291}
292
293#[cfg(any(test, feature = "test-support"))]
294pub fn sync_count(events: &[(EventKind, std::path::PathBuf)]) -> usize {
295    events
296        .iter()
297        .filter(|(kind, _)| matches!(kind, EventKind::FileSync | EventKind::DirectorySync))
298        .count()
299}