use std::fs::{self, OpenOptions};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
pub const SCHEMA_VERSION: u32 = 1;
const SCHEMA_FILE: &str = "persistence.version";
const OWNER_FILE: &str = ".mgui-owner";
const CHECKSUM_SUFFIX: &str = ".checksum";
const BACKUP_SUFFIX: &str = ".bak";
const TEMP_SUFFIX: &str = ".tmp";
static OWNER_SEQ: AtomicU64 = AtomicU64::new(0);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SchemaState {
Legacy,
Current,
Newer(u32),
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FileOutcome {
#[default]
Missing,
Loaded,
LegacyLoaded,
RecoveredFromBackup,
Unrecoverable,
IoUnavailable,
}
fn checksum_path(path: &Path) -> PathBuf {
let mut name = path.file_name().unwrap_or_default().to_os_string();
name.push(CHECKSUM_SUFFIX);
path.with_file_name(name)
}
fn backup_path(path: &Path) -> PathBuf {
let mut name = path.file_name().unwrap_or_default().to_os_string();
name.push(BACKUP_SUFFIX);
path.with_file_name(name)
}
fn temp_path(path: &Path) -> PathBuf {
let mut name = path.file_name().unwrap_or_default().to_os_string();
name.push(TEMP_SUFFIX);
path.with_file_name(name)
}
pub fn checksum(bytes: &[u8]) -> u64 {
let mut hash = 0xcbf2_9ce4_8422_2325_u64;
for byte in bytes {
hash ^= *byte as u64;
hash = hash.wrapping_mul(0x0100_0000_01b3);
}
hash
}
pub fn atomic_write(path: &Path, bytes: &[u8]) -> io::Result<()> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let temp = temp_path(path);
let result = (|| -> io::Result<()> {
let mut file = OpenOptions::new().write(true).create(true).truncate(true).open(&temp)?;
file.write_all(bytes)?;
file.sync_all()?;
drop(file);
fs::rename(&temp, path)
})();
if result.is_err() {
let _ = fs::remove_file(&temp);
}
result
}
fn write_checksum(path: &Path, bytes: &[u8]) -> io::Result<()> {
let text = format!("fnv1a64={:016x}\n", checksum(bytes));
atomic_write(&checksum_path(path), text.as_bytes())
}
fn read_checked(path: &Path) -> io::Result<Option<String>> {
let bytes = match fs::read(path) {
Ok(bytes) => bytes,
Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(err) => return Err(err),
};
let sidecar = checksum_path(path);
match fs::read_to_string(&sidecar) {
Ok(expected) => {
let expected = expected.trim().strip_prefix("fnv1a64=").and_then(|v| u64::from_str_radix(v, 16).ok());
if expected == Some(checksum(&bytes)) {
match String::from_utf8(bytes) {
Ok(text) => Ok(Some(text)),
Err(_) => Ok(None),
}
} else {
Ok(None)
}
}
Err(err) if err.kind() == io::ErrorKind::NotFound => {
match String::from_utf8(bytes) {
Ok(text) => Ok(Some(text)),
Err(_) => Ok(None),
}
}
Err(err) => Err(err),
}
}
pub fn read_with_recovery(path: &Path) -> io::Result<(String, FileOutcome)> {
match read_checked(path)? {
Some(text) => {
let outcome = if checksum_path(path).exists() { FileOutcome::Loaded } else { FileOutcome::LegacyLoaded };
Ok((text, outcome))
}
None => match read_checked(&backup_path(path))? {
Some(text) => Ok((text, FileOutcome::RecoveredFromBackup)),
None => Ok((String::new(), FileOutcome::Unrecoverable)),
},
}
}
pub fn write_with_backup(path: &Path, bytes: &[u8]) -> io::Result<()> {
if let Ok(old) = fs::read(path) {
let backup = backup_path(path);
atomic_write(&backup, &old)?;
let checksum_bytes = format!("fnv1a64={:016x}\n", checksum(&old));
atomic_write(&checksum_path(&backup), checksum_bytes.as_bytes())?;
}
atomic_write(path, bytes)?;
write_checksum(path, bytes)
}
pub fn read_schema(dir: &Path) -> SchemaState {
match fs::read_to_string(dir.join(SCHEMA_FILE)) {
Ok(text) => match text.trim().parse::<u32>() {
Ok(SCHEMA_VERSION) => SchemaState::Current,
Ok(other) => SchemaState::Newer(other),
Err(_) => SchemaState::Newer(u32::MAX),
},
Err(_) => SchemaState::Legacy,
}
}
pub fn write_schema(dir: &Path) -> io::Result<()> {
let text = format!("{SCHEMA_VERSION}\n");
atomic_write(&dir.join(SCHEMA_FILE), text.as_bytes())
}
#[derive(Debug)]
pub struct OwnerLease {
path: PathBuf,
token: String,
active: bool,
}
impl OwnerLease {
pub fn token(&self) -> &str {
&self.token
}
pub fn is_current(&self) -> bool {
self.active && fs::read_to_string(&self.path).map(|text| text.trim() == self.token).unwrap_or(false)
}
pub fn release(&mut self) -> io::Result<()> {
if !self.active {
return Ok(());
}
if !self.is_current() {
self.active = false;
return Ok(());
}
match fs::remove_file(&self.path) {
Ok(()) => {
self.active = false;
Ok(())
}
Err(err) => Err(err),
}
}
}
impl Drop for OwnerLease {
fn drop(&mut self) {
let _ = self.release();
}
}
#[derive(Debug)]
pub enum AcquireError {
Contested,
Io(io::Error),
}
pub fn try_acquire_owner(dir: &Path) -> Result<OwnerLease, AcquireError> {
fs::create_dir_all(dir).map_err(AcquireError::Io)?;
let path = dir.join(OWNER_FILE);
let token = format!("mgui-owner:{}:{}", std::process::id(), OWNER_SEQ.fetch_add(1, Ordering::Relaxed));
let result = OpenOptions::new().write(true).create_new(true).open(&path);
match result {
Ok(mut file) => {
file.write_all(format!("{token}\n").as_bytes()).map_err(AcquireError::Io)?;
file.sync_all().map_err(AcquireError::Io)?;
Ok(OwnerLease { path, token, active: true })
}
Err(err) if err.kind() == io::ErrorKind::AlreadyExists => Err(AcquireError::Contested),
Err(err) => Err(AcquireError::Io(err)),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn temp_dir(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("mgui-persist-{}-{tag}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn atomic_write_replaces_existing_file() {
let dir = temp_dir("atomic");
let path = dir.join("data.txt");
atomic_write(&path, b"first").unwrap();
atomic_write(&path, b"second").unwrap();
assert_eq!(fs::read_to_string(&path).unwrap(), "second");
assert!(!temp_path(&path).exists());
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn corruption_falls_back_to_backup() {
let dir = temp_dir("corrupt");
let path = dir.join("data.txt");
write_with_backup(&path, b"good").unwrap();
write_with_backup(&path, b"new").unwrap();
fs::write(&path, b"broken").unwrap();
let (text, outcome) = read_with_recovery(&path).unwrap();
assert_eq!(text, "good");
assert_eq!(outcome, FileOutcome::RecoveredFromBackup);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn legacy_file_without_checksum_is_accepted() {
let dir = temp_dir("legacy");
let path = dir.join("data.txt");
fs::write(&path, "key=value\n").unwrap();
let (text, outcome) = read_with_recovery(&path).unwrap();
assert_eq!(text, "key=value\n");
assert_eq!(outcome, FileOutcome::LegacyLoaded);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn unrecoverable_file_reports_explicitly() {
let dir = temp_dir("unrecoverable");
let path = dir.join("data.txt");
fs::write(&path, b"\xff\xfe").unwrap();
let (text, outcome) = read_with_recovery(&path).unwrap();
assert!(text.is_empty());
assert_eq!(outcome, FileOutcome::Unrecoverable);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn schema_marker_round_trip() {
let dir = temp_dir("schema");
assert_eq!(read_schema(&dir), SchemaState::Legacy);
write_schema(&dir).unwrap();
assert_eq!(read_schema(&dir), SchemaState::Current);
fs::write(dir.join(SCHEMA_FILE), "999\n").unwrap();
assert_eq!(read_schema(&dir), SchemaState::Newer(999));
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn owner_lease_is_exclusive_and_releases() {
let dir = temp_dir("owner");
let lease = try_acquire_owner(&dir).unwrap();
assert!(lease.is_current());
assert!(matches!(try_acquire_owner(&dir), Err(AcquireError::Contested)));
let mut lease = lease;
lease.release().unwrap();
assert!(!dir.join(OWNER_FILE).exists());
drop(try_acquire_owner(&dir).unwrap());
assert!(!dir.join(OWNER_FILE).exists(), "Drop 必须释放租约");
fs::remove_dir_all(dir).unwrap();
}
}