#[cfg(feature = "threads")]
use std::io::Write;
use std::path::{Path, PathBuf};
#[cfg(feature = "threads")]
use std::sync::atomic::{AtomicU64, Ordering};
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum StorageError {
#[error("the path has no file name")]
NoFileName,
#[error("could not create the temporary file: {0}")]
Create(String),
#[error("could not write the temporary file: {0}")]
Write(String),
#[error("could not flush the temporary file: {0}")]
Sync(String),
#[error("could not replace the target file: {0}")]
Rename(String),
#[error("could not read the file: {0}")]
Read(String),
}
#[cfg(feature = "threads")]
pub fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), StorageError> {
atomic_write_with(path, bytes, |file| file.sync_all())
}
#[cfg(feature = "threads")]
fn atomic_write_with(
path: &Path,
bytes: &[u8],
sync: impl FnOnce(&std::fs::File) -> std::io::Result<()>,
) -> Result<(), StorageError> {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let name = path
.file_name()
.and_then(|name| name.to_str())
.ok_or(StorageError::NoFileName)?;
let temp = path.with_file_name(format!(
".{name}.tmp-{}-{}",
std::process::id(),
COUNTER.fetch_add(1, Ordering::Relaxed)
));
let written = (|| {
let mut file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&temp)
.map_err(|error| StorageError::Create(error.to_string()))?;
file.write_all(bytes)
.map_err(|error| StorageError::Write(error.to_string()))?;
sync(&file).map_err(|error| StorageError::Sync(error.to_string()))
})();
if let Err(error) = written {
let _ = std::fs::remove_file(&temp);
return Err(error);
}
if let Err(error) = std::fs::rename(&temp, path) {
if path.exists() && std::fs::remove_file(path).is_ok() && std::fs::rename(&temp, path).is_ok() {
return Ok(());
}
return Err(StorageError::Rename(error.to_string()));
}
Ok(())
}
#[cfg(feature = "threads")]
pub fn read_to_string(path: impl AsRef<Path>) -> Result<String, StorageError> {
std::fs::read_to_string(path).map_err(|error| StorageError::Read(error.to_string()))
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Versioned<T> {
pub version: u32,
pub data: T,
}
impl<T> Versioned<T> {
pub fn new(version: u32, data: T) -> Self {
Self { version, data }
}
}
pub fn check_version(found: u32, latest: u32) -> Result<(), StorageError> {
if found > latest {
Err(StorageError::Read(format!(
"version {found} is newer than the supported version {latest}"
)))
} else {
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SessionPaths {
pub directory: PathBuf,
}
impl SessionPaths {
pub fn new(directory: impl Into<PathBuf>) -> Self {
Self {
directory: directory.into(),
}
}
pub fn directory(&self) -> &Path {
&self.directory
}
pub fn workspace(&self) -> PathBuf {
self.directory.join("workspace.json")
}
pub fn stash(&self) -> PathBuf {
self.directory.join("stash.json")
}
pub fn journal(&self) -> PathBuf {
self.directory.join("journal.json")
}
pub fn keybindings(&self) -> PathBuf {
self.directory.join("keybindings.json")
}
#[cfg(feature = "threads")]
pub fn create(&self) -> Result<(), StorageError> {
std::fs::create_dir_all(&self.directory).map_err(|error| StorageError::Write(error.to_string()))
}
}
#[cfg(all(test, feature = "threads"))]
mod tests {
use super::*;
fn directory(prefix: &str) -> PathBuf {
let thread: String = std::thread::current()
.name()
.unwrap_or("test")
.chars()
.map(|character| {
if character.is_ascii_alphanumeric() {
character
} else {
'_'
}
})
.collect();
std::env::temp_dir().join(format!("{prefix}-{}-{thread}", std::process::id()))
}
#[test]
fn a_write_replaces_the_file_and_leaves_no_temporary() {
let directory = directory("crisol-storage");
let _ = std::fs::remove_dir_all(&directory);
std::fs::create_dir_all(&directory).expect("create");
let path = directory.join("data.json");
atomic_write(&path, b"one").expect("first");
atomic_write(&path, b"two").expect("second");
assert_eq!(std::fs::read(&path).expect("read"), b"two");
assert_eq!(std::fs::read_dir(&directory).expect("dir").count(), 1);
let _ = std::fs::remove_dir_all(directory);
}
#[test]
fn a_failed_flush_keeps_the_previous_file_intact() {
let directory = directory("crisol-storage-fail");
let _ = std::fs::remove_dir_all(&directory);
std::fs::create_dir_all(&directory).expect("create");
let path = directory.join("data.json");
atomic_write(&path, b"original").expect("original");
let error = atomic_write_with(&path, b"replacement", |_| {
Err(std::io::Error::other("simulated disk failure"))
})
.expect_err("flush fails");
assert!(matches!(error, StorageError::Sync(_)));
assert_eq!(std::fs::read(&path).expect("read"), b"original");
assert_eq!(
std::fs::read_dir(&directory).expect("dir").count(),
1,
"no temporary stays"
);
let _ = std::fs::remove_dir_all(directory);
}
#[test]
fn a_path_without_a_file_name_is_rejected() {
let error = atomic_write(Path::new("/"), b"x").expect_err("no name");
assert_eq!(error, StorageError::NoFileName);
}
#[test]
fn version_checks_accept_equal_and_older_and_reject_newer() {
assert!(check_version(1, 1).is_ok());
assert!(check_version(0, 1).is_ok());
assert!(check_version(2, 1).is_err());
}
#[test]
fn session_paths_have_stable_names() {
let paths = SessionPaths::new("/tmp/session");
assert_eq!(paths.workspace(), Path::new("/tmp/session/workspace.json"));
assert_eq!(paths.stash(), Path::new("/tmp/session/stash.json"));
assert_eq!(paths.journal(), Path::new("/tmp/session/journal.json"));
assert_eq!(paths.keybindings(), Path::new("/tmp/session/keybindings.json"));
}
}