Skip to main content

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

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