Skip to main content

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 serde_json::Value;
209use tokio::fs;
210
211use super::{MountainEnvironment::MountainEnvironment, Utility};
212use crate::dev_log;
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		dev_log!(
222			"storage",
223			"[StorageProvider] Getting value from {} scope for key: {}",
224			ScopeName,
225			Key
226		);
227
228		// Validate key to prevent injection or invalid storage paths
229		if Key.is_empty() {
230			return Ok(None);
231		}
232
233		if Key.len() > 1024 {
234			return Err(CommonError::InvalidArgument {
235				ArgumentName:"Key".into(),
236				Reason:"Key length exceeds maximum allowed length of 1024 characters".into(),
237			});
238		}
239
240		let StorageMapMutex = if IsGlobalScope {
241			&self.ApplicationState.Configuration.MementoGlobalStorage
242		} else {
243			&self.ApplicationState.Configuration.MementoWorkspaceStorage
244		};
245
246		let StorageMapGuard = StorageMapMutex
247			.lock()
248			.map_err(Utility::MapApplicationStateLockErrorToCommonError)?;
249
250		Ok(StorageMapGuard.get(Key).cloned())
251	}
252
253	/// Updates or deletes a value in either global or workspace storage.
254	/// Includes comprehensive validation for key length, value size, and JSON
255	/// validity.
256	async fn UpdateStorageValue(
257		&self,
258
259		IsGlobalScope:bool,
260
261		Key:String,
262
263		ValueToSet:Option<Value>,
264	) -> Result<(), CommonError> {
265		let ScopeName = if IsGlobalScope { "Global" } else { "Workspace" };
266
267		if crate::IPC::DevLog::IsShort() {
268			crate::dev_log!("storage", "update {} {}", ScopeName, Key);
269		} else {
270			dev_log!(
271				"storage",
272				"[StorageProvider] Updating value in {} scope for key: {}",
273				ScopeName,
274				Key
275			);
276		}
277
278		// Validate key to prevent injection or invalid storage paths
279		if Key.is_empty() {
280			return Err(CommonError::InvalidArgument {
281				ArgumentName:"Key".into(),
282				Reason:"Key cannot be empty".into(),
283			});
284		}
285
286		if Key.len() > 1024 {
287			return Err(CommonError::InvalidArgument {
288				ArgumentName:"Key".into(),
289				Reason:"Key length exceeds maximum allowed length of 1024 characters".into(),
290			});
291		}
292
293		// If setting a value, validate it's not too large
294		if let Some(ref value) = ValueToSet {
295			if let Ok(json_string) = serde_json::to_string(value) {
296				if json_string.len() > 10 * 1024 * 1024 {
297					// 10MB limit per value
298					return Err(CommonError::InvalidArgument {
299						ArgumentName:"ValueToSet".into(),
300						Reason:"Value size exceeds maximum allowed size of 10MB".into(),
301					});
302				}
303			}
304		}
305
306		let (StorageMapMutex, StoragePathOption) = if IsGlobalScope {
307			(
308				self.ApplicationState.Configuration.MementoGlobalStorage.clone(),
309				Some(
310					self.ApplicationState
311						.GlobalMementoPath
312						.lock()
313						.map_err(Utility::MapApplicationStateLockErrorToCommonError)?
314						.clone(),
315				),
316			)
317		} else {
318			(
319				self.ApplicationState.Configuration.MementoWorkspaceStorage.clone(),
320				self.ApplicationState
321					.WorkspaceMementoPath
322					.lock()
323					.map_err(Utility::MapApplicationStateLockErrorToCommonError)?
324					.clone(),
325			)
326		};
327
328		// Perform the in-memory update.
329		let DataToSave = {
330			let mut StorageMapGuard = StorageMapMutex
331				.lock()
332				.map_err(Utility::MapApplicationStateLockErrorToCommonError)?;
333
334			if let Some(Value) = ValueToSet {
335				StorageMapGuard.insert(Key, Value);
336			} else {
337				StorageMapGuard.remove(&Key);
338			}
339
340			StorageMapGuard.clone()
341		};
342
343		if let Some(StoragePath) = StoragePathOption {
344			tokio::spawn(async move {
345				SaveStorageToDisk(StoragePath, DataToSave).await;
346			});
347		}
348
349		Ok(())
350	}
351
352	/// Retrieves the entire storage map for a given scope.
353	async fn GetAllStorage(&self, IsGlobalScope:bool) -> Result<Value, CommonError> {
354		let ScopeName = if IsGlobalScope { "Global" } else { "Workspace" };
355
356		dev_log!("storage", "[StorageProvider] Getting all values from {} scope.", ScopeName);
357
358		let StorageMapMutex = if IsGlobalScope {
359			&self.ApplicationState.Configuration.MementoGlobalStorage
360		} else {
361			&self.ApplicationState.Configuration.MementoWorkspaceStorage
362		};
363
364		let StorageMapGuard = StorageMapMutex
365			.lock()
366			.map_err(Utility::MapApplicationStateLockErrorToCommonError)?;
367
368		Ok(serde_json::to_value(&*StorageMapGuard)?)
369	}
370
371	/// Overwrites the entire storage map for a given scope and persists it.
372	async fn SetAllStorage(&self, IsGlobalScope:bool, FullState:Value) -> Result<(), CommonError> {
373		let ScopeName = if IsGlobalScope { "Global" } else { "Workspace" };
374
375		dev_log!("storage", "[StorageProvider] Setting all values for {} scope.", ScopeName);
376
377		let DeserializedState:HashMap<String, Value> = serde_json::from_value(FullState)?;
378
379		let (StorageMapMutex, StoragePathOption) = if IsGlobalScope {
380			(
381				self.ApplicationState.Configuration.MementoGlobalStorage.clone(),
382				Some(
383					self.ApplicationState
384						.GlobalMementoPath
385						.lock()
386						.map_err(Utility::MapApplicationStateLockErrorToCommonError)?
387						.clone(),
388				),
389			)
390		} else {
391			(
392				self.ApplicationState.Configuration.MementoWorkspaceStorage.clone(),
393				self.ApplicationState
394					.WorkspaceMementoPath
395					.lock()
396					.map_err(Utility::MapApplicationStateLockErrorToCommonError)?
397					.clone(),
398			)
399		};
400
401		// Update in-memory state
402		*StorageMapMutex
403			.lock()
404			.map_err(Utility::MapApplicationStateLockErrorToCommonError)? = DeserializedState.clone();
405
406		// Persist to disk asynchronously
407		if let Some(StoragePath) = StoragePathOption {
408			tokio::spawn(async move {
409				SaveStorageToDisk(StoragePath, DeserializedState).await;
410			});
411		}
412
413		Ok(())
414	}
415}
416
417// --- Internal Helper Functions ---
418
419/// An internal helper function to asynchronously write the storage map to a
420/// file.
421async fn SaveStorageToDisk(Path:PathBuf, Data:HashMap<String, Value>) {
422	dev_log!("storage", "[StorageProvider] Persisting storage to disk: {}", Path.display());
423
424	match serde_json::to_string_pretty(&Data) {
425		Ok(JSONString) => {
426			if let Some(ParentDirectory) = Path.parent() {
427				if let Err(Error) = fs::create_dir_all(ParentDirectory).await {
428					dev_log!(
429						"storage",
430						"error: [StorageProvider] Failed to create parent directory for '{}': {}",
431						Path.display(),
432						Error
433					);
434
435					return;
436				}
437			}
438
439			if let Err(Error) = fs::write(&Path, JSONString).await {
440				dev_log!(
441					"storage",
442					"error: [StorageProvider] Failed to write storage file to '{}': {}",
443					Path.display(),
444					Error
445				);
446			}
447		},
448
449		Err(Error) => {
450			dev_log!(
451				"storage",
452				"error: [StorageProvider] Failed to serialize storage data for '{}': {}",
453				Path.display(),
454				Error
455			);
456		},
457	}
458}