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

+24 -18
View File
@@ -101,29 +101,35 @@ impl ContentProvider for ModrinthProvider {
&self,
files: &[FingerprintQuery],
) -> Result<Vec<ResolvedFile>, crate::net::NetError> {
let by_hash = files
.iter()
.filter_map(|file| {
file.fingerprint
.hash("sha512")
.map(|hash| (hash.to_owned(), file.key.clone()))
})
.collect::<HashMap<_, _>>();
let mut by_hash = HashMap::<String, Vec<String>>::new();
for file in files {
if let Some(hash) = file.fingerprint.hash("sha512") {
by_hash
.entry(hash.to_owned())
.or_default()
.push(file.key.clone());
}
}
let hashes = by_hash.keys().cloned().collect::<Vec<_>>();
let versions =
crate::net::modrinth::resolve_version_files(&self.client, &hashes, "sha512").await?;
Ok(versions
.into_iter()
.filter_map(|(hash, version)| {
let key = by_hash.get(&hash)?.clone();
(!version.project_id.is_empty()).then_some(ResolvedFile {
key,
project: ProviderProject {
provider: self.id().to_owned(),
project_id: version.project_id,
version_id: version.id,
},
})
.flat_map(|(hash, version)| {
let keys = by_hash.get(&hash).cloned().unwrap_or_default();
if version.project_id.is_empty() {
return Vec::new();
}
keys.into_iter()
.map(|key| ResolvedFile {
key,
project: ProviderProject {
provider: self.id().to_owned(),
project_id: version.project_id.clone(),
version_id: version.id.clone(),
},
})
.collect()
})
.collect())
}
+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(())
+18 -13
View File
@@ -205,23 +205,28 @@ pub async fn download_file(
) -> Result<(), NetError> {
tracing::debug!("Downloading {} to {}", url, dest.display());
for attempt in 0..=MAX_RETRIES {
match download_file_once(client, url, dest, &progress_cb).await {
Ok(()) => {
tracing::debug!("Downloaded {} to {}", url, dest.display());
return Ok(());
}
Err(e) if is_retryable(&e) => {
if attempt == MAX_RETRIES {
return Err(e);
let result = 'download: {
for attempt in 0..=MAX_RETRIES {
match download_file_once(client, url, dest, &progress_cb).await {
Ok(()) => {
tracing::debug!("Downloaded {} to {}", url, dest.display());
break 'download Ok(());
}
sleep_before_retry("download", url, attempt, &e).await;
Err(e) if is_retryable(&e) => {
if attempt == MAX_RETRIES {
break 'download Err(e);
}
sleep_before_retry("download", url, attempt, &e).await;
}
Err(e) => break 'download Err(e),
}
Err(e) => return Err(e),
}
unreachable!("retry loop returns on success or final error")
};
if result.is_err() {
let _ = tokio::fs::remove_file(dest).await;
}
unreachable!("retry loop returns on success or final error")
result
}
// single attempt at downloading a file to disk
+58 -11
View File
@@ -15,7 +15,7 @@ pub struct ProjectInfo {
pub icon_url: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
#[derive(Debug, Clone, Deserialize, serde::Serialize)]
pub struct VersionInfo {
pub id: String,
#[serde(default)]
@@ -27,7 +27,7 @@ pub struct VersionInfo {
pub files: Vec<VersionFile>,
}
#[derive(Debug, Clone, Deserialize)]
#[derive(Debug, Clone, Deserialize, serde::Serialize)]
pub struct VersionFile {
pub url: String,
pub filename: String,
@@ -359,14 +359,32 @@ pub async fn download_version_file(
let file = select_primary_file(version)?;
let path = destination.join(&file.filename);
if path.exists() {
return Ok(DownloadOutcome::SkippedExisting(path));
if verify_version_file(&path, file)? {
return Ok(DownloadOutcome::SkippedExisting(path));
}
return Err(crate::net::NetError::Parse(format!(
"Existing file '{}' does not match the selected Modrinth version",
path.display()
)));
}
let temporary = destination.join(format!(".{}.{}.rmcl-download", file.filename, version.id));
if temporary.exists() {
tokio::fs::remove_file(&temporary).await?;
}
let progress =
crate::tui::progress::ProgressTask::start(format!("Downloading {}", file.filename));
crate::net::download_file(client, &file.url, &path, |current, total| {
crate::net::download_file(client, &file.url, &temporary, |current, total| {
progress.set_progress(current, total);
})
.await?;
if !verify_version_file(&temporary, file)? {
let _ = tokio::fs::remove_file(&temporary).await;
return Err(crate::net::NetError::Parse(format!(
"Downloaded file '{}' failed its size or hash verification",
file.filename
)));
}
tokio::fs::rename(&temporary, &path).await?;
progress.finish();
Ok(DownloadOutcome::Downloaded(path))
}
@@ -385,11 +403,15 @@ pub async fn download_version_file_for_update(
let temporary = destination.join(format!(".{}.{}.rmcl-download", file.filename, version.id));
let backup = destination.join(format!(".{}.{}.rmcl-backup", file.filename, version.id));
if temporary.exists() || backup.exists() {
return Err(crate::net::NetError::Parse(format!(
"A previous update of '{}' did not finish cleanly",
file.filename
)));
if backup.exists() {
if !installed_path.exists() {
tokio::fs::rename(&backup, installed_path).await?;
} else {
tokio::fs::remove_file(&backup).await?;
}
}
if temporary.exists() {
tokio::fs::remove_file(&temporary).await?;
}
let progress =
@@ -398,11 +420,36 @@ pub async fn download_version_file_for_update(
progress.set_progress(current, total);
})
.await?;
progress.finish();
if !verify_version_file(&temporary, file)? {
let _ = tokio::fs::remove_file(&temporary).await;
return Err(crate::net::NetError::Parse(format!(
"Downloaded file '{}' failed its size or hash verification",
file.filename
)));
}
replace_installed_file(&temporary, &target, installed_path, &backup).await?;
progress.finish();
Ok(DownloadOutcome::Downloaded(target))
}
fn verify_version_file(
path: &std::path::Path,
expected: &VersionFile,
) -> Result<bool, crate::net::NetError> {
let fingerprint = crate::instance::content::manifest::fingerprint(path)?;
if expected.size > 0 && fingerprint.size != expected.size {
return Ok(false);
}
for algorithm in ["sha512", "sha1"] {
if let Some(expected_hash) = expected.hashes.get(algorithm)
&& fingerprint.hash(algorithm) != Some(expected_hash.as_str())
{
return Ok(false);
}
}
Ok(true)
}
async fn replace_installed_file(
temporary: &std::path::Path,
target: &std::path::Path,
@@ -611,7 +658,7 @@ mod tests {
let version = version_with_files(vec![VersionFile {
url: "https://example.test/example.jar".to_owned(),
filename: "example.jar".to_owned(),
size: 1,
size: b"existing".len() as u64,
primary: true,
hashes: HashMap::new(),
}]);
+51 -22
View File
@@ -26,18 +26,25 @@ impl App {
let relative_path = conflict.relative_path.clone();
let project = conflict.candidates.get(conflict.selected).cloned();
if let Some(project) = project
&& let Some((instance_name, manifest)) = &mut self.content_manifest
&& let Some(record) = manifest
.files
.iter_mut()
.find(|record| record.relative_path == relative_path)
&& let Some((instance_name, _)) = &self.content_manifest
{
record.resolution = crate::instance::Resolution::Resolved { project };
let manifest_path = crate::storage::InstancePaths::new(
self.instance_manager.instances_dir.join(instance_name),
)
.content_manifest();
manifest.save(&manifest_path)?;
let updated =
crate::instance::ContentManifest::update(&manifest_path, |manifest| {
if let Some(record) = manifest
.files
.iter_mut()
.find(|record| record.relative_path == relative_path)
{
record.resolution =
crate::instance::Resolution::Resolved { project };
}
Ok(manifest.clone())
})?;
self.content_manifest = Some((instance_name.clone(), updated));
self.provider_conflict = None;
self.reconciliation_for = None;
}
@@ -641,11 +648,19 @@ impl App {
let Some(request) = state.begin_versions() else {
return;
};
let version_cache = crate::storage::MetadataPaths::new(&self.instance_manager.meta_dir)
.provider_versions("modrinth")
.join(&request.project_id)
.join(format!(
"{}-{}.json",
instance.game_version,
instance.loader.to_string().to_lowercase()
));
tokio::spawn(async move {
let registry =
crate::content_provider::ProviderRegistry::modrinth(crate::net::HttpClient::new());
let result = match registry.preferred("modrinth") {
Some(provider) => provider
Some(provider) => match provider
.compatible_versions(
&request.project_id,
discovery_content_kind(kind),
@@ -653,7 +668,21 @@ impl App {
instance.loader,
)
.await
.map_err(|error| error.to_string()),
{
Ok(versions) => {
if let Ok(bytes) = serde_json::to_vec_pretty(&versions) {
let _ = crate::storage::write_atomic(&version_cache, &bytes);
}
Ok(versions)
}
Err(error) => match std::fs::read(&version_cache)
.ok()
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
{
Some(versions) => Ok(versions),
None => Err(error.to_string()),
},
},
None => Err("Modrinth content provider is unavailable".to_owned()),
};
widgets::content::DiscoveryState::push_action_result(
@@ -731,20 +760,12 @@ impl App {
crate::net::modrinth::DownloadOutcome::SkippedExisting(path) => (path, true),
};
let replaced = request.installed_path.is_some() && !skipped;
let mut manifest = crate::instance::ContentManifest::load(&manifest_path)
.map_err(|error| crate::net::NetError::Parse(error.to_string()))?;
if let Some(old_path) = request.installed_path.as_ref()
&& let Ok(relative) = old_path.strip_prefix(&minecraft_dir)
&& old_path != &path
{
manifest.remove(relative);
}
let relative_path = path
.strip_prefix(&minecraft_dir)
.map_err(|error| crate::net::NetError::Parse(error.to_string()))?
.to_path_buf();
let fingerprint = crate::instance::content::manifest::fingerprint(&path)?;
manifest.upsert(crate::instance::ContentFileRecord {
let record = crate::instance::ContentFileRecord {
relative_path,
kind: content_kind,
enabled: !path
@@ -759,10 +780,18 @@ impl App {
version_id: request.version.id.clone(),
},
},
});
manifest
.save(&manifest_path)
.map_err(|error| crate::net::NetError::Parse(error.to_string()))?;
};
crate::instance::ContentManifest::update(&manifest_path, |manifest| {
if let Some(old_path) = request.installed_path.as_ref()
&& let Ok(relative) = old_path.strip_prefix(&minecraft_dir)
&& old_path != &path
{
manifest.remove(relative);
}
manifest.upsert(record);
Ok(())
})
.map_err(|error| crate::net::NetError::Parse(error.to_string()))?;
if !skipped
&& let Some(old_path) = request
.installed_path