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                    target: crate::telemetry_schema::TARGET_RUNTIME,
381                    stored = state_file.format_version,
382                    expected = StateFile::FORMAT_VERSION,
383                    "state file format version mismatch, ignoring stored state"
384                );
385                return Ok(HashMap::new());
386            }
387
388            // Convert file entries to StoredEntry
389            let mut result = HashMap::new();
390            for (key, entry) in state_file.entries {
391                use base64::Engine;
392                let data =
393                    match base64::engine::general_purpose::STANDARD.decode(&entry.data_base64) {
394                        Ok(d) => d,
395                        Err(e) => {
396                            tracing::warn!(
397                                target: crate::telemetry_schema::TARGET_RUNTIME,
398                                key = %key,
399                                error = %e,
400                                "failed to decode state entry, skipping"
401                            );
402                            continue;
403                        }
404                    };
405                result.insert(
406                    key.clone(),
407                    StoredEntry {
408                        key,
409                        version: entry.version,
410                        data,
411                    },
412                );
413            }
414
415            Ok(result)
416        }
417
418        fn save_all(&self, entries: &HashMap<String, StoredEntry>) -> StorageResult<()> {
419            use base64::Engine;
420
421            // Ensure parent directory exists
422            if let Some(parent) = self.path.parent() {
423                fs::create_dir_all(parent)?;
424            }
425
426            // Build file content
427            let mut state_file = StateFile::new();
428            for (key, entry) in entries {
429                state_file.entries.insert(
430                    key.clone(),
431                    FileEntry {
432                        version: entry.version,
433                        data_base64: base64::engine::general_purpose::STANDARD.encode(&entry.data),
434                    },
435                );
436            }
437
438            // Write to temp file first, then rename it into place (atomic pattern)
439            let tmp_path = self.temp_path();
440            let saved = (|| -> StorageResult<()> {
441                let file = File::create(&tmp_path)?;
442                let mut writer = BufWriter::new(file);
443                serde_json::to_writer_pretty(&mut writer, &state_file).map_err(|e| {
444                    StorageError::Serialization(format!("failed to serialize state: {e}"))
445                })?;
446                writer.flush()?;
447                writer.get_ref().sync_all()?;
448                fs::rename(&tmp_path, &self.path)?;
449                Ok(())
450            })();
451            if saved.is_err() {
452                // Each save names its own file, so nothing else would reuse
453                // and overwrite this one: remove it rather than strand it.
454                let _ = fs::remove_file(&tmp_path);
455            }
456            saved?;
457
458            tracing::debug!(
459                target: crate::telemetry_schema::TARGET_RUNTIME,
460                path = %self.path.display(),
461                entries = entries.len(),
462                "saved widget state"
463            );
464
465            Ok(())
466        }
467
468        fn clear(&self) -> StorageResult<()> {
469            if self.path.exists() {
470                fs::remove_file(&self.path)?;
471            }
472            Ok(())
473        }
474
475        fn is_available(&self) -> bool {
476            // Check if we can write to the directory
477            if let Some(parent) = self.path.parent() {
478                if !parent.exists() {
479                    return std::fs::create_dir_all(parent).is_ok();
480                }
481                // Check write permission (try to create temp file)
482                let test_path = parent.join(".ftui_test_write");
483                if std::fs::write(&test_path, b"test").is_ok() {
484                    let _ = std::fs::remove_file(&test_path);
485                    return true;
486                }
487            }
488            false
489        }
490    }
491
492    impl fmt::Debug for FileStorage {
493        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
494            f.debug_struct("FileStorage")
495                .field("path", &self.path)
496                .finish()
497        }
498    }
499}
500
501#[cfg(feature = "state-persistence")]
502pub use file_storage::FileStorage;
503
504// ─────────────────────────────────────────────────────────────────────────────
505// State Registry
506// ─────────────────────────────────────────────────────────────────────────────
507
508/// Central registry for widget state persistence.
509///
510/// The registry maintains an in-memory cache of widget states and delegates
511/// to a [`StorageBackend`] for persistence. It provides the main API for
512/// save/restore operations.
513///
514/// # Thread Safety
515///
516/// The registry is `Send + Sync` and uses internal locking for thread-safe access.
517///
518/// # Example
519///
520/// ```ignore
521/// use ftui_runtime::state_persistence::{StateRegistry, MemoryStorage};
522///
523/// // Create registry with memory storage
524/// let registry = StateRegistry::new(Box::new(MemoryStorage::new()));
525///
526/// // Load state for a widget
527/// if let Some(entry) = registry.get("ScrollView::main") {
528///     // Deserialize and restore...
529/// }
530///
531/// // Save state
532/// registry.set("ScrollView::main", 1, serialized_data);
533/// registry.flush()?;
534/// ```
535pub struct StateRegistry {
536    backend: Box<dyn StorageBackend>,
537    cache: RwLock<HashMap<String, StoredEntry>>,
538    dirty: RwLock<bool>,
539    /// Held across a whole flush. Two unserialized flushes could save their
540    /// snapshots in either order, leaving the older one in storage.
541    flush_lock: Mutex<()>,
542}
543
544impl StateRegistry {
545    /// Create a new registry with the given storage backend.
546    ///
547    /// Does not automatically load from storage; call [`load`](Self::load) first.
548    #[must_use]
549    pub fn new(backend: Box<dyn StorageBackend>) -> Self {
550        Self {
551            backend,
552            cache: RwLock::new(HashMap::new()),
553            dirty: RwLock::new(false),
554            flush_lock: Mutex::new(()),
555        }
556    }
557
558    /// Create a registry with memory storage (ephemeral, for testing).
559    #[must_use]
560    pub fn in_memory() -> Self {
561        Self::new(Box::new(MemoryStorage::new()))
562    }
563
564    /// Create a registry with file storage at the given path.
565    #[cfg(feature = "state-persistence")]
566    #[must_use]
567    pub fn with_file(path: impl AsRef<std::path::Path>) -> Self {
568        Self::new(Box::new(FileStorage::new(path)))
569    }
570
571    /// Load all state from the storage backend.
572    ///
573    /// This replaces the in-memory cache with stored data.
574    /// Safe to call multiple times; later calls refresh the cache.
575    pub fn load(&self) -> StorageResult<usize> {
576        let entries = self.backend.load_all()?;
577        let count = entries.len();
578
579        let mut cache = self
580            .cache
581            .write()
582            .map_err(|_| StorageError::Corruption("cache lock poisoned".into()))?;
583        *cache = entries;
584
585        let mut dirty = self
586            .dirty
587            .write()
588            .map_err(|_| StorageError::Corruption("dirty lock poisoned".into()))?;
589        *dirty = false;
590
591        tracing::debug!(
592            target: crate::telemetry_schema::TARGET_RUNTIME,
593            backend = %self.backend.name(),
594            count,
595            "loaded widget state"
596        );
597        Ok(count)
598    }
599
600    /// Flush dirty state to the storage backend.
601    ///
602    /// Only writes if changes have been made since last flush.
603    /// Returns `Ok(true)` if data was written, `Ok(false)` if no changes.
604    pub fn flush(&self) -> StorageResult<bool> {
605        let _flushing = self
606            .flush_lock
607            .lock()
608            .map_err(|_| StorageError::Corruption("flush lock poisoned".into()))?;
609        let dirty = {
610            let guard = self
611                .dirty
612                .read()
613                .map_err(|_| StorageError::Corruption("dirty lock poisoned".into()))?;
614            *guard
615        };
616
617        if !dirty {
618            return Ok(false);
619        }
620
621        let cache_snapshot = {
622            let cache_guard = self
623                .cache
624                .read()
625                .map_err(|_| StorageError::Corruption("cache lock poisoned".into()))?;
626            cache_guard.clone()
627        };
628
629        self.backend.save_all(&cache_snapshot)?;
630
631        let cache_guard = self
632            .cache
633            .read()
634            .map_err(|_| StorageError::Corruption("cache lock poisoned".into()))?;
635        let mut dirty_guard = self
636            .dirty
637            .write()
638            .map_err(|_| StorageError::Corruption("dirty lock poisoned".into()))?;
639        *dirty_guard = *cache_guard != cache_snapshot;
640
641        Ok(true)
642    }
643
644    /// Get a stored state entry by canonical key.
645    ///
646    /// Returns `None` if no state exists for the key.
647    #[must_use]
648    pub fn get(&self, key: &str) -> Option<StoredEntry> {
649        let cache = self.cache.read().ok()?;
650        cache.get(key).cloned()
651    }
652
653    /// Set a state entry.
654    ///
655    /// Marks the registry as dirty; call [`flush`](Self::flush) to persist.
656    pub fn set(&self, key: impl Into<String>, version: u32, data: Vec<u8>) {
657        let key = key.into();
658        if let Ok(mut cache) = self.cache.write() {
659            cache.insert(key.clone(), StoredEntry { key, version, data });
660            if let Ok(mut dirty) = self.dirty.write() {
661                *dirty = true;
662            }
663        }
664    }
665
666    /// Remove a state entry.
667    ///
668    /// Returns the removed entry if it existed.
669    pub fn remove(&self, key: &str) -> Option<StoredEntry> {
670        let result = self.cache.write().ok()?.remove(key);
671        if result.is_some()
672            && let Ok(mut dirty) = self.dirty.write()
673        {
674            *dirty = true;
675        }
676        result
677    }
678
679    /// Clear all state from both cache and storage.
680    pub fn clear(&self) -> StorageResult<()> {
681        self.backend.clear()?;
682        if let Ok(mut cache) = self.cache.write() {
683            cache.clear();
684        }
685        if let Ok(mut dirty) = self.dirty.write() {
686            *dirty = false;
687        }
688        Ok(())
689    }
690
691    /// Get the number of cached entries.
692    #[must_use]
693    pub fn len(&self) -> usize {
694        self.cache.read().map(|c| c.len()).unwrap_or(0)
695    }
696
697    /// Check if the cache is empty.
698    #[must_use]
699    pub fn is_empty(&self) -> bool {
700        self.len() == 0
701    }
702
703    /// Check if there are unsaved changes.
704    #[must_use]
705    pub fn is_dirty(&self) -> bool {
706        self.dirty.read().map(|d| *d).unwrap_or(false)
707    }
708
709    /// Get the backend name for logging.
710    #[must_use]
711    pub fn backend_name(&self) -> &str {
712        self.backend.name()
713    }
714
715    /// Check if the storage backend is available.
716    #[must_use]
717    pub fn is_available(&self) -> bool {
718        self.backend.is_available()
719    }
720
721    /// Get all cached keys.
722    #[must_use]
723    pub fn keys(&self) -> Vec<String> {
724        self.cache
725            .read()
726            .map(|c| c.keys().cloned().collect())
727            .unwrap_or_default()
728    }
729}
730
731impl fmt::Debug for StateRegistry {
732    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
733        f.debug_struct("StateRegistry")
734            .field("backend", &self.backend.name())
735            .field("entries", &self.len())
736            .field("dirty", &self.is_dirty())
737            .finish()
738    }
739}
740
741// Make it Arc-able for shared ownership
742impl StateRegistry {
743    /// Wrap in Arc for shared ownership.
744    #[must_use]
745    pub fn shared(self) -> Arc<Self> {
746        Arc::new(self)
747    }
748}
749
750// ─────────────────────────────────────────────────────────────────────────────
751// Statistics and Diagnostics
752// ─────────────────────────────────────────────────────────────────────────────
753
754/// Statistics about the state registry.
755#[derive(Clone, Debug, Default)]
756pub struct RegistryStats {
757    /// Number of entries in cache.
758    pub entry_count: usize,
759    /// Total bytes of state data.
760    pub total_bytes: usize,
761    /// Whether there are unsaved changes.
762    pub dirty: bool,
763    /// Backend name.
764    pub backend: String,
765}
766
767impl StateRegistry {
768    /// Get statistics about the registry.
769    #[must_use]
770    pub fn stats(&self) -> RegistryStats {
771        let (entry_count, total_bytes) = self
772            .cache
773            .read()
774            .map(|c| {
775                let count = c.len();
776                let bytes: usize = c.values().map(|e| e.data.len()).sum();
777                (count, bytes)
778            })
779            .unwrap_or((0, 0));
780
781        RegistryStats {
782            entry_count,
783            total_bytes,
784            dirty: self.is_dirty(),
785            backend: self.backend.name().to_string(),
786        }
787    }
788}
789
790// ─────────────────────────────────────────────────────────────────────────────
791// Tests
792// ─────────────────────────────────────────────────────────────────────────────
793
794#[cfg(test)]
795mod tests {
796    use super::*;
797    use std::sync::atomic::{AtomicBool, Ordering};
798    use std::sync::{Mutex, Weak};
799    use std::thread;
800    use web_time::Duration;
801
802    #[derive(Default)]
803    struct ReentrantFlushBackendState {
804        registry: Mutex<Option<Weak<StateRegistry>>>,
805        injected_during_save: AtomicBool,
806        saved_entries: RwLock<HashMap<String, StoredEntry>>,
807    }
808
809    impl ReentrantFlushBackendState {
810        fn bind_registry(&self, registry: &Arc<StateRegistry>) {
811            *self.registry.lock().unwrap_or_else(|e| e.into_inner()) =
812                Some(Arc::downgrade(registry));
813        }
814
815        fn saved_entries(&self) -> HashMap<String, StoredEntry> {
816            self.saved_entries
817                .read()
818                .unwrap_or_else(|e| e.into_inner())
819                .clone()
820        }
821    }
822
823    #[derive(Clone)]
824    struct ReentrantFlushBackend {
825        state: Arc<ReentrantFlushBackendState>,
826    }
827
828    impl StorageBackend for ReentrantFlushBackend {
829        fn name(&self) -> &str {
830            "ReentrantFlushBackend"
831        }
832
833        fn load_all(&self) -> StorageResult<HashMap<String, StoredEntry>> {
834            Ok(self.state.saved_entries())
835        }
836
837        fn save_all(&self, entries: &HashMap<String, StoredEntry>) -> StorageResult<()> {
838            *self
839                .state
840                .saved_entries
841                .write()
842                .map_err(|_| StorageError::Corruption("saved entries lock poisoned".into()))? =
843                entries.clone();
844
845            if !self.state.injected_during_save.swap(true, Ordering::SeqCst)
846                && let Some(registry) = self
847                    .state
848                    .registry
849                    .lock()
850                    .unwrap_or_else(|e| e.into_inner())
851                    .as_ref()
852                    .and_then(Weak::upgrade)
853            {
854                registry.set("backend::late", 2, b"late".to_vec());
855            }
856
857            Ok(())
858        }
859
860        fn clear(&self) -> StorageResult<()> {
861            self.state
862                .saved_entries
863                .write()
864                .map_err(|_| StorageError::Corruption("saved entries lock poisoned".into()))?
865                .clear();
866            Ok(())
867        }
868    }
869
870    #[test]
871    fn memory_storage_basic_operations() {
872        let storage = MemoryStorage::new();
873
874        // Initially empty
875        let entries = storage.load_all().unwrap();
876        assert!(entries.is_empty());
877
878        // Save some entries
879        let mut data = HashMap::new();
880        data.insert(
881            "key1".to_string(),
882            StoredEntry {
883                key: "key1".to_string(),
884                version: 1,
885                data: b"hello".to_vec(),
886            },
887        );
888        storage.save_all(&data).unwrap();
889
890        // Load back
891        let loaded = storage.load_all().unwrap();
892        assert_eq!(loaded.len(), 1);
893        assert_eq!(loaded["key1"].data, b"hello");
894
895        // Clear
896        storage.clear().unwrap();
897        assert!(storage.load_all().unwrap().is_empty());
898    }
899
900    #[test]
901    fn memory_storage_with_entries() {
902        let mut entries = HashMap::new();
903        entries.insert(
904            "test".to_string(),
905            StoredEntry {
906                key: "test".to_string(),
907                version: 2,
908                data: vec![1, 2, 3],
909            },
910        );
911        let storage = MemoryStorage::with_entries(entries);
912
913        let loaded = storage.load_all().unwrap();
914        assert_eq!(loaded.len(), 1);
915        assert_eq!(loaded["test"].version, 2);
916    }
917
918    #[test]
919    fn registry_basic_operations() {
920        let registry = StateRegistry::in_memory();
921
922        // Initially empty
923        assert!(registry.is_empty());
924        assert!(!registry.is_dirty());
925
926        // Set an entry
927        registry.set("widget::1", 1, b"data".to_vec());
928        assert_eq!(registry.len(), 1);
929        assert!(registry.is_dirty());
930
931        // Get the entry
932        let entry = registry.get("widget::1").unwrap();
933        assert_eq!(entry.version, 1);
934        assert_eq!(entry.data, b"data");
935
936        // Get non-existent
937        assert!(registry.get("widget::99").is_none());
938
939        // Flush
940        assert!(registry.flush().unwrap());
941        assert!(!registry.is_dirty());
942
943        // No-op flush when clean
944        assert!(!registry.flush().unwrap());
945
946        // Remove
947        let removed = registry.remove("widget::1").unwrap();
948        assert_eq!(removed.data, b"data");
949        assert!(registry.is_empty());
950        assert!(registry.is_dirty());
951    }
952
953    #[test]
954    fn registry_load_and_flush() {
955        let storage = MemoryStorage::new();
956        let mut initial = HashMap::new();
957        initial.insert(
958            "pre::existing".to_string(),
959            StoredEntry {
960                key: "pre::existing".to_string(),
961                version: 5,
962                data: b"old".to_vec(),
963            },
964        );
965        storage.save_all(&initial).unwrap();
966
967        let registry = StateRegistry::new(Box::new(storage));
968
969        // Load existing data
970        let count = registry.load().unwrap();
971        assert_eq!(count, 1);
972        assert!(!registry.is_dirty());
973
974        let entry = registry.get("pre::existing").unwrap();
975        assert_eq!(entry.version, 5);
976    }
977
978    #[test]
979    fn registry_clear() {
980        let registry = StateRegistry::in_memory();
981        registry.set("a", 1, vec![]);
982        registry.set("b", 1, vec![]);
983        assert_eq!(registry.len(), 2);
984
985        registry.clear().unwrap();
986        assert!(registry.is_empty());
987        assert!(!registry.is_dirty());
988    }
989
990    #[test]
991    fn registry_keys() {
992        let registry = StateRegistry::in_memory();
993        registry.set("widget::a", 1, vec![]);
994        registry.set("widget::b", 1, vec![]);
995
996        let mut keys = registry.keys();
997        keys.sort();
998        assert_eq!(keys, vec!["widget::a", "widget::b"]);
999    }
1000
1001    #[test]
1002    fn registry_stats() {
1003        let registry = StateRegistry::in_memory();
1004        registry.set("x", 1, vec![1, 2, 3, 4, 5]);
1005        registry.set("y", 1, vec![6, 7, 8]);
1006
1007        let stats = registry.stats();
1008        assert_eq!(stats.entry_count, 2);
1009        assert_eq!(stats.total_bytes, 8);
1010        assert!(stats.dirty);
1011        assert_eq!(stats.backend, "MemoryStorage");
1012    }
1013
1014    #[test]
1015    fn registry_shared() {
1016        let registry = StateRegistry::in_memory().shared();
1017        registry.set("test", 1, vec![42]);
1018
1019        let registry2 = Arc::clone(&registry);
1020        assert_eq!(registry2.get("test").unwrap().data, vec![42]);
1021    }
1022
1023    #[test]
1024    fn storage_error_display() {
1025        let io_err = StorageError::Io(std::io::Error::new(std::io::ErrorKind::NotFound, "missing"));
1026        assert!(io_err.to_string().contains("I/O error"));
1027
1028        let corrupt = StorageError::Corruption("bad data".into());
1029        assert!(corrupt.to_string().contains("corruption"));
1030
1031        let unavail = StorageError::Unavailable("no backend".into());
1032        assert!(unavail.to_string().contains("unavailable"));
1033    }
1034
1035    // ── StorageError ────────────────────────────────────────────────────
1036
1037    #[test]
1038    fn storage_error_source_io() {
1039        let err = StorageError::Io(std::io::Error::new(
1040            std::io::ErrorKind::BrokenPipe,
1041            "broken",
1042        ));
1043        let source = std::error::Error::source(&err);
1044        assert!(source.is_some());
1045    }
1046
1047    #[test]
1048    fn storage_error_source_corruption_none() {
1049        let err = StorageError::Corruption("test".into());
1050        assert!(std::error::Error::source(&err).is_none());
1051    }
1052
1053    #[test]
1054    fn storage_error_source_unavailable_none() {
1055        let err = StorageError::Unavailable("test".into());
1056        assert!(std::error::Error::source(&err).is_none());
1057    }
1058
1059    #[test]
1060    fn storage_error_from_io_error() {
1061        let io_err = std::io::Error::new(std::io::ErrorKind::TimedOut, "timeout");
1062        let err: StorageError = io_err.into();
1063        match err {
1064            StorageError::Io(e) => assert_eq!(e.kind(), std::io::ErrorKind::TimedOut),
1065            _ => panic!("expected Io variant"),
1066        }
1067    }
1068
1069    #[test]
1070    fn storage_error_debug_format() {
1071        let err = StorageError::Corruption("test".into());
1072        let dbg = format!("{:?}", err);
1073        assert!(dbg.contains("Corruption"));
1074    }
1075
1076    // ── MemoryStorage ───────────────────────────────────────────────────
1077
1078    #[test]
1079    fn memory_storage_name() {
1080        let storage = MemoryStorage::new();
1081        assert_eq!(storage.name(), "MemoryStorage");
1082    }
1083
1084    #[test]
1085    fn memory_storage_is_available() {
1086        let storage = MemoryStorage::new();
1087        assert!(storage.is_available());
1088    }
1089
1090    #[test]
1091    fn memory_storage_debug_format() {
1092        let storage = MemoryStorage::new();
1093        let dbg = format!("{:?}", storage);
1094        assert!(dbg.contains("MemoryStorage"));
1095        assert!(dbg.contains("entries"));
1096    }
1097
1098    #[test]
1099    fn memory_storage_debug_shows_count() {
1100        let mut entries = HashMap::new();
1101        entries.insert(
1102            "a".to_string(),
1103            StoredEntry {
1104                key: "a".to_string(),
1105                version: 1,
1106                data: vec![],
1107            },
1108        );
1109        let storage = MemoryStorage::with_entries(entries);
1110        let dbg = format!("{:?}", storage);
1111        assert!(dbg.contains("1"));
1112    }
1113
1114    #[test]
1115    fn memory_storage_save_replaces_all() {
1116        let storage = MemoryStorage::new();
1117
1118        let mut data1 = HashMap::new();
1119        data1.insert(
1120            "old".to_string(),
1121            StoredEntry {
1122                key: "old".to_string(),
1123                version: 1,
1124                data: vec![],
1125            },
1126        );
1127        storage.save_all(&data1).unwrap();
1128
1129        let mut data2 = HashMap::new();
1130        data2.insert(
1131            "new".to_string(),
1132            StoredEntry {
1133                key: "new".to_string(),
1134                version: 2,
1135                data: vec![],
1136            },
1137        );
1138        storage.save_all(&data2).unwrap();
1139
1140        let loaded = storage.load_all().unwrap();
1141        assert_eq!(loaded.len(), 1);
1142        assert!(loaded.contains_key("new"));
1143        assert!(!loaded.contains_key("old"));
1144    }
1145
1146    // ── StateRegistry ───────────────────────────────────────────────────
1147
1148    #[test]
1149    fn registry_backend_name() {
1150        let registry = StateRegistry::in_memory();
1151        assert_eq!(registry.backend_name(), "MemoryStorage");
1152    }
1153
1154    #[test]
1155    fn registry_is_available() {
1156        let registry = StateRegistry::in_memory();
1157        assert!(registry.is_available());
1158    }
1159
1160    #[test]
1161    fn registry_debug_format() {
1162        let registry = StateRegistry::in_memory();
1163        registry.set("x", 1, vec![]);
1164        let dbg = format!("{:?}", registry);
1165        assert!(dbg.contains("StateRegistry"));
1166        assert!(dbg.contains("MemoryStorage"));
1167        assert!(dbg.contains("dirty"));
1168    }
1169
1170    #[test]
1171    fn registry_set_overwrites() {
1172        let registry = StateRegistry::in_memory();
1173        registry.set("k", 1, b"first".to_vec());
1174        registry.set("k", 2, b"second".to_vec());
1175
1176        assert_eq!(registry.len(), 1);
1177        let entry = registry.get("k").unwrap();
1178        assert_eq!(entry.version, 2);
1179        assert_eq!(entry.data, b"second");
1180    }
1181
1182    #[test]
1183    fn registry_remove_nonexistent_returns_none() {
1184        let registry = StateRegistry::in_memory();
1185        assert!(registry.remove("nonexistent").is_none());
1186    }
1187
1188    #[test]
1189    fn registry_load_replaces_cache() {
1190        let storage = MemoryStorage::new();
1191        let mut initial = HashMap::new();
1192        initial.insert(
1193            "backend_key".to_string(),
1194            StoredEntry {
1195                key: "backend_key".to_string(),
1196                version: 1,
1197                data: b"from_backend".to_vec(),
1198            },
1199        );
1200        storage.save_all(&initial).unwrap();
1201
1202        let registry = StateRegistry::new(Box::new(storage));
1203        registry.set("local_key", 1, b"local".to_vec());
1204        assert!(registry.get("local_key").is_some());
1205
1206        // Load replaces entire cache
1207        registry.load().unwrap();
1208        assert!(registry.get("local_key").is_none());
1209        assert!(registry.get("backend_key").is_some());
1210    }
1211
1212    #[test]
1213    fn registry_load_clears_dirty_flag() {
1214        let registry = StateRegistry::in_memory();
1215        registry.set("x", 1, vec![]);
1216        assert!(registry.is_dirty());
1217
1218        registry.load().unwrap();
1219        assert!(!registry.is_dirty());
1220    }
1221
1222    #[test]
1223    fn registry_flush_persists_to_backend() {
1224        let registry = StateRegistry::in_memory();
1225        registry.set("widget::foo", 3, b"bar".to_vec());
1226        registry.flush().unwrap();
1227
1228        // Load fresh and verify data survived
1229        let count = registry.load().unwrap();
1230        assert_eq!(count, 1);
1231        let entry = registry.get("widget::foo").unwrap();
1232        assert_eq!(entry.version, 3);
1233        assert_eq!(entry.data, b"bar");
1234    }
1235
1236    #[test]
1237    fn registry_flush_drops_cache_lock_before_backend_save() {
1238        let backend_state = Arc::new(ReentrantFlushBackendState::default());
1239        let registry = Arc::new(StateRegistry::new(Box::new(ReentrantFlushBackend {
1240            state: Arc::clone(&backend_state),
1241        })));
1242        backend_state.bind_registry(&registry);
1243
1244        registry.set("widget::foo", 1, b"bar".to_vec());
1245
1246        let (done_tx, done_rx) = std::sync::mpsc::channel();
1247        let registry_for_thread = Arc::clone(&registry);
1248        let handle = thread::spawn(move || {
1249            let result = registry_for_thread.flush();
1250            done_tx.send(result).expect("flush result");
1251        });
1252
1253        done_rx
1254            .recv_timeout(Duration::from_secs(1))
1255            .expect("flush should complete without deadlocking")
1256            .expect("flush succeeds");
1257        handle.join().expect("flush thread");
1258
1259        let saved_entries = backend_state.saved_entries();
1260        assert!(saved_entries.contains_key("widget::foo"));
1261    }
1262
1263    #[test]
1264    fn registry_flush_preserves_dirty_when_backend_mutates_registry() {
1265        let backend_state = Arc::new(ReentrantFlushBackendState::default());
1266        let registry = Arc::new(StateRegistry::new(Box::new(ReentrantFlushBackend {
1267            state: Arc::clone(&backend_state),
1268        })));
1269        backend_state.bind_registry(&registry);
1270
1271        registry.set("widget::foo", 1, b"bar".to_vec());
1272        assert!(registry.flush().unwrap());
1273
1274        let first_saved = backend_state.saved_entries();
1275        assert!(first_saved.contains_key("widget::foo"));
1276        assert!(!first_saved.contains_key("backend::late"));
1277        assert!(registry.is_dirty());
1278        assert_eq!(registry.get("backend::late").unwrap().data, b"late");
1279
1280        assert!(registry.flush().unwrap());
1281
1282        let second_saved = backend_state.saved_entries();
1283        assert!(second_saved.contains_key("backend::late"));
1284        assert!(!registry.is_dirty());
1285    }
1286
1287    /// Counts how many `save_all` calls are in progress at once.
1288    struct OverlapBackend {
1289        in_flight: Arc<(
1290            std::sync::atomic::AtomicUsize,
1291            std::sync::atomic::AtomicUsize,
1292        )>,
1293    }
1294
1295    impl StorageBackend for OverlapBackend {
1296        fn name(&self) -> &str {
1297            "OverlapBackend"
1298        }
1299
1300        fn load_all(&self) -> StorageResult<HashMap<String, StoredEntry>> {
1301            Ok(HashMap::new())
1302        }
1303
1304        fn save_all(&self, _entries: &HashMap<String, StoredEntry>) -> StorageResult<()> {
1305            use std::sync::atomic::Ordering::SeqCst;
1306            let (current, peak) = &*self.in_flight;
1307            peak.fetch_max(current.fetch_add(1, SeqCst) + 1, SeqCst);
1308            thread::sleep(Duration::from_millis(5));
1309            current.fetch_sub(1, SeqCst);
1310            Ok(())
1311        }
1312
1313        fn clear(&self) -> StorageResult<()> {
1314            Ok(())
1315        }
1316    }
1317
1318    #[test]
1319    fn concurrent_flushes_save_one_at_a_time() {
1320        // Overlapping flushes could finish in either order, so an older
1321        // snapshot could land in storage after a newer one.
1322        let in_flight = Arc::new(Default::default());
1323        let registry = Arc::new(StateRegistry::new(Box::new(OverlapBackend {
1324            in_flight: Arc::clone(&in_flight),
1325        })));
1326        let start = Arc::new(std::sync::Barrier::new(4));
1327        let flushers: Vec<_> = (0..4)
1328            .map(|thread_index| {
1329                let (registry, start) = (Arc::clone(&registry), Arc::clone(&start));
1330                thread::spawn(move || {
1331                    start.wait();
1332                    for round in 0..10_u8 {
1333                        registry.set(format!("widget::{thread_index}"), 1, vec![round]);
1334                        registry.flush().unwrap();
1335                    }
1336                })
1337            })
1338            .collect();
1339        for flusher in flushers {
1340            flusher.join().unwrap();
1341        }
1342        assert_eq!(in_flight.1.load(std::sync::atomic::Ordering::SeqCst), 1);
1343    }
1344
1345    #[test]
1346    fn registry_multiple_keys() {
1347        let registry = StateRegistry::in_memory();
1348        registry.set("a", 1, vec![1]);
1349        registry.set("b", 2, vec![2]);
1350        registry.set("c", 3, vec![3]);
1351
1352        assert_eq!(registry.len(), 3);
1353        assert!(!registry.is_empty());
1354
1355        let mut keys = registry.keys();
1356        keys.sort();
1357        assert_eq!(keys, vec!["a", "b", "c"]);
1358    }
1359
1360    #[test]
1361    fn registry_remove_marks_dirty() {
1362        let registry = StateRegistry::in_memory();
1363        registry.set("x", 1, vec![]);
1364        registry.flush().unwrap();
1365        assert!(!registry.is_dirty());
1366
1367        registry.remove("x");
1368        assert!(registry.is_dirty());
1369    }
1370
1371    #[test]
1372    fn registry_clear_after_set_and_flush() {
1373        let registry = StateRegistry::in_memory();
1374        registry.set("a", 1, vec![]);
1375        registry.flush().unwrap();
1376        registry.clear().unwrap();
1377
1378        assert!(registry.is_empty());
1379        assert!(!registry.is_dirty());
1380
1381        // Backend is also cleared
1382        let count = registry.load().unwrap();
1383        assert_eq!(count, 0);
1384    }
1385
1386    // ── RegistryStats ───────────────────────────────────────────────────
1387
1388    #[test]
1389    fn registry_stats_default() {
1390        let stats = RegistryStats::default();
1391        assert_eq!(stats.entry_count, 0);
1392        assert_eq!(stats.total_bytes, 0);
1393        assert!(!stats.dirty);
1394        assert_eq!(stats.backend, "");
1395    }
1396
1397    #[test]
1398    fn registry_stats_empty() {
1399        let registry = StateRegistry::in_memory();
1400        let stats = registry.stats();
1401        assert_eq!(stats.entry_count, 0);
1402        assert_eq!(stats.total_bytes, 0);
1403        assert!(!stats.dirty);
1404    }
1405
1406    // ── StoredEntry ─────────────────────────────────────────────────────
1407
1408    #[test]
1409    fn stored_entry_clone() {
1410        let entry = StoredEntry {
1411            key: "test".to_string(),
1412            version: 7,
1413            data: vec![1, 2, 3],
1414        };
1415        let cloned = entry.clone();
1416        assert_eq!(cloned.key, "test");
1417        assert_eq!(cloned.version, 7);
1418        assert_eq!(cloned.data, vec![1, 2, 3]);
1419    }
1420
1421    #[test]
1422    fn stored_entry_debug() {
1423        let entry = StoredEntry {
1424            key: "k".to_string(),
1425            version: 1,
1426            data: vec![],
1427        };
1428        let dbg = format!("{:?}", entry);
1429        assert!(dbg.contains("StoredEntry"));
1430    }
1431
1432    // ── Arc shared access ───────────────────────────────────────────────
1433
1434    #[test]
1435    fn registry_shared_concurrent_access() {
1436        let registry = StateRegistry::in_memory().shared();
1437        let r2 = Arc::clone(&registry);
1438
1439        registry.set("from_1", 1, vec![10]);
1440        r2.set("from_2", 1, vec![20]);
1441
1442        assert_eq!(registry.len(), 2);
1443        assert!(r2.get("from_1").is_some());
1444        assert!(registry.get("from_2").is_some());
1445    }
1446}
1447
1448#[cfg(all(test, feature = "state-persistence"))]
1449mod file_storage_tests {
1450    use super::*;
1451    use std::io::Write;
1452
1453    #[test]
1454    fn file_storage_round_trip() {
1455        let tmp = tempfile::Builder::new()
1456            .prefix("ftui-state-persistence-")
1457            .disable_cleanup(true)
1458            .tempdir()
1459            .unwrap();
1460        let path = tmp.path().join("state.json");
1461        let storage = FileStorage::new(&path);
1462
1463        // Save
1464        let mut entries = HashMap::new();
1465        entries.insert(
1466            "widget::test".to_string(),
1467            StoredEntry {
1468                key: "widget::test".to_string(),
1469                version: 3,
1470                data: b"hello world".to_vec(),
1471            },
1472        );
1473        storage.save_all(&entries).unwrap();
1474
1475        // File should exist
1476        assert!(path.exists());
1477
1478        // Load back
1479        let loaded = storage.load_all().unwrap();
1480        assert_eq!(loaded.len(), 1);
1481        assert_eq!(loaded["widget::test"].version, 3);
1482        assert_eq!(loaded["widget::test"].data, b"hello world");
1483    }
1484
1485    #[test]
1486    fn file_storage_load_nonexistent() {
1487        let tmp = tempfile::Builder::new()
1488            .prefix("ftui-state-persistence-")
1489            .disable_cleanup(true)
1490            .tempdir()
1491            .unwrap();
1492        let path = tmp.path().join("does_not_exist.json");
1493        let storage = FileStorage::new(&path);
1494
1495        let entries = storage.load_all().unwrap();
1496        assert!(entries.is_empty());
1497    }
1498
1499    #[test]
1500    fn file_storage_clear() {
1501        let tmp = tempfile::Builder::new()
1502            .prefix("ftui-state-persistence-")
1503            .disable_cleanup(true)
1504            .tempdir()
1505            .unwrap();
1506        let path = tmp.path().join("state.json");
1507
1508        // Create file
1509        std::fs::write(&path, "{}").unwrap();
1510        assert!(path.exists());
1511
1512        let storage = FileStorage::new(&path);
1513        storage.clear().unwrap();
1514        assert!(!path.exists());
1515    }
1516
1517    #[test]
1518    fn file_storage_creates_parent_dirs() {
1519        let tmp = tempfile::Builder::new()
1520            .prefix("ftui-state-persistence-")
1521            .disable_cleanup(true)
1522            .tempdir()
1523            .unwrap();
1524        let path = tmp.path().join("nested").join("dirs").join("state.json");
1525        let storage = FileStorage::new(&path);
1526
1527        let mut entries = HashMap::new();
1528        entries.insert(
1529            "k".to_string(),
1530            StoredEntry {
1531                key: "k".to_string(),
1532                version: 1,
1533                data: vec![],
1534            },
1535        );
1536        storage.save_all(&entries).unwrap();
1537        assert!(path.exists());
1538    }
1539
1540    #[test]
1541    fn file_storage_handles_corrupt_entry() {
1542        let tmp = tempfile::Builder::new()
1543            .prefix("ftui-state-persistence-")
1544            .disable_cleanup(true)
1545            .tempdir()
1546            .unwrap();
1547        let path = tmp.path().join("state.json");
1548
1549        // Write valid JSON but with invalid base64
1550        let mut f = std::fs::File::create(&path).unwrap();
1551        writeln!(
1552            f,
1553            r#"{{"format_version":1,"entries":{{"bad":{{"version":1,"data_base64":"!!invalid!!"}},"good":{{"version":1,"data_base64":"aGVsbG8="}}}}}}"#
1554        )
1555        .unwrap();
1556
1557        let storage = FileStorage::new(&path);
1558        let loaded = storage.load_all().unwrap();
1559
1560        // Bad entry skipped, good entry loaded
1561        assert_eq!(loaded.len(), 1);
1562        assert!(loaded.contains_key("good"));
1563        assert_eq!(loaded["good"].data, b"hello");
1564    }
1565
1566    fn one_entry(fill: u8) -> HashMap<String, StoredEntry> {
1567        let entry = StoredEntry {
1568            key: "k".to_string(),
1569            version: 1,
1570            data: vec![fill; 64 * 1024],
1571        };
1572        HashMap::from([("k".to_string(), entry)])
1573    }
1574
1575    fn temp_files_beside(path: &std::path::Path) -> Vec<std::path::PathBuf> {
1576        std::fs::read_dir(path.parent().unwrap())
1577            .unwrap()
1578            .map(|entry| entry.unwrap().path())
1579            .filter(|p| p.extension().is_some_and(|ext| ext == "tmp"))
1580            .collect()
1581    }
1582
1583    #[test]
1584    fn concurrent_saves_each_rename_a_complete_file() {
1585        // With one shared `state.json.tmp`, saves truncated each other's temp
1586        // file: readers found `state.json` empty or cut short, and saves
1587        // failed when another had already renamed the file away.
1588        let tmp = tempfile::Builder::new()
1589            .prefix("ftui-state-persistence-")
1590            .disable_cleanup(true)
1591            .tempdir()
1592            .unwrap();
1593        let path = tmp.path().join("state.json");
1594        let storage = std::sync::Arc::new(FileStorage::new(&path));
1595        storage.save_all(&one_entry(0)).unwrap();
1596
1597        let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
1598        let reader = {
1599            let (storage, stop) = (
1600                std::sync::Arc::clone(&storage),
1601                std::sync::Arc::clone(&stop),
1602            );
1603            std::thread::spawn(move || {
1604                while !stop.load(std::sync::atomic::Ordering::Relaxed) {
1605                    let loaded = storage.load_all().expect("a reader sees a whole file");
1606                    let data = &loaded["k"].data;
1607                    assert_eq!(data.len(), 64 * 1024);
1608                    assert!(data.iter().all(|&byte| byte == data[0]));
1609                }
1610            })
1611        };
1612        let writers: Vec<_> = (1..=4_u8)
1613            .map(|fill| {
1614                let storage = std::sync::Arc::clone(&storage);
1615                std::thread::spawn(move || {
1616                    for _ in 0..10 {
1617                        storage
1618                            .save_all(&one_entry(fill))
1619                            .expect("every save succeeds");
1620                    }
1621                })
1622            })
1623            .collect();
1624        for writer in writers {
1625            writer.join().unwrap();
1626        }
1627        stop.store(true, std::sync::atomic::Ordering::Relaxed);
1628        reader.join().unwrap();
1629        assert!(temp_files_beside(&path).is_empty());
1630    }
1631
1632    #[test]
1633    fn failed_save_removes_its_temporary_file() {
1634        let tmp = tempfile::Builder::new()
1635            .prefix("ftui-state-persistence-")
1636            .disable_cleanup(true)
1637            .tempdir()
1638            .unwrap();
1639        // A directory where the state file belongs makes the final rename fail.
1640        let path = tmp.path().join("state.json");
1641        std::fs::create_dir(&path).unwrap();
1642        let storage = FileStorage::new(&path);
1643        assert!(storage.save_all(&one_entry(1)).is_err());
1644        assert!(temp_files_beside(&path).is_empty());
1645    }
1646}