Skip to main content

Mountain/ApplicationState/Internal/Persistence/MementoLoader/
LoadMementoWithRecovery.rs

1//! Result-typed memento loader. Returns `Ok(empty)` for missing
2//! files, `Err(FileSystemIO)` for read failures, and
3//! `Err(SerializationError)` for parse failures (with a timestamped
4//! corruption backup written as a side effect). Used during recovery
5//! flows where the caller needs to know that loading actually
6//! failed.
7
8use std::{collections::HashMap, fs, path::Path};
9
10use CommonLibrary::Error::CommonError::CommonError;
11use serde_json::Value;
12
13use crate::{ApplicationState::Internal::Persistence::MementoLoader::CreateCorruptedBackup, dev_log};
14
15pub fn Fn(StorageFilePath:&Path) -> Result<HashMap<String, Value>, CommonError> {
16	if !StorageFilePath.exists() {
17		dev_log!(
18			"storage",
19			"[MementoLoader] Memento file does not exist: {}",
20			StorageFilePath.display()
21		);
22
23		return Ok(HashMap::new());
24	}
25
26	let Content = fs::read_to_string(StorageFilePath).map_err(|E| {
27		CommonError::FileSystemIO {
28			Path:StorageFilePath.to_path_buf(),
29			Description:format!("Failed to read memento file: {}", E),
30		}
31	})?;
32
33	serde_json::from_str(&Content).map_err(|E| {
34		CreateCorruptedBackup::Fn(StorageFilePath, &Content);
35		CommonError::SerializationError {
36			Description:format!("Failed to parse memento JSON from '{}': {}", StorageFilePath.display(), E),
37		}
38	})
39}