Mountain/Environment/
StorageProvider.rs

1//! # StorageProvider (Environment)
2//!
3//! Implements the `StorageProvider` trait for `MountainEnvironment`, providing
4//! persistent key-value storage for extensions and application components.
5//!
6//! ## RESPONSIBILITIES
7//!
8//! ### 1. Storage Management
9//! - Provide global storage (shared across all workspaces)
10//! - Provide workspace-scoped storage (per workspace)
11//! - Support namespaced keys to avoid collisions
12//! - Handle storage quota limits
13//!
14//! ### 2. CRUD Operations
15//! - `Get(scope, key)`: Retrieve value by key
16//! - `Set(scope, key, value)`: Store value (create or update)
17//! - `Remove(scope, key)`: Delete key-value pair
18//! - `Clear(scope)`: Remove all keys in a scope
19//! - `Keys(scope)`: List all keys in a scope
20//!
21//! ### 3. Data Persistence
22//! - Write storage changes to disk immediately
23//! - Load storage from disk on startup
24//! - Handle corrupted storage files with recovery
25//! - Backup storage before writes (optional)
26//!
27//! ### 4. Type Safety
28//! - Store and retrieve arbitrary JSON-serializable values
29//! - Handle serialization/deserialization errors
30//! - Support primitive types and complex objects
31//!
32//! ## ARCHITECTURAL ROLE
33//!
34//! StorageProvider is the **persistent key-value store** for Mountain:
35//!
36//! ```text
37//! Extension ──► StorageProvider ──► Disk (JSON files)
38//!                      │
39//!                      └─► ApplicationState (Cache)
40//! ```
41//!
42//! ### Position in Mountain
43//! - `Environment` module: Persistence capability provider
44//! - Implements `CommonLibrary::Storage::StorageProvider` trait
45//! - Accessible via `Environment.Require<dyn StorageProvider>()`
46//!
47//! ### Storage Scopes
48//! - **Global**: `{AppData}/User/globalStorage.json`
49//!   - Shared across all workspaces
50//!   - Used for user preferences, extension state
51//! - **Workspace**:
52//!   `{AppData}/User/workspaceStorage/{workspace-id}/storage.json`
53//!   - Specific to current workspace
54//!   - Used for workspace-specific settings and state
55//!
56//! ### Storage Format
57//! - JSON file with simple key-value pairs
58//! - Values are `serde_json::Value` (any JSON type)
59//! - Keys are strings with namespace prefix (e.g., "extensionId.setting")
60//!
61//! ### Dependencies
62//! - `ApplicationState`: Access to global/workspace memento maps
63//! - `FileSystemWriter`: To persist storage to disk
64//! - `Log`: Storage change logging
65//!
66//! ### Dependents
67//! - Extensions: Store extension-specific state
68//! - `ConfigurationProvider`: Uses global storage for user settings
69//! - `ExtensionManagement`: Store extension metadata
70//! - Any component needing persistent settings
71//!
72//! ## STORAGE LIFECYCLE
73//!
74//! 1. **App Start**: `ApplicationState::default()` loads global and workspace
75//!    memento
76//! 2. **Workspace Change**: `UpdateWorkspaceMementoPathAndReload()` loads new
77//!    workspace storage
78//! 3. **Runtime**: Providers read/write to in-memory maps (`GlobalMemento`,
79//!    `WorkspaceMemento`)
80//! 4. **Shutdown**: `ApplicationRunTime::SaveApplicationState()` writes memento
81//!    to disk
82//! 5. **Crash Recovery**: `Internal::LoadInitialMementoFromDisk()` with
83//!    backup/restore
84//!
85//! ## ERROR HANDLING
86//!
87//! - Disk full: `CommonError::FileSystemIO`
88//! - Permission denied: `CommonError::FileSystemIO`
89//! - JSON parse error: `CommonError::SerializationError` (with recovery)
90//! - Quota exceeded: `CommonError::StorageFull` (TODO)
91//!
92//! ## PERFORMANCE
93//!
94//! - All storage operations are in-memory (fast)
95//! - Disk writes are async and batched
96//! - Consider size limits (configurable max per storage file)
97//! - Large values (>1MB) should be stored in files, not storage
98//!
99//! ## RECOVERY MECHANISMS
100//!
101//! - Corrupted JSON files are backed up with timestamps
102//! - On parse error, storage is reset to empty and continues
103//! - Directories are created automatically
104//! - Writes are atomic (write to temp, then rename)
105//!
106//! ## VS CODE REFERENCE
107//!
108//! Patterns from VS Code:
109//! - `vs/platform/storage/common/storageService.ts` - Storage service
110//! - `vs/platform/storage/common/memento.ts` - Memento pattern for state
111//!
112//! ## TODO
113//!
114//! - [ ] Implement storage quotas (per-extension limits)
115//! - [ ] Add storage encryption for sensitive data
116//! - [ ] Support storage compression for large datasets
117//! - [ ] Implement storage migration/versioning
118//! - [ ] Add storage inspection and debugging tools
119//! - [ ] Support storage syncing across devices (via Air)
120//! - [ ] Implement storage TTL (time-to-live) for auto-expiring keys
121//! - [ ] Add storage subscriptions/notifications on change
122//! - [ ] Support binary data storage (not just JSON)
123//! - [ ] Implement storage transactions (batch operations with rollback)
124//!
125//! ## MODULE CONTENTS
126//!
127//! - [`StorageProvider`]: Main struct implementing the trait
128//! - Storage access methods (Get, Set, Remove, Clear, Keys)
129//! - Memento loading and saving
130//! - Recovery and backup logic
131
132// Responsibilities:
133//   - Core logic for Memento storage operations.
134//   - Reading from and writing to global and workspace JSON storage files.
135//   - Provides both per-key and high-performance batch operations.
136//   - Enhances keychain integration with the `keyring` crate for secure storage.
137//   - Adds secure storage with encryption for sensitive data.
138//   - Handles storage errors gracefully with proper error handling.
139//   - Manages storage file location and directory creation.
140//   - Supports both global (application-level) and workspace-specific storage.
141//
142// TODOs:
143//   - Implement encryption for sensitive data in JSON storage
144//   - Add storage migration support for version upgrades
145//   - Implement storage compression for large datasets
146//   - Add storage change notifications and watchers
147//   - Implement storage quota management
148//   - Add storage backup and restore functionality
149//   - Support storage sync across multiple devices
150//   - Implement storage conflict resolution
151//   - Add storage validation and schema checking
152//   - Support storage transaction support for atomic operations
153//   - Implement storage garbage collection for deprecated keys
154//   - Add storage performance metrics and optimization
155//   - Support storage for secrets via the SecretProvider (keychain)
156//   - Implement cache invalidation on external changes
157//
158// Inspired by VSCode's secrets service which:
159// - Uses operating system keychain for secure secret storage
160// - Provides consistent API across platforms
161// - Handles keychain access failures gracefully
162// - Implements secret encryption and secure storage
163// - Supports secret sharing between processes
164//
165// ## Storage Scopes
166//
167// 1. **Global Storage**: Application-level settings that persist across all workspaces
168//    - Location: App config directory (platform-specific)
169//    - File: `global.json` or similar
170//    - Scope: `IsGlobalScope = true`
171//    - Use case: User preferences, extension settings
172//
173// 2. **Workspace Storage**: Workspace-specific settings and state
174//    - Location: Within workspace directory (usually `.vscode/storage`)
175//    - File: `workspace.json`
176//    - Scope: `IsGlobalScope = false`
177//    - Use case: Workspace-specific configurations, workspace state
178//
179// ## Storage Operations
180//
181// - **GetStorageValue**: Retrieve a single key value
182// - **UpdateStorageValue**: Set or delete a single key value
183// - **GetAllStorage**: Retrieve the entire storage map
184// - **SetAllStorage**: Replace the entire storage map
185//
186// Persistence is handled asynchronously via `tokio::spawn` to avoid blocking
187// the main thread while writing to disk.
188//
189// ## Error Handling
190//
191// The provider handles various error conditions:
192// - File I/O errors (read/write/creation)
193// - Serialization/deserialization errors
194// - Directory creation failures
195// - Lock poisoning from concurrent access
196// - Missing permissions for storage paths
197
198//! # StorageProvider Implementation
199//!
200//! Implements the `StorageProvider` trait for the `MountainEnvironment`. This
201//! provider contains the core logic for Memento storage operations, including
202//! reading from and writing to the appropriate JSON storage files on disk.
203
204use std::{collections::HashMap, path::PathBuf};
205
206use CommonLibrary::{Error::CommonError::CommonError, Storage::StorageProvider::StorageProvider};
207use async_trait::async_trait;
208use log::{error, info, trace};
209use serde_json::Value;
210use tokio::fs;
211
212use super::{MountainEnvironment::MountainEnvironment, Utility};
213
214#[async_trait]
215impl StorageProvider for MountainEnvironment {
216	/// Retrieves a value from either global or workspace storage.
217	/// Includes defensive validation to prevent invalid keys and invalid JSON.
218	async fn GetStorageValue(&self, IsGlobalScope:bool, Key:&str) -> Result<Option<Value>, CommonError> {
219		let ScopeName = if IsGlobalScope { "Global" } else { "Workspace" };
220
221		trace!("[StorageProvider] Getting value from {} scope for key: {}", ScopeName, Key);
222
223		// Validate key to prevent injection or invalid storage paths
224		if Key.is_empty() {
225			return Ok(None);
226		}
227
228		if Key.len() > 1024 {
229			return Err(CommonError::InvalidArgument {
230				ArgumentName:"Key".into(),
231				Reason:"Key length exceeds maximum allowed length of 1024 characters".into(),
232			});
233		}
234
235		let StorageMapMutex = if IsGlobalScope {
236			&self.ApplicationState.Configuration.MementoGlobalStorage
237		} else {
238			&self.ApplicationState.Configuration.MementoWorkspaceStorage
239		};
240
241		let StorageMapGuard = StorageMapMutex
242			.lock()
243			.map_err(Utility::MapApplicationStateLockErrorToCommonError)?;
244
245		Ok(StorageMapGuard.get(Key).cloned())
246	}
247
248	/// Updates or deletes a value in either global or workspace storage.
249	/// Includes comprehensive validation for key length, value size, and JSON
250	/// validity.
251	async fn UpdateStorageValue(
252		&self,
253
254		IsGlobalScope:bool,
255
256		Key:String,
257
258		ValueToSet:Option<Value>,
259	) -> Result<(), CommonError> {
260		let ScopeName = if IsGlobalScope { "Global" } else { "Workspace" };
261
262		info!("[StorageProvider] Updating value in {} scope for key: {}", ScopeName, Key);
263
264		// Validate key to prevent injection or invalid storage paths
265		if Key.is_empty() {
266			return Err(CommonError::InvalidArgument {
267				ArgumentName:"Key".into(),
268				Reason:"Key cannot be empty".into(),
269			});
270		}
271
272		if Key.len() > 1024 {
273			return Err(CommonError::InvalidArgument {
274				ArgumentName:"Key".into(),
275				Reason:"Key length exceeds maximum allowed length of 1024 characters".into(),
276			});
277		}
278
279		// If setting a value, validate it's not too large
280		if let Some(ref value) = ValueToSet {
281			if let Ok(json_string) = serde_json::to_string(value) {
282				if json_string.len() > 10 * 1024 * 1024 {
283					// 10MB limit per value
284					return Err(CommonError::InvalidArgument {
285						ArgumentName:"ValueToSet".into(),
286						Reason:"Value size exceeds maximum allowed size of 10MB".into(),
287					});
288				}
289			}
290		}
291
292		let (StorageMapMutex, StoragePathOption) = if IsGlobalScope {
293			(
294				self.ApplicationState.Configuration.MementoGlobalStorage.clone(),
295				Some(self.ApplicationState.GlobalMementoPath.clone()),
296			)
297		} else {
298			(
299				self.ApplicationState.Configuration.MementoWorkspaceStorage.clone(),
300				self.ApplicationState
301					.WorkspaceMementoPath
302					.lock()
303					.map_err(Utility::MapApplicationStateLockErrorToCommonError)?
304					.clone(),
305			)
306		};
307
308		// Perform the in-memory update.
309		let DataToSave = {
310			let mut StorageMapGuard = StorageMapMutex
311				.lock()
312				.map_err(Utility::MapApplicationStateLockErrorToCommonError)?;
313
314			if let Some(Value) = ValueToSet {
315				StorageMapGuard.insert(Key, Value);
316			} else {
317				StorageMapGuard.remove(&Key);
318			}
319
320			StorageMapGuard.clone()
321		};
322
323		if let Some(StoragePath) = StoragePathOption {
324			tokio::spawn(async move {
325				SaveStorageToDisk(StoragePath, DataToSave).await;
326			});
327		}
328
329		Ok(())
330	}
331
332	/// Retrieves the entire storage map for a given scope.
333	async fn GetAllStorage(&self, IsGlobalScope:bool) -> Result<Value, CommonError> {
334		let ScopeName = if IsGlobalScope { "Global" } else { "Workspace" };
335
336		trace!("[StorageProvider] Getting all values from {} scope.", ScopeName);
337
338		let StorageMapMutex = if IsGlobalScope {
339			&self.ApplicationState.Configuration.MementoGlobalStorage
340		} else {
341			&self.ApplicationState.Configuration.MementoWorkspaceStorage
342		};
343
344		let StorageMapGuard = StorageMapMutex
345			.lock()
346			.map_err(Utility::MapApplicationStateLockErrorToCommonError)?;
347
348		Ok(serde_json::to_value(&*StorageMapGuard)?)
349	}
350
351	/// Overwrites the entire storage map for a given scope and persists it.
352	async fn SetAllStorage(&self, IsGlobalScope:bool, FullState:Value) -> Result<(), CommonError> {
353		let ScopeName = if IsGlobalScope { "Global" } else { "Workspace" };
354
355		info!("[StorageProvider] Setting all values for {} scope.", ScopeName);
356
357		let DeserializedState:HashMap<String, Value> = serde_json::from_value(FullState)?;
358
359		let (StorageMapMutex, StoragePathOption) = if IsGlobalScope {
360			(
361				self.ApplicationState.Configuration.MementoGlobalStorage.clone(),
362				Some(self.ApplicationState.GlobalMementoPath.clone()),
363			)
364		} else {
365			(
366				self.ApplicationState.Configuration.MementoWorkspaceStorage.clone(),
367				self.ApplicationState
368					.WorkspaceMementoPath
369					.lock()
370					.map_err(Utility::MapApplicationStateLockErrorToCommonError)?
371					.clone(),
372			)
373		};
374
375		// Update in-memory state
376		*StorageMapMutex
377			.lock()
378			.map_err(Utility::MapApplicationStateLockErrorToCommonError)? = DeserializedState.clone();
379
380		// Persist to disk asynchronously
381		if let Some(StoragePath) = StoragePathOption {
382			tokio::spawn(async move {
383				SaveStorageToDisk(StoragePath, DeserializedState).await;
384			});
385		}
386
387		Ok(())
388	}
389}
390
391// --- Internal Helper Functions ---
392
393/// An internal helper function to asynchronously write the storage map to a
394/// file.
395async fn SaveStorageToDisk(Path:PathBuf, Data:HashMap<String, Value>) {
396	trace!("[StorageProvider] Persisting storage to disk: {}", Path.display());
397
398	match serde_json::to_string_pretty(&Data) {
399		Ok(JSONString) => {
400			if let Some(ParentDirectory) = Path.parent() {
401				if let Err(Error) = fs::create_dir_all(ParentDirectory).await {
402					error!(
403						"[StorageProvider] Failed to create parent directory for '{}': {}",
404						Path.display(),
405						Error
406					);
407
408					return;
409				}
410			}
411
412			if let Err(Error) = fs::write(&Path, JSONString).await {
413				error!(
414					"[StorageProvider] Failed to write storage file to '{}': {}",
415					Path.display(),
416					Error
417				);
418			}
419		},
420
421		Err(Error) => {
422			error!(
423				"[StorageProvider] Failed to serialize storage data for '{}': {}",
424				Path.display(),
425				Error
426			);
427		},
428	}
429}