fix: make snapshot writes atomic and reject unsupported stats
This commit is contained in:
parent
f1e3addc16
commit
c24e4b5696
|
|
@ -43,7 +43,7 @@ work belongs here before implementation.
|
|||
diff, and delete by name and stable identifier.
|
||||
- [ ] Test epoch workflows: next, log, switch, diff, tag, summary, and reset.
|
||||
- [ ] Test malformed/corrupt configuration and snapshot files without panics.
|
||||
- [ ] Test interrupted/failed writes where feasible and implement atomic file
|
||||
- [x] Test interrupted/failed writes where feasible and implement atomic file
|
||||
replacement for repository metadata and epoch snapshots.
|
||||
- [x] Remove currently reported unused dependencies and the demo `show` path.
|
||||
- [x] Make format, tests, strict Clippy, and release build pass.
|
||||
|
|
|
|||
|
|
@ -17,9 +17,10 @@ and blockers. The full world is duplicated per epoch.
|
|||
|
||||
Entity commands edit the current snapshot directly. `epoch next` creates a new
|
||||
snapshot; `epoch switch` only changes the current pointer. `epoch reset` deletes
|
||||
later directories. This is not yet Git-equivalent: there is no working
|
||||
tree/index separation, reflog, locking, atomic multi-file transaction, or
|
||||
built-in undelete.
|
||||
later directories. Individual JSON files are written through same-directory
|
||||
temporary files and atomically replaced. This is not yet Git-equivalent: there
|
||||
is no working tree/index separation, reflog, repository locking, atomic
|
||||
transaction spanning multiple files, or built-in undelete.
|
||||
|
||||
## Safety and recovery
|
||||
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ colored = {workspace = true}
|
|||
uuid = {workspace = true}
|
||||
rand = "0.9.2"
|
||||
once_cell = "1.21.3"
|
||||
tempfile = "3.23.0"
|
||||
|
||||
[dev-dependencies]
|
||||
insta = {workspace = true}
|
||||
tempfile = "3.23.0"
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@
|
|||
|
||||
use cli_table::{Style, Table, WithTitle};
|
||||
use serde::Serialize;
|
||||
use std::{fmt::Display, fs::File, io::Write};
|
||||
use std::{fmt::Display, io::Write, path::Path};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{epoch::SaveMode, error::EpochError, items_table};
|
||||
|
|
@ -95,13 +95,22 @@ pub trait ConfigWritable: Serialize {
|
|||
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_description.to_owned())?)
|
||||
let save_path = self.save_path();
|
||||
let destination = Path::new(&save_path);
|
||||
let parent = destination.parent().unwrap_or_else(|| Path::new("."));
|
||||
let json = self.as_json(action_description.to_owned())?;
|
||||
let mut temporary = tempfile::NamedTempFile::new_in(parent)
|
||||
.map_err(|error| EpochError::ConfigCreation(save_path.clone(), error))?;
|
||||
temporary
|
||||
.write_all(json.as_bytes())
|
||||
.and_then(|_| temporary.as_file().sync_all())
|
||||
.map_err(EpochError::ConfigWrite)?;
|
||||
|
||||
let persisted = match *do_not_erase {
|
||||
SaveMode::Erase => temporary.persist(destination),
|
||||
SaveMode::DoNotErase => temporary.persist_noclobber(destination),
|
||||
};
|
||||
persisted.map_err(|error| EpochError::ConfigCreation(save_path, error.error))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
@ -184,6 +193,55 @@ mod tests {
|
|||
assert_snapshot!(json);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_with_context_atomically_replaces_existing_content() {
|
||||
let directory = tempdir().expect("temporary directory");
|
||||
let path = directory.path().join("dummy.json");
|
||||
std::fs::write(&path, "old content").expect("seed destination");
|
||||
let item = DummyItem {
|
||||
id: Uuid::nil(),
|
||||
value: 42,
|
||||
save: path.to_string_lossy().into_owned(),
|
||||
};
|
||||
|
||||
item.save_with_context("replace test", &SaveMode::Erase)
|
||||
.expect("replace destination");
|
||||
|
||||
let saved: serde_json::Value = serde_json::from_str(
|
||||
&std::fs::read_to_string(&path).expect("read replaced destination"),
|
||||
)
|
||||
.expect("valid JSON");
|
||||
assert_eq!(saved["value"], 42);
|
||||
assert_eq!(
|
||||
std::fs::read_dir(directory.path())
|
||||
.expect("list temporary directory")
|
||||
.count(),
|
||||
1,
|
||||
"the temporary file must be removed after persistence"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_with_context_does_not_clobber_when_forbidden() {
|
||||
let directory = tempdir().expect("temporary directory");
|
||||
let path = directory.path().join("dummy.json");
|
||||
std::fs::write(&path, "keep this").expect("seed destination");
|
||||
let item = DummyItem {
|
||||
id: Uuid::nil(),
|
||||
value: 42,
|
||||
save: path.to_string_lossy().into_owned(),
|
||||
};
|
||||
|
||||
assert!(
|
||||
item.save_with_context("no-clobber test", &SaveMode::DoNotErase)
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(path).expect("read preserved destination"),
|
||||
"keep this"
|
||||
);
|
||||
}
|
||||
|
||||
// fn dummy_with_tempfile(value: i32) -> (DummyItem, std::path::PathBuf) {
|
||||
// let dummy = DummyItem::new(value);
|
||||
// (dummy.clone(), dummy.save.clone().into())
|
||||
|
|
|
|||
|
|
@ -226,6 +226,14 @@ pub enum EpochError {
|
|||
#[diagnostic(code(EpochError::IllFormedStatQualifier))]
|
||||
IllFormedStatQualifier(String),
|
||||
|
||||
/// The statistic name is recognised but is not stored by this release.
|
||||
#[error("Statistic `{0}` is not implemented in this release")]
|
||||
#[diagnostic(code(EpochError::UnsupportedStat))]
|
||||
#[diagnostic(help(
|
||||
"Use `efo <entity> add --help` and choose a currently supported statistic."
|
||||
))]
|
||||
UnsupportedStat(String),
|
||||
|
||||
/// User error, meant to be very explicit over what happened and what to do.
|
||||
#[error("An user facing error")]
|
||||
#[diagnostic(code(EpochError::UserError))]
|
||||
|
|
|
|||
|
|
@ -27,6 +27,16 @@ impl FromStr for StatPair {
|
|||
};
|
||||
|
||||
let stat: ListStats = stat_str.parse()?;
|
||||
if matches!(
|
||||
stat,
|
||||
ListStats::Social
|
||||
| ListStats::Culture
|
||||
| ListStats::Education
|
||||
| ListStats::Tourism
|
||||
| ListStats::Influence
|
||||
) {
|
||||
return Err(EpochError::UnsupportedStat(stat_str.to_owned()));
|
||||
}
|
||||
let value: isize = val_str
|
||||
.parse()
|
||||
.map_err(|_| EpochError::IllFormedStatQualifier(val_str.to_owned()))?;
|
||||
|
|
|
|||
|
|
@ -90,6 +90,14 @@ fn stat_pair_ill_formed_errors_are_detected() {
|
|||
let err = stats::StatPair::from_str("unknown:5").unwrap_err();
|
||||
assert!(matches!(err, EpochError::UnknownStatAcronim(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stat_pair_rejects_recognised_but_unimplemented_stats() {
|
||||
for name in ["social", "culture", "education", "tourism", "influence"] {
|
||||
let err = stats::StatPair::from_str(&format!("{name}:10")).unwrap_err();
|
||||
assert!(matches!(err, EpochError::UnsupportedStat(_)));
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn position_invalid_format_errors_are_detected() {
|
||||
// 1️⃣ No comma
|
||||
|
|
|
|||
Loading…
Reference in New Issue