fix(content): make provider metadata durable

This commit is contained in:
objz committed 2026-07-25 12:39:34 +02:00
1 parent c59228e1fd
commit 0a930a4f86
6 files changed
+267 -98

No files matched your search

+27 -9
View File
@@ -1,12 +1,15 @@
use std::collections::BTreeMap;
use std::collections::{BTreeMap, HashMap};
use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::{Arc, LazyLock, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use sha1::Digest as _;
const MANIFEST_VERSION: u32 = 1;
static MANIFEST_LOCKS: LazyLock<Mutex<HashMap<PathBuf, Arc<Mutex<()>>>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
@@ -112,18 +115,31 @@ impl ContentManifest {
ManifestError::InvalidPath(format!("{} has no parent", path.display()))
})?;
std::fs::create_dir_all(parent)?;
let temporary = parent.join(format!(
".{}.tmp",
path.file_name()
.and_then(|name| name.to_str())
.unwrap_or("manifest")
));
let bytes = serde_json::to_vec_pretty(self)?;
std::fs::write(&temporary, bytes)?;
std::fs::rename(temporary, path)?;
crate::storage::write_atomic(path, &bytes)?;
Ok(())
}
pub fn update<T>(
path: &Path,
update: impl FnOnce(&mut Self) -> Result<T, ManifestError>,
) -> Result<T, ManifestError> {
let lock = {
let mut locks = MANIFEST_LOCKS
.lock()
.map_err(|_| ManifestError::LockPoisoned)?;
locks
.entry(path.to_owned())
.or_insert_with(|| Arc::new(Mutex::new(())))
.clone()
};
let _guard = lock.lock().map_err(|_| ManifestError::LockPoisoned)?;
let mut manifest = Self::load(path)?;
let result = update(&mut manifest)?;
manifest.save(path)?;
Ok(result)
}
pub fn record(&self, relative_path: &Path) -> Option<&ContentFileRecord> {
self.files
.iter()
@@ -175,6 +191,8 @@ pub enum ManifestError {
UnsupportedVersion(u32),
#[error("Invalid manifest path: {0}")]
InvalidPath(String),
#[error("Content manifest lock was poisoned")]
LockPoisoned,
}
pub fn fingerprint(path: &Path) -> Result<FileFingerprint, std::io::Error> {
+89 -25
View File
@@ -157,10 +157,11 @@ async fn reconcile(job: ReconcileJob, task: &ProgressTask) -> ReconcileResult {
let retry_hours = crate::config::SETTINGS.content.unmatched_retry_hours;
let max_fingerprint_size_mib = crate::config::SETTINGS.content.max_fingerprint_size_mib;
let inventory_progress = task.handle();
let inventory_minecraft_dir = minecraft_dir.clone();
let inventory = tokio::task::spawn_blocking(move || {
reconcile_inventory(
&manifest_path,
&minecraft_dir,
&inventory_minecraft_dir,
retry_hours,
max_fingerprint_size_mib,
&inventory_progress,
@@ -195,27 +196,38 @@ async fn reconcile(job: ReconcileJob, task: &ProgressTask) -> ReconcileResult {
&task,
)
.await;
match inventory.manifest.save(&manifest_path) {
Ok(()) => ReconcileResult {
match save_reconciled_manifest(
&manifest_path,
&minecraft_dir,
inventory.manifest,
) {
Ok(manifest) => ReconcileResult {
instance_name,
manifest: inventory.manifest,
manifest,
icons: icon_result.unwrap_or_default(),
error: None,
},
Err(error) => ReconcileResult {
instance_name,
manifest: inventory.manifest,
manifest: ContentManifest::default(),
icons: HashMap::new(),
error: Some(error.to_string()),
},
}
}
Err(error) => ReconcileResult {
instance_name,
manifest: inventory.manifest,
icons: HashMap::new(),
error: Some(error.to_string()),
},
Err(error) => {
let saved = save_reconciled_manifest(
&manifest_path,
&minecraft_dir,
inventory.manifest,
);
ReconcileResult {
instance_name,
manifest: saved.unwrap_or_default(),
icons: HashMap::new(),
error: Some(error.to_string()),
}
}
}
}
Ok(Err(error)) => ReconcileResult {
@@ -234,6 +246,36 @@ async fn reconcile(job: ReconcileJob, task: &ProgressTask) -> ReconcileResult {
result
}
fn save_reconciled_manifest(
manifest_path: &Path,
minecraft_dir: &Path,
reconciled: ContentManifest,
) -> Result<ContentManifest, crate::instance::content::manifest::ManifestError> {
let reconciled_paths = reconciled
.files
.iter()
.map(|record| record.relative_path.clone())
.collect::<HashSet<_>>();
ContentManifest::update(manifest_path, |current| {
current.files.retain(|record| {
reconciled_paths.contains(&record.relative_path)
|| minecraft_dir.join(&record.relative_path).exists()
});
for record in reconciled.files {
let keep_resolved = current
.record(&record.relative_path)
.is_some_and(|existing| {
existing.fingerprint == record.fingerprint
&& matches!(existing.resolution, Resolution::Resolved { .. })
});
if !keep_resolved {
current.upsert(record);
}
}
Ok(current.clone())
})
}
struct Inventory {
manifest: ContentManifest,
queries: Vec<FingerprintQuery>,
@@ -369,6 +411,7 @@ async fn resolve_queries(
}
let mut matches: HashMap<String, Vec<ProviderProject>> = HashMap::new();
let mut checked = Vec::new();
let mut last_error = None;
for provider in registry.providers() {
let provider_id = provider.id();
match tokio::time::timeout(
@@ -390,14 +433,21 @@ async fn resolve_queries(
tracing::warn!(
"Skipping {provider_id} content matching after provider error: {error}"
);
last_error = Some(error.to_string());
}
Err(_) => {
tracing::warn!(
"Skipping {provider_id} content matching after the 10 second timeout"
);
last_error = Some(format!("{provider_id} content matching timed out"));
}
}
}
if checked.is_empty() {
return Err(crate::net::NetError::TaskFailed(last_error.unwrap_or_else(
|| "No content providers are available".to_owned(),
)));
}
let query_keys = queries
.iter()
.map(|query| query.key.as_str())
@@ -483,13 +533,30 @@ async fn load_project_icons(
break;
}
task.set_sub_action(&project_id);
match tokio::time::timeout(
remaining.min(std::time::Duration::from_secs(3)),
provider.project(&project_id),
)
.await
{
Ok(Ok(project)) => {
let cached_project = metadata
.provider_projects(&provider_id)
.join(format!("{project_id}.json"));
let project_result = match tokio::fs::read(&cached_project).await {
Ok(bytes) => serde_json::from_slice(&bytes)
.map_err(|error| crate::net::NetError::Parse(error.to_string())),
Err(_) => match tokio::time::timeout(
remaining.min(std::time::Duration::from_secs(3)),
provider.project(&project_id),
)
.await
{
Ok(result) => result,
Err(_) => {
tracing::debug!(
"Timed out loading {provider_id} project {project_id}; using fallback"
);
task.set_progress(index as u64 + 1, project_count);
continue;
}
},
};
match project_result {
Ok(project) => {
if let Err(error) = cache_project(metadata, &provider_id, &project) {
tracing::warn!("Failed to cache {provider_id} project {project_id}: {error}");
}
@@ -527,12 +594,9 @@ async fn load_project_icons(
}
}
}
Ok(Err(error)) => {
Err(error) => {
tracing::warn!("Failed to load {provider_id} project {project_id}: {error}")
}
Err(_) => tracing::debug!(
"Timed out loading {provider_id} project {project_id}; using fallback"
),
}
task.set_progress(index as u64 + 1, project_count);
}
@@ -550,9 +614,9 @@ fn cache_project(
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(
path,
serde_json::to_vec_pretty(project)
crate::storage::write_atomic(
&path,
&serde_json::to_vec_pretty(project)
.map_err(|error| crate::net::NetError::Parse(error.to_string()))?,
)?;
Ok(())