From 4ce081d6ed0278c59cff7daffe1e11dc0249c093 Mon Sep 17 00:00:00 2001 From: objz Date: Sat, 15 Aug 2026 21:24:51 +0200 Subject: [PATCH] fix(content): stop dropping update labels Update labels disappeared at random and only came back after switching instances, and mods installed from a modpack never got one. - display no longer requires the snapshot inventory to match the manifest exactly; a single changed file wiped every label in the instance even though each update is keyed by its exact installed version - a finished scan is applied instead of discarded when the manifest moved on in the meantime, and the pending queue no longer leaks or replays stale snapshots over newer ones - compare versions by publish date and ask the provider for the installed version when it is missing from the compatible list, which is the normal case for modpack pinned files; also fixes the modpack update label - keep known updates for checks that failed so an offline scan no longer overwrites a good cache - rescan only when the inventory changed or the snapshot is older than 30 minutes, with one pooled http client per scan instead of one per mod --- src/instance/content/provider.rs | 35 +++++- src/instance/content/updates.rs | 142 ++++++++++++++++++++---- src/instance/tests/content/provider.rs | 42 ++++++- src/tui/event.rs | 55 ++++----- src/tui/input.rs | 6 +- src/tui/tests/widgets/content/update.rs | 1 + src/tui/widgets/instances.rs | 14 ++- 7 files changed, 223 insertions(+), 72 deletions(-) diff --git a/src/instance/content/provider.rs b/src/instance/content/provider.rs index 8fc72ee..3d233ca 100644 --- a/src/instance/content/provider.rs +++ b/src/instance/content/provider.rs @@ -372,14 +372,43 @@ pub struct ProviderRegistry { providers: Vec>, } +/// Newest entry by publish date. Providers are not required to sort their +/// responses, so list order is only the tie-breaker. +pub(crate) fn newest_version(versions: &[VersionInfo]) -> Option<&VersionInfo> { + let first = versions.first()?; + Some(versions.iter().fold(first, |newest, version| { + match (published_at(version), published_at(newest)) { + (Some(candidate), Some(current)) if candidate > current => version, + _ => newest, + } + })) +} + +/// Whether `target` supersedes `installed`. Falls back to identity when a +/// provider omits publish dates, which keeps the newest-first list order as the +/// only signal we have left. +pub(crate) fn is_newer(target: &VersionInfo, installed: &VersionInfo) -> bool { + match (published_at(target), published_at(installed)) { + (Some(target), Some(installed)) => target > installed, + _ => target.id != installed.id, + } +} + +fn published_at(version: &VersionInfo) -> Option> { + chrono::DateTime::parse_from_rfc3339(&version.date_published).ok() +} + pub(crate) fn has_newer_compatible_version( versions: &[VersionInfo], installed_version_id: &str, ) -> bool { - versions + let Some(installed) = versions .iter() - .position(|version| version.id == installed_version_id) - .is_some_and(|position| position > 0) + .find(|version| version.id == installed_version_id) + else { + return false; + }; + newest_version(versions).is_some_and(|target| is_newer(target, installed)) } impl ProviderRegistry { diff --git a/src/instance/content/updates.rs b/src/instance/content/updates.rs index ed3bcd0..696b95b 100644 --- a/src/instance/content/updates.rs +++ b/src/instance/content/updates.rs @@ -22,10 +22,17 @@ pub struct UpdateSnapshot { pub loader: ModLoader, #[serde(default)] pub inventory: Vec, + #[serde(default)] + pub checked_at: i64, pub updates: Vec, pub failures: Vec, } +/// How long a snapshot is trusted before the next reconciliation rechecks it. +/// Anything shorter re-scans every mod against the provider APIs each time the +/// instance is selected. +const RECHECK_AFTER_SECONDS: i64 = 30 * 60; + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct UpdateCheckFailure { pub installed: ProviderProject, @@ -87,6 +94,29 @@ impl UpdateSnapshot { self.inventory == resolved_inventory(manifest) } + /// Whether the snapshot is worth re-scanning. Note that a stale snapshot is + /// still displayed: every entry is keyed by its exact installed version, so + /// content that changed since the scan simply stops matching instead of + /// invalidating the labels of everything else. + pub fn is_stale(&self, manifest: &ContentManifest) -> bool { + !self.matches_manifest(manifest) + || chrono::Utc::now() + .timestamp() + .saturating_sub(self.checked_at) + >= RECHECK_AFTER_SECONDS + } + + /// Keeps known updates for entries whose check failed this round so a flaky + /// network or a rate limited provider does not drop labels that were correct. + fn carry_over(&mut self, previous: &Self) { + for failure in &self.failures { + if let Some(update) = previous.update_for(&failure.installed) { + self.updates.push(update.clone()); + } + } + sort_updates(&mut self.updates); + } + pub fn update_for(&self, installed: &ProviderProject) -> Option<&AvailableUpdate> { self.updates.iter().find(|update| { update.installed.provider == installed.provider @@ -98,7 +128,12 @@ impl UpdateSnapshot { pub fn spawn(instance: InstanceConfig, manifest: ContentManifest, path: std::path::PathBuf) { tokio::spawn(async move { - let snapshot = scan(&instance, &manifest).await; + let previous = + UpdateSnapshot::load(&path).filter(|previous| previous.applies_to(&instance)); + let mut snapshot = scan(&instance, &manifest).await; + if let Some(previous) = previous { + snapshot.carry_over(&previous); + } if let Ok(bytes) = serde_json::to_vec_pretty(&snapshot) && let Err(error) = crate::storage::write_atomic(&path, &bytes) { @@ -144,9 +179,16 @@ pub async fn scan(instance: &InstanceConfig, manifest: &ContentManifest) -> Upda .collect(); let slots = Arc::new(tokio::sync::Semaphore::new(8)); + // one registry (and therefore one pooled http client) for the whole scan + let registry = Arc::new( + crate::instance::content::provider::ProviderRegistry::configured( + crate::net::HttpClient::new(), + ), + ); let mut tasks = tokio::task::JoinSet::new(); for (installed, kind) in projects { let slots = slots.clone(); + let registry = registry.clone(); let game_version = instance.game_version.clone(); let loader = instance.loader; tasks.spawn(async move { @@ -155,9 +197,6 @@ pub async fn scan(instance: &InstanceConfig, manifest: &ContentManifest) -> Upda .acquire_owned() .await .map_err(|error| error.to_string())?; - let registry = crate::instance::content::provider::ProviderRegistry::configured( - crate::net::HttpClient::new(), - ); let provider = registry.get(&installed.provider).ok_or_else(|| { format!("{} content provider is unavailable", installed.provider) })?; @@ -165,17 +204,27 @@ pub async fn scan(instance: &InstanceConfig, manifest: &ContentManifest) -> Upda .compatible_versions(&installed.project_id, kind, &game_version, loader) .await .map_err(|error| error.to_string())?; - let current = versions + let Some(newest) = crate::instance::content::provider::newest_version(&versions) + else { + return Ok(None); + }; + // a modpack pins files that are often not tagged for the exact + // game version of the instance, so the installed version can be + // missing from the compatible list. asking the provider for it + // directly is the only way to tell "up to date" from "unknown". + let current = match versions .iter() .find(|version| version.id == installed.version_id) - .cloned(); - let target = versions.first().cloned().filter(|_| { - crate::instance::content::provider::has_newer_compatible_version( - &versions, - &installed.version_id, - ) - }); - Ok::<_, String>(target.map(|target| (current, target))) + { + Some(current) => current.clone(), + None => provider + .version(&installed.version_id) + .await + .map_err(|error| error.to_string())?, + }; + let target = crate::instance::content::provider::is_newer(newest, ¤t) + .then(|| newest.clone()); + Ok::<_, String>(target.map(|target| (Some(current), target))) } .await; (installed, kind, result) @@ -201,19 +250,24 @@ pub async fn scan(instance: &InstanceConfig, manifest: &ContentManifest) -> Upda Err(error) => tracing::debug!("Content update task failed: {error}"), } } - updates.sort_by(|left, right| { - (&left.installed.provider, &left.installed.project_id) - .cmp(&(&right.installed.provider, &right.installed.project_id)) - }); + sort_updates(&mut updates); UpdateSnapshot { game_version: instance.game_version.clone(), loader: instance.loader, inventory, + checked_at: chrono::Utc::now().timestamp(), updates, failures, } } +fn sort_updates(updates: &mut [AvailableUpdate]) { + updates.sort_by(|left, right| { + (&left.installed.provider, &left.installed.project_id) + .cmp(&(&right.installed.provider, &right.installed.project_id)) + }); +} + fn resolved_inventory(manifest: &ContentManifest) -> Vec { let mut inventory = manifest .files @@ -375,6 +429,7 @@ mod tests { game_version: "1.21.1".to_owned(), loader: ModLoader::Fabric, inventory: vec![installed.clone()], + checked_at: chrono::Utc::now().timestamp(), updates: vec![AvailableUpdate { installed: installed.clone(), current: Some(version("old")), @@ -396,7 +451,7 @@ mod tests { } #[test] - fn cached_updates_require_the_same_content_inventory() { + fn a_changed_content_inventory_only_schedules_a_rescan() { let project = ProviderProject { provider: "modrinth".to_owned(), project_id: "project".to_owned(), @@ -406,6 +461,7 @@ mod tests { game_version: "1.21.1".to_owned(), loader: ModLoader::Fabric, inventory: vec![project.clone()], + checked_at: chrono::Utc::now().timestamp(), updates: Vec::new(), failures: Vec::new(), }; @@ -427,12 +483,58 @@ mod tests { cleanup_eligible: false, }); - assert!(snapshot.matches_manifest(&manifest)); + assert!(!snapshot.is_stale(&manifest)); manifest.files[0].resolution = crate::instance::Resolution::Unmatched { checked_at: 0, providers: Vec::new(), }; - assert!(!snapshot.matches_manifest(&manifest)); + assert!(snapshot.is_stale(&manifest)); + + let expired = UpdateSnapshot { + checked_at: chrono::Utc::now().timestamp() - RECHECK_AFTER_SECONDS, + ..snapshot + }; + assert!(expired.is_stale(&manifest)); + } + + #[test] + fn failed_checks_keep_the_previously_known_update() { + let installed = ProviderProject { + provider: "modrinth".to_owned(), + project_id: "project".to_owned(), + version_id: "old".to_owned(), + }; + let previous = UpdateSnapshot { + game_version: "1.21.1".to_owned(), + loader: ModLoader::Fabric, + inventory: vec![installed.clone()], + checked_at: 0, + updates: vec![AvailableUpdate { + installed: installed.clone(), + current: Some(version("old")), + target: version("new"), + kind: ContentKind::Mod, + }], + failures: Vec::new(), + }; + let mut offline = UpdateSnapshot { + updates: Vec::new(), + failures: vec![UpdateCheckFailure { + installed: installed.clone(), + kind: ContentKind::Mod, + reason: "request timed out".to_owned(), + }], + ..previous.clone() + }; + + offline.carry_over(&previous); + + assert_eq!( + offline + .update_for(&installed) + .map(|update| &update.target.id), + Some(&"new".to_owned()) + ); } #[test] diff --git a/src/instance/tests/content/provider.rs b/src/instance/tests/content/provider.rs index acb56a5..eb6de94 100644 --- a/src/instance/tests/content/provider.rs +++ b/src/instance/tests/content/provider.rs @@ -6,9 +6,8 @@ fn registry_falls_back_to_first_capable_provider() { assert_eq!(registry.preferred("unknown").unwrap().id(), "modrinth"); } -#[test] -fn update_check_requires_the_installed_version_behind_a_newer_result() { - let version = |id: &str| VersionInfo { +fn version(id: &str, date_published: &str) -> VersionInfo { + VersionInfo { id: id.to_owned(), project_id: "project".to_owned(), name: id.to_owned(), @@ -17,12 +16,43 @@ fn update_check_requires_the_installed_version_behind_a_newer_result() { loaders: vec!["fabric".to_owned()], version_type: crate::net::modrinth::VersionType::Release, dependencies: Vec::new(), - date_published: String::new(), + date_published: date_published.to_owned(), files: Vec::new(), - }; - let versions = vec![version("new"), version("installed")]; + } +} + +#[test] +fn update_check_requires_the_installed_version_behind_a_newer_result() { + let versions = vec![version("new", ""), version("installed", "")]; assert!(has_newer_compatible_version(&versions, "installed")); assert!(!has_newer_compatible_version(&versions, "new")); assert!(!has_newer_compatible_version(&versions, "missing")); } + +#[test] +fn update_check_uses_publish_dates_not_response_order() { + // curseforge does not promise a newest-first ordering + let versions = vec![ + version("installed", "2024-01-01T00:00:00Z"), + version("new", "2024-06-01T00:00:00.500Z"), + ]; + + assert_eq!( + newest_version(&versions).map(|v| v.id.as_str()), + Some("new") + ); + assert!(has_newer_compatible_version(&versions, "installed")); + assert!(!has_newer_compatible_version(&versions, "new")); +} + +#[test] +fn a_version_missing_from_the_compatible_list_can_still_be_outdated() { + // a modpack pins files that are not tagged for the instance's exact game + // version, so the installed version never shows up in the filtered list + let compatible = vec![version("new", "2024-06-01T00:00:00Z")]; + let pinned = version("pinned", "2023-01-01T00:00:00Z"); + + assert!(is_newer(newest_version(&compatible).unwrap(), &pinned)); + assert!(!has_newer_compatible_version(&compatible, &pinned.id)); +} diff --git a/src/tui/event.rs b/src/tui/event.rs index a7e9f5a..01cfba0 100644 --- a/src/tui/event.rs +++ b/src/tui/event.rs @@ -402,19 +402,23 @@ impl App { .instances_dir .join(&result.instance_name), ); - self.content_update_snapshot = + let cached = crate::instance::content::updates::UpdateSnapshot::load(&paths.content_updates()) - .filter(|snapshot| { - snapshot.applies_to(&selected) && snapshot.matches_manifest(&result.manifest) - }) - .map(|snapshot| (result.instance_name.clone(), snapshot)); + .filter(|snapshot| snapshot.applies_to(&selected)); + let stale = cached + .as_ref() + .is_none_or(|snapshot| snapshot.is_stale(&result.manifest)); + self.content_update_snapshot = + cached.map(|snapshot| (result.instance_name.clone(), snapshot)); self.content_manifest = Some((result.instance_name.clone(), result.manifest.clone())); self.apply_content_update_snapshot(); - crate::instance::content::updates::spawn( - selected, - result.manifest, - paths.content_updates(), - ); + if stale { + crate::instance::content::updates::spawn( + selected, + result.manifest, + paths.content_updates(), + ); + } } fn apply_cached_content_manifest(&mut self) { @@ -458,36 +462,30 @@ impl App { }; let snapshot = match crate::instance::content::updates::PENDING_UPDATE_SNAPSHOTS.lock() { Ok(mut pending) => { - pending.retain(|pending| { - pending.instance_name != selected.name - || pending.instance_created == selected.created - }); - pending + let latest = pending .iter() .rposition(|pending| { pending.instance_name == selected.name && pending.instance_created == selected.created }) - .map(|index| pending.remove(index)) + .map(|index| pending.remove(index)); + // every scan also writes its result to disk, so whatever is left + // here is recovered on the next reconciliation of that instance + pending.clear(); + latest } Err(_) => return, }; let Some(snapshot) = snapshot else { return; }; - let current_manifest = self - .content_manifest - .as_ref() - .filter(|(name, _)| name == &snapshot.instance_name) - .map(|(_, manifest)| manifest); - if current_manifest.is_none_or(|manifest| !snapshot.snapshot.matches_manifest(manifest)) { - return; - } self.content_update_snapshot = Some((snapshot.instance_name, snapshot.snapshot)); self.apply_content_update_snapshot(); } fn apply_content_update_snapshot(&mut self) { + // matched per entry by exact installed version, so a snapshot that no + // longer covers the whole manifest still labels everything it does cover let snapshot = self .content_update_snapshot .as_ref() @@ -495,14 +493,7 @@ impl App { self.instances_state .selected_instance() .filter(|instance| instance.name == *name && snapshot.applies_to(instance)) - .and_then(|_| { - self.content_manifest - .as_ref() - .filter(|(manifest_name, manifest)| { - manifest_name == name && snapshot.matches_manifest(manifest) - }) - .map(|_| snapshot) - }) + .map(|_| snapshot) }); self.mods_state.apply_update_snapshot(snapshot); self.resource_packs_state.apply_update_snapshot(snapshot); diff --git a/src/tui/input.rs b/src/tui/input.rs index 8df7d01..30dc02c 100644 --- a/src/tui/input.rs +++ b/src/tui/input.rs @@ -1158,11 +1158,7 @@ impl App { let cached_snapshot = self .content_update_snapshot .as_ref() - .filter(|(name, snapshot)| { - name == &instance.name - && snapshot.applies_to(&instance) - && snapshot.matches_manifest(&manifest) - }) + .filter(|(name, snapshot)| name == &instance.name && snapshot.applies_to(&instance)) .map(|(_, snapshot)| snapshot.clone()); if cached_snapshot .as_ref() diff --git a/src/tui/tests/widgets/content/update.rs b/src/tui/tests/widgets/content/update.rs index 9dc6007..1e24320 100644 --- a/src/tui/tests/widgets/content/update.rs +++ b/src/tui/tests/widgets/content/update.rs @@ -62,6 +62,7 @@ fn snapshot() -> UpdateSnapshot { game_version: "1.21.1".to_owned(), loader: crate::instance::ModLoader::Fabric, inventory: Vec::new(), + checked_at: 0, updates: Vec::new(), failures: Vec::new(), } diff --git a/src/tui/widgets/instances.rs b/src/tui/widgets/instances.rs index 6c00134..abfc552 100644 --- a/src/tui/widgets/instances.rs +++ b/src/tui/widgets/instances.rs @@ -50,12 +50,14 @@ pub fn spawn_modpack_update_check(instance: &InstanceConfig) { let Ok(versions) = crate::instance::import::provider_versions(&source).await else { return; }; - let update = versions.first().cloned().filter(|_| { - crate::instance::content::provider::has_newer_compatible_version( - &versions, - &source.version_id, - ) - }); + let update = crate::instance::content::provider::newest_version(&versions) + .cloned() + .filter(|_| { + crate::instance::content::provider::has_newer_compatible_version( + &versions, + &source.version_id, + ) + }); if let Ok(mut pending) = PENDING_MODPACK_UPDATES.lock() { pending.push((instance.name, source, update)); crate::feedback::request_redraw();