From f994019c242ecb097a8fdabc7650f00721dddf10 Mon Sep 17 00:00:00 2001 From: tv Date: Tue, 1 Dec 2026 00:51:40 +0000 Subject: enstate: snapshots flushed to disk before they are put in place A new snapshot's files and directories are flushed before the link to it is replaced, and the link before the old snapshot goes: a crash leaves the old snapshot or the new one, whole. --- src/store.rs | 35 ++++++++++++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/store.rs b/src/store.rs index 7e6531e..08d0959 100644 --- a/src/store.rs +++ b/src/store.rs @@ -14,9 +14,10 @@ //! RUN/tmp/ scratch //! ``` //! -//! Entries are root's (mode 0600). A new snapshot or view generation is written -//! next to the old one and put in place by replacing a symbolic link, so a reader -//! sees one or the other, never a mix. +//! Entries are root's (mode 0600). A new snapshot +//! or view generation is written next to the old one and put in place by replacing +//! a symbolic link, so a reader sees one or the other, never a mix; a snapshot is +//! flushed to disk before that, so a crash leaves the old one or the new one. use std::fs::File; use std::os::unix::fs::DirBuilderExt; @@ -193,12 +194,17 @@ impl Store { .collect(); content::write_dir(&kept, &new.join("kept"), 0o600)?; } + // On disk before it is put in place, and in place before the old one goes: a + // crash leaves the old snapshot or the new one, whole. + sync_tree(&new)?; std::fs::rename(&new, snapshots.join(&id))?; + sync_dir(&snapshots)?; let old = std::fs::read_link(self.channel_dir(channel).join("current")).ok(); replace_link( &self.channel_dir(channel).join("current"), &Path::new("snapshots").join(&id), )?; + sync_dir(&self.channel_dir(channel))?; if let Some(old) = old { std::fs::remove_dir_all(self.channel_dir(channel).join(old))?; } @@ -356,3 +362,26 @@ fn copy_tree(from: &Path, to: &Path) -> Result<()> { } Ok(()) } + +/// Flushes the files below `dir`, and the directories (`dir` too), to disk. +fn sync_tree(dir: &Path) -> Result<()> { + for entry in std::fs::read_dir(dir)? { + let entry = entry?; + let kind = entry.file_type()?; + if kind.is_dir() { + sync_tree(&entry.path())?; + } else if kind.is_file() { + File::open(entry.path()) + .and_then(|file| file.sync_all()) + .with_context(|| format!("flushing {}", entry.path().display()))?; + } + } + sync_dir(dir) +} + +/// Flushes the directory `dir`, its entries' names, to disk. +fn sync_dir(dir: &Path) -> Result<()> { + File::open(dir) + .and_then(|file| file.sync_all()) + .with_context(|| format!("flushing {}", dir.display())) +} -- cgit v1.3.1