1use std::fs::{self, OpenOptions};
12use std::io::{self, Write};
13use std::path::{Path, PathBuf};
14use std::sync::atomic::{AtomicU64, Ordering};
15
16pub const SCHEMA_VERSION: u32 = 1;
18const SCHEMA_FILE: &str = "persistence.version";
19const OWNER_FILE: &str = ".mgui-owner";
20const CHECKSUM_SUFFIX: &str = ".checksum";
21const BACKUP_SUFFIX: &str = ".bak";
22const TEMP_SUFFIX: &str = ".tmp";
23
24static OWNER_SEQ: AtomicU64 = AtomicU64::new(0);
25
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub enum SchemaState {
29 Legacy,
31 Current,
33 Newer(u32),
35}
36
37#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
39pub enum FileOutcome {
40 #[default]
42 Missing,
43 Loaded,
45 LegacyLoaded,
47 RecoveredFromBackup,
49 Unrecoverable,
51 IoUnavailable,
53}
54
55fn checksum_path(path: &Path) -> PathBuf {
56 let mut name = path.file_name().unwrap_or_default().to_os_string();
57 name.push(CHECKSUM_SUFFIX);
58 path.with_file_name(name)
59}
60
61fn backup_path(path: &Path) -> PathBuf {
62 let mut name = path.file_name().unwrap_or_default().to_os_string();
63 name.push(BACKUP_SUFFIX);
64 path.with_file_name(name)
65}
66
67fn temp_path(path: &Path) -> PathBuf {
68 let mut name = path.file_name().unwrap_or_default().to_os_string();
69 name.push(TEMP_SUFFIX);
70 path.with_file_name(name)
71}
72
73pub fn checksum(bytes: &[u8]) -> u64 {
75 let mut hash = 0xcbf2_9ce4_8422_2325_u64;
76 for byte in bytes {
77 hash ^= *byte as u64;
78 hash = hash.wrapping_mul(0x0100_0000_01b3);
79 }
80 hash
81}
82
83pub fn atomic_write(path: &Path, bytes: &[u8]) -> io::Result<()> {
85 if let Some(parent) = path.parent() {
86 fs::create_dir_all(parent)?;
87 }
88 let temp = temp_path(path);
89 let result = (|| -> io::Result<()> {
90 let mut file = OpenOptions::new().write(true).create(true).truncate(true).open(&temp)?;
91 file.write_all(bytes)?;
92 file.sync_all()?;
93 drop(file);
94 fs::rename(&temp, path)
95 })();
96 if result.is_err() {
97 let _ = fs::remove_file(&temp);
98 }
99 result
100}
101
102fn write_checksum(path: &Path, bytes: &[u8]) -> io::Result<()> {
103 let text = format!("fnv1a64={:016x}\n", checksum(bytes));
104 atomic_write(&checksum_path(path), text.as_bytes())
105}
106
107fn read_checked(path: &Path) -> io::Result<Option<String>> {
109 let bytes = match fs::read(path) {
110 Ok(bytes) => bytes,
111 Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(None),
112 Err(err) => return Err(err),
113 };
114 let sidecar = checksum_path(path);
115 match fs::read_to_string(&sidecar) {
116 Ok(expected) => {
117 let expected = expected.trim().strip_prefix("fnv1a64=").and_then(|v| u64::from_str_radix(v, 16).ok());
118 if expected == Some(checksum(&bytes)) {
119 match String::from_utf8(bytes) {
120 Ok(text) => Ok(Some(text)),
121 Err(_) => Ok(None),
122 }
123 } else {
124 Ok(None)
125 }
126 }
127 Err(err) if err.kind() == io::ErrorKind::NotFound => {
128 match String::from_utf8(bytes) {
130 Ok(text) => Ok(Some(text)),
131 Err(_) => Ok(None),
132 }
133 }
134 Err(err) => Err(err),
135 }
136}
137
138pub fn read_with_recovery(path: &Path) -> io::Result<(String, FileOutcome)> {
140 match read_checked(path)? {
141 Some(text) => {
142 let outcome = if checksum_path(path).exists() { FileOutcome::Loaded } else { FileOutcome::LegacyLoaded };
143 Ok((text, outcome))
144 }
145 None => match read_checked(&backup_path(path))? {
146 Some(text) => Ok((text, FileOutcome::RecoveredFromBackup)),
147 None => Ok((String::new(), FileOutcome::Unrecoverable)),
148 },
149 }
150}
151
152pub fn write_with_backup(path: &Path, bytes: &[u8]) -> io::Result<()> {
154 if let Ok(old) = fs::read(path) {
155 let backup = backup_path(path);
156 atomic_write(&backup, &old)?;
157 let checksum_bytes = format!("fnv1a64={:016x}\n", checksum(&old));
158 atomic_write(&checksum_path(&backup), checksum_bytes.as_bytes())?;
159 }
160 atomic_write(path, bytes)?;
161 write_checksum(path, bytes)
162}
163
164pub fn read_schema(dir: &Path) -> SchemaState {
165 match fs::read_to_string(dir.join(SCHEMA_FILE)) {
166 Ok(text) => match text.trim().parse::<u32>() {
167 Ok(SCHEMA_VERSION) => SchemaState::Current,
168 Ok(other) => SchemaState::Newer(other),
169 Err(_) => SchemaState::Newer(u32::MAX),
170 },
171 Err(_) => SchemaState::Legacy,
172 }
173}
174
175pub fn write_schema(dir: &Path) -> io::Result<()> {
176 let text = format!("{SCHEMA_VERSION}\n");
177 atomic_write(&dir.join(SCHEMA_FILE), text.as_bytes())
178}
179
180#[derive(Debug)]
183pub struct OwnerLease {
184 path: PathBuf,
185 token: String,
186 active: bool,
187}
188
189impl OwnerLease {
190 pub fn token(&self) -> &str {
191 &self.token
192 }
193
194 pub fn is_current(&self) -> bool {
196 self.active && fs::read_to_string(&self.path).map(|text| text.trim() == self.token).unwrap_or(false)
197 }
198
199 pub fn release(&mut self) -> io::Result<()> {
200 if !self.active {
201 return Ok(());
202 }
203 if !self.is_current() {
204 self.active = false;
205 return Ok(());
206 }
207 match fs::remove_file(&self.path) {
208 Ok(()) => {
209 self.active = false;
210 Ok(())
211 }
212 Err(err) => Err(err),
213 }
214 }
215}
216
217impl Drop for OwnerLease {
218 fn drop(&mut self) {
219 let _ = self.release();
220 }
221}
222
223#[derive(Debug)]
224pub enum AcquireError {
225 Contested,
227 Io(io::Error),
228}
229
230pub fn try_acquire_owner(dir: &Path) -> Result<OwnerLease, AcquireError> {
231 fs::create_dir_all(dir).map_err(AcquireError::Io)?;
232 let path = dir.join(OWNER_FILE);
233 let token = format!("mgui-owner:{}:{}", std::process::id(), OWNER_SEQ.fetch_add(1, Ordering::Relaxed));
234 let result = OpenOptions::new().write(true).create_new(true).open(&path);
235 match result {
236 Ok(mut file) => {
237 file.write_all(format!("{token}\n").as_bytes()).map_err(AcquireError::Io)?;
238 file.sync_all().map_err(AcquireError::Io)?;
239 Ok(OwnerLease { path, token, active: true })
240 }
241 Err(err) if err.kind() == io::ErrorKind::AlreadyExists => Err(AcquireError::Contested),
242 Err(err) => Err(AcquireError::Io(err)),
243 }
244}
245
246#[cfg(test)]
247mod tests {
248 use super::*;
249
250 fn temp_dir(tag: &str) -> PathBuf {
251 let dir = std::env::temp_dir().join(format!("mgui-persist-{}-{tag}", std::process::id()));
252 let _ = fs::remove_dir_all(&dir);
253 fs::create_dir_all(&dir).unwrap();
254 dir
255 }
256
257 #[test]
258 fn atomic_write_replaces_existing_file() {
259 let dir = temp_dir("atomic");
260 let path = dir.join("data.txt");
261 atomic_write(&path, b"first").unwrap();
262 atomic_write(&path, b"second").unwrap();
263 assert_eq!(fs::read_to_string(&path).unwrap(), "second");
264 assert!(!temp_path(&path).exists());
265 fs::remove_dir_all(dir).unwrap();
266 }
267
268 #[test]
269 fn corruption_falls_back_to_backup() {
270 let dir = temp_dir("corrupt");
271 let path = dir.join("data.txt");
272 write_with_backup(&path, b"good").unwrap();
273 write_with_backup(&path, b"new").unwrap();
274 fs::write(&path, b"broken").unwrap();
276 let (text, outcome) = read_with_recovery(&path).unwrap();
277 assert_eq!(text, "good");
278 assert_eq!(outcome, FileOutcome::RecoveredFromBackup);
279 fs::remove_dir_all(dir).unwrap();
280 }
281
282 #[test]
283 fn legacy_file_without_checksum_is_accepted() {
284 let dir = temp_dir("legacy");
285 let path = dir.join("data.txt");
286 fs::write(&path, "key=value\n").unwrap();
287 let (text, outcome) = read_with_recovery(&path).unwrap();
288 assert_eq!(text, "key=value\n");
289 assert_eq!(outcome, FileOutcome::LegacyLoaded);
290 fs::remove_dir_all(dir).unwrap();
291 }
292
293 #[test]
294 fn unrecoverable_file_reports_explicitly() {
295 let dir = temp_dir("unrecoverable");
296 let path = dir.join("data.txt");
297 fs::write(&path, b"\xff\xfe").unwrap();
298 let (text, outcome) = read_with_recovery(&path).unwrap();
299 assert!(text.is_empty());
300 assert_eq!(outcome, FileOutcome::Unrecoverable);
301 fs::remove_dir_all(dir).unwrap();
302 }
303
304 #[test]
305 fn schema_marker_round_trip() {
306 let dir = temp_dir("schema");
307 assert_eq!(read_schema(&dir), SchemaState::Legacy);
308 write_schema(&dir).unwrap();
309 assert_eq!(read_schema(&dir), SchemaState::Current);
310 fs::write(dir.join(SCHEMA_FILE), "999\n").unwrap();
311 assert_eq!(read_schema(&dir), SchemaState::Newer(999));
312 fs::remove_dir_all(dir).unwrap();
313 }
314
315 #[test]
316 fn owner_lease_is_exclusive_and_releases() {
317 let dir = temp_dir("owner");
318 let lease = try_acquire_owner(&dir).unwrap();
319 assert!(lease.is_current());
320 assert!(matches!(try_acquire_owner(&dir), Err(AcquireError::Contested)));
321 let mut lease = lease;
322 lease.release().unwrap();
323 assert!(!dir.join(OWNER_FILE).exists());
324 drop(try_acquire_owner(&dir).unwrap());
325 assert!(!dir.join(OWNER_FILE).exists(), "Drop 必须释放租约");
326 fs::remove_dir_all(dir).unwrap();
327 }
328}