use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; use serde::{Deserialize, Serialize}; use crate::types::*; /// Everything the server needs to survive a restart, in one JSON blob. /// Written atomically (tmp file + rename) on every mutation. #[derive(Serialize, Deserialize)] pub struct Snapshot { pub users: Vec, pub signup_keys: HashMap, pub invites: HashMap, pub links: HashSet, // Vec of pairs because JSON object keys must be strings pub positions: Vec<(DirectedLink, RingBuffer)>, pub admin_id: Option, } /// Resolves the on-disk state file location. Overridable with `PP_DATA_PATH`. pub fn data_path() -> PathBuf { std::env::var("PP_DATA_PATH") .map(PathBuf::from) .unwrap_or_else(|_| PathBuf::from("data/state.json")) } /// Loads a snapshot from disk. Returns `None` if the file doesn't exist. /// Panics on a corrupt file: silently starting fresh would wipe user data on /// the next save. pub fn load(path: &Path) -> Option { let bytes = match std::fs::read(path) { Ok(b) => b, Err(e) if e.kind() == std::io::ErrorKind::NotFound => return None, Err(e) => panic!("failed to read state file {}: {e}", path.display()), }; let snapshot = serde_json::from_slice(&bytes) .unwrap_or_else(|e| panic!("corrupt state file {}: {e}", path.display())); return Some(snapshot); } /// Snapshots the whole state and writes it to disk atomically. /// Failures are logged but never bubble up to the client: the data is still /// live in memory, so the request itself did succeed. pub async fn persist(state: &AppState) { let snapshot = { let users = state.users.lock().await; let signup_keys = state.signup_keys.lock().await; let invites = state.invites.lock().await; let links = state.links.lock().await; let positions = state.positions.lock().await; let admin_id = state.admin_id.lock().await; Snapshot { users: users.clone(), signup_keys: signup_keys.clone(), invites: invites.clone(), links: links.clone(), positions: positions.iter().map(|(k, v)| (k.clone(), v.clone())).collect(), admin_id: admin_id.clone(), } }; if let Err(e) = write_snapshot(&state.data_path, &snapshot).await { eprintln!("failed to persist state to {}: {e}", state.data_path.display()); } } async fn write_snapshot(path: &Path, snapshot: &Snapshot) -> std::io::Result<()> { let json = serde_json::to_vec_pretty(snapshot)?; if let Some(parent) = path.parent() { if !parent.as_os_str().is_empty() { tokio::fs::create_dir_all(parent).await?; } } // atomic-ish: readers never observe a half-written file let tmp = path.with_extension("json.tmp"); tokio::fs::write(&tmp, &json).await?; tokio::fs::rename(&tmp, path).await?; return Ok(()); }