Skip to main content

crisol_core/
storage.rs

1//! Atomic file writes and versioned persistence helpers.
2//!
3//! A write goes to a hidden temporary sibling, is flushed with `sync_all`, and is then
4//! renamed over the target. A crash leaves the old file or the new one, never a partial
5//! write; a failed write leaves the old file untouched (CORE-DET-04).
6//!
7//! ```
8//! use crisol_core::storage;
9//! ```
10
11#[cfg(feature = "threads")]
12use std::io::Write;
13use std::path::{Path, PathBuf};
14#[cfg(feature = "threads")]
15use std::sync::atomic::{AtomicU64, Ordering};
16
17/// Why a file could not be written.
18#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
19#[non_exhaustive]
20/// # Example
21///
22/// ```
23/// use crisol_core::storage::StorageError;
24/// ```
25pub enum StorageError {
26    /// The path has no file name, so no sibling temporary can be made.
27    #[error("the path has no file name")]
28    NoFileName,
29    /// The temporary file could not be created.
30    #[error("could not create the temporary file: {0}")]
31    Create(String),
32    /// The bytes could not be written.
33    #[error("could not write the temporary file: {0}")]
34    Write(String),
35    /// The bytes could not be flushed to disk.
36    #[error("could not flush the temporary file: {0}")]
37    Sync(String),
38    /// The temporary file could not be renamed over the target.
39    #[error("could not replace the target file: {0}")]
40    Rename(String),
41    /// The target could not be read.
42    #[error("could not read the file: {0}")]
43    Read(String),
44}
45
46/// Write `bytes` to `path` atomically.
47///
48/// The temporary file is a hidden sibling named after the target, the process id, and a
49/// counter, so two writers never share it. It is opened with `create_new`, flushed with
50/// `sync_all`, and renamed over the target. On Windows, where a rename cannot replace an
51/// existing file, the old file is removed only after the complete temporary exists.
52///
53/// # Errors
54/// When the temporary cannot be created, written, or flushed, or the rename fails. The
55/// target is left as it was.
56#[cfg(feature = "threads")]
57/// # Example
58///
59/// ```
60/// use crisol_core::storage::atomic_write;
61/// ```
62pub fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), StorageError> {
63    atomic_write_with(path, bytes, |file| file.sync_all())
64}
65
66/// The write path with an injectable flush, so tests can fail after the bytes are on
67/// disk but before the rename.
68#[cfg(feature = "threads")]
69fn atomic_write_with(
70    path: &Path,
71    bytes: &[u8],
72    sync: impl FnOnce(&std::fs::File) -> std::io::Result<()>,
73) -> Result<(), StorageError> {
74    static COUNTER: AtomicU64 = AtomicU64::new(0);
75
76    let name = path
77        .file_name()
78        .and_then(|name| name.to_str())
79        .ok_or(StorageError::NoFileName)?;
80    // A hidden sibling named after the whole file name: `with_extension` made `a.json`
81    // and `a.txt` share a temporary, and two writers in one process shared it too.
82    // `process::id` is not implemented on wasm; one wasm instance is one process.
83    let process: u32 = if cfg!(target_family = "wasm") {
84        0
85    } else {
86        std::process::id()
87    };
88    let temp = path.with_file_name(format!(
89        ".{name}.tmp-{process}-{}",
90        COUNTER.fetch_add(1, Ordering::Relaxed)
91    ));
92    let written = (|| {
93        // `create_new` refuses an existing file or symlink at the temporary path.
94        let mut file = std::fs::OpenOptions::new()
95            .write(true)
96            .create_new(true)
97            .open(&temp)
98            .map_err(|error| StorageError::Create(error.to_string()))?;
99        file.write_all(bytes)
100            .map_err(|error| StorageError::Write(error.to_string()))?;
101        sync(&file).map_err(|error| StorageError::Sync(error.to_string()))
102    })();
103    if let Err(error) = written {
104        let _ = std::fs::remove_file(&temp);
105        return Err(error);
106    }
107    // POSIX `rename` replaces the target atomically. Removing the old file first opened a
108    // window in which a crash left no file at all.
109    if let Err(error) = std::fs::rename(&temp, path) {
110        // Windows refuses to rename over an existing file; fall back to remove + rename,
111        // and keep the complete temporary file if that also fails.
112        if path.exists() && std::fs::remove_file(path).is_ok() && std::fs::rename(&temp, path).is_ok() {
113            return Ok(());
114        }
115        return Err(StorageError::Rename(error.to_string()));
116    }
117    Ok(())
118}
119
120/// Read a UTF-8 file, mapping the error to [`StorageError`].
121///
122/// # Errors
123/// When the file cannot be read.
124#[cfg(feature = "threads")]
125/// # Example
126///
127/// ```
128/// use crisol_core::storage::read_to_string;
129/// ```
130pub fn read_to_string(path: impl AsRef<Path>) -> Result<String, StorageError> {
131    std::fs::read_to_string(path).map_err(|error| StorageError::Read(error.to_string()))
132}
133
134/// A version envelope around a serializable payload.
135///
136/// Versioned files store `{"version": N, "data": …}`. A reader rejects a version newer
137/// than the latest it knows; older versions are migrated by the caller (CORE-DET-03).
138#[derive(Clone, Debug, PartialEq, Eq)]
139#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
140/// # Example
141///
142/// ```
143/// use crisol_core::storage::Versioned;
144/// ```
145pub struct Versioned<T> {
146    /// The file format version.
147    pub version: u32,
148    /// The payload.
149    pub data: T,
150}
151
152impl<T> Versioned<T> {
153    /// A payload at the current version.
154    pub fn new(version: u32, data: T) -> Self {
155        Self { version, data }
156    }
157}
158
159/// Check a stored version against the newest one the code writes.
160///
161/// # Errors
162/// When `found` is newer than `latest`.
163/// # Example
164///
165/// ```
166/// use crisol_core::storage::check_version;
167/// ```
168pub fn check_version(found: u32, latest: u32) -> Result<(), StorageError> {
169    if found > latest {
170        Err(StorageError::Read(format!(
171            "version {found} is newer than the supported version {latest}"
172        )))
173    } else {
174        Ok(())
175    }
176}
177
178/// A directory and the files a session keeps in it.
179#[derive(Clone, Debug, PartialEq, Eq)]
180/// # Example
181///
182/// ```
183/// use crisol_core::storage::SessionPaths;
184/// ```
185pub struct SessionPaths {
186    /// The session directory.
187    pub directory: PathBuf,
188}
189
190impl SessionPaths {
191    /// Paths under `directory`.
192    pub fn new(directory: impl Into<PathBuf>) -> Self {
193        Self {
194            directory: directory.into(),
195        }
196    }
197
198    /// The directory.
199    pub fn directory(&self) -> &Path {
200        &self.directory
201    }
202
203    /// `workspace.json`.
204    pub fn workspace(&self) -> PathBuf {
205        self.directory.join("workspace.json")
206    }
207
208    /// `stash.json`.
209    pub fn stash(&self) -> PathBuf {
210        self.directory.join("stash.json")
211    }
212
213    /// `journal.json`.
214    pub fn journal(&self) -> PathBuf {
215        self.directory.join("journal.json")
216    }
217
218    /// `keybindings.json`.
219    pub fn keybindings(&self) -> PathBuf {
220        self.directory.join("keybindings.json")
221    }
222
223    /// Create the directory, including parents.
224    ///
225    /// # Errors
226    /// When the directory cannot be created.
227    #[cfg(feature = "threads")]
228    pub fn create(&self) -> Result<(), StorageError> {
229        std::fs::create_dir_all(&self.directory).map_err(|error| StorageError::Write(error.to_string()))
230    }
231}
232
233// spec: CORE-DET-04
234#[cfg(all(test, feature = "threads"))]
235mod tests {
236    use super::*;
237
238    fn directory(prefix: &str) -> PathBuf {
239        let thread: String = std::thread::current()
240            .name()
241            .unwrap_or("test")
242            .chars()
243            .map(|character| {
244                if character.is_ascii_alphanumeric() {
245                    character
246                } else {
247                    '_'
248                }
249            })
250            .collect();
251        std::path::PathBuf::from("/tmp").join(format!("{prefix}-{thread}"))
252    }
253
254    #[test]
255    fn a_write_replaces_the_file_and_leaves_no_temporary() {
256        let directory = directory("crisol-storage");
257        let _ = std::fs::remove_dir_all(&directory);
258        std::fs::create_dir_all(&directory).expect("create");
259        let path = directory.join("data.json");
260        atomic_write(&path, b"one").expect("first");
261        atomic_write(&path, b"two").expect("second");
262        assert_eq!(std::fs::read(&path).expect("read"), b"two");
263        assert_eq!(std::fs::read_dir(&directory).expect("dir").count(), 1);
264        let _ = std::fs::remove_dir_all(directory);
265    }
266
267    #[test]
268    fn a_failed_flush_keeps_the_previous_file_intact() {
269        let directory = directory("crisol-storage-fail");
270        let _ = std::fs::remove_dir_all(&directory);
271        std::fs::create_dir_all(&directory).expect("create");
272        let path = directory.join("data.json");
273        atomic_write(&path, b"original").expect("original");
274        let error = atomic_write_with(&path, b"replacement", |_| {
275            Err(std::io::Error::other("simulated disk failure"))
276        })
277        .expect_err("flush fails");
278        assert!(matches!(error, StorageError::Sync(_)));
279        assert_eq!(std::fs::read(&path).expect("read"), b"original");
280        assert_eq!(
281            std::fs::read_dir(&directory).expect("dir").count(),
282            1,
283            "no temporary stays"
284        );
285        let _ = std::fs::remove_dir_all(directory);
286    }
287
288    #[test]
289    fn a_path_without_a_file_name_is_rejected() {
290        let error = atomic_write(Path::new("/"), b"x").expect_err("no name");
291        assert_eq!(error, StorageError::NoFileName);
292    }
293
294    #[test]
295    fn version_checks_accept_equal_and_older_and_reject_newer() {
296        assert!(check_version(1, 1).is_ok());
297        assert!(check_version(0, 1).is_ok());
298        assert!(check_version(2, 1).is_err());
299    }
300
301    #[test]
302    fn session_paths_have_stable_names() {
303        let paths = SessionPaths::new("/tmp/session");
304        assert_eq!(paths.workspace(), Path::new("/tmp/session/workspace.json"));
305        assert_eq!(paths.stash(), Path::new("/tmp/session/stash.json"));
306        assert_eq!(paths.journal(), Path::new("/tmp/session/journal.json"));
307        assert_eq!(paths.keybindings(), Path::new("/tmp/session/keybindings.json"));
308    }
309}