Skip to main content

ftui_runtime/
state_persistence.rs

1//! Widget state persistence for save/restore across sessions.
2//!
3//! This module provides the [`StateRegistry`] and [`StorageBackend`] infrastructure
4//! for persisting widget state. It works with the `Stateful` trait from `ftui-widgets`.
5//!
6//! # Architecture
7//!
8//! ```text
9//! ┌──────────────────────────────────────────────────────────────┐
10//! │                      StateRegistry                            │
11//! │   - In-memory cache of widget states                          │
12//! │   - Delegates to StorageBackend for persistence               │
13//! │   - Provides load/save/clear operations                       │
14//! └──────────────────────────────────────────────────────────────┘
15//!                              │
16//!                              ▼
17//! ┌──────────────────────────────────────────────────────────────┐
18//! │                     StorageBackend                            │
19//! │   - MemoryStorage: in-memory (testing, ephemeral)             │
20//! │   - FileStorage: JSON file (requires state-persistence)       │
21//! └──────────────────────────────────────────────────────────────┘
22//! ```
23//!
24//! # Design Invariants
25//!
26//! 1. **Graceful degradation**: Storage failures never panic; operations return `Result`.
27//! 2. **Atomic writes**: File storage uses write-rename pattern to prevent corruption.
28//! 3. **Partial load tolerance**: Missing or corrupt entries use `Default::default()`.
29//! 4. **Type safety**: Registry is type-erased internally but type-safe at boundaries.
30//!
31//! # Failure Modes
32//!
33//! | Failure | Cause | Behavior |
34//! |---------|-------|----------|
35//! | `StorageError::Io` | File I/O failure | Returns error, cache unaffected |
36//! | `StorageError::Serialization` | JSON encode/decode | Entry skipped, logged |
37//! | `StorageError::Corruption` | Invalid file format | Load returns partial data |
38//! | Missing entry | First run, key changed | `Default::default()` used |
39//!
40//! # Feature Gates
41//!
42//! - `state-persistence`: Enables `FileStorage` with JSON serialization.
43//!   Without this feature, only `MemoryStorage` is available.
44//!
45//! `Stateful` lives in `ftui_widgets::stateful`.
46
47use std::collections::HashMap;
48use std::fmt;
49use std::sync::{Arc, Mutex, RwLock};
50
51// ─────────────────────────────────────────────────────────────────────────────
52// Error Types
53// ─────────────────────────────────────────────────────────────────────────────
54
55/// Errors that can occur during state storage operations.
56#[derive(Debug)]
57pub enum StorageError {
58    /// I/O error during file operations.
59    Io(std::io::Error),
60    /// Serialization or deserialization error.
61    #[cfg(feature = "state-persistence")]
62    Serialization(String),
63    /// Storage file is corrupted or invalid format.
64    Corruption(String),
65    /// Backend is not available (e.g., file storage without feature).
66    Unavailable(String),
67}
68
69impl fmt::Display for StorageError {
70    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71        match self {
72            StorageError::Io(e) => write!(f, "I/O error: {e}"),
73            #[cfg(feature = "state-persistence")]
74            StorageError::Serialization(msg) => write!(f, "serialization error: {msg}"),
75            StorageError::Corruption(msg) => write!(f, "storage corruption: {msg}"),
76            StorageError::Unavailable(msg) => write!(f, "storage unavailable: {msg}"),
77        }
78    }
79}
80
81impl std::error::Error for StorageError {
82    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
83        match self {
84            StorageError::Io(e) => Some(e),
85            #[cfg(feature = "state-persistence")]
86            StorageError::Serialization(_) => None,
87            StorageError::Corruption(_) => None,
88            StorageError::Unavailable(_) => None,
89        }
90    }
91}
92
93impl From<std::io::Error> for StorageError {
94    fn from(e: std::io::Error) -> Self {
95        StorageError::Io(e)
96    }
97}
98
99/// Result type for storage operations.
100pub type StorageResult<T> = Result<T, StorageError>;
101
102// ─────────────────────────────────────────────────────────────────────────────
103// Storage Backend Trait
104// ─────────────────────────────────────────────────────────────────────────────
105
106/// A serialized state entry with version metadata.
107///
108/// This is the storage format used by backends. The actual state data
109/// is serialized to bytes by the caller.
110#[derive(Clone, Debug, PartialEq, Eq)]
111pub struct StoredEntry {
112    /// The canonical state key (widget_type::instance_id).
113    pub key: String,
114    /// Schema version from `Stateful::state_version()`.
115    pub version: u32,
116    /// Serialized state data (JSON bytes with `state-persistence` feature).
117    pub data: Vec<u8>,
118}
119
120/// Trait for pluggable state storage backends.
121///
122/// Implementations must be thread-safe (`Send + Sync`) to support
123/// concurrent access from the registry.
124///
125/// # Implementation Notes
126///
127/// - `load_all` should be resilient to partial corruption.
128/// - `save_all` should be atomic (write-then-rename pattern for files).
129/// - `clear` should remove all stored state for the application.
130pub trait StorageBackend: Send + Sync {
131    /// Human-readable name for logging.
132    fn name(&self) -> &str;
133
134    /// Load all stored state entries.
135    ///
136    /// Returns an empty map if no state exists (first run).
137    /// Skips corrupted entries rather than failing entirely.
138    fn load_all(&self) -> StorageResult<HashMap<String, StoredEntry>>;
139
140    /// Save all state entries atomically.
141    ///
142    /// This should replace all existing state (not merge).
143    fn save_all(&self, entries: &HashMap<String, StoredEntry>) -> StorageResult<()>;
144
145    /// Clear all stored state.
146    fn clear(&self) -> StorageResult<()>;
147
148    /// Check if the backend is available and functional.
149    fn is_available(&self) -> bool {
150        true
151    }
152}
153
154// ─────────────────────────────────────────────────────────────────────────────
155// Memory Storage (always available)
156// ─────────────────────────────────────────────────────────────────────────────
157
158/// In-memory storage backend for testing and ephemeral state.
159///
160/// State is lost when the process exits. Useful for:
161/// - Unit testing widget persistence logic
162/// - Applications that don't need cross-session persistence
163/// - Development/debugging without file I/O
164#[derive(Default)]
165pub struct MemoryStorage {
166    data: RwLock<HashMap<String, StoredEntry>>,
167}
168
169impl MemoryStorage {
170    /// Create a new empty memory storage.
171    #[must_use]
172    pub fn new() -> Self {
173        Self::default()
174    }
175
176    /// Create memory storage pre-populated with entries.
177    #[must_use]
178    pub fn with_entries(entries: HashMap<String, StoredEntry>) -> Self {
179        Self {
180            data: RwLock::new(entries),
181        }
182    }
183}
184
185impl StorageBackend for MemoryStorage {
186    fn name(&self) -> &str {
187        "MemoryStorage"
188    }
189
190    fn load_all(&self) -> StorageResult<HashMap<String, StoredEntry>> {
191        let guard = self
192            .data
193            .read()
194            .map_err(|_| StorageError::Corruption("lock poisoned".into()))?;
195        Ok(guard.clone())
196    }
197
198    fn save_all(&self, entries: &HashMap<String, StoredEntry>) -> StorageResult<()> {
199        let mut guard = self
200            .data
201            .write()
202            .map_err(|_| StorageError::Corruption("lock poisoned".into()))?;
203        *guard = entries.clone();
204        Ok(())
205    }
206
207    fn clear(&self) -> StorageResult<()> {
208        let mut guard = self
209            .data
210            .write()
211            .map_err(|_| StorageError::Corruption("lock poisoned".into()))?;
212        guard.clear();
213        Ok(())
214    }
215}
216
217impl fmt::Debug for MemoryStorage {
218    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219        let count = self.data.read().map(|g| g.len()).unwrap_or(0);
220        f.debug_struct("MemoryStorage")
221            .field("entries", &count)
222            .finish()
223    }
224}
225
226// ─────────────────────────────────────────────────────────────────────────────
227// File Storage (requires state-persistence feature)
228// ─────────────────────────────────────────────────────────────────────────────
229
230#[cfg(feature = "state-persistence")]
231mod file_storage {
232    use super::*;
233    use serde::{Deserialize, Serialize};
234    use std::ffi::OsString;
235    use std::fs::{self, File};
236    use std::io::{BufReader, BufWriter, Write};
237    use std::path::{Path, PathBuf};
238    use std::sync::atomic::{AtomicU64, Ordering};
239
240    /// File format for stored state (JSON).
241    #[derive(Serialize, Deserialize)]
242    struct StateFile {
243        /// Format version for future migrations.
244        format_version: u32,
245        /// Map of canonical key -> entry.
246        entries: HashMap<String, FileEntry>,
247    }
248
249    /// Serialized entry in the state file.
250    #[derive(Serialize, Deserialize)]
251    struct FileEntry {
252        version: u32,
253        /// Base64-encoded data for binary safety.
254        data_base64: String,
255    }
256
257    impl StateFile {
258        const FORMAT_VERSION: u32 = 1;
259
260        fn new() -> Self {
261            Self {
262                format_version: Self::FORMAT_VERSION,
263                entries: HashMap::new(),
264            }
265        }
266    }
267
268    /// File-based storage backend using JSON.
269    ///
270    /// State is persisted to a JSON file with atomic write-rename pattern.
271    /// Suitable for applications that need cross-session persistence.
272    ///
273    /// # File Format
274    ///
275    /// ```json
276    /// {
277    ///   "format_version": 1,
278    ///   "entries": {
279    ///     "ScrollView::main": {
280    ///       "version": 1,
281    ///       "data_base64": "eyJzY3JvbGxfb2Zmc2V0IjogNDJ9"
282    ///     }
283    ///   }
284    /// }
285    /// ```
286    ///
287    /// # Atomic Writes
288    ///
289    /// Writes use a temporary file + rename pattern to prevent corruption:
290    /// 1. Write to `{path}.{pid}.{n}.tmp`, a name no other save is using
291    /// 2. Flush and sync
292    /// 3. Rename it to `{path}`
293    ///
294    /// Concurrent saves, from threads or from other processes, each rename a
295    /// complete file, so readers see one save or another and the last rename
296    /// wins. A save that fails removes its temporary file.
297    pub struct FileStorage {
298        path: PathBuf,
299    }
300
301    impl FileStorage {
302        /// Create a file storage at the given path.
303        ///
304        /// The file does not need to exist; it will be created on first save.
305        #[must_use]
306        pub fn new(path: impl AsRef<Path>) -> Self {
307            Self {
308                path: path.as_ref().to_path_buf(),
309            }
310        }
311
312        /// Create storage at the default location for the application.
313        ///
314        /// Uses `$XDG_STATE_HOME/ftui/{app_name}/state.json` on Linux,
315        /// or platform-appropriate equivalents.
316        #[must_use]
317        pub fn default_for_app(app_name: &str) -> Self {
318            let base = dirs_or_fallback();
319            let path = base.join("ftui").join(app_name).join("state.json");
320            Self { path }
321        }
322
323        /// A temporary file beside the state file, unique to this save.
324        ///
325        /// Every save of a path used to share `state.json.tmp`. Two at once
326        /// truncated each other's file, so one rename moved a file the other
327        /// was still rewriting (readers found it empty or cut short) and the
328        /// other rename failed with `NotFound`. The process id separates
329        /// processes and the counter separates saves within one.
330        fn temp_path(&self) -> PathBuf {
331            static NEXT_SAVE: AtomicU64 = AtomicU64::new(0);
332            let mut name = self
333                .path
334                .file_name()
335                .map_or_else(|| OsString::from("state"), OsString::from);
336            name.push(format!(
337                ".{}.{}.tmp",
338                std::process::id(),
339                NEXT_SAVE.fetch_add(1, Ordering::Relaxed)
340            ));
341            self.path.with_file_name(name)
342        }
343    }
344
345    /// Get state directory, falling back to current dir if unavailable.
346    fn dirs_or_fallback() -> PathBuf {
347        // Try XDG_STATE_HOME first
348        if let Ok(state_home) = std::env::var("XDG_STATE_HOME") {
349            return PathBuf::from(state_home);
350        }
351        // Fall back to ~/.local/state
352        if let Ok(home) = std::env::var("HOME") {
353            return PathBuf::from(home).join(".local").join("state");
354        }
355        // Last resort: current directory
356        PathBuf::from(".")
357    }
358
359    impl StorageBackend for FileStorage {
360        fn name(&self) -> &str {
361            "FileStorage"
362        }
363
364        fn load_all(&self) -> StorageResult<HashMap<String, StoredEntry>> {
365            if !self.path.exists() {
366                // First run - no state yet
367                return Ok(HashMap::new());
368            }
369
370            let file = File::open(&self.path)?;
371            let reader = BufReader::new(file);
372
373            let state_file: StateFile = serde_json::from_reader(reader).map_err(|e| {
374                StorageError::Serialization(format!("failed to parse state file: {e}"))
375            })?;
376
377            // Validate format version
378            if state_file.format_version != StateFile::FORMAT_VERSION {
379                tracing::warn!(
380                    stored = state_file.format_version,
381                    expected = StateFile::FORMAT_VERSION,
382                    "state file format version mismatch, ignoring stored state"
383                );
384                return Ok(HashMap::new());
385            }
386
387            // Convert file entries to StoredEntry
388            let mut result = HashMap::new();
389            for (key, entry) in state_file.entries {
390                use base64::Engine;
391                let data = match base64::engine::general_purpose::STANDARD
392                    .decode(&entry.data_base64)
393                {
394                    Ok(d) => d,
395                    Err(e) => {
396                        tracing::warn!(key = %key, error = %e, "failed to decode state entry, skipping");
397                        continue;
398                    }
399                };
400                result.insert(
401                    key.clone(),
402                    StoredEntry {
403                        key,
404                        version: entry.version,
405                        data,
406                    },
407                );
408            }
409
410            Ok(result)
411        }
412
413        fn save_all(&self, entries: &HashMap<String, StoredEntry>) -> StorageResult<()> {
414            use base64::Engine;
415
416            // Ensure parent directory exists
417            if let Some(parent) = self.path.parent() {
418                fs::create_dir_all(parent)?;
419            }
420
421            // Build file content
422            let mut state_file = StateFile::new();
423            for (key, entry) in entries {
424                state_file.entries.insert(
425                    key.clone(),
426                    FileEntry {
427                        version: entry.version,
428                        data_base64: base64::engine::general_purpose::STANDARD.encode(&entry.data),
429                    },
430                );
431            }
432
433            // Write to temp file first, then rename it into place (atomic pattern)
434            let tmp_path = self.temp_path();
435            let saved = (|| -> StorageResult<()> {
436                let file = File::create(&tmp_path)?;
437                let mut writer = BufWriter::new(file);
438                serde_json::to_writer_pretty(&mut writer, &state_file).map_err(|e| {
439                    StorageError::Serialization(format!("failed to serialize state: {e}"))
440                })?;
441                writer.flush()?;
442                writer.get_ref().sync_all()?;
443                fs::rename(&tmp_path, &self.path)?;
444                Ok(())
445            })();
446            if saved.is_err() {
447                // Each save names its own file, so nothing else would reuse
448                // and overwrite this one: remove it rather than strand it.
449                let _ = fs::remove_file(&tmp_path);
450            }
451            saved?;
452
453            tracing::debug!(
454                path = %self.path.display(),
455                entries = entries.len(),
456                "saved widget state"
457            );
458
459            Ok(())
460        }
461
462        fn clear(&self) -> StorageResult<()> {
463            if self.path.exists() {
464                fs::remove_file(&self.path)?;
465            }
466            Ok(())
467        }
468
469        fn is_available(&self) -> bool {
470            // Check if we can write to the directory
471            if let Some(parent) = self.path.parent() {
472                if !parent.exists() {
473                    return std::fs::create_dir_all(parent).is_ok();
474                }
475                // Check write permission (try to create temp file)
476                let test_path = parent.join(".ftui_test_write");
477                if std::fs::write(&test_path, b"test").is_ok() {
478                    let _ = std::fs::remove_file(&test_path);
479                    return true;
480                }
481            }
482            false
483        }
484    }
485
486    impl fmt::Debug for FileStorage {
487        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
488            f.debug_struct("FileStorage")
489                .field("path", &self.path)
490                .finish()
491        }
492    }
493}
494
495#[cfg(feature = "state-persistence")]
496pub use file_storage::FileStorage;
497
498// ─────────────────────────────────────────────────────────────────────────────
499// State Registry
500// ─────────────────────────────────────────────────────────────────────────────
501
502/// Central registry for widget state persistence.
503///
504/// The registry maintains an in-memory cache of widget states and delegates
505/// to a [`StorageBackend`] for persistence. It provides the main API for
506/// save/restore operations.
507///
508/// # Thread Safety
509///
510/// The registry is `Send + Sync` and uses internal locking for thread-safe access.
511///
512/// # Example
513///
514/// ```ignore
515/// use ftui_runtime::state_persistence::{StateRegistry, MemoryStorage};
516///
517/// // Create registry with memory storage
518/// let registry = StateRegistry::new(Box::new(MemoryStorage::new()));
519///
520/// // Load state for a widget
521/// if let Some(entry) = registry.get("ScrollView::main") {
522///     // Deserialize and restore...
523/// }
524///
525/// // Save state
526/// registry.set("ScrollView::main", 1, serialized_data);
527/// registry.flush()?;
528/// ```
529pub struct StateRegistry {
530    backend: Box<dyn StorageBackend>,
531    cache: RwLock<HashMap<String, StoredEntry>>,
532    dirty: RwLock<bool>,
533    /// Held across a whole flush. Two unserialized flushes could save their
534    /// snapshots in either order, leaving the older one in storage.
535    flush_lock: Mutex<()>,
536}
537
538impl StateRegistry {
539    /// Create a new registry with the given storage backend.
540    ///
541    /// Does not automatically load from storage; call [`load`](Self::load) first.
542    #[must_use]
543    pub fn new(backend: Box<dyn StorageBackend>) -> Self {
544        Self {
545            backend,
546            cache: RwLock::new(HashMap::new()),
547            dirty: RwLock::new(false),
548            flush_lock: Mutex::new(()),
549        }
550    }
551
552    /// Create a registry with memory storage (ephemeral, for testing).
553    #[must_use]
554    pub fn in_memory() -> Self {
555        Self::new(Box::new(MemoryStorage::new()))
556    }
557
558    /// Create a registry with file storage at the given path.
559    #[cfg(feature = "state-persistence")]
560    #[must_use]
561    pub fn with_file(path: impl AsRef<std::path::Path>) -> Self {
562        Self::new(Box::new(FileStorage::new(path)))
563    }
564
565    /// Load all state from the storage backend.
566    ///
567    /// This replaces the in-memory cache with stored data.
568    /// Safe to call multiple times; later calls refresh the cache.
569    pub fn load(&self) -> StorageResult<usize> {
570        let entries = self.backend.load_all()?;
571        let count = entries.len();
572
573        let mut cache = self
574            .cache
575            .write()
576            .map_err(|_| StorageError::Corruption("cache lock poisoned".into()))?;
577        *cache = entries;
578
579        let mut dirty = self
580            .dirty
581            .write()
582            .map_err(|_| StorageError::Corruption("dirty lock poisoned".into()))?;
583        *dirty = false;
584
585        tracing::debug!(backend = %self.backend.name(), count, "loaded widget state");
586        Ok(count)
587    }
588
589    /// Flush dirty state to the storage backend.
590    ///
591    /// Only writes if changes have been made since last flush.
592    /// Returns `Ok(true)` if data was written, `Ok(false)` if no changes.
593    pub fn flush(&self) -> StorageResult<bool> {
594        let _flushing = self
595            .flush_lock
596            .lock()
597            .map_err(|_| StorageError::Corruption("flush lock poisoned".into()))?;
598        let dirty = {
599            let guard = self
600                .dirty
601                .read()
602                .map_err(|_| StorageError::Corruption("dirty lock poisoned".into()))?;
603            *guard
604        };
605
606        if !dirty {
607            return Ok(false);
608        }
609
610        let cache_snapshot = {
611            let cache_guard = self
612                .cache
613                .read()
614                .map_err(|_| StorageError::Corruption("cache lock poisoned".into()))?;
615            cache_guard.clone()
616        };
617
618        self.backend.save_all(&cache_snapshot)?;
619
620        let cache_guard = self
621            .cache
622            .read()
623            .map_err(|_| StorageError::Corruption("cache lock poisoned".into()))?;
624        let mut dirty_guard = self
625            .dirty
626            .write()
627            .map_err(|_| StorageError::Corruption("dirty lock poisoned".into()))?;
628        *dirty_guard = *cache_guard != cache_snapshot;
629
630        Ok(true)
631    }
632
633    /// Get a stored state entry by canonical key.
634    ///
635    /// Returns `None` if no state exists for the key.
636    #[must_use]
637    pub fn get(&self, key: &str) -> Option<StoredEntry> {
638        let cache = self.cache.read().ok()?;
639        cache.get(key).cloned()
640    }
641
642    /// Set a state entry.
643    ///
644    /// Marks the registry as dirty; call [`flush`](Self::flush) to persist.
645    pub fn set(&self, key: impl Into<String>, version: u32, data: Vec<u8>) {
646        let key = key.into();
647        if let Ok(mut cache) = self.cache.write() {
648            cache.insert(key.clone(), StoredEntry { key, version, data });
649            if let Ok(mut dirty) = self.dirty.write() {
650                *dirty = true;
651            }
652        }
653    }
654
655    /// Remove a state entry.
656    ///
657    /// Returns the removed entry if it existed.
658    pub fn remove(&self, key: &str) -> Option<StoredEntry> {
659        let result = self.cache.write().ok()?.remove(key);
660        if result.is_some()
661            && let Ok(mut dirty) = self.dirty.write()
662        {
663            *dirty = true;
664        }
665        result
666    }
667
668    /// Clear all state from both cache and storage.
669    pub fn clear(&self) -> StorageResult<()> {
670        self.backend.clear()?;
671        if let Ok(mut cache) = self.cache.write() {
672            cache.clear();
673        }
674        if let Ok(mut dirty) = self.dirty.write() {
675            *dirty = false;
676        }
677        Ok(())
678    }
679
680    /// Get the number of cached entries.
681    #[must_use]
682    pub fn len(&self) -> usize {
683        self.cache.read().map(|c| c.len()).unwrap_or(0)
684    }
685
686    /// Check if the cache is empty.
687    #[must_use]
688    pub fn is_empty(&self) -> bool {
689        self.len() == 0
690    }
691
692    /// Check if there are unsaved changes.
693    #[must_use]
694    pub fn is_dirty(&self) -> bool {
695        self.dirty.read().map(|d| *d).unwrap_or(false)
696    }
697
698    /// Get the backend name for logging.
699    #[must_use]
700    pub fn backend_name(&self) -> &str {
701        self.backend.name()
702    }
703
704    /// Check if the storage backend is available.
705    #[must_use]
706    pub fn is_available(&self) -> bool {
707        self.backend.is_available()
708    }
709
710    /// Get all cached keys.
711    #[must_use]
712    pub fn keys(&self) -> Vec<String> {
713        self.cache
714            .read()
715            .map(|c| c.keys().cloned().collect())
716            .unwrap_or_default()
717    }
718}
719
720impl fmt::Debug for StateRegistry {
721    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
722        f.debug_struct("StateRegistry")
723            .field("backend", &self.backend.name())
724            .field("entries", &self.len())
725            .field("dirty", &self.is_dirty())
726            .finish()
727    }
728}
729
730// Make it Arc-able for shared ownership
731impl StateRegistry {
732    /// Wrap in Arc for shared ownership.
733    #[must_use]
734    pub fn shared(self) -> Arc<Self> {
735        Arc::new(self)
736    }
737}
738
739// ─────────────────────────────────────────────────────────────────────────────
740// Statistics and Diagnostics
741// ─────────────────────────────────────────────────────────────────────────────
742
743/// Statistics about the state registry.
744#[derive(Clone, Debug, Default)]
745pub struct RegistryStats {
746    /// Number of entries in cache.
747    pub entry_count: usize,
748    /// Total bytes of state data.
749    pub total_bytes: usize,
750    /// Whether there are unsaved changes.
751    pub dirty: bool,
752    /// Backend name.
753    pub backend: String,
754}
755
756impl StateRegistry {
757    /// Get statistics about the registry.
758    #[must_use]
759    pub fn stats(&self) -> RegistryStats {
760        let (entry_count, total_bytes) = self
761            .cache
762            .read()
763            .map(|c| {
764                let count = c.len();
765                let bytes: usize = c.values().map(|e| e.data.len()).sum();
766                (count, bytes)
767            })
768            .unwrap_or((0, 0));
769
770        RegistryStats {
771            entry_count,
772            total_bytes,
773            dirty: self.is_dirty(),
774            backend: self.backend.name().to_string(),
775        }
776    }
777}
778
779// ─────────────────────────────────────────────────────────────────────────────
780// Tests
781// ─────────────────────────────────────────────────────────────────────────────
782
783#[cfg(test)]
784mod tests {
785    use super::*;
786    use std::sync::atomic::{AtomicBool, Ordering};
787    use std::sync::{Mutex, Weak};
788    use std::thread;
789    use web_time::Duration;
790
791    #[derive(Default)]
792    struct ReentrantFlushBackendState {
793        registry: Mutex<Option<Weak<StateRegistry>>>,
794        injected_during_save: AtomicBool,
795        saved_entries: RwLock<HashMap<String, StoredEntry>>,
796    }
797
798    impl ReentrantFlushBackendState {
799        fn bind_registry(&self, registry: &Arc<StateRegistry>) {
800            *self.registry.lock().unwrap_or_else(|e| e.into_inner()) =
801                Some(Arc::downgrade(registry));
802        }
803
804        fn saved_entries(&self) -> HashMap<String, StoredEntry> {
805            self.saved_entries
806                .read()
807                .unwrap_or_else(|e| e.into_inner())
808                .clone()
809        }
810    }
811
812    #[derive(Clone)]
813    struct ReentrantFlushBackend {
814        state: Arc<ReentrantFlushBackendState>,
815    }
816
817    impl StorageBackend for ReentrantFlushBackend {
818        fn name(&self) -> &str {
819            "ReentrantFlushBackend"
820        }
821
822        fn load_all(&self) -> StorageResult<HashMap<String, StoredEntry>> {
823            Ok(self.state.saved_entries())
824        }
825
826        fn save_all(&self, entries: &HashMap<String, StoredEntry>) -> StorageResult<()> {
827            *self
828                .state
829                .saved_entries
830                .write()
831                .map_err(|_| StorageError::Corruption("saved entries lock poisoned".into()))? =
832                entries.clone();
833
834            if !self.state.injected_during_save.swap(true, Ordering::SeqCst)
835                && let Some(registry) = self
836                    .state
837                    .registry
838                    .lock()
839                    .unwrap_or_else(|e| e.into_inner())
840                    .as_ref()
841                    .and_then(Weak::upgrade)
842            {
843                registry.set("backend::late", 2, b"late".to_vec());
844            }
845
846            Ok(())
847        }
848
849        fn clear(&self) -> StorageResult<()> {
850            self.state
851                .saved_entries
852                .write()
853                .map_err(|_| StorageError::Corruption("saved entries lock poisoned".into()))?
854                .clear();
855            Ok(())
856        }
857    }
858
859    #[test]
860    fn memory_storage_basic_operations() {
861        let storage = MemoryStorage::new();
862
863        // Initially empty
864        let entries = storage.load_all().unwrap();
865        assert!(entries.is_empty());
866
867        // Save some entries
868        let mut data = HashMap::new();
869        data.insert(
870            "key1".to_string(),
871            StoredEntry {
872                key: "key1".to_string(),
873                version: 1,
874                data: b"hello".to_vec(),
875            },
876        );
877        storage.save_all(&data).unwrap();
878
879        // Load back
880        let loaded = storage.load_all().unwrap();
881        assert_eq!(loaded.len(), 1);
882        assert_eq!(loaded["key1"].data, b"hello");
883
884        // Clear
885        storage.clear().unwrap();
886        assert!(storage.load_all().unwrap().is_empty());
887    }
888
889    #[test]
890    fn memory_storage_with_entries() {
891        let mut entries = HashMap::new();
892        entries.insert(
893            "test".to_string(),
894            StoredEntry {
895                key: "test".to_string(),
896                version: 2,
897                data: vec![1, 2, 3],
898            },
899        );
900        let storage = MemoryStorage::with_entries(entries);
901
902        let loaded = storage.load_all().unwrap();
903        assert_eq!(loaded.len(), 1);
904        assert_eq!(loaded["test"].version, 2);
905    }
906
907    #[test]
908    fn registry_basic_operations() {
909        let registry = StateRegistry::in_memory();
910
911        // Initially empty
912        assert!(registry.is_empty());
913        assert!(!registry.is_dirty());
914
915        // Set an entry
916        registry.set("widget::1", 1, b"data".to_vec());
917        assert_eq!(registry.len(), 1);
918        assert!(registry.is_dirty());
919
920        // Get the entry
921        let entry = registry.get("widget::1").unwrap();
922        assert_eq!(entry.version, 1);
923        assert_eq!(entry.data, b"data");
924
925        // Get non-existent
926        assert!(registry.get("widget::99").is_none());
927
928        // Flush
929        assert!(registry.flush().unwrap());
930        assert!(!registry.is_dirty());
931
932        // No-op flush when clean
933        assert!(!registry.flush().unwrap());
934
935        // Remove
936        let removed = registry.remove("widget::1").unwrap();
937        assert_eq!(removed.data, b"data");
938        assert!(registry.is_empty());
939        assert!(registry.is_dirty());
940    }
941
942    #[test]
943    fn registry_load_and_flush() {
944        let storage = MemoryStorage::new();
945        let mut initial = HashMap::new();
946        initial.insert(
947            "pre::existing".to_string(),
948            StoredEntry {
949                key: "pre::existing".to_string(),
950                version: 5,
951                data: b"old".to_vec(),
952            },
953        );
954        storage.save_all(&initial).unwrap();
955
956        let registry = StateRegistry::new(Box::new(storage));
957
958        // Load existing data
959        let count = registry.load().unwrap();
960        assert_eq!(count, 1);
961        assert!(!registry.is_dirty());
962
963        let entry = registry.get("pre::existing").unwrap();
964        assert_eq!(entry.version, 5);
965    }
966
967    #[test]
968    fn registry_clear() {
969        let registry = StateRegistry::in_memory();
970        registry.set("a", 1, vec![]);
971        registry.set("b", 1, vec![]);
972        assert_eq!(registry.len(), 2);
973
974        registry.clear().unwrap();
975        assert!(registry.is_empty());
976        assert!(!registry.is_dirty());
977    }
978
979    #[test]
980    fn registry_keys() {
981        let registry = StateRegistry::in_memory();
982        registry.set("widget::a", 1, vec![]);
983        registry.set("widget::b", 1, vec![]);
984
985        let mut keys = registry.keys();
986        keys.sort();
987        assert_eq!(keys, vec!["widget::a", "widget::b"]);
988    }
989
990    #[test]
991    fn registry_stats() {
992        let registry = StateRegistry::in_memory();
993        registry.set("x", 1, vec![1, 2, 3, 4, 5]);
994        registry.set("y", 1, vec![6, 7, 8]);
995
996        let stats = registry.stats();
997        assert_eq!(stats.entry_count, 2);
998        assert_eq!(stats.total_bytes, 8);
999        assert!(stats.dirty);
1000        assert_eq!(stats.backend, "MemoryStorage");
1001    }
1002
1003    #[test]
1004    fn registry_shared() {
1005        let registry = StateRegistry::in_memory().shared();
1006        registry.set("test", 1, vec![42]);
1007
1008        let registry2 = Arc::clone(&registry);
1009        assert_eq!(registry2.get("test").unwrap().data, vec![42]);
1010    }
1011
1012    #[test]
1013    fn storage_error_display() {
1014        let io_err = StorageError::Io(std::io::Error::new(std::io::ErrorKind::NotFound, "missing"));
1015        assert!(io_err.to_string().contains("I/O error"));
1016
1017        let corrupt = StorageError::Corruption("bad data".into());
1018        assert!(corrupt.to_string().contains("corruption"));
1019
1020        let unavail = StorageError::Unavailable("no backend".into());
1021        assert!(unavail.to_string().contains("unavailable"));
1022    }
1023
1024    // ── StorageError ────────────────────────────────────────────────────
1025
1026    #[test]
1027    fn storage_error_source_io() {
1028        let err = StorageError::Io(std::io::Error::new(
1029            std::io::ErrorKind::BrokenPipe,
1030            "broken",
1031        ));
1032        let source = std::error::Error::source(&err);
1033        assert!(source.is_some());
1034    }
1035
1036    #[test]
1037    fn storage_error_source_corruption_none() {
1038        let err = StorageError::Corruption("test".into());
1039        assert!(std::error::Error::source(&err).is_none());
1040    }
1041
1042    #[test]
1043    fn storage_error_source_unavailable_none() {
1044        let err = StorageError::Unavailable("test".into());
1045        assert!(std::error::Error::source(&err).is_none());
1046    }
1047
1048    #[test]
1049    fn storage_error_from_io_error() {
1050        let io_err = std::io::Error::new(std::io::ErrorKind::TimedOut, "timeout");
1051        let err: StorageError = io_err.into();
1052        match err {
1053            StorageError::Io(e) => assert_eq!(e.kind(), std::io::ErrorKind::TimedOut),
1054            _ => panic!("expected Io variant"),
1055        }
1056    }
1057
1058    #[test]
1059    fn storage_error_debug_format() {
1060        let err = StorageError::Corruption("test".into());
1061        let dbg = format!("{:?}", err);
1062        assert!(dbg.contains("Corruption"));
1063    }
1064
1065    // ── MemoryStorage ───────────────────────────────────────────────────
1066
1067    #[test]
1068    fn memory_storage_name() {
1069        let storage = MemoryStorage::new();
1070        assert_eq!(storage.name(), "MemoryStorage");
1071    }
1072
1073    #[test]
1074    fn memory_storage_is_available() {
1075        let storage = MemoryStorage::new();
1076        assert!(storage.is_available());
1077    }
1078
1079    #[test]
1080    fn memory_storage_debug_format() {
1081        let storage = MemoryStorage::new();
1082        let dbg = format!("{:?}", storage);
1083        assert!(dbg.contains("MemoryStorage"));
1084        assert!(dbg.contains("entries"));
1085    }
1086
1087    #[test]
1088    fn memory_storage_debug_shows_count() {
1089        let mut entries = HashMap::new();
1090        entries.insert(
1091            "a".to_string(),
1092            StoredEntry {
1093                key: "a".to_string(),
1094                version: 1,
1095                data: vec![],
1096            },
1097        );
1098        let storage = MemoryStorage::with_entries(entries);
1099        let dbg = format!("{:?}", storage);
1100        assert!(dbg.contains("1"));
1101    }
1102
1103    #[test]
1104    fn memory_storage_save_replaces_all() {
1105        let storage = MemoryStorage::new();
1106
1107        let mut data1 = HashMap::new();
1108        data1.insert(
1109            "old".to_string(),
1110            StoredEntry {
1111                key: "old".to_string(),
1112                version: 1,
1113                data: vec![],
1114            },
1115        );
1116        storage.save_all(&data1).unwrap();
1117
1118        let mut data2 = HashMap::new();
1119        data2.insert(
1120            "new".to_string(),
1121            StoredEntry {
1122                key: "new".to_string(),
1123                version: 2,
1124                data: vec![],
1125            },
1126        );
1127        storage.save_all(&data2).unwrap();
1128
1129        let loaded = storage.load_all().unwrap();
1130        assert_eq!(loaded.len(), 1);
1131        assert!(loaded.contains_key("new"));
1132        assert!(!loaded.contains_key("old"));
1133    }
1134
1135    // ── StateRegistry ───────────────────────────────────────────────────
1136
1137    #[test]
1138    fn registry_backend_name() {
1139        let registry = StateRegistry::in_memory();
1140        assert_eq!(registry.backend_name(), "MemoryStorage");
1141    }
1142
1143    #[test]
1144    fn registry_is_available() {
1145        let registry = StateRegistry::in_memory();
1146        assert!(registry.is_available());
1147    }
1148
1149    #[test]
1150    fn registry_debug_format() {
1151        let registry = StateRegistry::in_memory();
1152        registry.set("x", 1, vec![]);
1153        let dbg = format!("{:?}", registry);
1154        assert!(dbg.contains("StateRegistry"));
1155        assert!(dbg.contains("MemoryStorage"));
1156        assert!(dbg.contains("dirty"));
1157    }
1158
1159    #[test]
1160    fn registry_set_overwrites() {
1161        let registry = StateRegistry::in_memory();
1162        registry.set("k", 1, b"first".to_vec());
1163        registry.set("k", 2, b"second".to_vec());
1164
1165        assert_eq!(registry.len(), 1);
1166        let entry = registry.get("k").unwrap();
1167        assert_eq!(entry.version, 2);
1168        assert_eq!(entry.data, b"second");
1169    }
1170
1171    #[test]
1172    fn registry_remove_nonexistent_returns_none() {
1173        let registry = StateRegistry::in_memory();
1174        assert!(registry.remove("nonexistent").is_none());
1175    }
1176
1177    #[test]
1178    fn registry_load_replaces_cache() {
1179        let storage = MemoryStorage::new();
1180        let mut initial = HashMap::new();
1181        initial.insert(
1182            "backend_key".to_string(),
1183            StoredEntry {
1184                key: "backend_key".to_string(),
1185                version: 1,
1186                data: b"from_backend".to_vec(),
1187            },
1188        );
1189        storage.save_all(&initial).unwrap();
1190
1191        let registry = StateRegistry::new(Box::new(storage));
1192        registry.set("local_key", 1, b"local".to_vec());
1193        assert!(registry.get("local_key").is_some());
1194
1195        // Load replaces entire cache
1196        registry.load().unwrap();
1197        assert!(registry.get("local_key").is_none());
1198        assert!(registry.get("backend_key").is_some());
1199    }
1200
1201    #[test]
1202    fn registry_load_clears_dirty_flag() {
1203        let registry = StateRegistry::in_memory();
1204        registry.set("x", 1, vec![]);
1205        assert!(registry.is_dirty());
1206
1207        registry.load().unwrap();
1208        assert!(!registry.is_dirty());
1209    }
1210
1211    #[test]
1212    fn registry_flush_persists_to_backend() {
1213        let registry = StateRegistry::in_memory();
1214        registry.set("widget::foo", 3, b"bar".to_vec());
1215        registry.flush().unwrap();
1216
1217        // Load fresh and verify data survived
1218        let count = registry.load().unwrap();
1219        assert_eq!(count, 1);
1220        let entry = registry.get("widget::foo").unwrap();
1221        assert_eq!(entry.version, 3);
1222        assert_eq!(entry.data, b"bar");
1223    }
1224
1225    #[test]
1226    fn registry_flush_drops_cache_lock_before_backend_save() {
1227        let backend_state = Arc::new(ReentrantFlushBackendState::default());
1228        let registry = Arc::new(StateRegistry::new(Box::new(ReentrantFlushBackend {
1229            state: Arc::clone(&backend_state),
1230        })));
1231        backend_state.bind_registry(&registry);
1232
1233        registry.set("widget::foo", 1, b"bar".to_vec());
1234
1235        let (done_tx, done_rx) = std::sync::mpsc::channel();
1236        let registry_for_thread = Arc::clone(&registry);
1237        let handle = thread::spawn(move || {
1238            let result = registry_for_thread.flush();
1239            done_tx.send(result).expect("flush result");
1240        });
1241
1242        done_rx
1243            .recv_timeout(Duration::from_secs(1))
1244            .expect("flush should complete without deadlocking")
1245            .expect("flush succeeds");
1246        handle.join().expect("flush thread");
1247
1248        let saved_entries = backend_state.saved_entries();
1249        assert!(saved_entries.contains_key("widget::foo"));
1250    }
1251
1252    #[test]
1253    fn registry_flush_preserves_dirty_when_backend_mutates_registry() {
1254        let backend_state = Arc::new(ReentrantFlushBackendState::default());
1255        let registry = Arc::new(StateRegistry::new(Box::new(ReentrantFlushBackend {
1256            state: Arc::clone(&backend_state),
1257        })));
1258        backend_state.bind_registry(&registry);
1259
1260        registry.set("widget::foo", 1, b"bar".to_vec());
1261        assert!(registry.flush().unwrap());
1262
1263        let first_saved = backend_state.saved_entries();
1264        assert!(first_saved.contains_key("widget::foo"));
1265        assert!(!first_saved.contains_key("backend::late"));
1266        assert!(registry.is_dirty());
1267        assert_eq!(registry.get("backend::late").unwrap().data, b"late");
1268
1269        assert!(registry.flush().unwrap());
1270
1271        let second_saved = backend_state.saved_entries();
1272        assert!(second_saved.contains_key("backend::late"));
1273        assert!(!registry.is_dirty());
1274    }
1275
1276    /// Counts how many `save_all` calls are in progress at once.
1277    struct OverlapBackend {
1278        in_flight: Arc<(
1279            std::sync::atomic::AtomicUsize,
1280            std::sync::atomic::AtomicUsize,
1281        )>,
1282    }
1283
1284    impl StorageBackend for OverlapBackend {
1285        fn name(&self) -> &str {
1286            "OverlapBackend"
1287        }
1288
1289        fn load_all(&self) -> StorageResult<HashMap<String, StoredEntry>> {
1290            Ok(HashMap::new())
1291        }
1292
1293        fn save_all(&self, _entries: &HashMap<String, StoredEntry>) -> StorageResult<()> {
1294            use std::sync::atomic::Ordering::SeqCst;
1295            let (current, peak) = &*self.in_flight;
1296            peak.fetch_max(current.fetch_add(1, SeqCst) + 1, SeqCst);
1297            thread::sleep(Duration::from_millis(5));
1298            current.fetch_sub(1, SeqCst);
1299            Ok(())
1300        }
1301
1302        fn clear(&self) -> StorageResult<()> {
1303            Ok(())
1304        }
1305    }
1306
1307    #[test]
1308    fn concurrent_flushes_save_one_at_a_time() {
1309        // Overlapping flushes could finish in either order, so an older
1310        // snapshot could land in storage after a newer one.
1311        let in_flight = Arc::new(Default::default());
1312        let registry = Arc::new(StateRegistry::new(Box::new(OverlapBackend {
1313            in_flight: Arc::clone(&in_flight),
1314        })));
1315        let start = Arc::new(std::sync::Barrier::new(4));
1316        let flushers: Vec<_> = (0..4)
1317            .map(|thread_index| {
1318                let (registry, start) = (Arc::clone(&registry), Arc::clone(&start));
1319                thread::spawn(move || {
1320                    start.wait();
1321                    for round in 0..10_u8 {
1322                        registry.set(format!("widget::{thread_index}"), 1, vec![round]);
1323                        registry.flush().unwrap();
1324                    }
1325                })
1326            })
1327            .collect();
1328        for flusher in flushers {
1329            flusher.join().unwrap();
1330        }
1331        assert_eq!(in_flight.1.load(std::sync::atomic::Ordering::SeqCst), 1);
1332    }
1333
1334    #[test]
1335    fn registry_multiple_keys() {
1336        let registry = StateRegistry::in_memory();
1337        registry.set("a", 1, vec![1]);
1338        registry.set("b", 2, vec![2]);
1339        registry.set("c", 3, vec![3]);
1340
1341        assert_eq!(registry.len(), 3);
1342        assert!(!registry.is_empty());
1343
1344        let mut keys = registry.keys();
1345        keys.sort();
1346        assert_eq!(keys, vec!["a", "b", "c"]);
1347    }
1348
1349    #[test]
1350    fn registry_remove_marks_dirty() {
1351        let registry = StateRegistry::in_memory();
1352        registry.set("x", 1, vec![]);
1353        registry.flush().unwrap();
1354        assert!(!registry.is_dirty());
1355
1356        registry.remove("x");
1357        assert!(registry.is_dirty());
1358    }
1359
1360    #[test]
1361    fn registry_clear_after_set_and_flush() {
1362        let registry = StateRegistry::in_memory();
1363        registry.set("a", 1, vec![]);
1364        registry.flush().unwrap();
1365        registry.clear().unwrap();
1366
1367        assert!(registry.is_empty());
1368        assert!(!registry.is_dirty());
1369
1370        // Backend is also cleared
1371        let count = registry.load().unwrap();
1372        assert_eq!(count, 0);
1373    }
1374
1375    // ── RegistryStats ───────────────────────────────────────────────────
1376
1377    #[test]
1378    fn registry_stats_default() {
1379        let stats = RegistryStats::default();
1380        assert_eq!(stats.entry_count, 0);
1381        assert_eq!(stats.total_bytes, 0);
1382        assert!(!stats.dirty);
1383        assert_eq!(stats.backend, "");
1384    }
1385
1386    #[test]
1387    fn registry_stats_empty() {
1388        let registry = StateRegistry::in_memory();
1389        let stats = registry.stats();
1390        assert_eq!(stats.entry_count, 0);
1391        assert_eq!(stats.total_bytes, 0);
1392        assert!(!stats.dirty);
1393    }
1394
1395    // ── StoredEntry ─────────────────────────────────────────────────────
1396
1397    #[test]
1398    fn stored_entry_clone() {
1399        let entry = StoredEntry {
1400            key: "test".to_string(),
1401            version: 7,
1402            data: vec![1, 2, 3],
1403        };
1404        let cloned = entry.clone();
1405        assert_eq!(cloned.key, "test");
1406        assert_eq!(cloned.version, 7);
1407        assert_eq!(cloned.data, vec![1, 2, 3]);
1408    }
1409
1410    #[test]
1411    fn stored_entry_debug() {
1412        let entry = StoredEntry {
1413            key: "k".to_string(),
1414            version: 1,
1415            data: vec![],
1416        };
1417        let dbg = format!("{:?}", entry);
1418        assert!(dbg.contains("StoredEntry"));
1419    }
1420
1421    // ── Arc shared access ───────────────────────────────────────────────
1422
1423    #[test]
1424    fn registry_shared_concurrent_access() {
1425        let registry = StateRegistry::in_memory().shared();
1426        let r2 = Arc::clone(&registry);
1427
1428        registry.set("from_1", 1, vec![10]);
1429        r2.set("from_2", 1, vec![20]);
1430
1431        assert_eq!(registry.len(), 2);
1432        assert!(r2.get("from_1").is_some());
1433        assert!(registry.get("from_2").is_some());
1434    }
1435}
1436
1437#[cfg(all(test, feature = "state-persistence"))]
1438mod file_storage_tests {
1439    use super::*;
1440    use std::io::Write;
1441
1442    #[test]
1443    fn file_storage_round_trip() {
1444        let tmp = tempfile::Builder::new()
1445            .prefix("ftui-state-persistence-")
1446            .disable_cleanup(true)
1447            .tempdir()
1448            .unwrap();
1449        let path = tmp.path().join("state.json");
1450        let storage = FileStorage::new(&path);
1451
1452        // Save
1453        let mut entries = HashMap::new();
1454        entries.insert(
1455            "widget::test".to_string(),
1456            StoredEntry {
1457                key: "widget::test".to_string(),
1458                version: 3,
1459                data: b"hello world".to_vec(),
1460            },
1461        );
1462        storage.save_all(&entries).unwrap();
1463
1464        // File should exist
1465        assert!(path.exists());
1466
1467        // Load back
1468        let loaded = storage.load_all().unwrap();
1469        assert_eq!(loaded.len(), 1);
1470        assert_eq!(loaded["widget::test"].version, 3);
1471        assert_eq!(loaded["widget::test"].data, b"hello world");
1472    }
1473
1474    #[test]
1475    fn file_storage_load_nonexistent() {
1476        let tmp = tempfile::Builder::new()
1477            .prefix("ftui-state-persistence-")
1478            .disable_cleanup(true)
1479            .tempdir()
1480            .unwrap();
1481        let path = tmp.path().join("does_not_exist.json");
1482        let storage = FileStorage::new(&path);
1483
1484        let entries = storage.load_all().unwrap();
1485        assert!(entries.is_empty());
1486    }
1487
1488    #[test]
1489    fn file_storage_clear() {
1490        let tmp = tempfile::Builder::new()
1491            .prefix("ftui-state-persistence-")
1492            .disable_cleanup(true)
1493            .tempdir()
1494            .unwrap();
1495        let path = tmp.path().join("state.json");
1496
1497        // Create file
1498        std::fs::write(&path, "{}").unwrap();
1499        assert!(path.exists());
1500
1501        let storage = FileStorage::new(&path);
1502        storage.clear().unwrap();
1503        assert!(!path.exists());
1504    }
1505
1506    #[test]
1507    fn file_storage_creates_parent_dirs() {
1508        let tmp = tempfile::Builder::new()
1509            .prefix("ftui-state-persistence-")
1510            .disable_cleanup(true)
1511            .tempdir()
1512            .unwrap();
1513        let path = tmp.path().join("nested").join("dirs").join("state.json");
1514        let storage = FileStorage::new(&path);
1515
1516        let mut entries = HashMap::new();
1517        entries.insert(
1518            "k".to_string(),
1519            StoredEntry {
1520                key: "k".to_string(),
1521                version: 1,
1522                data: vec![],
1523            },
1524        );
1525        storage.save_all(&entries).unwrap();
1526        assert!(path.exists());
1527    }
1528
1529    #[test]
1530    fn file_storage_handles_corrupt_entry() {
1531        let tmp = tempfile::Builder::new()
1532            .prefix("ftui-state-persistence-")
1533            .disable_cleanup(true)
1534            .tempdir()
1535            .unwrap();
1536        let path = tmp.path().join("state.json");
1537
1538        // Write valid JSON but with invalid base64
1539        let mut f = std::fs::File::create(&path).unwrap();
1540        writeln!(
1541            f,
1542            r#"{{"format_version":1,"entries":{{"bad":{{"version":1,"data_base64":"!!invalid!!"}},"good":{{"version":1,"data_base64":"aGVsbG8="}}}}}}"#
1543        )
1544        .unwrap();
1545
1546        let storage = FileStorage::new(&path);
1547        let loaded = storage.load_all().unwrap();
1548
1549        // Bad entry skipped, good entry loaded
1550        assert_eq!(loaded.len(), 1);
1551        assert!(loaded.contains_key("good"));
1552        assert_eq!(loaded["good"].data, b"hello");
1553    }
1554
1555    fn one_entry(fill: u8) -> HashMap<String, StoredEntry> {
1556        let entry = StoredEntry {
1557            key: "k".to_string(),
1558            version: 1,
1559            data: vec![fill; 64 * 1024],
1560        };
1561        HashMap::from([("k".to_string(), entry)])
1562    }
1563
1564    fn temp_files_beside(path: &std::path::Path) -> Vec<std::path::PathBuf> {
1565        std::fs::read_dir(path.parent().unwrap())
1566            .unwrap()
1567            .map(|entry| entry.unwrap().path())
1568            .filter(|p| p.extension().is_some_and(|ext| ext == "tmp"))
1569            .collect()
1570    }
1571
1572    #[test]
1573    fn concurrent_saves_each_rename_a_complete_file() {
1574        // With one shared `state.json.tmp`, saves truncated each other's temp
1575        // file: readers found `state.json` empty or cut short, and saves
1576        // failed when another had already renamed the file away.
1577        let tmp = tempfile::Builder::new()
1578            .prefix("ftui-state-persistence-")
1579            .disable_cleanup(true)
1580            .tempdir()
1581            .unwrap();
1582        let path = tmp.path().join("state.json");
1583        let storage = std::sync::Arc::new(FileStorage::new(&path));
1584        storage.save_all(&one_entry(0)).unwrap();
1585
1586        let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
1587        let reader = {
1588            let (storage, stop) = (
1589                std::sync::Arc::clone(&storage),
1590                std::sync::Arc::clone(&stop),
1591            );
1592            std::thread::spawn(move || {
1593                while !stop.load(std::sync::atomic::Ordering::Relaxed) {
1594                    let loaded = storage.load_all().expect("a reader sees a whole file");
1595                    let data = &loaded["k"].data;
1596                    assert_eq!(data.len(), 64 * 1024);
1597                    assert!(data.iter().all(|&byte| byte == data[0]));
1598                }
1599            })
1600        };
1601        let writers: Vec<_> = (1..=4_u8)
1602            .map(|fill| {
1603                let storage = std::sync::Arc::clone(&storage);
1604                std::thread::spawn(move || {
1605                    for _ in 0..10 {
1606                        storage
1607                            .save_all(&one_entry(fill))
1608                            .expect("every save succeeds");
1609                    }
1610                })
1611            })
1612            .collect();
1613        for writer in writers {
1614            writer.join().unwrap();
1615        }
1616        stop.store(true, std::sync::atomic::Ordering::Relaxed);
1617        reader.join().unwrap();
1618        assert!(temp_files_beside(&path).is_empty());
1619    }
1620
1621    #[test]
1622    fn failed_save_removes_its_temporary_file() {
1623        let tmp = tempfile::Builder::new()
1624            .prefix("ftui-state-persistence-")
1625            .disable_cleanup(true)
1626            .tempdir()
1627            .unwrap();
1628        // A directory where the state file belongs makes the final rename fail.
1629        let path = tmp.path().join("state.json");
1630        std::fs::create_dir(&path).unwrap();
1631        let storage = FileStorage::new(&path);
1632        assert!(storage.save_all(&one_entry(1)).is_err());
1633        assert!(temp_files_beside(&path).is_empty());
1634    }
1635}