Skip to main content

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

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