Skip to main content

blockworx/
storage.rs

1//! Crash-safe file writes.
2//!
3//! Every write of something a user would mind losing goes through
4//! [`write_atomically`]. `std::fs::write` truncates the target and then fills it,
5//! so a crash, a kill, or a power cut partway through leaves a half-written file
6//! where the previous good one used to be — and for the document save that is the
7//! drawing itself.
8
9use std::io::Write as _;
10use std::path::{Path, PathBuf};
11
12/// Write `contents` to `path` so that dying partway through leaves the previous
13/// contents intact: the bytes land in a sibling temporary file, are flushed to
14/// the storage device, and only then replace `path` with one atomic rename.
15///
16/// The target is never opened for writing, so there is no window in which it
17/// holds a partial document.
18pub fn write_atomically(path: &Path, contents: &[u8]) -> std::io::Result<()> {
19    let target = resolve(path);
20    let temp = temp_path(&target)?;
21    write_and_replace(&temp, &target, contents).inspect_err(|_| {
22        // A temp file left behind would be overwritten by the next attempt
23        // anyway; removing it just keeps the directory tidy.
24        let _ = std::fs::remove_file(&temp);
25    })
26}
27
28/// Follow symlinks, so writing a symlinked document replaces what it points at —
29/// the way `fs::write` does. Renaming onto the link would instead replace the
30/// link with a regular file and quietly detach it from its target.
31fn resolve(path: &Path) -> PathBuf {
32    std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
33}
34
35/// A dot-prefixed sibling of `target`. It has to share the directory: `rename`
36/// is only atomic within one filesystem.
37fn temp_path(target: &Path) -> std::io::Result<PathBuf> {
38    let name = target.file_name().ok_or_else(|| {
39        std::io::Error::new(
40            std::io::ErrorKind::InvalidInput,
41            format!("{} names no file to write", target.display()),
42        )
43    })?;
44    let mut temp = std::ffi::OsString::from(".");
45    temp.push(name);
46    temp.push(".tmp");
47    Ok(target.with_file_name(temp))
48}
49
50fn write_and_replace(temp: &Path, target: &Path, contents: &[u8]) -> std::io::Result<()> {
51    let mut file = std::fs::File::create(temp)?;
52    file.write_all(contents)?;
53    // Without this the rename can be recorded while the bytes are still in the
54    // page cache, so a power cut yields an intact rename onto empty content.
55    file.sync_all()?;
56    drop(file);
57    std::fs::rename(temp, target)?;
58    sync_dir(parent_dir(target))
59}
60
61/// The directory holding `target`. A bare relative filename has an empty parent,
62/// which names nothing openable.
63fn parent_dir(target: &Path) -> &Path {
64    match target.parent() {
65        Some(dir) if !dir.as_os_str().is_empty() => dir,
66        _ => Path::new("."),
67    }
68}
69
70/// Flush the directory entry itself, so the rename survives a power cut and not
71/// just a process crash.
72#[cfg(unix)]
73fn sync_dir(dir: &Path) -> std::io::Result<()> {
74    std::fs::File::open(dir)?.sync_all()
75}
76
77/// Windows has no directory handle to sync; `MoveFileEx` metadata ordering is
78/// the filesystem's business there.
79#[cfg(not(unix))]
80fn sync_dir(_dir: &Path) -> std::io::Result<()> {
81    Ok(())
82}
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87
88    /// A unique directory per test, removed on drop. Named for the test so a
89    /// failure leaves an identifiable directory behind.
90    struct TempDir(PathBuf);
91
92    impl TempDir {
93        fn new(name: &str) -> Self {
94            let dir = std::env::temp_dir().join(format!("blockworx-{}-{name}", std::process::id()));
95            let _ = std::fs::remove_dir_all(&dir);
96            std::fs::create_dir_all(&dir).unwrap();
97            Self(dir)
98        }
99
100        fn join(&self, name: &str) -> PathBuf {
101            self.0.join(name)
102        }
103    }
104
105    impl Drop for TempDir {
106        fn drop(&mut self) {
107            let _ = std::fs::remove_dir_all(&self.0);
108        }
109    }
110
111    fn read(path: &Path) -> String {
112        std::fs::read_to_string(path).unwrap()
113    }
114
115    #[test]
116    fn it_creates_and_then_overwrites() {
117        let dir = TempDir::new("create-overwrite");
118        let doc = dir.join("doc.kdl");
119
120        write_atomically(&doc, b"first").unwrap();
121        assert_eq!(read(&doc), "first");
122
123        write_atomically(&doc, b"second").unwrap();
124        assert_eq!(read(&doc), "second");
125    }
126
127    #[test]
128    fn a_successful_write_leaves_no_temp_behind() {
129        let dir = TempDir::new("no-temp");
130        let doc = dir.join("doc.kdl");
131        write_atomically(&doc, b"content").unwrap();
132
133        let leftovers: Vec<_> = std::fs::read_dir(&dir.0)
134            .unwrap()
135            .map(|e| e.unwrap().file_name())
136            .filter(|name| name != "doc.kdl")
137            .collect();
138        assert!(leftovers.is_empty(), "left {leftovers:?} behind");
139    }
140
141    /// The property the whole module exists for: a write that fails partway
142    /// cannot have touched the target. The failure is forced by occupying the
143    /// temp path with a directory, so `File::create` fails after the target
144    /// already holds content worth keeping.
145    #[test]
146    fn a_failed_write_leaves_the_previous_contents_intact() {
147        let dir = TempDir::new("failed-write");
148        let doc = dir.join("doc.kdl");
149        write_atomically(&doc, b"the good version").unwrap();
150
151        let blocker = dir.join(".doc.kdl.tmp");
152        std::fs::create_dir(&blocker).unwrap();
153        // Proves the precondition: this is the path the write would have used.
154        assert_eq!(temp_path(&resolve(&doc)).unwrap(), blocker);
155
156        assert!(write_atomically(&doc, b"a doomed longer version").is_err());
157        assert_eq!(read(&doc), "the good version");
158    }
159
160    #[test]
161    fn a_path_naming_no_file_is_an_error() {
162        assert!(write_atomically(Path::new(".."), b"x").is_err());
163    }
164
165    /// A symlinked document is written *through*, not replaced by a regular
166    /// file — the behavior `fs::write` had and a bare rename would lose.
167    #[cfg(unix)]
168    #[test]
169    fn writing_a_symlink_updates_its_target() {
170        let dir = TempDir::new("symlink");
171        let target = dir.join("real.kdl");
172        let link = dir.join("link.kdl");
173        write_atomically(&target, b"before").unwrap();
174        std::os::unix::fs::symlink(&target, &link).unwrap();
175
176        write_atomically(&link, b"after").unwrap();
177
178        assert!(
179            std::fs::symlink_metadata(&link).unwrap().is_symlink(),
180            "the link itself was replaced"
181        );
182        assert_eq!(read(&target), "after");
183    }
184}