Skip to main content

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

1#![allow(non_snake_case)]
2
3//! Best-effort synchronous memento loader for `ApplicationState`'s
4//! `default()` path. Failures don't propagate - corrupted files are
5//! backed up, missing directories are created, and an empty map is
6//! returned so initialisation always succeeds.
7
8use std::{collections::HashMap, fs, path::Path};
9
10use serde_json::Value;
11
12use crate::{ApplicationState::Internal::Persistence::MementoLoader::AttemptMementoRecovery, dev_log};
13
14pub fn Fn(StorageFilePath:&Path) -> HashMap<String, Value> {
15	if !StorageFilePath.exists() {
16		dev_log!(
17			"storage",
18			"[MementoLoader] Memento file does not exist: {}",
19			StorageFilePath.display()
20		);
21		return HashMap::new();
22	}
23
24	match fs::read_to_string(StorageFilePath) {
25		Ok(Content) => {
26			serde_json::from_str(&Content).unwrap_or_else(|Error| {
27				dev_log!(
28					"storage",
29					"error: [MementoLoader] Failed to parse JSON from '{}': {}. Attempting recovery.",
30					StorageFilePath.display(),
31					Error
32				);
33				AttemptMementoRecovery::Fn(StorageFilePath, &Content);
34				HashMap::new()
35			})
36		},
37		Err(Error) => {
38			dev_log!(
39				"storage",
40				"error: [MementoLoader] Failed to read '{}': {}. Attempting recovery.",
41				StorageFilePath.display(),
42				Error
43			);
44			if let Some(Parent) = StorageFilePath.parent()
45				&& !Parent.exists()
46				&& let Err(DirError) = fs::create_dir_all(Parent)
47			{
48				dev_log!(
49					"storage",
50					"warn: [MementoLoader] Failed to create directory '{}': {}",
51					Parent.display(),
52					DirError
53				);
54			}
55			HashMap::new()
56		},
57	}
58}