use crate::library_manager::LibraryManager;
use chrono::Local;
use serde::de::{IgnoredAny, MapAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT_FILE_TRANSACTION_ID: AtomicU64 = AtomicU64::new(1);
#[allow(dead_code)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ThermoLibraryDropReport {
pub library: String,
pub substance: String,
pub removed_from_substance_base: bool,
pub removed_from_all_keys: usize,
pub removed_from_elements: usize,
}
#[allow(dead_code)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ThermoLibraryWriteReport {
pub library: String,
pub substance: String,
pub replaced_existing: bool,
pub refreshed_all_keys: usize,
pub refreshed_elements: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ElementIndexAuditReport {
pub records_seen: usize,
pub records_with_valid_composition: usize,
pub records_missing_composition: Vec<String>,
pub records_with_invalid_composition: Vec<ElementIndexAuditIssue>,
pub missing_index_entries: Vec<String>,
pub stale_index_entries: Vec<String>,
pub duplicate_index_entries: Vec<String>,
#[serde(default)]
pub duplicate_canonical_source_addresses: Vec<String>,
}
impl ElementIndexAuditReport {
pub fn is_clean(&self) -> bool {
self.records_with_invalid_composition.is_empty()
&& self.missing_index_entries.is_empty()
&& self.stale_index_entries.is_empty()
&& self.duplicate_index_entries.is_empty()
&& self.duplicate_canonical_source_addresses.is_empty()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ElementIndexAuditIssue {
pub record: String,
pub reason: String,
}
#[derive(Default)]
struct RawSourceAddresses(Vec<(String, String)>);
impl<'de> Deserialize<'de> for RawSourceAddresses {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct AddressVisitor;
impl<'de> Visitor<'de> for AddressVisitor {
type Value = RawSourceAddresses;
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("a thermo library object")
}
fn visit_map<A>(self, mut libraries: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let mut addresses = Vec::new();
while let Some(library) = libraries.next_key::<String>()? {
for substance in libraries.next_value::<RawSubstanceKeys>()?.0 {
addresses.push((library.clone(), substance));
}
}
Ok(RawSourceAddresses(addresses))
}
}
deserializer.deserialize_map(AddressVisitor)
}
}
#[derive(Default)]
struct RawSubstanceKeys(Vec<String>);
impl<'de> Deserialize<'de> for RawSubstanceKeys {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct SubstanceKeysVisitor;
impl<'de> Visitor<'de> for SubstanceKeysVisitor {
type Value = RawSubstanceKeys;
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("a thermo substance object")
}
fn visit_map<A>(self, mut records: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let mut substances = Vec::new();
while let Some(substance) = records.next_key::<String>()? {
records.next_value::<IgnoredAny>()?;
substances.push(substance);
}
Ok(RawSubstanceKeys(substances))
}
fn visit_seq<A>(self, mut records: A) -> Result<Self::Value, A::Error>
where
A: serde::de::SeqAccess<'de>,
{
while records.next_element::<IgnoredAny>()?.is_some() {}
Ok(RawSubstanceKeys::default())
}
fn visit_bool<E: serde::de::Error>(self, _: bool) -> Result<Self::Value, E> {
Ok(RawSubstanceKeys::default())
}
fn visit_i64<E: serde::de::Error>(self, _: i64) -> Result<Self::Value, E> {
Ok(RawSubstanceKeys::default())
}
fn visit_u64<E: serde::de::Error>(self, _: u64) -> Result<Self::Value, E> {
Ok(RawSubstanceKeys::default())
}
fn visit_f64<E: serde::de::Error>(self, _: f64) -> Result<Self::Value, E> {
Ok(RawSubstanceKeys::default())
}
fn visit_str<E: serde::de::Error>(self, _: &str) -> Result<Self::Value, E> {
Ok(RawSubstanceKeys::default())
}
fn visit_string<E: serde::de::Error>(self, _: String) -> Result<Self::Value, E> {
Ok(RawSubstanceKeys::default())
}
fn visit_unit<E: serde::de::Error>(self) -> Result<Self::Value, E> {
Ok(RawSubstanceKeys::default())
}
}
deserializer.deserialize_any(SubstanceKeysVisitor)
}
}
#[allow(dead_code)]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum ThermoLibraryWriteOperation {
Upsert,
Drop,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[allow(dead_code)]
pub(crate) struct ThermoLibraryJournalEntry {
pub timestamp: String,
#[serde(default)]
pub source_format: String,
pub operation: ThermoLibraryWriteOperation,
pub library: String,
pub substance: String,
pub canonical_names: Vec<String>,
pub files: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[allow(dead_code)]
pub(crate) struct ThermoSubstanceWriteSpec {
pub library: String,
pub substance: String,
pub source_format: ThermoSubstanceSourceFormat,
pub composition: String,
#[serde(default)]
pub fields: BTreeMap<String, serde_json::Value>,
}
impl ThermoSubstanceWriteSpec {
#[allow(dead_code)]
fn into_record(self) -> serde_json::Value {
let mut payload = serde_json::Map::new();
payload.insert(
"composition".to_string(),
serde_json::Value::String(self.composition),
);
for (key, value) in self.fields {
payload.insert(key, value);
}
serde_json::Value::Object(payload)
}
}
#[allow(dead_code)]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum ThermoSubstanceSourceFormat {
Nasa,
Nist,
Aramco,
Cea,
Custom(String),
}
impl ThermoSubstanceSourceFormat {
#[allow(dead_code)]
fn as_str(&self) -> &str {
match self {
Self::Nasa => "NASA",
Self::Nist => "NIST",
Self::Aramco => "Aramco",
Self::Cea => "CEA",
Self::Custom(value) => value.as_str(),
}
}
#[allow(dead_code)]
fn expected_library_prefix(&self) -> Option<&str> {
match self {
Self::Nasa => Some("NASA"),
Self::Nist => Some("NIST"),
Self::Aramco => Some("Aramco"),
Self::Cea => Some("CEA"),
Self::Custom(_) => None,
}
}
}
#[allow(dead_code)]
#[derive(Debug)]
pub(crate) enum ThermoLibraryWriteError {
MissingLibraryFile {
path: String,
source: io::Error,
},
InvalidLibraryJson {
path: String,
source: serde_json::Error,
},
MissingLibraryEntry {
library: String,
},
MissingSubstanceEntry {
library: String,
substance: String,
},
LibraryFormatMismatch {
library: String,
source_format: String,
},
InvalidComposition {
library: String,
substance: String,
reason: String,
},
TransactionRollbackFailed {
failed_path: String,
failure: io::Error,
rollback_path: String,
rollback: io::Error,
},
BackupCleanupFailed {
failures: Vec<(String, io::Error)>,
},
WriteFailed {
path: String,
source: io::Error,
},
}
impl std::fmt::Display for ThermoLibraryWriteError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::MissingLibraryFile { path, source } => {
write!(
f,
"failed to open thermo library file '{}': {}",
path, source
)
}
Self::InvalidLibraryJson { path, source } => {
write!(
f,
"failed to parse thermo library file '{}': {}",
path, source
)
}
Self::MissingLibraryEntry { library } => {
write!(f, "library '{}' was not found in substance base", library)
}
Self::MissingSubstanceEntry { library, substance } => {
write!(
f,
"substance '{}' was not found in library '{}'",
substance, library
)
}
Self::LibraryFormatMismatch {
library,
source_format,
} => {
write!(
f,
"library '{}' does not match typed source format '{}'",
library, source_format
)
}
Self::InvalidComposition {
library,
substance,
reason,
} => write!(
f,
"invalid composition for '{substance}' in library '{library}': {reason}"
),
Self::TransactionRollbackFailed {
failed_path,
failure,
rollback_path,
rollback,
} => write!(
f,
"thermo library transaction failed at '{}': {}; rollback also failed at '{}': {}",
failed_path, failure, rollback_path, rollback
),
Self::BackupCleanupFailed { failures } => {
write!(
f,
"catalog publication committed, but {} obsolete backup(s) could not be removed",
failures.len()
)?;
for (path, source) in failures {
write!(f, "; '{}': {}", path, source)?;
}
Ok(())
}
Self::WriteFailed { path, source } => {
write!(
f,
"failed to write thermo library file '{}': {}",
path, source
)
}
}
}
}
impl std::error::Error for ThermoLibraryWriteError {}
#[allow(dead_code)]
fn read_json_file<T: serde::de::DeserializeOwned>(
path: &str,
) -> Result<T, ThermoLibraryWriteError> {
let content =
fs::read_to_string(path).map_err(|source| ThermoLibraryWriteError::MissingLibraryFile {
path: path.to_string(),
source,
})?;
serde_json::from_str(&content).map_err(|source| ThermoLibraryWriteError::InvalidLibraryJson {
path: path.to_string(),
source,
})
}
#[allow(dead_code)]
fn serialize_json<T: serde::Serialize>(
path: &Path,
value: &T,
) -> Result<Vec<u8>, ThermoLibraryWriteError> {
serde_json::to_vec_pretty(value).map_err(|source| ThermoLibraryWriteError::InvalidLibraryJson {
path: path.display().to_string(),
source,
})
}
struct StagedFile {
target: PathBuf,
staged: PathBuf,
backup: PathBuf,
had_original: bool,
installed: bool,
}
fn transaction_sibling_path(target: &Path, id: u64, suffix: &str, index: usize) -> PathBuf {
let parent = target
.parent()
.filter(|path| !path.as_os_str().is_empty())
.unwrap_or(Path::new("."));
let file_name = target
.file_name()
.map(|name| name.to_string_lossy())
.unwrap_or_default();
parent.join(format!(
".{file_name}.{}.{}.{}.{}",
std::process::id(),
id,
index,
suffix
))
}
fn cleanup_staged_files(files: &[StagedFile]) {
for file in files {
let _ = fs::remove_file(&file.staged);
}
}
fn regular_file_exists(path: &Path) -> io::Result<bool> {
match fs::symlink_metadata(path) {
Ok(metadata) if metadata.file_type().is_file() => Ok(true),
Ok(_) => Err(io::Error::new(
io::ErrorKind::InvalidInput,
"catalog transaction target must be a regular file",
)),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error),
}
}
fn path_exists_without_following_symlinks(path: &Path) -> io::Result<bool> {
match fs::symlink_metadata(path) {
Ok(_) => Ok(true),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error),
}
}
fn rollback_file_transaction(files: &mut [StagedFile]) -> Option<(String, io::Error)> {
let mut first_error = None;
for file in files.iter_mut().rev() {
if file.installed {
if let Err(error) = fs::remove_file(&file.target) {
if first_error.is_none() {
first_error = Some((file.target.display().to_string(), error));
}
}
file.installed = false;
}
if file.had_original {
if let Err(error) = fs::rename(&file.backup, &file.target) {
if first_error.is_none() {
first_error = Some((file.target.display().to_string(), error));
}
} else {
file.had_original = false;
}
}
}
cleanup_staged_files(files);
first_error
}
fn commit_file_transaction(
changes: Vec<(PathBuf, Vec<u8>)>,
) -> Result<(), ThermoLibraryWriteError> {
commit_file_transaction_with_hook(changes, |_, _| Ok(()))
}
fn commit_file_transaction_with_hook<F>(
changes: Vec<(PathBuf, Vec<u8>)>,
before_install: F,
) -> Result<(), ThermoLibraryWriteError>
where
F: FnMut(usize, &Path) -> io::Result<()>,
{
let id = NEXT_FILE_TRANSACTION_ID.fetch_add(1, Ordering::Relaxed);
commit_file_transaction_with_id_and_hook(changes, id, before_install)
}
fn commit_file_transaction_with_id_and_hook<F>(
changes: Vec<(PathBuf, Vec<u8>)>,
id: u64,
before_install: F,
) -> Result<(), ThermoLibraryWriteError>
where
F: FnMut(usize, &Path) -> io::Result<()>,
{
commit_file_transaction_with_hooks(changes, id, before_install, |path| fs::remove_file(path))
}
fn commit_file_transaction_with_hooks<F, R>(
changes: Vec<(PathBuf, Vec<u8>)>,
id: u64,
mut before_install: F,
mut remove_backup: R,
) -> Result<(), ThermoLibraryWriteError>
where
F: FnMut(usize, &Path) -> io::Result<()>,
R: FnMut(&Path) -> io::Result<()>,
{
let mut targets = HashSet::with_capacity(changes.len());
for (target, _) in &changes {
if !targets.insert(target.clone()) {
return Err(ThermoLibraryWriteError::WriteFailed {
path: target.display().to_string(),
source: io::Error::new(
io::ErrorKind::InvalidInput,
"file transaction contains the same target path more than once",
),
});
}
}
let mut files = Vec::with_capacity(changes.len());
for (index, (target, bytes)) in changes.into_iter().enumerate() {
let staged = transaction_sibling_path(&target, id, "stage", index);
let backup = transaction_sibling_path(&target, id, "backup", index);
let backup_exists = match path_exists_without_following_symlinks(&backup) {
Ok(exists) => exists,
Err(source) => {
cleanup_staged_files(&files);
return Err(ThermoLibraryWriteError::WriteFailed {
path: backup.display().to_string(),
source,
});
}
};
if backup_exists {
cleanup_staged_files(&files);
return Err(ThermoLibraryWriteError::WriteFailed {
path: backup.display().to_string(),
source: io::Error::new(
io::ErrorKind::AlreadyExists,
"transaction backup path already exists",
),
});
}
let mut stage_file = match fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&staged)
{
Ok(file) => file,
Err(source) => {
cleanup_staged_files(&files);
return Err(ThermoLibraryWriteError::WriteFailed {
path: target.display().to_string(),
source,
});
}
};
let stage_result = stage_file
.write_all(&bytes)
.and_then(|()| stage_file.sync_all());
if let Err(source) = stage_result {
drop(stage_file);
let _ = fs::remove_file(&staged);
cleanup_staged_files(&files);
return Err(ThermoLibraryWriteError::WriteFailed {
path: target.display().to_string(),
source,
});
}
files.push(StagedFile {
target,
staged,
backup,
had_original: false,
installed: false,
});
}
for index in 0..files.len() {
let target = files[index].target.clone();
let staged = files[index].staged.clone();
let backup = files[index].backup.clone();
match regular_file_exists(&target) {
Ok(true) => {
if let Err(failure) = fs::rename(&target, &backup) {
let failed_path = target.display().to_string();
if let Some((rollback_path, rollback)) = rollback_file_transaction(&mut files) {
return Err(ThermoLibraryWriteError::TransactionRollbackFailed {
failed_path,
failure,
rollback_path,
rollback,
});
}
return Err(ThermoLibraryWriteError::WriteFailed {
path: failed_path,
source: failure,
});
}
files[index].had_original = true;
}
Ok(false) => {}
Err(failure) => {
let failed_path = target.display().to_string();
if let Some((rollback_path, rollback)) = rollback_file_transaction(&mut files) {
return Err(ThermoLibraryWriteError::TransactionRollbackFailed {
failed_path,
failure,
rollback_path,
rollback,
});
}
return Err(ThermoLibraryWriteError::WriteFailed {
path: failed_path,
source: failure,
});
}
}
if let Err(failure) = before_install(index, &target) {
let failed_path = target.display().to_string();
if let Some((rollback_path, rollback)) = rollback_file_transaction(&mut files) {
return Err(ThermoLibraryWriteError::TransactionRollbackFailed {
failed_path,
failure,
rollback_path,
rollback,
});
}
return Err(ThermoLibraryWriteError::WriteFailed {
path: failed_path,
source: failure,
});
}
if let Err(failure) = fs::rename(&staged, &target) {
let failed_path = target.display().to_string();
if let Some((rollback_path, rollback)) = rollback_file_transaction(&mut files) {
return Err(ThermoLibraryWriteError::TransactionRollbackFailed {
failed_path,
failure,
rollback_path,
rollback,
});
}
return Err(ThermoLibraryWriteError::WriteFailed {
path: failed_path,
source: failure,
});
}
files[index].installed = true;
}
let mut cleanup_failures = Vec::new();
for file in &files {
if file.had_original {
if let Err(source) = remove_backup(&file.backup) {
cleanup_failures.push((file.backup.display().to_string(), source));
}
}
}
if !cleanup_failures.is_empty() {
return Err(ThermoLibraryWriteError::BackupCleanupFailed {
failures: cleanup_failures,
});
}
Ok(())
}
#[allow(dead_code)]
fn write_json_file<T: serde::Serialize>(
path: &str,
value: &T,
) -> Result<(), ThermoLibraryWriteError> {
let path_buf = PathBuf::from(path);
let bytes = serialize_json(&path_buf, value)?;
commit_file_transaction(vec![(path_buf, bytes)])
}
#[allow(dead_code)]
fn append_journal_entry(
path: &str,
entry: ThermoLibraryJournalEntry,
) -> Result<(), ThermoLibraryWriteError> {
let mut entries: Vec<ThermoLibraryJournalEntry> = if Path::new(path).exists() {
read_json_file(path)?
} else {
Vec::new()
};
entries.push(entry);
write_json_file(path, &entries)
}
impl LibraryManager {
#[allow(dead_code)]
pub(crate) fn upsert_substance_in_library(
&self,
library: &str,
substance: &str,
substance_data: serde_json::Value,
) -> Result<ThermoLibraryWriteReport, ThermoLibraryWriteError> {
self.upsert_substance_in_library_with_format(library, substance, substance_data, "manual")
}
fn upsert_substance_in_library_with_format(
&self,
library: &str,
substance: &str,
substance_data: serde_json::Value,
source_format: &str,
) -> Result<ThermoLibraryWriteReport, ThermoLibraryWriteError> {
let substance_base_path = self.substance_base_path().to_string();
let all_keys_path = self.all_keys_substance_path().to_string();
let elements_path = self.elements_path().to_string();
let journal_path = self.thermo_write_journal_path().to_string();
let mut substance_base: HashMap<String, HashMap<String, serde_json::Value>> =
read_json_file(&substance_base_path)?;
let library_bucket = substance_base
.entry(library.to_string())
.or_insert_with(HashMap::new);
let replaced_existing = library_bucket
.insert(substance.to_string(), substance_data)
.is_some();
let validated_elements = build_elements_index(&substance_base)?;
let all_keys = all_keys_from_substance_base(&substance_base);
let mut journal: Vec<ThermoLibraryJournalEntry> = if Path::new(&journal_path).exists() {
read_json_file(&journal_path)?
} else {
Vec::new()
};
journal.push(ThermoLibraryJournalEntry {
timestamp: Local::now().to_rfc3339(),
operation: ThermoLibraryWriteOperation::Upsert,
source_format: source_format.to_string(),
library: library.to_string(),
substance: substance.to_string(),
canonical_names: vec![substance.to_string()],
files: vec![
substance_base_path.clone(),
all_keys_path.clone(),
elements_path.clone(),
],
});
commit_file_transaction(vec![
(
PathBuf::from(&substance_base_path),
serialize_json(Path::new(&substance_base_path), &substance_base)?,
),
(
PathBuf::from(&all_keys_path),
serialize_json(Path::new(&all_keys_path), &all_keys)?,
),
(
PathBuf::from(&elements_path),
serialize_json(Path::new(&elements_path), &validated_elements)?,
),
(
PathBuf::from(&journal_path),
serialize_json(Path::new(&journal_path), &journal)?,
),
])?;
Ok(ThermoLibraryWriteReport {
library: library.to_string(),
substance: substance.to_string(),
replaced_existing,
refreshed_all_keys: 1,
refreshed_elements: 1,
})
}
#[allow(dead_code)]
pub(crate) fn write_substance_from_spec(
&self,
spec: ThermoSubstanceWriteSpec,
) -> Result<ThermoLibraryWriteReport, ThermoLibraryWriteError> {
if let Some(expected_prefix) = spec.source_format.expected_library_prefix() {
if !spec.library.starts_with(expected_prefix) {
return Err(ThermoLibraryWriteError::LibraryFormatMismatch {
library: spec.library,
source_format: spec.source_format.as_str().to_string(),
});
}
}
let record = spec.clone().into_record();
let library = spec.library;
let substance = spec.substance;
let source_format = spec.source_format.as_str().to_string();
self.upsert_substance_in_library_with_format(&library, &substance, record, &source_format)
}
#[allow(dead_code)]
pub(crate) fn drop_substance_from_library(
&self,
library: &str,
substance: &str,
) -> Result<ThermoLibraryDropReport, ThermoLibraryWriteError> {
let substance_base_path = self.substance_base_path().to_string();
let all_keys_path = self.all_keys_substance_path().to_string();
let elements_path = self.elements_path().to_string();
let journal_path = self.thermo_write_journal_path().to_string();
let mut substance_base: HashMap<String, HashMap<String, serde_json::Value>> =
read_json_file(&substance_base_path)?;
let Some(library_bucket) = substance_base.get_mut(library) else {
return Err(ThermoLibraryWriteError::MissingLibraryEntry {
library: library.to_string(),
});
};
if library_bucket.remove(substance).is_none() {
return Err(ThermoLibraryWriteError::MissingSubstanceEntry {
library: library.to_string(),
substance: substance.to_string(),
});
}
if library_bucket.is_empty() {
substance_base.remove(library);
}
let validated_elements = build_elements_index(&substance_base)?;
let mut all_keys: Vec<(String, String)> = read_json_file(&all_keys_path)?;
let removed_from_all_keys_before = all_keys.len();
let elements: HashMap<String, Vec<Vec<String>>> = read_json_file(&elements_path)?;
all_keys.retain(|(lib, sub)| !(lib == library && sub == substance));
let removed_from_all_keys = removed_from_all_keys_before.saturating_sub(all_keys.len());
let removed_from_elements = elements
.values()
.flatten()
.filter(|pair| pair.len() >= 2 && pair[0] == substance && pair[1] == library)
.count();
let all_keys = all_keys_from_substance_base(&substance_base);
let mut journal: Vec<ThermoLibraryJournalEntry> = if Path::new(&journal_path).exists() {
read_json_file(&journal_path)?
} else {
Vec::new()
};
journal.push(ThermoLibraryJournalEntry {
timestamp: Local::now().to_rfc3339(),
source_format: "manual".to_string(),
operation: ThermoLibraryWriteOperation::Drop,
library: library.to_string(),
substance: substance.to_string(),
canonical_names: vec![substance.to_string()],
files: vec![
substance_base_path.clone(),
all_keys_path.clone(),
elements_path.clone(),
],
});
commit_file_transaction(vec![
(
PathBuf::from(&substance_base_path),
serialize_json(Path::new(&substance_base_path), &substance_base)?,
),
(
PathBuf::from(&all_keys_path),
serialize_json(Path::new(&all_keys_path), &all_keys)?,
),
(
PathBuf::from(&elements_path),
serialize_json(Path::new(&elements_path), &validated_elements)?,
),
(
PathBuf::from(&journal_path),
serialize_json(Path::new(&journal_path), &journal)?,
),
])?;
Ok(ThermoLibraryDropReport {
library: library.to_string(),
substance: substance.to_string(),
removed_from_substance_base: true,
removed_from_all_keys,
removed_from_elements,
})
}
pub fn recreate_all_keys_substance(&self) -> Result<(), Box<dyn std::error::Error>> {
let substance_base_path = self.substance_base_path();
let all_keys_path = self.all_keys_substance_path();
let substance_base: HashMap<String, HashMap<String, serde_json::Value>> =
read_json_file(substance_base_path)?;
let all_keys = all_keys_from_substance_base(&substance_base);
write_json_file(all_keys_path, &all_keys)?;
Ok(())
}
pub fn audit_elements_base(
&self,
) -> Result<ElementIndexAuditReport, Box<dyn std::error::Error>> {
let base_path = self.substance_base_path();
let index_path = self.elements_path();
let base_bytes = fs::read(base_path)?;
let raw_addresses: RawSourceAddresses = serde_json::from_slice(&base_bytes)?;
let base: serde_json::Value = serde_json::from_slice(&base_bytes)?;
let current: HashMap<String, Vec<Vec<String>>> =
serde_json::from_slice(&fs::read(index_path)?)?;
let databases = base
.as_object()
.ok_or("substance base root must be a JSON object")?;
let mut report = ElementIndexAuditReport {
records_seen: 0,
records_with_valid_composition: 0,
records_missing_composition: Vec::new(),
records_with_invalid_composition: Vec::new(),
missing_index_entries: Vec::new(),
stale_index_entries: Vec::new(),
duplicate_index_entries: Vec::new(),
duplicate_canonical_source_addresses: Vec::new(),
};
let mut address_counts = BTreeMap::<(String, String), usize>::new();
for (library, substance) in raw_addresses.0 {
let canonical =
crate::Thermodynamics::thermo_lib_api::ThermoData::canonical_library_name(&library);
*address_counts.entry((canonical, substance)).or_default() += 1;
}
report.duplicate_canonical_source_addresses = address_counts
.into_iter()
.filter_map(|((library, substance), count)| {
(count > 1).then(|| format!("{library}/{substance} ({count} raw entries)"))
})
.collect();
let mut expected = BTreeSet::new();
for (library, bucket) in databases {
let Some(records) = bucket.as_object() else {
report
.records_with_invalid_composition
.push(ElementIndexAuditIssue {
record: library.clone(),
reason: "library bucket must be a JSON object".into(),
});
continue;
};
for (substance, payload) in records {
report.records_seen += 1;
let key = format!("{library}/{substance}");
let Some(composition) = payload.get("composition") else {
report.records_missing_composition.push(key);
continue;
};
let Some(composition) = composition.as_str() else {
report
.records_with_invalid_composition
.push(ElementIndexAuditIssue {
record: key,
reason: "composition must be a string".into(),
});
continue;
};
match parse_element_composition(composition) {
Ok(elements) => {
report.records_with_valid_composition += 1;
for element in elements {
expected.insert((element, substance.clone(), library.clone()));
}
}
Err(reason) => {
report
.records_with_invalid_composition
.push(ElementIndexAuditIssue {
record: key,
reason,
})
}
}
}
}
let mut observed = BTreeSet::new();
for (element, entries) in ¤t {
for entry in entries {
if entry.len() != 2 {
report.stale_index_entries.push(format!(
"{element}: malformed entry {entry:?}; expected [substance, library]"
));
continue;
}
let pair = (element.clone(), entry[0].clone(), entry[1].clone());
if !observed.insert(pair.clone()) {
report
.duplicate_index_entries
.push(format!("{} [{}, {}]", pair.0, pair.1, pair.2));
}
}
}
for pair in expected.difference(&observed) {
report
.missing_index_entries
.push(format!("{} [{}, {}]", pair.0, pair.1, pair.2));
}
for pair in observed.difference(&expected) {
report
.stale_index_entries
.push(format!("{} [{}, {}]", pair.0, pair.1, pair.2));
}
Ok(report)
}
pub fn create_elements_base(&self) -> Result<(), Box<dyn std::error::Error>> {
let substance_base_path = self.substance_base_path();
let elements_path = self.elements_path();
if !Path::new(substance_base_path).exists() {
return Err(
format!("SubstanceBase file does not exist: {}", substance_base_path).into(),
);
}
let substance_base: HashMap<String, HashMap<String, serde_json::Value>> =
read_json_file(substance_base_path)?;
let elements_map = build_elements_index(&substance_base)?;
write_json_file(elements_path, &elements_map)?;
Ok(())
}
}
fn all_keys_from_substance_base(
substance_base: &HashMap<String, HashMap<String, serde_json::Value>>,
) -> Vec<(String, String)> {
let mut keys = substance_base
.iter()
.flat_map(|(library, substances)| {
substances
.keys()
.map(|substance| (library.clone(), substance.clone()))
})
.collect::<Vec<_>>();
keys.sort();
keys
}
fn build_elements_index(
substance_base: &HashMap<String, HashMap<String, serde_json::Value>>,
) -> Result<HashMap<String, Vec<Vec<String>>>, ThermoLibraryWriteError> {
let mut elements = HashMap::<String, Vec<Vec<String>>>::new();
for (library, records) in substance_base {
for (substance, payload) in records {
let Some(composition) = payload.get("composition") else {
continue;
};
let Some(composition) = composition.as_str() else {
return Err(ThermoLibraryWriteError::InvalidComposition {
library: library.clone(),
substance: substance.clone(),
reason: "composition must be a string".into(),
});
};
let parsed = parse_element_composition(composition).map_err(|reason| {
ThermoLibraryWriteError::InvalidComposition {
library: library.clone(),
substance: substance.clone(),
reason,
}
})?;
for element in parsed {
elements
.entry(element)
.or_default()
.push(vec![substance.clone(), library.clone()]);
}
}
}
for records in elements.values_mut() {
records.sort();
}
Ok(elements)
}
fn parse_element_composition(value: &str) -> Result<BTreeSet<String>, String> {
let value = value.trim();
let body = value
.strip_prefix('{')
.and_then(|value| value.strip_suffix('}'))
.ok_or_else(|| "composition must be enclosed in braces".to_string())?;
if body.trim().is_empty() {
return Err("composition must contain at least one element".into());
}
let mut elements = BTreeSet::new();
for pair in body.split(',') {
let (element, amount) = pair
.split_once(':')
.ok_or_else(|| format!("missing ':' in composition entry {pair:?}"))?;
let element = element.trim();
if element.is_empty() {
return Err("composition contains an empty element name".into());
}
let amount = amount
.trim()
.parse::<f64>()
.map_err(|_| format!("invalid atom count in composition entry {pair:?}"))?;
if !amount.is_finite() || amount == 0.0 {
return Err(format!(
"composition count must be finite and nonzero in {pair:?}"
));
}
if !elements.insert(element.to_string()) {
return Err(format!("duplicate element {element:?}"));
}
}
Ok(elements)
}
#[cfg(test)]
mod write_workflow_tests {
use super::*;
use serde_json::json;
use tempfile::tempdir;
#[test]
#[ignore = "prints a read-only audit of the bundled thermochemistry element index"]
fn print_bundled_element_index_audit_table() {
use tabled::{builder::Builder, settings::Style};
let manager = LibraryManager::new();
let report = manager
.audit_elements_base()
.expect("bundled element-index audit should complete");
let base: serde_json::Value =
serde_json::from_slice(&fs::read(manager.substance_base_path()).unwrap()).unwrap();
let index: HashMap<String, Vec<Vec<String>>> =
serde_json::from_slice(&fs::read(manager.elements_path()).unwrap()).unwrap();
let mut table = Builder::default();
table.push_record([
"Library",
"Records",
"Composition OK",
"No composition",
"Invalid composition",
"Indexed pairs",
]);
if let Some(libraries) = base.as_object() {
let mut names: Vec<_> = libraries.keys().collect();
names.sort();
for library in names {
let records = libraries[library].as_object().unwrap();
let mut valid = 0usize;
let mut missing = 0usize;
let mut invalid = 0usize;
for payload in records.values() {
match payload
.get("composition")
.and_then(serde_json::Value::as_str)
{
None => missing += 1,
Some(value) if parse_element_composition(value).is_ok() => valid += 1,
Some(_) => invalid += 1,
}
}
let indexed = index
.values()
.flatten()
.filter(|pair| pair.len() == 2 && pair[1] == *library)
.count();
table.push_record([
library.clone(),
records.len().to_string(),
valid.to_string(),
missing.to_string(),
invalid.to_string(),
indexed.to_string(),
]);
}
}
println!(
"Bundled element-index audit (read-only):\n{}",
table.build().with(Style::rounded())
);
println!(
"Overall: records={}, valid_composition={}, missing_composition={}, invalid_composition={}, missing_index={}, stale_index={}, duplicate_index={}, duplicate_source_addresses={}",
report.records_seen,
report.records_with_valid_composition,
report.records_missing_composition.len(),
report.records_with_invalid_composition.len(),
report.missing_index_entries.len(),
report.stale_index_entries.len(),
report.duplicate_index_entries.len(),
report.duplicate_canonical_source_addresses.len(),
);
for issue in report.records_with_invalid_composition.iter().take(20) {
println!("INVALID {}: {}", issue.record, issue.reason);
}
for entry in report.missing_index_entries.iter().take(20) {
println!("MISSING INDEX {entry}");
}
for entry in report.stale_index_entries.iter().take(20) {
println!("STALE INDEX {entry}");
}
for entry in report.duplicate_canonical_source_addresses.iter().take(20) {
println!("DUPLICATE SOURCE ADDRESS {entry}");
}
}
#[test]
fn element_index_audit_reports_composition_and_index_drift_without_writes() {
let dir = tempdir().expect("tempdir should be created");
let config_path = dir.path().join("library_config.json");
let base_path = dir.path().join("substance_base.json");
let index_path = dir.path().join("elements.json");
fs::write(
&base_path,
serde_json::to_vec(&json!({
"NASA_gas": {
"H2O": { "composition": "{H:2, O:1}" },
"Broken": { "composition": "{C:1, malformed}" },
"Unknown": { "Cp": [1.0] }
}
}))
.unwrap(),
)
.unwrap();
fs::write(
&index_path,
serde_json::to_vec(&json!({ "H": [["H2O", "NASA_gas"]], "X": [["Old", "NASA_gas"]] }))
.unwrap(),
)
.unwrap();
let index_before = fs::read(&index_path).unwrap();
let mut manager = LibraryManager::with_config_file(config_path.to_str().unwrap());
manager
.set_substance_base(base_path.to_str().unwrap())
.unwrap();
manager.set_elements(index_path.to_str().unwrap()).unwrap();
let report = manager.audit_elements_base().unwrap();
assert_eq!(report.records_seen, 3);
assert_eq!(report.records_with_valid_composition, 1);
assert_eq!(report.records_missing_composition, vec!["NASA_gas/Unknown"]);
assert_eq!(report.records_with_invalid_composition.len(), 1);
assert_eq!(report.missing_index_entries, vec!["O [H2O, NASA_gas]"]);
assert_eq!(report.stale_index_entries, vec!["X [Old, NASA_gas]"]);
assert!(report.duplicate_canonical_source_addresses.is_empty());
assert!(!report.is_clean());
assert_eq!(fs::read(&index_path).unwrap(), index_before);
}
#[test]
fn element_audit_detects_raw_duplicate_and_aliased_canonical_addresses() {
let dir = tempdir().expect("tempdir should be created");
let config_path = dir.path().join("library_config.json");
let base_path = dir.path().join("substance_base.json");
let index_path = dir.path().join("elements.json");
let raw_base = br#"{
"NASA_gas": {
"CO": {"composition": "{C:1, O:1}", "revision": 1},
"CO": {"composition": "{C:1, O:1}", "revision": 2}
},
"Cantera_nasa_base_gas": {
"CO": {"composition": "{C:1, O:1}"}
}
}"#;
fs::write(&base_path, raw_base).unwrap();
fs::write(
&index_path,
serde_json::to_vec(&json!({
"C": [["CO", "NASA_gas"], ["CO", "Cantera_nasa_base_gas"]],
"O": [["CO", "NASA_gas"], ["CO", "Cantera_nasa_base_gas"]]
}))
.unwrap(),
)
.unwrap();
let mut manager = LibraryManager::with_config_file(config_path.to_str().unwrap());
manager
.set_substance_base(base_path.to_str().unwrap())
.unwrap();
manager.set_elements(index_path.to_str().unwrap()).unwrap();
let before = fs::read(&base_path).unwrap();
let report = manager.audit_elements_base().unwrap();
assert_eq!(report.records_seen, 2);
assert_eq!(
report.duplicate_canonical_source_addresses,
vec!["NASA_gas/CO (3 raw entries)"]
);
assert!(!report.is_clean());
assert_eq!(fs::read(&base_path).unwrap(), before);
}
#[test]
fn bundled_thermo_catalog_has_no_duplicate_canonical_source_addresses() {
let report = LibraryManager::new()
.audit_elements_base()
.expect("bundled read-only catalog audit should succeed");
assert!(
report.duplicate_canonical_source_addresses.is_empty(),
"duplicate canonical source addresses: {:?}",
report.duplicate_canonical_source_addresses
);
}
#[test]
fn element_index_generation_rejects_malformed_composition_without_writing() {
let dir = tempdir().expect("tempdir should be created");
let config_path = dir.path().join("library_config.json");
let base_path = dir.path().join("substance_base.json");
let index_path = dir.path().join("elements.json");
fs::write(
&base_path,
serde_json::to_vec(&json!({
"NASA_gas": {
"H2O": { "composition": "{H:2, O:1}" },
"Broken": { "composition": "{C:1, malformed}" },
"NoComposition": { "Cp": [1.0] }
}
}))
.unwrap(),
)
.unwrap();
fs::write(&index_path, b"old-index").unwrap();
let mut manager = LibraryManager::with_config_file(config_path.to_str().unwrap());
manager
.set_substance_base(base_path.to_str().unwrap())
.unwrap();
manager.set_elements(index_path.to_str().unwrap()).unwrap();
let error = manager
.create_elements_base()
.expect_err("malformed composition must reject index generation");
assert!(error.to_string().contains("NASA_gas"));
assert!(error.to_string().contains("Broken"));
assert_eq!(fs::read(&index_path).unwrap(), b"old-index");
}
#[test]
fn invalid_composition_upsert_does_not_publish_partial_catalog() {
let dir = tempdir().expect("tempdir should be created");
let config_path = dir.path().join("library_config.json");
let base_path = dir.path().join("substance_base.json");
let all_keys_path = dir.path().join("all_keys_substance.json");
let elements_path = dir.path().join("elements.json");
let journal_path = dir.path().join("thermo_write_journal.json");
fs::write(
&base_path,
serde_json::to_vec(&json!({
"NASA_gas": { "H2O": { "composition": "{H:2, O:1}" } }
}))
.unwrap(),
)
.unwrap();
fs::write(&all_keys_path, b"old-keys").unwrap();
fs::write(&elements_path, b"old-index").unwrap();
fs::write(&journal_path, b"[]").unwrap();
let base_before = fs::read(&base_path).unwrap();
let mut manager = LibraryManager::with_config_file(config_path.to_str().unwrap());
manager
.set_substance_base(base_path.to_str().unwrap())
.unwrap();
manager
.set_all_keys_substance(all_keys_path.to_str().unwrap())
.unwrap();
manager
.set_elements(elements_path.to_str().unwrap())
.unwrap();
manager
.set_thermo_write_journal(journal_path.to_str().unwrap())
.unwrap();
let error = manager
.upsert_substance_in_library(
"NASA_gas",
"Broken",
json!({ "composition": "{C:1, malformed}" }),
)
.expect_err("invalid composition must reject the upsert");
assert!(error.to_string().contains("NASA_gas"));
assert!(error.to_string().contains("Broken"));
assert_eq!(fs::read(&base_path).unwrap(), base_before);
assert_eq!(fs::read(&all_keys_path).unwrap(), b"old-keys");
assert_eq!(fs::read(&elements_path).unwrap(), b"old-index");
assert_eq!(fs::read(&journal_path).unwrap(), b"[]");
}
#[test]
fn multi_file_publication_rolls_back_when_a_later_install_fails() {
let dir = tempdir().expect("tempdir should be created");
let first = dir.path().join("substance_base.json");
let second = dir.path().join("all_keys.json");
let third = dir.path().join("elements.json");
fs::write(&first, b"old-base").unwrap();
fs::write(&second, b"old-keys").unwrap();
fs::write(&third, b"old-elements").unwrap();
let error = commit_file_transaction_with_hook(
vec![
(first.clone(), b"new-base".to_vec()),
(second.clone(), b"new-keys".to_vec()),
(third.clone(), b"new-elements".to_vec()),
],
|index, _| {
if index == 1 {
Err(io::Error::other("injected install failure"))
} else {
Ok(())
}
},
)
.expect_err("injected later-file failure must abort the transaction");
assert!(error.to_string().contains("injected install failure"));
assert_eq!(fs::read(&first).unwrap(), b"old-base");
assert_eq!(fs::read(&second).unwrap(), b"old-keys");
assert_eq!(fs::read(&third).unwrap(), b"old-elements");
let leftovers = fs::read_dir(dir.path())
.unwrap()
.map(|entry| entry.unwrap().file_name())
.filter(|name| {
name.to_string_lossy().contains(".stage")
|| name.to_string_lossy().contains(".backup")
})
.collect::<Vec<_>>();
assert!(
leftovers.is_empty(),
"transaction temp files remain: {leftovers:?}"
);
}
#[test]
fn catalog_transaction_rejects_directory_targets_and_rolls_back_prior_files() {
let dir = tempdir().expect("tempdir should be created");
let first = dir.path().join("substance_base.json");
let directory_target = dir.path().join("elements.json");
fs::write(&first, b"old-base").unwrap();
fs::create_dir(&directory_target).unwrap();
fs::write(directory_target.join("keep.txt"), b"preserve-me").unwrap();
let error = commit_file_transaction(vec![
(first.clone(), b"new-base".to_vec()),
(directory_target.clone(), b"new-index".to_vec()),
])
.expect_err("a directory must not be moved or replaced as a catalog file");
assert!(error.to_string().contains("regular file"));
assert_eq!(fs::read(&first).unwrap(), b"old-base");
assert_eq!(
fs::read(directory_target.join("keep.txt")).unwrap(),
b"preserve-me"
);
let leftovers = fs::read_dir(dir.path())
.unwrap()
.map(|entry| entry.unwrap().file_name())
.filter(|name| {
name.to_string_lossy().contains(".stage")
|| name.to_string_lossy().contains(".backup")
})
.collect::<Vec<_>>();
assert!(
leftovers.is_empty(),
"transaction temp files remain: {leftovers:?}"
);
}
#[test]
fn stage_name_collision_does_not_remove_the_preexisting_file() {
let dir = tempdir().expect("tempdir should be created");
let target = dir.path().join("catalog.json");
let transaction_id = u64::MAX;
let staged = transaction_sibling_path(&target, transaction_id, "stage", 0);
fs::write(&staged, b"owned-by-another-process").unwrap();
let error = commit_file_transaction_with_id_and_hook(
vec![(target.clone(), b"new-catalog".to_vec())],
transaction_id,
|_, _| Ok(()),
)
.expect_err("create_new must reject an existing stage path");
assert!(matches!(
error,
ThermoLibraryWriteError::WriteFailed { source, .. }
if source.kind() == io::ErrorKind::AlreadyExists
));
assert_eq!(fs::read(&staged).unwrap(), b"owned-by-another-process");
assert!(!target.exists());
}
#[test]
fn backup_cleanup_error_reports_committed_catalog_without_rolling_it_back() {
let dir = tempdir().expect("tempdir should be created");
let target = dir.path().join("catalog.json");
fs::write(&target, b"old-catalog").unwrap();
let id = u64::MAX - 1;
let error = commit_file_transaction_with_hooks(
vec![(target.clone(), b"new-catalog".to_vec())],
id,
|_, _| Ok(()),
|_| Err(io::Error::other("injected backup cleanup failure")),
)
.expect_err("backup cleanup failure must be surfaced");
assert!(matches!(
error,
ThermoLibraryWriteError::BackupCleanupFailed { .. }
));
assert!(error.to_string().contains("publication committed"));
assert!(
error
.to_string()
.contains("injected backup cleanup failure")
);
assert_eq!(fs::read(&target).unwrap(), b"new-catalog");
let backup = transaction_sibling_path(&target, id, "backup", 0);
assert_eq!(fs::read(backup).unwrap(), b"old-catalog");
}
#[test]
fn recreating_all_keys_uses_the_shared_atomic_catalog_writer() {
let dir = tempdir().expect("tempdir should be created");
let config_path = dir.path().join("library_config.json");
let base_path = dir.path().join("substance_base.json");
let all_keys_path = dir.path().join("all_keys_substance.json");
fs::write(
&base_path,
serde_json::to_vec(&json!({
"NASA_gas": {"H2O": {}, "H2": {}},
"NASA_cond": {"C(gr)": {}}
}))
.unwrap(),
)
.unwrap();
fs::write(&all_keys_path, b"old-catalog").unwrap();
let mut manager = LibraryManager::with_config_file(config_path.to_str().unwrap());
manager
.set_substance_base(base_path.to_str().unwrap())
.unwrap();
manager
.set_all_keys_substance(all_keys_path.to_str().unwrap())
.unwrap();
manager
.recreate_all_keys_substance()
.expect("catalog recreation should publish the sorted key list");
let all_keys: Vec<(String, String)> =
serde_json::from_slice(&fs::read(&all_keys_path).unwrap()).unwrap();
assert_eq!(
all_keys,
vec![
("NASA_cond".to_string(), "C(gr)".to_string()),
("NASA_gas".to_string(), "H2".to_string()),
("NASA_gas".to_string(), "H2O".to_string()),
]
);
}
#[test]
fn upsert_staging_failure_leaves_every_catalog_file_unchanged() {
let dir = tempdir().expect("tempdir should be created");
let config_path = dir.path().join("library_config.json");
let base_path = dir.path().join("substance_base.json");
let all_keys_path = dir.path().join("all_keys_substance.json");
let elements_path = dir.path().join("elements.json");
let journal_path = dir.path().join("missing").join("thermo_write_journal.json");
fs::write(
&base_path,
serde_json::to_vec(&json!({
"NASA_gas": { "H2O": { "composition": "{H:2, O:1}" } }
}))
.unwrap(),
)
.unwrap();
fs::write(&all_keys_path, b"old-keys").unwrap();
fs::write(&elements_path, b"old-index").unwrap();
fs::create_dir(journal_path.parent().unwrap()).unwrap();
fs::write(&journal_path, b"[]").unwrap();
let before = [
fs::read(&base_path).unwrap(),
fs::read(&all_keys_path).unwrap(),
fs::read(&elements_path).unwrap(),
];
let mut manager = LibraryManager::with_config_file(config_path.to_str().unwrap());
manager
.set_substance_base(base_path.to_str().unwrap())
.unwrap();
manager
.set_all_keys_substance(all_keys_path.to_str().unwrap())
.unwrap();
manager
.set_elements(elements_path.to_str().unwrap())
.unwrap();
manager
.set_thermo_write_journal(journal_path.to_str().unwrap())
.unwrap();
fs::remove_file(&journal_path).unwrap();
fs::remove_dir(journal_path.parent().unwrap()).unwrap();
let error = manager
.upsert_substance_in_library("NASA_gas", "CO", json!({"composition": "{C:1, O:1}"}))
.expect_err("unwritable journal path must abort the complete upsert");
assert!(error.to_string().contains("thermo_write_journal.json"));
assert_eq!(fs::read(&base_path).unwrap(), before[0]);
assert_eq!(fs::read(&all_keys_path).unwrap(), before[1]);
assert_eq!(fs::read(&elements_path).unwrap(), before[2]);
}
#[test]
fn drop_staging_failure_leaves_every_catalog_file_unchanged() {
let dir = tempdir().expect("tempdir should be created");
let config_path = dir.path().join("library_config.json");
let base_path = dir.path().join("substance_base.json");
let all_keys_path = dir.path().join("all_keys_substance.json");
let elements_path = dir.path().join("elements.json");
let journal_path = dir.path().join("missing").join("thermo_write_journal.json");
fs::write(
&base_path,
serde_json::to_vec(&json!({
"NASA_gas": {
"CO": { "composition": "{C:1, O:1}" },
"H2O": { "composition": "{H:2, O:1}" }
}
}))
.unwrap(),
)
.unwrap();
fs::write(
&all_keys_path,
serde_json::to_vec(&json!([["NASA_gas", "CO"], ["NASA_gas", "H2O"]])).unwrap(),
)
.unwrap();
fs::write(
&elements_path,
serde_json::to_vec(&json!({
"C": [["CO", "NASA_gas"]],
"H": [["H2O", "NASA_gas"]],
"O": [["CO", "NASA_gas"], ["H2O", "NASA_gas"]]
}))
.unwrap(),
)
.unwrap();
fs::create_dir(journal_path.parent().unwrap()).unwrap();
fs::write(&journal_path, b"[]").unwrap();
let before = [
fs::read(&base_path).unwrap(),
fs::read(&all_keys_path).unwrap(),
fs::read(&elements_path).unwrap(),
];
let mut manager = LibraryManager::with_config_file(config_path.to_str().unwrap());
manager
.set_substance_base(base_path.to_str().unwrap())
.unwrap();
manager
.set_all_keys_substance(all_keys_path.to_str().unwrap())
.unwrap();
manager
.set_elements(elements_path.to_str().unwrap())
.unwrap();
manager
.set_thermo_write_journal(journal_path.to_str().unwrap())
.unwrap();
fs::remove_file(&journal_path).unwrap();
fs::remove_dir(journal_path.parent().unwrap()).unwrap();
let error = manager
.drop_substance_from_library("NASA_gas", "CO")
.expect_err("unwritable journal path must abort the complete drop");
assert!(error.to_string().contains("thermo_write_journal.json"));
assert_eq!(fs::read(&base_path).unwrap(), before[0]);
assert_eq!(fs::read(&all_keys_path).unwrap(), before[1]);
assert_eq!(fs::read(&elements_path).unwrap(), before[2]);
}
#[test]
fn drop_substance_updates_all_catalog_files() {
let dir = tempdir().expect("tempdir should be created");
let config_path = dir.path().join("library_config.json");
let substance_base_path = dir.path().join("substance_base.json");
let all_keys_path = dir.path().join("all_keys_substance.json");
let elements_path = dir.path().join("elements.json");
let journal_path = dir.path().join("thermo_write_journal.json");
let substance_base = json!({
"NASA_gas": {
"CO": { "composition": "{C:1, O:1}", "Cp": [1.0] },
"H2O": { "composition": "{H:2, O:1}", "Cp": [2.0] }
},
"NIST": {
"CO": { "composition": "{C:1, O:1}", "Cp": [3.0] }
}
});
let all_keys = json!([["NASA_gas", "CO"], ["NASA_gas", "H2O"], ["NIST", "CO"]]);
let elements = json!({
"C": [["CO", "NASA_gas"], ["CO", "NIST"]],
"H": [["H2O", "NASA_gas"]],
"O": [["CO", "NASA_gas"], ["H2O", "NASA_gas"], ["CO", "NIST"]]
});
fs::write(
&substance_base_path,
serde_json::to_string_pretty(&substance_base).unwrap(),
)
.unwrap();
fs::write(
&all_keys_path,
serde_json::to_string_pretty(&all_keys).unwrap(),
)
.unwrap();
fs::write(
&elements_path,
serde_json::to_string_pretty(&elements).unwrap(),
)
.unwrap();
fs::write(&journal_path, "[]").unwrap();
let mut manager = LibraryManager::with_config_file(config_path.to_str().unwrap());
manager
.set_substance_base(substance_base_path.to_str().unwrap())
.unwrap();
manager
.set_all_keys_substance(all_keys_path.to_str().unwrap())
.unwrap();
manager
.set_elements(elements_path.to_str().unwrap())
.unwrap();
manager
.set_thermo_write_journal(journal_path.to_str().unwrap())
.unwrap();
let report = manager
.drop_substance_from_library("NASA_gas", "CO")
.expect("drop should succeed");
assert_eq!(report.library, "NASA_gas");
assert_eq!(report.substance, "CO");
assert!(report.removed_from_substance_base);
assert_eq!(report.removed_from_all_keys, 1);
assert_eq!(report.removed_from_elements, 2);
let updated_base: HashMap<String, HashMap<String, serde_json::Value>> =
serde_json::from_str(&fs::read_to_string(&substance_base_path).unwrap()).unwrap();
assert!(!updated_base.get("NASA_gas").unwrap().contains_key("CO"));
assert!(updated_base.get("NASA_gas").unwrap().contains_key("H2O"));
assert!(updated_base.get("NIST").unwrap().contains_key("CO"));
let updated_all_keys: Vec<(String, String)> =
serde_json::from_str(&fs::read_to_string(&all_keys_path).unwrap()).unwrap();
assert_eq!(
updated_all_keys,
vec![
("NASA_gas".to_string(), "H2O".to_string()),
("NIST".to_string(), "CO".to_string())
]
);
let updated_elements: HashMap<String, Vec<Vec<String>>> =
serde_json::from_str(&fs::read_to_string(&elements_path).unwrap()).unwrap();
assert_eq!(
updated_elements.get("C").unwrap(),
&vec![vec!["CO".to_string(), "NIST".to_string()]]
);
assert_eq!(
updated_elements.get("H").unwrap(),
&vec![vec!["H2O".to_string(), "NASA_gas".to_string()]]
);
assert_eq!(
updated_elements.get("O").unwrap(),
&vec![
vec!["CO".to_string(), "NIST".to_string()],
vec!["H2O".to_string(), "NASA_gas".to_string()]
]
);
let journal: Vec<ThermoLibraryJournalEntry> =
serde_json::from_str(&fs::read_to_string(&journal_path).unwrap()).unwrap();
assert_eq!(journal.len(), 1);
assert_eq!(journal[0].operation, ThermoLibraryWriteOperation::Drop);
assert_eq!(journal[0].library, "NASA_gas");
assert_eq!(journal[0].substance, "CO");
assert_eq!(journal[0].canonical_names, vec!["CO".to_string()]);
assert_eq!(
journal[0].files,
vec![
substance_base_path.to_str().unwrap().to_string(),
all_keys_path.to_str().unwrap().to_string(),
elements_path.to_str().unwrap().to_string()
]
);
}
#[test]
fn drop_substance_rejects_missing_pair() {
let dir = tempdir().expect("tempdir should be created");
let config_path = dir.path().join("library_config.json");
let substance_base_path = dir.path().join("substance_base.json");
let all_keys_path = dir.path().join("all_keys_substance.json");
let elements_path = dir.path().join("elements.json");
let journal_path = dir.path().join("thermo_write_journal.json");
let substance_base = json!({
"NASA_gas": {
"H2O": { "composition": "{H:2, O:1}", "Cp": [2.0] }
}
});
let all_keys = json!([["NASA_gas", "H2O"]]);
let elements = json!({
"H": [["H2O", "NASA_gas"]],
"O": [["H2O", "NASA_gas"]]
});
fs::write(
&substance_base_path,
serde_json::to_string_pretty(&substance_base).unwrap(),
)
.unwrap();
fs::write(
&all_keys_path,
serde_json::to_string_pretty(&all_keys).unwrap(),
)
.unwrap();
fs::write(
&elements_path,
serde_json::to_string_pretty(&elements).unwrap(),
)
.unwrap();
fs::write(&journal_path, "[]").unwrap();
let mut manager = LibraryManager::with_config_file(config_path.to_str().unwrap());
manager
.set_substance_base(substance_base_path.to_str().unwrap())
.unwrap();
manager
.set_all_keys_substance(all_keys_path.to_str().unwrap())
.unwrap();
manager
.set_elements(elements_path.to_str().unwrap())
.unwrap();
manager
.set_thermo_write_journal(journal_path.to_str().unwrap())
.unwrap();
let err = manager
.drop_substance_from_library("NASA_gas", "CO")
.expect_err("missing substance should fail");
let message = err.to_string();
assert!(message.contains("substance 'CO'"));
assert!(message.contains("NASA_gas"));
let journal: Vec<ThermoLibraryJournalEntry> =
serde_json::from_str(&fs::read_to_string(&journal_path).unwrap()).unwrap();
assert!(journal.is_empty());
}
#[test]
fn upsert_substance_updates_all_catalog_files_without_touching_real_paths() {
let dir = tempdir().expect("tempdir should be created");
let config_path = dir.path().join("library_config.json");
let substance_base_path = dir.path().join("substance_base.json");
let all_keys_path = dir.path().join("all_keys_substance.json");
let elements_path = dir.path().join("elements.json");
let journal_path = dir.path().join("thermo_write_journal.json");
let substance_base = json!({
"NASA_gas": {
"H2O": { "composition": "{H:2, O:1}", "Cp": [2.0] }
},
"NIST": {
"CO": { "composition": "{C:1, O:1}", "Cp": [3.0] }
}
});
let all_keys = json!([["NASA_gas", "H2O"], ["NIST", "CO"]]);
let elements = json!({
"C": [["CO", "NIST"]],
"H": [["H2O", "NASA_gas"]],
"O": [["CO", "NIST"], ["H2O", "NASA_gas"]]
});
fs::write(
&substance_base_path,
serde_json::to_string_pretty(&substance_base).unwrap(),
)
.unwrap();
fs::write(
&all_keys_path,
serde_json::to_string_pretty(&all_keys).unwrap(),
)
.unwrap();
fs::write(
&elements_path,
serde_json::to_string_pretty(&elements).unwrap(),
)
.unwrap();
fs::write(&journal_path, "[]").unwrap();
let mut manager = LibraryManager::with_config_file(config_path.to_str().unwrap());
manager
.set_substance_base(substance_base_path.to_str().unwrap())
.unwrap();
manager
.set_all_keys_substance(all_keys_path.to_str().unwrap())
.unwrap();
manager
.set_elements(elements_path.to_str().unwrap())
.unwrap();
manager
.set_thermo_write_journal(journal_path.to_str().unwrap())
.unwrap();
let report = manager
.write_substance_from_spec(ThermoSubstanceWriteSpec {
library: "NASA_gas".to_string(),
substance: "CH4".to_string(),
source_format: ThermoSubstanceSourceFormat::Nasa,
composition: "{C:1, H:4}".to_string(),
fields: BTreeMap::from([("Cp".to_string(), json!([4.0]))]),
})
.expect("upsert should succeed");
assert_eq!(report.library, "NASA_gas");
assert_eq!(report.substance, "CH4");
assert!(!report.replaced_existing);
assert_eq!(report.refreshed_all_keys, 1);
assert_eq!(report.refreshed_elements, 1);
let updated_base: HashMap<String, HashMap<String, serde_json::Value>> =
serde_json::from_str(&fs::read_to_string(&substance_base_path).unwrap()).unwrap();
assert!(updated_base.get("NASA_gas").unwrap().contains_key("CH4"));
assert!(updated_base.get("NASA_gas").unwrap().contains_key("H2O"));
assert!(updated_base.get("NIST").unwrap().contains_key("CO"));
let updated_all_keys: Vec<(String, String)> =
serde_json::from_str(&fs::read_to_string(&all_keys_path).unwrap()).unwrap();
assert_eq!(
updated_all_keys,
vec![
("NASA_gas".to_string(), "CH4".to_string()),
("NASA_gas".to_string(), "H2O".to_string()),
("NIST".to_string(), "CO".to_string())
]
);
let updated_elements: HashMap<String, Vec<Vec<String>>> =
serde_json::from_str(&fs::read_to_string(&elements_path).unwrap()).unwrap();
assert_eq!(
updated_elements.get("C").unwrap(),
&vec![
vec!["CH4".to_string(), "NASA_gas".to_string()],
vec!["CO".to_string(), "NIST".to_string()]
]
);
assert_eq!(
updated_elements.get("H").unwrap(),
&vec![
vec!["CH4".to_string(), "NASA_gas".to_string()],
vec!["H2O".to_string(), "NASA_gas".to_string()]
]
);
assert_eq!(
updated_elements.get("O").unwrap(),
&vec![
vec!["CO".to_string(), "NIST".to_string()],
vec!["H2O".to_string(), "NASA_gas".to_string()]
]
);
let journal: Vec<ThermoLibraryJournalEntry> =
serde_json::from_str(&fs::read_to_string(&journal_path).unwrap()).unwrap();
assert_eq!(journal.len(), 1);
assert_eq!(journal[0].source_format, "NASA");
assert_eq!(journal[0].operation, ThermoLibraryWriteOperation::Upsert);
assert_eq!(journal[0].library, "NASA_gas");
assert_eq!(journal[0].substance, "CH4");
assert_eq!(journal[0].canonical_names, vec!["CH4".to_string()]);
}
#[test]
fn typed_write_rejects_library_format_mismatch() {
let dir = tempdir().expect("tempdir should be created");
let config_path = dir.path().join("library_config.json");
let substance_base_path = dir.path().join("substance_base.json");
let all_keys_path = dir.path().join("all_keys_substance.json");
let elements_path = dir.path().join("elements.json");
let journal_path = dir.path().join("thermo_write_journal.json");
let substance_base = json!({
"NASA_gas": {}
});
fs::write(
&substance_base_path,
serde_json::to_string_pretty(&substance_base).unwrap(),
)
.unwrap();
fs::write(&all_keys_path, "[]").unwrap();
fs::write(&elements_path, "{}").unwrap();
fs::write(&journal_path, "[]").unwrap();
let mut manager = LibraryManager::with_config_file(config_path.to_str().unwrap());
manager
.set_substance_base(substance_base_path.to_str().unwrap())
.unwrap();
manager
.set_all_keys_substance(all_keys_path.to_str().unwrap())
.unwrap();
manager
.set_elements(elements_path.to_str().unwrap())
.unwrap();
manager
.set_thermo_write_journal(journal_path.to_str().unwrap())
.unwrap();
let err = manager
.write_substance_from_spec(ThermoSubstanceWriteSpec {
library: "NASA_gas".to_string(),
substance: "CO".to_string(),
source_format: ThermoSubstanceSourceFormat::Nist,
composition: "{C:1, O:1}".to_string(),
fields: BTreeMap::from([("Cp".to_string(), json!([1.0]))]),
})
.expect_err("mismatched format should fail");
let message = err.to_string();
assert!(message.contains("NASA_gas"));
assert!(message.contains("NIST"));
let journal: Vec<ThermoLibraryJournalEntry> =
serde_json::from_str(&fs::read_to_string(&journal_path).unwrap()).unwrap();
assert!(journal.is_empty());
}
#[test]
fn upsert_then_drop_restores_original_catalog_snapshot() {
let dir = tempdir().expect("tempdir should be created");
let config_path = dir.path().join("library_config.json");
let substance_base_path = dir.path().join("substance_base.json");
let all_keys_path = dir.path().join("all_keys_substance.json");
let elements_path = dir.path().join("elements.json");
let journal_path = dir.path().join("thermo_write_journal.json");
let substance_base = json!({
"NASA_gas": {
"H2O": { "composition": "{H:2, O:1}", "Cp": [2.0] }
}
});
let all_keys = json!([["NASA_gas", "H2O"]]);
let elements = json!({
"H": [["H2O", "NASA_gas"]],
"O": [["H2O", "NASA_gas"]]
});
let original_base: serde_json::Value = substance_base.clone();
let original_keys: serde_json::Value = all_keys.clone();
let original_elements: serde_json::Value = elements.clone();
fs::write(
&substance_base_path,
serde_json::to_string_pretty(&original_base).unwrap(),
)
.unwrap();
fs::write(
&all_keys_path,
serde_json::to_string_pretty(&original_keys).unwrap(),
)
.unwrap();
fs::write(
&elements_path,
serde_json::to_string_pretty(&original_elements).unwrap(),
)
.unwrap();
fs::write(&journal_path, "[]").unwrap();
let mut manager = LibraryManager::with_config_file(config_path.to_str().unwrap());
manager
.set_substance_base(substance_base_path.to_str().unwrap())
.unwrap();
manager
.set_all_keys_substance(all_keys_path.to_str().unwrap())
.unwrap();
manager
.set_elements(elements_path.to_str().unwrap())
.unwrap();
manager
.set_thermo_write_journal(journal_path.to_str().unwrap())
.unwrap();
manager
.write_substance_from_spec(ThermoSubstanceWriteSpec {
library: "NASA_gas".to_string(),
substance: "CH4".to_string(),
source_format: ThermoSubstanceSourceFormat::Nasa,
composition: "{C:1, H:4}".to_string(),
fields: BTreeMap::from([("Cp".to_string(), json!([4.0]))]),
})
.unwrap();
manager
.drop_substance_from_library("NASA_gas", "CH4")
.unwrap();
let final_base: serde_json::Value =
serde_json::from_str(&fs::read_to_string(&substance_base_path).unwrap()).unwrap();
let final_keys: serde_json::Value =
serde_json::from_str(&fs::read_to_string(&all_keys_path).unwrap()).unwrap();
let final_elements: serde_json::Value =
serde_json::from_str(&fs::read_to_string(&elements_path).unwrap()).unwrap();
assert_eq!(final_base, original_base);
assert_eq!(final_keys, original_keys);
assert_eq!(final_elements, original_elements);
let journal: Vec<ThermoLibraryJournalEntry> =
serde_json::from_str(&fs::read_to_string(&journal_path).unwrap()).unwrap();
assert_eq!(journal.len(), 2);
assert_eq!(journal[0].source_format, "NASA");
assert_eq!(journal[0].operation, ThermoLibraryWriteOperation::Upsert);
assert_eq!(journal[1].source_format, "manual");
assert_eq!(journal[1].operation, ThermoLibraryWriteOperation::Drop);
}
}