epoch_forge/lib_efo/src/epoch_struct.rs

300 lines
9.9 KiB
Rust
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! # Epoch configuration and state
//!
//! The *epoch* system is deliberately split into two tiny, serialisable
//! structures so that the binary can quickly read/write its “current
//! position” without pulling the whole world into memory.
//!
//! * `EpochConfig` – lives in `.epochconfig`. It only remembers
//! which epoch folder should be considered “current” and a few
//! convenience fields (tags, path). It never holds any event or
//! world data.
//!
//! * `EpochInfo` – stored inside `epoch/<epoch_id>/.epochinfo`.
//! This file contains the *metadata* for that particular epoch
//! (seed, selected events, parent link, etc.). Again, it does **not**
//! hold the full world; that is handled elsewhere in the engine.
//!
//! Keeping these two structs tiny means that switching epochs, logging,
//! or resetting can be done by reading/writing a handful of JSON/YAML
//! files, just like a git repository tracks its commits and
//! `HEAD` pointer.
use clap::error::ErrorKind;
use serde::{Deserialize, Serialize};
use std::io::Write;
use std::str::FromStr;
use std::{
collections::HashMap,
fmt,
fs::{File, read_to_string},
path::Path,
};
use crate::{epoch_struct, error::EpochError};
/// The file written to *~/.epochconfig* that tells the CLI which
/// epoch folder is the “current” one.
///
/// Only the minimal information needed for fast switches is stored:
/// * the numeric identifier of the selected epoch,
/// * a list of human‑readable tags,
/// * the absolute path to the epoch’s directory.
///
/// No world or event data lives here – it is purely a lightweight pointer.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EpochConfig {
/// The epoch ID that the binary should consider “current”.
pub epoch_id: EpochId,
/// Optional human‑friendly tags (e.g. `"winter‑B"`, `"post‑war"`).
pub tags: HashMap<String, EpochId>,
// /// Absolute path to `epoch/<epoch_id>/`.
// pub path: PathBuf,
/// A hashmap containing the name of all existing epochs, only loaded in memory if used
// TODO: Only serialize epoch valid folders and map EpochId instead of Strings ?
#[serde(skip)]
pub list_existing_epochs: HashMap<String, Option<EpochInfo>>,
}
impl EpochConfig {
/// Create an empty config, mainly for initialisation
pub fn empty() -> Self {
EpochConfig {
epoch_id: EpochId::new(0),
tags: HashMap::new(),
list_existing_epochs: HashMap::new(),
}
}
/// Create a new config from an existig path
pub fn new_from_path(_path: Option<&Path>) -> Result<Self, EpochError> {
let path = Path::new(".").join(".epoch");
if path.is_file() {
// TODO: write a trait for this
let config: EpochConfig =
serde_json::from_str(&read_to_string(&path)?).map_err(|e| EpochError::Serde {
source: e,
file_name: path.to_string_lossy().to_string(),
help: None,
})?;
Ok(config.initialize()?)
} else {
Err(EpochError::MainFolderInvalid(".".into()))
}
}
/// Initialize the epoch more in depth
fn initialize(mut self) -> Result<Self, EpochError> {
let path = Path::new(".").read_dir()?;
// let mut valid_folders = HashMap::new();
for elt in path {
let elt = elt?;
if elt.file_type()?.is_dir() {
self.list_existing_epochs
.insert(elt.file_name().to_string_lossy().into_owned(), None);
}
}
Ok(self)
}
/// Try to load into memory the given epoch id
pub fn try_load(&mut self, epoch_id: &EpochId) -> Result<(), EpochError> {
// TODO: Cleanse this abomination
let _ep = self
.list_existing_epochs
.contains_key(&epoch_id.to_string())
.then_some(epoch_id)
.ok_or(EpochError::EpochFolderMissing(*epoch_id, ".".into()))
.copied()?;
let path = Path::new(&epoch_id.to_string()).join(".epochinfo");
let maybe_epoch: EpochInfo =
serde_json::from_str(&read_to_string(&path)?).map_err(|e| EpochError::Serde {
source: e,
file_name: path.to_string_lossy().to_string(),
help: None,
})?;
let value = self
.list_existing_epochs
.get_mut(&epoch_id.to_string())
.unwrap();
*value = Some(maybe_epoch);
Ok(())
}
/// Get an identifier or returns None
pub fn get(&self, id: &EpochIdentifier) -> Result<EpochId, EpochError> {
match id {
EpochIdentifier::Tag(s) => self
.tags
.get(s)
.copied()
.ok_or(EpochError::AmbiguousTag(s.to_string())),
EpochIdentifier::Id(epoch_id) => self
.list_existing_epochs
.contains_key(&epoch_id.to_string())
.then_some(epoch_id)
.ok_or(EpochError::EpochFolderMissing(*epoch_id, ".".into()))
.copied(),
}
}
}
/// Trait representing a serialisable / writable config
pub trait ConfigWritable: Serialize {
/// Where to save the config
fn save_path(&self) -> String;
/// Have the config as JSON
fn as_json(&self, action: String) -> Result<String, EpochError> {
serde_json::to_string_pretty(self).map_err(|e| EpochError::Serde {
source: e,
file_name: action,
help: None,
})
}
/// Save the config into it's nominal path
fn save(
&self,
action: String,
do_not_erase: SaveMode,
// advice: Option<String>,
) -> Result<(), EpochError> {
let mut f = match do_not_erase {
SaveMode::Erase => File::create(self.save_path()),
SaveMode::DoNotErase => File::create_new(self.save_path()),
}
.map_err(|e| EpochError::ConfigCreation(self.save_path(), e))?;
write!(f, "{}", self.as_json(action)?).map_err(EpochError::ConfigWrite)?;
Ok(())
}
}
/// The metadata file stored inside each epoch directory
/// (`epoch/<epoch_id>/.epochinfo`).
///
/// It contains only the information that is needed for the engine to
/// reconstruct the state *of that particular epoch* (seed, selected
/// events, parent link, etc.). The full world data is kept in
/// separate storage (e.g. `world.json`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EpochInfo {
/// The ID of this epoch – should match the directory name.
pub epoch_id: EpochId,
/// The ID of the parent (previous) epoch, if not a root.
pub parent_id: Option<u64>,
/// RNG seed that was used to generate randomised data for
/// this epoch. Keeping it in the file guarantees repeatable
/// behaviour when replaying the same epoch.
pub rng_seed: u64,
// /// List of event IDs that were accepted for this epoch.
// /// The engine uses this to replay the world from the
// /// parent epoch to the current one.
// pub selected_events: Vec<u64>,
/// Optional tags that help identify the epoch (e.g. `"Winter‑B"`).
pub tags: Vec<String>,
/// Human‑readable description or summary, useful for the `log` command.
pub summary: Option<String>,
}
pub enum SaveMode {
DoNotErase,
Erase,
}
impl EpochInfo {
pub fn empty() -> Self {
Self {
epoch_id: epoch_struct::EpochId::new(0),
parent_id: None,
rng_seed: 0,
tags: Vec::new(),
summary: None,
}
}
}
/// Thin type to handle EpochIds
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct EpochId {
/// The underlying numeric value. A value of `0` is never used –
/// epoch IDs start at 1.
pub id: u64,
}
impl std::fmt::Display for EpochId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.id)
}
}
impl EpochId {
/// Creates a new `EpochId` from a numeric value.
pub fn new(id: u64) -> Self {
Self { id }
}
}
impl std::ops::Deref for EpochId {
type Target = u64;
fn deref(&self) -> &Self::Target {
&self.id
}
}
impl ConfigWritable for EpochConfig {
fn save_path(&self) -> String {
".epoch".to_string()
}
}
impl ConfigWritable for EpochInfo {
fn save_path(&self) -> String {
format!("{}/.epochinfo", self.epoch_id)
}
}
/// A flexible identifier for *any* epoch – the world may be
/// addressed by a numeric ID or by a friendly tag (e.g. `"winter‑b"`).
///
/// The enum is `untagged` so that serialising/deserialising does
/// **not** add a wrapper field, e.g. `{"Tag":"foo"}`.
/// Instead the JSON representation is exactly the inner value:
/// * `"42"` → `EpochIdentifier::Id(EpochId::new(42))`
/// * `"foo"` → `EpochIdentifier::Tag("foo".into())`
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)]
#[serde(untagged)] // <‑‑ no “type” wrapper is written to JSON
pub enum EpochIdentifier {
/// A textual tag that maps to a numeric epoch ID in `EpochConfig::tags`.
Tag(String),
/// The raw numeric identifier of the epoch.
Id(EpochId),
}
impl FromStr for EpochIdentifier {
type Err = clap::Error; // any `std::error::Error` works
/// Try to parse either a decimal number (-> `Id`) or any non‑empty
/// string (-> `Tag`).
///
/// Errors are converted to a Clap error so that the CLI shows a
/// nice message.
fn from_str(s: &str) -> Result<Self, Self::Err> {
if let Ok(num) = s.parse::<u64>() {
Ok(EpochIdentifier::Id(EpochId::new(num)))
} else if !s.is_empty() {
Ok(EpochIdentifier::Tag(s.to_owned()))
} else {
Err(clap::Error::raw(
ErrorKind::InvalidValue,
format!("{} is not a valid epoch id or tag", s),
))
}
}
}