1#[cfg(feature = "threads")]
12use std::io::Write;
13use std::path::{Path, PathBuf};
14#[cfg(feature = "threads")]
15use std::sync::atomic::{AtomicU64, Ordering};
16
17#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
19#[non_exhaustive]
20pub enum StorageError {
26 #[error("the path has no file name")]
28 NoFileName,
29 #[error("could not create the temporary file: {0}")]
31 Create(String),
32 #[error("could not write the temporary file: {0}")]
34 Write(String),
35 #[error("could not flush the temporary file: {0}")]
37 Sync(String),
38 #[error("could not replace the target file: {0}")]
40 Rename(String),
41 #[error("could not read the file: {0}")]
43 Read(String),
44}
45
46#[cfg(feature = "threads")]
57pub fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), StorageError> {
63 atomic_write_with(path, bytes, |file| file.sync_all())
64}
65
66#[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 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 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 if let Err(error) = std::fs::rename(&temp, path) {
110 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#[cfg(feature = "threads")]
125pub 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#[derive(Clone, Debug, PartialEq, Eq)]
139#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
140pub struct Versioned<T> {
146 pub version: u32,
148 pub data: T,
150}
151
152impl<T> Versioned<T> {
153 pub fn new(version: u32, data: T) -> Self {
155 Self { version, data }
156 }
157}
158
159pub 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#[derive(Clone, Debug, PartialEq, Eq)]
180pub struct SessionPaths {
186 pub directory: PathBuf,
188}
189
190impl SessionPaths {
191 pub fn new(directory: impl Into<PathBuf>) -> Self {
193 Self {
194 directory: directory.into(),
195 }
196 }
197
198 pub fn directory(&self) -> &Path {
200 &self.directory
201 }
202
203 pub fn workspace(&self) -> PathBuf {
205 self.directory.join("workspace.json")
206 }
207
208 pub fn stash(&self) -> PathBuf {
210 self.directory.join("stash.json")
211 }
212
213 pub fn journal(&self) -> PathBuf {
215 self.directory.join("journal.json")
216 }
217
218 pub fn keybindings(&self) -> PathBuf {
220 self.directory.join("keybindings.json")
221 }
222
223 #[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#[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}