Mountain/ApplicationState/
mod.rs

1//! # ApplicationState Module
2//!
3//! ## Responsibilities
4//!
5//! This module defines the central, shared, thread-safe state for the entire
6//! Mountain application. It serves as the **single source of truth** for all
7//! runtime state including:
8//!
9//! **State Management:**
10//! - Main `ApplicationState` struct with all runtime state
11//! - Thread-safe access via `Arc<Mutex<...>>` wrappers
12//! - State transitions and invariants enforcement
13//! - Recovery mechanisms for corrupted state
14//! - Disk persistence for memento (workspace and global) state
15//!
16//! **Data Structures:**
17//! - Data Transfer Objects (DTOs) for various components
18//! - Type-safe state representations
19//! - Serialization/deserialization support
20//! - Validation for state updates
21//!
22//! **Internal Utilities:**
23//! - File I/O and path resolution
24//! - State initialization and loading
25//! - Extension scanning and population
26//! - URL serialization helpers
27//! - Recovery utilities for corrupted state
28//!
29//! ## Architectural Role
30//!
31//! The ApplicationState module is the **state management layer** of Mountain:
32//!
33//! ```text
34//! UI ──► Commands ──► ApplicationState (State) ──► Providers/Services
35//!                      │
36//!                      ↓
37//!                   Disk (Persistence)
38//! ```
39//!
40//! ### Design Principles:
41//! 1. **Single Source of Truth**: All state lives in one place
42//! 2. **Thread Safety**: All state is protected by Arc<Mutex<...>>
43//! 3. **Recovery-Oriented**: Comprehensive error handling and recovery
44//! 4. **Type Safety**: Strong typing at all levels
45//! 5. **Observability**: Comprehensive logging for state changes
46//!
47//! ### VS Code Reference:
48//! This module borrows from VS Code's state management patterns in:
49//! - `vs/base/parts/storage/common/storageService.ts` - Storage management
50//! - `vs/workbench/services/environment/common/environmentService.ts` -
51//!   Environment state
52//! - `vs/platform/workspace/common/workspace.ts` - Workspace state
53//! - `vs/workbench/services/extensions/common/extensions.ts` - Extension state
54//!
55//! Key concepts:
56//! - Global vs workspace-scoped storage
57//! - Memento (state serialization) for crash recovery
58//! - Thread-safe state access with proper locking
59//! - State validation and invariants
60//
61//! ## Key Components
62//!
63//! ### ApplicationState
64//! The central state struct containing all runtime state:
65//!
66//! **Workspace State:**
67//! - `WorkspaceFolders` - Currently open workspace folders
68//! - `WorkspaceConfigurationPath` - Path to workspace config
69//! - `IsTrusted` - Workspace trust status
70//! - `WindowState` - Window size, position, etc.
71//! - `ActiveDocumentURI` - Currently active document
72//!
73//! **Configuration & Storage:**
74//! - `Configuration` - Merged configuration state
75//! - `GlobalMemento` - Global storage (keys → values)
76//! - `WorkspaceMemento` - Workspace-scoped storage
77//! - Memento paths for persistence
78//!
79//! **Extension & Provider Management:**
80//! - `CommandRegistry` - Registered commands
81//! - `LanguageProviders` - Language feature providers
82//! - `ScannedExtensions` - Discovered extensions
83//! - `ExtensionScanPaths` - Paths to search for extensions
84//! - `EnabledProposedAPIs` - Proposed API permissions
85//!
86//! **Feature-specific State:**
87//! - `DiagnosticsMap` - Compiler/diagnostic errors
88//! - `OpenDocuments` - Currently open documents
89//! - `OutputChannels` - Output channel state
90//! - `ActiveTerminals` - Active terminal instances
91//! - `ActiveWebviews` - Active webview panels
92//! - `ActiveCustomDocuments` - Custom editor state
93//! - `ActiveStatusBarItems` - Status bar entries
94//! - `ActiveTreeViews` - Tree view providers
95//! - `SourceControlManagement*` - SCM provider state
96//!
97//! **IPC & UI State:**
98//! - `PendingUserInterfaceRequests` - Pending UI interactions (dialogs, etc.)
99//!
100//! ### DTOs
101//! Type-safe representations of state components:
102//! - `WorkspaceFolderStateDTO` - Workspace folder representation
103//! - `DocumentStateDTO` - Document metadata and content
104//! - `ExtensionDescriptionStateDTO` - Extension metadata
105//! - `TreeViewStateDTO` - Tree view state
106//! - `WebviewStateDTO` - Webview panel state
107//! - etc.
108//!
109//! ### Internal
110//! Helper functions for state management:
111//! - `LoadInitialMementoFromDisk` - Load persistent state from disk
112//! - `ResolveMementoStorageFilePath` - Resolve storage paths
113//! - `ScanAndPopulateExtensions` - Scan for extensions
114//! - `AnalyzeTextLinesAndEOL` - Text content analysis
115//! - Recovery utilities and error handling
116//!
117//! ## Thread Safety
118//!
119//! All state is protected by `Arc<Mutex<...>>` for thread-safe access:
120//!
121//! ```rust
122//! pub struct ApplicationState {
123//! 	pub WorkspaceFolders:Arc<Mutex<Vec<WorkspaceFolderStateDTO>>>,
124//! 	pub Configuration:Arc<Mutex<MergedConfigurationStateDTO>>,
125//! 	// ... all fields follow this pattern
126//! }
127//! ```
128//!
129//! **Best Practices:**
130//! - Always lock mutexes before accessing state
131//! - Use `map_err(MapLockError)` for lock error handling
132//! - Release locks as soon as possible (use RAII)
133//! - Avoid nested locks to prevent deadlocks
134//!
135//! ## State Persistence
136//!
137//! ### Memento System
138//! Mountain uses a memento system for state persistence:
139//!
140//! **Global Memento:**
141//! - Lives at `{AppData}/globalStorage.json`
142//! - Contains global application state
143//! - Persists across workspace changes
144//!
145//! **Workspace Memento:**
146//! - Lives at `{AppData}/workspaceStorage/{workspace-id}/storage.json`
147//! - Contains workspace-specific state
148//! - Changes when workspace changes
149//!
150//! **Recovery:**
151//! - Corrupted JSON files are backed up with timestamps
152//! - Empty maps are returned on parse errors
153//! - Directories are created automatically
154//!
155//! ## Error Handling
156//!
157//! All state operations return `Result<T, CommonError>` where:
158//! - `Ok(T)` - Successful operation with result
159//! - `Err(CommonError)` - Error with context
160//!
161//! Error types:
162//! - `StateLockPoisoned` - Mutex was poisoned (another thread panicked)
163//! - `FileSystemIO` - File system operations failed
164//! - `SerializationError` - JSON parsing failed
165//! - `Unknown` - Uncategorized errors
166//!
167//! Recovery mechanisms:
168//! - `MapLockErrorWithRecovery` - Attempt recovery from poisoned locks
169//! - `SafeStateOperation` - Safe state operation with recovery
170//! - `RecoverApplicationState` - Comprehensive state recovery
171//!
172//! ## State Transitions
173//!
174//! Valid state transitions:
175//!
176//! ```text
177//! Uninitialized → Default State → Workspace Loaded → Workspace Unloaded
178//!      ↓                ↓                 ↓                  ↓
179//!    Load           Recover          Update Memento      Clean Up
180//! ```
181//!
182//! **Invariants:**
183//! - Workspace identifier is computed from folder or config
184//! - Memento paths are synced with workspace changes
185//! - Provider handles are monotonically increasing
186//! - Unique IDs are never reused
187//!
188//! ## TODOs
189//!
190//! High Priority:
191//! - [ ] Add state migration support for version changes
192//! - [ ] Implement state diffing for better debugging
193//! - [ ] Add state snapshots for rollback support
194//!
195//! Medium Priority:
196//! - [ ] Add state compression for large workspaces
197//! - [ ] Implement incremental memento updates
198//! - [ ] Add state validation on load
199//!
200//! Low Priority:
201//! - [ ] Add state analytics and metrics
202//! - [ ] Implement state cloning for testing
203//! - [ ] Add state export/import functionality
204
205// --- Public Modules ---
206
207/// State management sub-modules.
208pub mod State;
209
210/// Internal utility sub-modules for persistence, scanning, etc.
211pub mod Internal;
212
213/// Data Transfer Objects for serialization.
214pub mod DTO;
215
216// --- Re-exports for backward compatibility ---
217
218/// Re-export the main ApplicationState struct and helpers for backward
219/// compatibility
220pub use State::ApplicationState::{ApplicationState, MapLockError, MapLockErrorWithRecovery, StateOperationResult};
221pub use State::{ConfigurationState, ExtensionState, FeatureState, UIState, WorkspaceState};
222pub use Internal::{ExtensionScanner, PathResolution, Persistence, Recovery, Serialization, TextProcessing};