Skip to main content

toolblox_lib/
storage.rs

1//! Validated, atomic JSON persistence serialized by one application state.
2
3use std::collections::HashSet;
4use std::fmt;
5use std::fs::{self, File, OpenOptions};
6use std::io::{self, Write};
7use std::path::{Path, PathBuf};
8use std::sync::Mutex;
9
10use serde::Serialize;
11use serde::de::DeserializeOwned;
12
13use crate::models::{Settings, StoredAccount};
14
15/// Distinguishes temporary files written concurrently by this process.
16static TEMP_SEQUENCE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
17
18/// Why local data couldn't be read or written.
19#[derive(Debug)]
20pub enum StorageError {
21    Io(io::Error),
22    /// The data failed validation. Holds a user-facing message.
23    Invalid(String),
24    Json(serde_json::Error),
25    /// The storage lock was poisoned by a panic.
26    Locked,
27}
28
29impl fmt::Display for StorageError {
30    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
31        match self {
32            Self::Io(_) => write!(
33                formatter,
34                "Toolblox couldn't access its local data. Is the data folder available?"
35            ),
36            Self::Invalid(message) => formatter.write_str(message),
37            Self::Json(_) => write!(
38                formatter,
39                "Toolblox couldn't read its local data. Is the file intact?"
40            ),
41            Self::Locked => write!(
42                formatter,
43                "Toolblox couldn't lock its local data. Can you restart the app?"
44            ),
45        }
46    }
47}
48
49impl std::error::Error for StorageError {
50    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
51        match self {
52            Self::Io(error) => Some(error),
53            Self::Json(error) => Some(error),
54            Self::Invalid(_) | Self::Locked => None,
55        }
56    }
57}
58
59impl From<io::Error> for StorageError {
60    fn from(error: io::Error) -> Self {
61        Self::Io(error)
62    }
63}
64
65impl From<serde_json::Error> for StorageError {
66    fn from(error: serde_json::Error) -> Self {
67        Self::Json(error)
68    }
69}
70
71/// Reads and writes `settings.json`, `accounts.json`, and `theme.css` in the data folder.
72///
73/// One lock serializes every read and write, so read-modify-write updates can't lose changes.
74pub struct Storage {
75    root: PathBuf,
76    gate: Mutex<()>,
77}
78
79impl Storage {
80    /// Creates storage rooted at `root`. Files are created on first write.
81    pub fn new(root: PathBuf) -> Self {
82        Self {
83            root,
84            gate: Mutex::new(()),
85        }
86    }
87
88    /// Returns the data folder.
89    pub fn root(&self) -> &Path {
90        &self.root
91    }
92
93    /// Loads settings, or the defaults when none are saved.
94    pub fn load_settings(&self) -> Result<Settings, StorageError> {
95        let _guard = self.gate.lock().map_err(|_| StorageError::Locked)?;
96        self.load_settings_unlocked()
97    }
98
99    /// Validates and atomically replaces the saved settings.
100    pub fn save_settings(&self, settings: &Settings) -> Result<(), StorageError> {
101        let _guard = self.gate.lock().map_err(|_| StorageError::Locked)?;
102        settings.validate().map_err(StorageError::Invalid)?;
103        write_json_atomic(&self.root.join("settings.json"), settings)
104    }
105
106    /// Loads, changes, validates, and saves settings under one lock. Nothing is written when
107    /// `update` fails.
108    pub fn update_settings<T>(
109        &self,
110        update: impl FnOnce(&mut Settings) -> Result<T, StorageError>,
111    ) -> Result<T, StorageError> {
112        let _guard = self.gate.lock().map_err(|_| StorageError::Locked)?;
113        let mut settings = self.load_settings_unlocked()?;
114        let result = update(&mut settings)?;
115        settings.validate().map_err(StorageError::Invalid)?;
116        write_json_atomic(&self.root.join("settings.json"), &settings)?;
117        Ok(result)
118    }
119
120    /// Saves `current` as the last version that opened and returns whether it's newer than the
121    /// version that opened before. The first run on this device isn't an update. Data saved before
122    /// 0.4.8 has no version, so it counts as an update.
123    pub fn record_version(&self, current: &semver::Version) -> Result<bool, StorageError> {
124        let _guard = self.gate.lock().map_err(|_| StorageError::Locked)?;
125        let path = self.root.join("settings.json");
126        let used_before = path.exists() || self.root.join("accounts.json").exists();
127        let mut settings = self.load_settings_unlocked()?;
128        let updated = used_before
129            && settings
130                .last_seen_version
131                .as_deref()
132                .is_none_or(|seen| semver::Version::parse(seen).is_ok_and(|seen| *current > seen));
133        let current = current.to_string();
134        if settings.last_seen_version.as_deref() != Some(current.as_str()) {
135            settings.last_seen_version = Some(current);
136            write_json_atomic(&path, &settings)?;
137        }
138        Ok(updated)
139    }
140
141    /// Loads the saved accounts, or none when the file doesn't exist.
142    pub fn load_accounts(&self) -> Result<Vec<StoredAccount>, StorageError> {
143        let _guard = self.gate.lock().map_err(|_| StorageError::Locked)?;
144        self.load_accounts_unlocked()
145    }
146
147    /// Validates and atomically replaces the saved accounts.
148    #[cfg(test)]
149    pub fn save_accounts(&self, accounts: &[StoredAccount]) -> Result<(), StorageError> {
150        let _guard = self.gate.lock().map_err(|_| StorageError::Locked)?;
151        validate_accounts(accounts)?;
152        write_json_atomic(&self.root.join("accounts.json"), accounts)
153    }
154
155    /// Loads, changes, validates, and saves accounts under one lock. Nothing is written when
156    /// `update` fails.
157    pub fn update_accounts<T>(
158        &self,
159        update: impl FnOnce(&mut Vec<StoredAccount>) -> Result<T, StorageError>,
160    ) -> Result<T, StorageError> {
161        let _guard = self.gate.lock().map_err(|_| StorageError::Locked)?;
162        let mut accounts = self.load_accounts_unlocked()?;
163        let result = update(&mut accounts)?;
164        validate_accounts(&accounts)?;
165        write_json_atomic(&self.root.join("accounts.json"), &accounts)?;
166        Ok(result)
167    }
168
169    /// Loads the custom theme CSS, or none when it isn't saved.
170    pub fn load_theme(&self) -> Result<String, StorageError> {
171        let _guard = self.gate.lock().map_err(|_| StorageError::Locked)?;
172        let path = self.root.join("theme.css");
173        if !path.exists() {
174            return Ok(String::new());
175        }
176        let css = fs::read_to_string(path)?;
177        crate::theme::validate(&css).map_err(StorageError::Invalid)?;
178        Ok(css)
179    }
180
181    /// Validates and atomically replaces the custom theme CSS.
182    pub fn save_theme(&self, css: &str) -> Result<(), StorageError> {
183        let _guard = self.gate.lock().map_err(|_| StorageError::Locked)?;
184        crate::theme::validate(css).map_err(StorageError::Invalid)?;
185        write_atomic(&self.root.join("theme.css"), css.as_bytes())
186    }
187
188    /// Loads settings without taking the lock. Callers must hold it.
189    fn load_settings_unlocked(&self) -> Result<Settings, StorageError> {
190        let path = self.root.join("settings.json");
191        if !path.exists() {
192            return Ok(Settings::default());
193        }
194        let settings: Settings = read_json(&path)?;
195        settings.validate().map_err(StorageError::Invalid)?;
196        Ok(settings)
197    }
198
199    /// Loads accounts without taking the lock. Callers must hold it. Secret-like fields saved by
200    /// older versions are removed and the file is rewritten without them.
201    fn load_accounts_unlocked(&self) -> Result<Vec<StoredAccount>, StorageError> {
202        let path = self.root.join("accounts.json");
203        if !path.exists() {
204            return Ok(Vec::new());
205        }
206        let mut accounts: Vec<StoredAccount> = read_json(&path)?;
207        let mut scrubbed = false;
208        for account in &mut accounts {
209            scrubbed |= account.remove_secrets();
210        }
211        validate_accounts(&accounts)?;
212        if scrubbed {
213            write_json_atomic(&path, &accounts)?;
214        }
215        Ok(accounts)
216    }
217}
218
219/// Validates each account and rejects duplicate IDs.
220fn validate_accounts(accounts: &[StoredAccount]) -> Result<(), StorageError> {
221    let mut ids = HashSet::with_capacity(accounts.len());
222    for account in accounts {
223        account.validate().map_err(StorageError::Invalid)?;
224        if !ids.insert(account.id) {
225            return Err(StorageError::Invalid(
226                "The account list contains a duplicate. Can you remove and add it again?".into(),
227            ));
228        }
229    }
230    Ok(())
231}
232
233/// Parses a JSON file.
234fn read_json<T: DeserializeOwned>(path: &Path) -> Result<T, StorageError> {
235    Ok(serde_json::from_reader(File::open(path)?)?)
236}
237
238/// Writes pretty-printed JSON with `write_atomic`.
239fn write_json_atomic(path: &Path, value: &(impl Serialize + ?Sized)) -> Result<(), StorageError> {
240    let mut contents = serde_json::to_vec_pretty(value)?;
241    contents.push(b'\n');
242    write_atomic(path, &contents)
243}
244
245/// Writes to a temporary file, flushes it, and moves it over `path`, so a crash leaves either
246/// the old or the new file. On Unix the file is readable only by its owner.
247fn write_atomic(path: &Path, contents: &[u8]) -> Result<(), StorageError> {
248    let parent = path.parent().ok_or_else(|| {
249        StorageError::Invalid("The local data path isn't valid. Can you restart the app?".into())
250    })?;
251    fs::create_dir_all(parent)?;
252    let sequence = TEMP_SEQUENCE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
253    let temp = parent.join(format!(
254        ".{}.{}.{}.tmp",
255        path.file_name()
256            .and_then(|name| name.to_str())
257            .unwrap_or("data"),
258        std::process::id(),
259        sequence
260    ));
261
262    let result = (|| {
263        let mut options = OpenOptions::new();
264        options.write(true).create_new(true);
265        #[cfg(unix)]
266        {
267            use std::os::unix::fs::OpenOptionsExt;
268
269            options.mode(0o600);
270        }
271        let mut file = options.open(&temp)?;
272        file.write_all(contents)?;
273        file.sync_all()?;
274        replace_file(&temp, path)?;
275        sync_directory(parent)?;
276        Ok(())
277    })();
278    if result.is_err() {
279        let _ = fs::remove_file(&temp);
280    }
281    result
282}
283
284/// Replaces `to` with `from` in one step, flushing the move to disk.
285#[cfg(windows)]
286pub(crate) fn replace_file(from: &Path, to: &Path) -> io::Result<()> {
287    use std::os::windows::ffi::OsStrExt;
288    use windows_sys::Win32::Storage::FileSystem::{
289        MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH, MoveFileExW,
290    };
291
292    let from: Vec<u16> = from.as_os_str().encode_wide().chain(Some(0)).collect();
293    let to: Vec<u16> = to.as_os_str().encode_wide().chain(Some(0)).collect();
294    let moved = unsafe {
295        MoveFileExW(
296            from.as_ptr(),
297            to.as_ptr(),
298            MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH,
299        )
300    };
301    if moved == 0 {
302        Err(io::Error::last_os_error())
303    } else {
304        Ok(())
305    }
306}
307
308/// Replaces `to` with `from` in one step.
309#[cfg(not(windows))]
310pub(crate) fn replace_file(from: &Path, to: &Path) -> io::Result<()> {
311    fs::rename(from, to)
312}
313
314/// Flushes a directory entry change to disk.
315#[cfg(unix)]
316fn sync_directory(path: &Path) -> io::Result<()> {
317    File::open(path)?.sync_all()
318}
319
320/// Does nothing; this platform doesn't need directory flushes.
321#[cfg(not(unix))]
322fn sync_directory(_path: &Path) -> io::Result<()> {
323    Ok(())
324}
325
326#[cfg(test)]
327mod tests {
328    use std::sync::Arc;
329    use std::thread;
330
331    use serde_json::Map;
332
333    use super::*;
334
335    fn test_root(name: &str) -> PathBuf {
336        std::env::temp_dir().join(format!(
337            "toolblox-{name}-{}-{}",
338            std::process::id(),
339            TEMP_SEQUENCE.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
340        ))
341    }
342
343    fn account() -> StoredAccount {
344        StoredAccount {
345            id: 1,
346            name: "builderman".into(),
347            display_name: "Builderman".into(),
348            avatar_url: None,
349            notes: String::new(),
350            game_notes: Default::default(),
351            added_at: 1.0,
352            last_played_at: None,
353            play_count: 0,
354            widget_data: Default::default(),
355            place_id: None,
356            last_place_id: None,
357            pinned: false,
358            extra: Map::new(),
359        }
360    }
361
362    #[test]
363    fn settings_round_trip_preserves_unknown_fields() {
364        let root = test_root("settings");
365        let store = Storage::new(root.clone());
366        let mut settings = Settings::default();
367        settings.extra.insert("future_setting".into(), true.into());
368        store.save_settings(&settings).unwrap();
369        assert_eq!(store.load_settings().unwrap(), settings);
370        fs::remove_dir_all(root).unwrap();
371    }
372
373    #[test]
374    fn record_version_reports_only_the_first_launch_after_an_update() {
375        let version = |text: &str| semver::Version::parse(text).unwrap();
376        let root = test_root("version");
377        let store = Storage::new(root.clone());
378        assert!(!store.record_version(&version("0.4.8-beta")).unwrap());
379        assert!(!store.record_version(&version("0.4.8-beta")).unwrap());
380        assert!(store.record_version(&version("0.4.9-beta")).unwrap());
381        assert!(!store.record_version(&version("0.4.9-beta")).unwrap());
382        assert!(!store.record_version(&version("0.4.8-beta")).unwrap());
383        assert_eq!(
384            store.load_settings().unwrap().last_seen_version.as_deref(),
385            Some("0.4.8-beta")
386        );
387        fs::remove_dir_all(root).unwrap();
388    }
389
390    #[test]
391    fn record_version_treats_data_without_a_version_as_an_update() {
392        let version = semver::Version::parse("0.4.8-beta").unwrap();
393        let root = test_root("version-legacy");
394        let store = Storage::new(root.clone());
395        store.save_settings(&Settings::default()).unwrap();
396        assert!(store.record_version(&version).unwrap());
397        assert!(!store.record_version(&version).unwrap());
398        fs::remove_dir_all(&root).unwrap();
399
400        let store = Storage::new(root.clone());
401        store.save_accounts(&[account()]).unwrap();
402        assert!(store.record_version(&version).unwrap());
403        fs::remove_dir_all(root).unwrap();
404    }
405
406    #[test]
407    fn updates_are_serialized_without_lost_writes() {
408        let root = test_root("serialized");
409        let store = Arc::new(Storage::new(root.clone()));
410        store.save_accounts(&[account()]).unwrap();
411        let threads: Vec<_> = (0..8)
412            .map(|_| {
413                let store = Arc::clone(&store);
414                thread::spawn(move || {
415                    store
416                        .update_accounts(|accounts| {
417                            accounts[0].play_count += 1;
418                            Ok(())
419                        })
420                        .unwrap();
421                })
422            })
423            .collect();
424        for thread in threads {
425            thread.join().unwrap();
426        }
427        assert_eq!(store.load_accounts().unwrap()[0].play_count, 8);
428        fs::remove_dir_all(root).unwrap();
429    }
430
431    #[test]
432    fn theme_round_trips_and_rejects_remote_css() {
433        let root = test_root("theme");
434        let store = Storage::new(root.clone());
435        assert_eq!(store.load_theme().unwrap(), "");
436        let css = ":root.dark { --primary: #336699; }";
437        store.save_theme(css).unwrap();
438        assert!(
439            store
440                .save_theme("@import 'https://example.com/a.css';")
441                .is_err()
442        );
443        assert_eq!(store.load_theme().unwrap(), css);
444        fs::remove_dir_all(root).unwrap();
445    }
446
447    #[test]
448    fn legacy_session_fields_are_removed_on_load() {
449        let root = test_root("legacy");
450        fs::create_dir_all(&root).unwrap();
451        let path = root.join("accounts.json");
452        fs::write(
453            &path,
454            r#"[{"id":1,"name":"builderman","display_name":"Builderman","avatar_url":null,"added_at":1.0,"cookie":"_|WARNING:-DO-NOT-SHARE","ROBLOSECURITY":"x","note":"kept"}]"#,
455        )
456        .unwrap();
457        let store = Storage::new(root.clone());
458        let accounts = store.load_accounts().unwrap();
459        assert_eq!(accounts[0].name, "builderman");
460        assert_eq!(accounts[0].extra.keys().collect::<Vec<_>>(), ["note"]);
461        let saved = fs::read_to_string(&path).unwrap();
462        assert!(!saved.contains("WARNING") && !saved.to_lowercase().contains("security"));
463        fs::remove_dir_all(root).unwrap();
464    }
465
466    #[test]
467    fn invalid_data_is_rejected_before_replacing_the_file() {
468        let root = test_root("validation");
469        let store = Storage::new(root.clone());
470        store.save_accounts(&[account()]).unwrap();
471        let mut invalid = account();
472        invalid.name.clear();
473        assert!(store.save_accounts(&[invalid]).is_err());
474        assert_eq!(store.load_accounts().unwrap()[0].name, "builderman");
475        fs::remove_dir_all(root).unwrap();
476    }
477}