diff --git a/lib_efo/src/lib.rs b/lib_efo/src/lib.rs index 292825e..6f9940b 100644 --- a/lib_efo/src/lib.rs +++ b/lib_efo/src/lib.rs @@ -16,6 +16,7 @@ use crate::epoch::EpochInfo; pub mod error; pub mod entity; pub mod epoch; +pub mod migration; pub mod naming; pub mod output; pub mod repository_format; diff --git a/lib_efo/src/migration.rs b/lib_efo/src/migration.rs new file mode 100644 index 0000000..221b14a --- /dev/null +++ b/lib_efo/src/migration.rs @@ -0,0 +1,364 @@ +//! Planning and execution for explicit repository-format migrations. + +use std::{ + collections::{BTreeMap, BTreeSet}, + fs::{self, File}, + io::Write, + path::{Path, PathBuf}, + time::{SystemTime, UNIX_EPOCH}, +}; + +use serde::Serialize; +use uuid::Uuid; + +use crate::{ + epoch::{EpochId, EpochInfo}, + repository_format::{ + DetectedManifest, LegacyManifest, RepositoryManifest, RepositorySnapshot, detect_manifest, + }, + stats::EntityType, +}; + +/// A validated, read-only description of a version-1 migration. +#[derive(Debug, Clone)] +pub struct MigrationPlan { + /// Canonical repository root. + root: PathBuf, + /// Fully decoded legacy manifest. + legacy: LegacyManifest, + /// Sorted legacy epoch identifiers. + epoch_ids: Vec, + /// Selected snapshot used to seed both transient layers. + current: EpochInfo, + /// Monotonic allocator value derived from all observed history. + next_epoch_id: EpochId, +} + +impl MigrationPlan { + /// Repository root that will be migrated. + pub fn root(&self) -> &Path { + &self.root + } + + /// Currently selected legacy epoch. + pub fn current_epoch(&self) -> EpochId { + self.legacy.epoch_id + } + + /// Number of immutable snapshots validated by the plan. + pub fn epoch_count(&self) -> usize { + self.epoch_ids.len() + } + + /// First epoch ID that a version-2 commit may allocate. + pub fn next_epoch_id(&self) -> EpochId { + self.next_epoch_id + } + + /// Tags that will be retained unchanged. + pub fn tags(&self) -> &BTreeMap { + &self.legacy.tags + } +} + +/// Result of a completed migration. +#[derive(Debug, Clone)] +pub struct MigrationOutcome { + /// Directory containing the byte-for-byte legacy manifest backup. + pub backup_directory: PathBuf, + /// Stable identity assigned to the migrated repository. + pub repository_id: Uuid, +} + +/// A migration planning or execution failure. +#[derive(Debug, thiserror::Error)] +pub enum MigrationError { + /// A filesystem operation failed. + #[error("migration could not access `{path}`: {source}")] + Io { + /// Affected path. + path: PathBuf, + /// Underlying filesystem error. + #[source] + source: std::io::Error, + }, + /// The manifest is malformed or uses an unsupported format. + #[error("cannot migrate repository manifest: {0}")] + Format(#[from] crate::repository_format::FormatError), + /// This repository is already on the requested format. + #[error("repository already uses format version 2; nothing was changed")] + AlreadyCurrent, + /// Legacy repository invariants do not hold. + #[error("legacy repository is inconsistent: {0}")] + Invalid(String), + /// Existing migration state may not be overwritten. + #[error("migration workspace `{0}` already exists; nothing was changed")] + WorkspaceExists(PathBuf), + /// JSON data could not be decoded or encoded. + #[error("migration data at `{path}` is invalid: {source}")] + Json { + /// Affected path. + path: PathBuf, + /// Serialization error. + #[source] + source: serde_json::Error, + }, +} + +/// Validate a version-1 repository without changing any bytes. +pub fn plan_migration(root: &Path) -> Result { + let root = root.canonicalize().map_err(|source| MigrationError::Io { + path: root.to_path_buf(), + source, + })?; + let manifest_path = root.join(".epoch"); + let manifest_bytes = read(&manifest_path)?; + let legacy = match detect_manifest(&manifest_bytes)? { + DetectedManifest::Legacy(manifest) => manifest, + DetectedManifest::Current(_) => return Err(MigrationError::AlreadyCurrent), + }; + + let epoch_root = root.join("epoch"); + let entries = fs::read_dir(&epoch_root).map_err(|source| MigrationError::Io { + path: epoch_root.clone(), + source, + })?; + let mut epoch_ids = Vec::new(); + let mut snapshots = BTreeMap::new(); + for entry in entries { + let entry = entry.map_err(|source| MigrationError::Io { + path: epoch_root.clone(), + source, + })?; + if !entry + .file_type() + .map_err(|source| MigrationError::Io { + path: entry.path(), + source, + })? + .is_dir() + { + continue; + } + let name = entry.file_name().to_string_lossy().into_owned(); + let numeric = name.parse::().map_err(|_| { + MigrationError::Invalid(format!("epoch directory `{name}` is not numeric")) + })?; + let id = EpochId::new(numeric); + let snapshot_path = entry.path().join("epochinfo.json"); + let snapshot: EpochInfo = + serde_json::from_slice(&read(&snapshot_path)?).map_err(|source| { + MigrationError::Json { + path: snapshot_path.clone(), + source, + } + })?; + if snapshot.epoch_id != id { + return Err(MigrationError::Invalid(format!( + "epoch directory {id} contains snapshot {}", + snapshot.epoch_id + ))); + } + validate_entities(id, &snapshot)?; + epoch_ids.push(id); + snapshots.insert(id, snapshot); + } + epoch_ids.sort_unstable(); + if epoch_ids.is_empty() { + return Err(MigrationError::Invalid( + "no epoch snapshots were found".to_owned(), + )); + } + let current = snapshots.get(&legacy.epoch_id).cloned().ok_or_else(|| { + MigrationError::Invalid(format!("selected epoch {} is missing", legacy.epoch_id)) + })?; + for (tag, id) in &legacy.tags { + if !snapshots.contains_key(id) { + return Err(MigrationError::Invalid(format!( + "tag `{tag}` points to missing epoch {id}" + ))); + } + } + let maximum = epoch_ids + .last() + .map(|id| id.id) + .ok_or_else(|| MigrationError::Invalid("no epoch snapshots were found".to_owned()))?; + let next = maximum + .checked_add(1) + .ok_or_else(|| MigrationError::Invalid("epoch ID allocator is exhausted".to_owned()))?; + + Ok(MigrationPlan { + root, + legacy, + epoch_ids, + current, + next_epoch_id: EpochId::new(next), + }) +} + +/// Execute a previously validated migration, committing `.epoch` last. +pub fn execute_migration(plan: &MigrationPlan) -> Result { + let workspace = plan.root.join(".efo"); + if workspace.exists() { + return Err(MigrationError::WorkspaceExists(workspace)); + } + let repository_id = Uuid::new_v4(); + let stamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(|_| MigrationError::Invalid("system clock is before Unix epoch".to_owned()))? + .as_secs(); + let temporary = plan.root.join(format!(".efo-migration-{}", Uuid::new_v4())); + let backup_relative = PathBuf::from(format!("migrations/v1-{stamp}")); + let backup = temporary.join(&backup_relative); + fs::create_dir_all(&backup).map_err(|source| MigrationError::Io { + path: backup.clone(), + source, + })?; + + let result = prepare_workspace(plan, repository_id, &temporary, &backup).and_then(|manifest| { + fs::rename(&temporary, &workspace).map_err(|source| MigrationError::Io { + path: workspace.clone(), + source, + })?; + atomic_json(&plan.root.join(".epoch"), &manifest) + }); + if result.is_err() && temporary.exists() { + let _ = fs::remove_dir_all(&temporary); + } + result?; + + Ok(MigrationOutcome { + backup_directory: workspace.join(backup_relative), + repository_id, + }) +} + +/// Write and flush the complete version-2 workspace before its final rename. +fn prepare_workspace( + plan: &MigrationPlan, + repository_id: Uuid, + temporary: &Path, + backup: &Path, +) -> Result { + let legacy_path = plan.root.join(".epoch"); + let legacy_bytes = read(&legacy_path)?; + write_synced(&backup.join(".epoch"), &legacy_bytes)?; + let checksum = format!("{:016x} .epoch\n", fnv1a64(&legacy_bytes)); + write_synced(&backup.join("checksums.fnv1a64"), checksum.as_bytes())?; + + let snapshot = + RepositorySnapshot::new(repository_id, plan.legacy.epoch_id, plan.current.clone()); + atomic_json(&temporary.join("index.json"), &snapshot)?; + atomic_json(&temporary.join("worktree.json"), &snapshot)?; + sync_directory(backup)?; + sync_directory(temporary)?; + + Ok(RepositoryManifest::new( + repository_id, + plan.legacy.epoch_id, + plan.next_epoch_id, + plan.legacy.version.clone(), + plan.legacy.tags.clone(), + )) +} + +/// Check identity and collection invariants that migration must preserve. +fn validate_entities(epoch: EpochId, snapshot: &EpochInfo) -> Result<(), MigrationError> { + let mut ids = BTreeSet::new(); + for (entities, expected) in [ + (&snapshot.characters, EntityType::Character), + (&snapshot.towns, EntityType::Town), + (&snapshot.events, EntityType::Event), + (&snapshot.calamities, EntityType::Calamity), + (&snapshot.organizations, EntityType::Organization), + (&snapshot.blockers, EntityType::Blocker), + ] { + for entity in entities { + if entity.id.is_nil() || !ids.insert(entity.id) { + return Err(MigrationError::Invalid(format!( + "epoch {epoch} has a missing or duplicate entity UUID" + ))); + } + if entity.entity_type != expected { + return Err(MigrationError::Invalid(format!( + "entity `{}` in epoch {epoch} is stored as {:?}, expected {:?}", + entity.name, entity.entity_type, expected + ))); + } + } + } + Ok(()) +} + +/// Read bytes while retaining the affected path in diagnostics. +fn read(path: &Path) -> Result, MigrationError> { + fs::read(path).map_err(|source| MigrationError::Io { + path: path.to_path_buf(), + source, + }) +} + +/// Serialize, flush, and atomically replace one JSON file. +fn atomic_json(path: &Path, value: &T) -> Result<(), MigrationError> { + let bytes = serde_json::to_vec_pretty(value).map_err(|source| MigrationError::Json { + path: path.to_path_buf(), + source, + })?; + let parent = path.parent().ok_or_else(|| { + MigrationError::Invalid(format!("path `{}` has no parent", path.display())) + })?; + fs::create_dir_all(parent).map_err(|source| MigrationError::Io { + path: parent.to_path_buf(), + source, + })?; + let mut temporary = + tempfile::NamedTempFile::new_in(parent).map_err(|source| MigrationError::Io { + path: parent.to_path_buf(), + source, + })?; + temporary + .write_all(&bytes) + .and_then(|_| temporary.as_file().sync_all()) + .map_err(|source| MigrationError::Io { + path: path.to_path_buf(), + source, + })?; + temporary + .persist(path) + .map_err(|error| MigrationError::Io { + path: path.to_path_buf(), + source: error.error, + })?; + sync_directory(parent) +} + +/// Create one backup file and flush its contents. +fn write_synced(path: &Path, bytes: &[u8]) -> Result<(), MigrationError> { + let mut file = File::create(path).map_err(|source| MigrationError::Io { + path: path.to_path_buf(), + source, + })?; + file.write_all(bytes) + .and_then(|_| file.sync_all()) + .map_err(|source| MigrationError::Io { + path: path.to_path_buf(), + source, + }) +} + +/// Flush directory metadata after creating or renaming entries. +fn sync_directory(path: &Path) -> Result<(), MigrationError> { + File::open(path) + .and_then(|directory| directory.sync_all()) + .map_err(|source| MigrationError::Io { + path: path.to_path_buf(), + source, + }) +} + +/// Compute the documented checksum used to verify migration backup bytes. +fn fnv1a64(bytes: &[u8]) -> u64 { + bytes.iter().fold(0xcbf2_9ce4_8422_2325, |hash, byte| { + (hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3) + }) +} diff --git a/lib_efo/tests/migration_fixtures.rs b/lib_efo/tests/migration_fixtures.rs index e602327..5a6ac04 100644 --- a/lib_efo/tests/migration_fixtures.rs +++ b/lib_efo/tests/migration_fixtures.rs @@ -1,8 +1,13 @@ -use std::collections::{BTreeMap, BTreeSet}; +use std::{ + collections::{BTreeMap, BTreeSet}, + fs, + path::Path, +}; use lib_efo::{ entity::Entity, epoch::{EpochId, EpochInfo}, + migration::{MigrationError, execute_migration, plan_migration}, repository_format::{DetectedManifest, LegacyManifest, detect_manifest}, stats::{EntityType, Role, TypedLink}, }; @@ -156,3 +161,90 @@ fn legacy_monster_spelling_remains_loadable() { serde_json::from_value(value).expect("load legacy Monster spelling"); assert_eq!(decoded.entity_type, lib_efo::stats::EntityType::Calamity); } + +#[test] +fn migration_plan_is_read_only_and_allocates_after_future_history() { + let directory = tempfile::tempdir().expect("temporary fixture repository"); + materialize_repository(directory.path(), 1, &[0, 1, 2, 3]); + let manifest_before = fs::read(directory.path().join(".epoch")).expect("legacy manifest"); + + let plan = plan_migration(directory.path()).expect("valid migration plan"); + + assert_eq!(plan.current_epoch(), EpochId::new(1)); + assert_eq!(plan.next_epoch_id(), EpochId::new(4)); + assert_eq!(plan.epoch_count(), 4); + assert_eq!( + fs::read(directory.path().join(".epoch")).expect("manifest after plan"), + manifest_before + ); + assert!(!directory.path().join(".efo").exists()); +} + +#[test] +fn migration_rejects_missing_selected_epoch_without_writing() { + let directory = tempfile::tempdir().expect("temporary fixture repository"); + materialize_repository(directory.path(), 4, &[0]); + + let error = plan_migration(directory.path()).expect_err("invalid migration must fail"); + assert!(matches!(error, MigrationError::Invalid(_))); + assert!(!directory.path().join(".efo").exists()); +} + +#[test] +fn migration_backs_up_manifest_and_commits_version_two_last() { + let directory = tempfile::tempdir().expect("temporary fixture repository"); + materialize_repository(directory.path(), 1, &[0, 1, 2]); + let legacy_bytes = fs::read(directory.path().join(".epoch")).expect("legacy manifest"); + let plan = plan_migration(directory.path()).expect("valid migration plan"); + + let outcome = execute_migration(&plan).expect("execute migration"); + + assert_eq!( + fs::read(outcome.backup_directory.join(".epoch")).expect("backup manifest"), + legacy_bytes + ); + assert!(outcome.backup_directory.join("checksums.fnv1a64").is_file()); + let manifest_bytes = fs::read(directory.path().join(".epoch")).expect("current manifest"); + let DetectedManifest::Current(manifest) = + detect_manifest(&manifest_bytes).expect("version two manifest") + else { + panic!("migration did not commit version two") + }; + assert_eq!(manifest.repository_id, outcome.repository_id); + assert_eq!(manifest.next_epoch_id, EpochId::new(3)); + for layer in ["index.json", "worktree.json"] { + let snapshot: lib_efo::repository_format::RepositorySnapshot = serde_json::from_slice( + &fs::read(directory.path().join(".efo").join(layer)).expect("transient snapshot"), + ) + .expect("decode transient snapshot"); + assert_eq!(snapshot.repository_id, outcome.repository_id); + assert_eq!(snapshot.base_epoch_id, EpochId::new(1)); + assert_eq!(snapshot.world.epoch_id, EpochId::new(1)); + } +} + +fn materialize_repository(root: &Path, current: u64, epochs: &[u64]) { + let manifest = LegacyManifest { + epoch_id: EpochId::new(current), + version: "fixture-v1".to_owned(), + tags: BTreeMap::new(), + }; + fs::write( + root.join(".epoch"), + serde_json::to_vec_pretty(&manifest).expect("serialize legacy manifest"), + ) + .expect("write legacy manifest"); + for id in epochs { + let directory = root.join(format!("epoch/{id}")); + fs::create_dir_all(&directory).expect("create epoch directory"); + let snapshot = EpochInfo { + epoch_id: EpochId::new(*id), + ..EpochInfo::default() + }; + fs::write( + directory.join("epochinfo.json"), + serde_json::to_vec_pretty(&snapshot).expect("serialize legacy snapshot"), + ) + .expect("write legacy snapshot"); + } +}