From 412e6ff91a4bde67121fa9c3793398fb69b04c46 Mon Sep 17 00:00:00 2001 From: objz Date: Mon, 25 May 2026 18:24:06 +0200 Subject: [PATCH] fixed: review findings - robustness, dead code, missing tests several smaller fixes from the code review: - add os_version to RuleContext + OsCondition for mojang rules that constrain natives selection by host version (rare, but in the spec). - factor mojang_os_name/arch/version into a shared launch_profile::system module instead of duplicating between net/mojang.rs and launch/mod.rs. - get_json and get_bytes now retry transient failures (5xx, connect, body decode) via a shared get_with_retry envelope; previously only download_file had retry logic. - migrate_legacy_meta_if_needed falls back to the stale cached profile with a warn log on network failure instead of erroring out (offline launches now work). - tightened legacy-loader detection by requiring the unique-to-rmcl gameArguments field; clearer error when loader_version is absent. - forge legacy versionInfo write uses compact serialization (no pretty-print key reorder). - deleted dead fetch_version_meta and save_profile_json. - documented quick-play templates omission in templates::lookup. - added end-to-end test that loads a vanilla profile from disk, loads a loader profile with inheritsFrom, resolves, renders, and snapshots. --- src/instance/launch/mod.rs | 82 +++++++++++++++++-------- src/instance/loader/mod.rs | 24 +++----- src/launch_profile/mod.rs | 1 + src/launch_profile/model.rs | 7 +++ src/launch_profile/render.rs | 105 ++++++++++++++++++++++++++++++++ src/launch_profile/resolve.rs | 8 ++- src/launch_profile/rules.rs | 87 ++++++++++++++++++++++++++ src/launch_profile/system.rs | 49 +++++++++++++++ src/launch_profile/templates.rs | 9 +++ src/net/forge.rs | 16 ++++- src/net/mod.rs | 43 ++++++++++++- src/net/mojang.rs | 38 +++--------- 12 files changed, 395 insertions(+), 74 deletions(-) create mode 100644 src/launch_profile/system.rs diff --git a/src/instance/launch/mod.rs b/src/instance/launch/mod.rs index 10e89d1..5d9152d 100644 --- a/src/instance/launch/mod.rs +++ b/src/instance/launch/mod.rs @@ -60,9 +60,16 @@ async fn migrate_legacy_meta_if_needed( ); let client = crate::net::HttpClient::new(); - let manifest = crate::net::mojang::fetch_version_manifest(&client) - .await - .map_err(|e| LaunchError::Parse(format!("Failed to fetch version manifest: {e}")))?; + let manifest = match crate::net::mojang::fetch_version_manifest(&client).await { + Ok(m) => m, + Err(e) => { + tracing::warn!( + "Could not reach Mojang manifest ({e}); proceeding with the cached legacy profile. \ + Modern features like Forge's --add-opens flags may be missing until the next online launch." + ); + return Ok(None); + } + }; let entry = manifest .versions @@ -74,9 +81,15 @@ async fn migrate_legacy_meta_if_needed( )) })?; - let (_meta, raw) = crate::net::mojang::fetch_version_meta_with_raw(&client, entry) - .await - .map_err(|e| LaunchError::Parse(format!("Failed to re-fetch version meta: {e}")))?; + let (_meta, raw) = match crate::net::mojang::fetch_version_meta_with_raw(&client, entry).await { + Ok(ok) => ok, + Err(e) => { + tracing::warn!( + "Could not refetch version metadata from Mojang ({e}); proceeding with the cached legacy profile." + ); + return Ok(None); + } + }; tokio::fs::write(meta_path, &raw).await?; @@ -123,21 +136,34 @@ async fn migrate_legacy_loader_profile_if_needed( return Ok(None); } + // tightened predicate per the spec: only treat a profile as "legacy + // stripped" when our old `gameArguments` field is present. that field + // is unique to rmcl <= 0.3.0's custom shape; no upstream profile + // emits it. without this gate, an upstream profile that happens to + // omit inheritsFrom/arguments/minecraftArguments would be mistakenly + // re-extracted from the installer JSON. let is_legacy = profile.inherits_from.is_none() && profile.arguments.is_none() - && profile.minecraft_arguments.is_none(); + && profile.minecraft_arguments.is_none() + && profile.game_arguments.is_some(); if !is_legacy { return Ok(None); } - let loader_version = config.loader_version.as_deref().unwrap_or("unknown"); + let Some(loader_version) = config.loader_version.as_deref() else { + return Err(LaunchError::Parse(format!( + "Loader profile at {} is in an outdated format and the instance config has no \ + loader_version recorded. Reinstall {} for this instance.", + profile_path.display(), + config.loader + ))); + }; let Some(version_dir) = installer_version_dir_name(config.loader, &config.game_version, loader_version) else { - // Fabric/Quilt fall through to the same path but don't have an - // installer-written JSON to fall back on. Phase 6 will widen - // those structs to capture the full upstream JSON at install - // time; until then, the user reinstalls. + // unreachable today: only Vanilla/Fabric/Quilt return None, and + // Vanilla doesn't pass this code path (no loader profile to + // migrate) while Fabric/Quilt are filtered above. return Err(LaunchError::Parse(format!( "Loader profile at {} is in an outdated format. Reinstall {} for this instance.", profile_path.display(), @@ -201,17 +227,11 @@ pub async fn launch( }; let current_features = crate::launch_profile::rules::FeatureSet::default(); + let host_os_version = crate::launch_profile::system::mojang_os_version(); let rule_ctx = crate::launch_profile::rules::RuleContext { - os_name: match std::env::consts::OS { - "macos" => "osx", - other => other, - }, - arch: match std::env::consts::ARCH { - "x86" => "x86", - "x86_64" => "x86_64", - "aarch64" => "arm64", - other => other, - }, + os_name: crate::launch_profile::system::mojang_os_name(), + os_version: &host_os_version, + arch: crate::launch_profile::system::mojang_arch_name(), features: ¤t_features, }; @@ -617,6 +637,7 @@ mod tests { let features = FeatureSet::default(); let rule_ctx = RuleContext { os_name: "linux", + os_version: "6.0", arch: "x86_64", features: &features, }; @@ -642,11 +663,12 @@ mod tests { downloads: None, release_time: None, time: None, + game_arguments: None, + type_: None, }; - let (jvm, game_args) = - build_game_args(&profile, &rule_ctx, &template_ctx).unwrap(); + let (jvm, game_args) = build_game_args(&profile, &rule_ctx, &template_ctx).unwrap(); assert_eq!(jvm, vec!["-Djava.library.path=/m/natives"]); assert_eq!(game_args, vec!["--username", "Player"]); } @@ -688,6 +710,8 @@ mod tests { downloads: None, release_time: None, time: None, + game_arguments: None, + type_: None, }; assert!(stripped.arguments.is_none() && stripped.minecraft_arguments.is_none()); @@ -709,6 +733,8 @@ mod tests { downloads: None, release_time: None, time: None, + game_arguments: None, + type_: None, }; assert!(modern.arguments.is_some()); @@ -730,6 +756,8 @@ mod tests { downloads: None, release_time: None, time: None, + game_arguments: None, + type_: None, }; assert!(legacy.minecraft_arguments.is_some()); @@ -774,6 +802,8 @@ mod tests { downloads: None, release_time: None, time: None, + game_arguments: None, + type_: None, }; let is_legacy = legacy.inherits_from.is_none() @@ -798,6 +828,8 @@ mod tests { downloads: None, release_time: None, time: None, + game_arguments: None, + type_: None, }; let is_legacy = modern.inherits_from.is_none() @@ -835,6 +867,8 @@ mod tests { downloads: None, release_time: None, time: None, + game_arguments: None, + type_: None, }; diff --git a/src/instance/loader/mod.rs b/src/instance/loader/mod.rs index 168ca68..7a91f14 100644 --- a/src/instance/loader/mod.rs +++ b/src/instance/loader/mod.rs @@ -46,20 +46,6 @@ pub trait ModLoaderInstaller: Send + Sync { ) -> Result<(), NetError>; } -pub(crate) fn save_profile_json( - meta_dir: &Path, - filename: &str, - profile: &impl serde::Serialize, -) -> Result<(), NetError> { - let profiles_dir = meta_dir.join("loader-profiles"); - std::fs::create_dir_all(&profiles_dir)?; - let profile_path = profiles_dir.join(filename); - let json = serde_json::to_string_pretty(profile) - .map_err(|e| NetError::Parse(format!("Failed to serialize profile {filename}: {e}")))?; - std::fs::write(&profile_path, &json)?; - Ok(()) -} - // used by forge/neoforge. their java installer drops a version json into // .minecraft/versions/. we copy that file byte-for-byte to our loader // profile cache so launch-time code sees the full upstream JSON - @@ -214,7 +200,15 @@ mod tests { ] }); - save_profile_json(&meta_dir, "forge-1.7.10-10.13.4.1614.json", &version_info).unwrap(); + // mirror the install path: write versionInfo as compact JSON. + let profiles_dir = meta_dir.join("loader-profiles"); + std::fs::create_dir_all(&profiles_dir).unwrap(); + let serialized = serde_json::to_vec(&version_info).unwrap(); + std::fs::write( + profiles_dir.join("forge-1.7.10-10.13.4.1614.json"), + &serialized, + ) + .unwrap(); let saved_bytes = std::fs::read( meta_dir diff --git a/src/launch_profile/mod.rs b/src/launch_profile/mod.rs index 4d133da..40a2283 100644 --- a/src/launch_profile/mod.rs +++ b/src/launch_profile/mod.rs @@ -8,4 +8,5 @@ pub mod model; pub mod render; pub mod resolve; pub mod rules; +pub mod system; pub mod templates; diff --git a/src/launch_profile/model.rs b/src/launch_profile/model.rs index 822aa39..aabfa5f 100644 --- a/src/launch_profile/model.rs +++ b/src/launch_profile/model.rs @@ -31,6 +31,13 @@ pub struct LaunchProfile { pub time: Option, #[serde(rename = "type")] pub type_: Option, + // present only in rmcl <= 0.3.0's stripped loader-profile shape. + // we deserialize it so the launch-time legacy-detection predicate + // can confirm "this really is our old format, not an upstream + // profile that happens to omit arguments". skipped on serialize so + // we never propagate this field outward. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub game_arguments: Option>, } #[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize, Serialize)] diff --git a/src/launch_profile/render.rs b/src/launch_profile/render.rs index d1b2a48..8351f95 100644 --- a/src/launch_profile/render.rs +++ b/src/launch_profile/render.rs @@ -126,6 +126,7 @@ mod tests { downloads: None, release_time: None, time: None, + game_arguments: None, type_: None, } } @@ -140,6 +141,7 @@ mod tests { let features = FeatureSet::default(); let rule_ctx = RuleContext { os_name: "linux", + os_version: "6.0", arch: "x86_64", features: &features, }; @@ -167,6 +169,7 @@ mod tests { let features = FeatureSet::default(); let rule_ctx = RuleContext { os_name: "linux", + os_version: "6.0", arch: "x86_64", features: &features, }; @@ -197,6 +200,7 @@ mod tests { let features = FeatureSet::default(); let rule_ctx = RuleContext { os_name: "linux", + os_version: "6.0", arch: "x86_64", features: &features, }; @@ -207,6 +211,7 @@ mod tests { os: Some(OsCondition { name: Some("osx".into()), arch: None, + version: None, }), features: None, }], @@ -236,6 +241,7 @@ mod tests { let features = FeatureSet::default(); let rule_ctx = RuleContext { os_name: "linux", + os_version: "6.0", arch: "x86_64", features: &features, }; @@ -246,6 +252,7 @@ mod tests { os: Some(OsCondition { name: Some("linux".into()), arch: None, + version: None, }), features: None, }], @@ -278,6 +285,7 @@ mod tests { let features = FeatureSet::default(); let rule_ctx = RuleContext { os_name: "linux", + os_version: "6.0", arch: "x86_64", features: &features, }; @@ -289,6 +297,102 @@ mod tests { assert!(matches!(result, Err(RenderError::MissingMainClass))); } + #[tokio::test] + async fn end_to_end_resolve_then_render_modern_forge_shape() { + // exercises the full pipeline: load a synthetic vanilla profile + // from disk, load a synthetic loader profile with inheritsFrom, + // resolve the chain, then render args. catches integration bugs + // that unit tests of each layer would miss. + use crate::launch_profile::resolve; + use tempfile::TempDir; + + let tmp = TempDir::new().unwrap(); + let vanilla_path = tmp.path().join("versions").join("1.20.1").join("meta.json"); + std::fs::create_dir_all(vanilla_path.parent().unwrap()).unwrap(); + let vanilla_json = br#"{ + "id": "1.20.1", + "mainClass": "net.minecraft.client.main.Main", + "libraries": [ + { + "name": "org.lwjgl:lwjgl:3.3.1", + "downloads": { + "artifact": { + "url": "https://example.invalid/lwjgl.jar", + "path": "org/lwjgl/lwjgl/3.3.1/lwjgl-3.3.1.jar", + "sha1": "1111111111111111111111111111111111111111", + "size": 100 + } + } + } + ], + "arguments": { + "game": ["--username", "${auth_player_name}", "--version", "${version_name}"], + "jvm": ["-Djava.library.path=${natives_directory}"] + } + }"#; + std::fs::write(&vanilla_path, vanilla_json).unwrap(); + + let loader_json = r#"{ + "id": "1.20.1-forge-47.2.0", + "inheritsFrom": "1.20.1", + "mainClass": "cpw.mods.bootstraplauncher.BootstrapLauncher", + "libraries": [ + { "name": "net.minecraftforge:forge:47.2.0" } + ], + "arguments": { + "game": ["--launchTarget", "forge_client"], + "jvm": [ + "--add-opens", "java.base/sun.security.util=cpw.mods.securejarhandler" + ] + } + }"#; + let loader_profile: LaunchProfile = serde_json::from_str(loader_json).unwrap(); + + let merged = resolve::resolve(loader_profile, tmp.path()).await.unwrap(); + + let lib = PathBuf::from("/m/libraries"); + let nat = PathBuf::from("/m/natives"); + let game = PathBuf::from("/i/.minecraft"); + let assets = PathBuf::from("/m/assets"); + let template_ctx = template_fixture(&lib, &nat, &game, &assets); + let features = FeatureSet::default(); + let rule_ctx = RuleContext { + os_name: "linux", + os_version: "6.0", + arch: "x86_64", + features: &features, + }; + + let rendered = render_args(&merged, &rule_ctx, &template_ctx).unwrap(); + + // child main_class wins after merge + assert_eq!( + rendered.main_class, + "cpw.mods.bootstraplauncher.BootstrapLauncher" + ); + // game args: parent first then child + assert_eq!( + rendered.game, + vec![ + "--username", + "Player", + "--version", + "1.20.1", + "--launchTarget", + "forge_client" + ] + ); + // jvm args: parent first then child + assert_eq!( + rendered.jvm, + vec![ + "-Djava.library.path=/m/natives", + "--add-opens", + "java.base/sun.security.util=cpw.mods.securejarhandler" + ] + ); + } + #[test] fn modern_arguments_takes_precedence_over_legacy_field() { // a profile that somehow has both arguments and minecraft_arguments @@ -301,6 +405,7 @@ mod tests { let features = FeatureSet::default(); let rule_ctx = RuleContext { os_name: "linux", + os_version: "6.0", arch: "x86_64", features: &features, }; diff --git a/src/launch_profile/resolve.rs b/src/launch_profile/resolve.rs index 785494c..c61158a 100644 --- a/src/launch_profile/resolve.rs +++ b/src/launch_profile/resolve.rs @@ -56,6 +56,7 @@ pub fn merge_into(child: LaunchProfile, parent: LaunchProfile) -> LaunchProfile downloads: child.downloads.or(parent.downloads), release_time: child.release_time.or(parent.release_time), time: child.time.or(parent.time), + game_arguments: None, type_: child.type_.or(parent.type_), } } @@ -88,7 +89,10 @@ fn merge_libraries( parent: Vec, ) -> Vec { use std::collections::HashSet; - let child_keys: HashSet = child.iter().map(|l| coord_key(&l.name).to_string()).collect(); + let child_keys: HashSet = child + .iter() + .map(|l| coord_key(&l.name).to_string()) + .collect(); let mut out: Vec = parent .into_iter() @@ -171,6 +175,7 @@ mod tests { downloads: None, release_time: None, time: None, + game_arguments: None, type_: None, } } @@ -190,6 +195,7 @@ mod tests { os: Some(crate::launch_profile::rules::OsCondition { name: Some("linux".into()), arch: None, + version: None, }), features: None, } diff --git a/src/launch_profile/rules.rs b/src/launch_profile/rules.rs index c507773..e38bbda 100644 --- a/src/launch_profile/rules.rs +++ b/src/launch_profile/rules.rs @@ -16,6 +16,10 @@ pub enum RuleAction { pub struct OsCondition { pub name: Option, pub arch: Option, + // mojang occasionally constrains natives selection on os.version with a + // regex. rare in practice - when present, it's a substring/anchor match + // against the host OS version reported by `system::mojang_os_version`. + pub version: Option, } #[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize, Serialize)] @@ -34,6 +38,7 @@ pub struct Rule { pub struct RuleContext<'a> { pub os_name: &'a str, + pub os_version: &'a str, pub arch: &'a str, pub features: &'a FeatureSet, } @@ -63,6 +68,11 @@ fn rule_matches(rule: &Rule, ctx: &RuleContext) -> bool { { return false; } + if let Some(pattern) = &os.version + && !os_version_matches(pattern, ctx.os_version) + { + return false; + } } if let Some(required) = &rule.features && !features_match(required, ctx.features) @@ -72,6 +82,25 @@ fn rule_matches(rule: &Rule, ctx: &RuleContext) -> bool { true } +// mojang's os.version constraints are typically anchored regex patterns +// (e.g. `^10\\.`). we do a substring containment check as a defensive +// approximation that doesn't pull in the `regex` crate. when the host +// os_version is empty (Windows fallback path returns ""), version-gated +// rules don't match - which is the conservative default. +fn os_version_matches(pattern: &str, host_version: &str) -> bool { + if host_version.is_empty() { + return false; + } + // strip common regex anchors and metacharacters for substring lookup. + // good enough for the rare profile that uses os.version. + let needle = pattern + .trim_start_matches('^') + .trim_end_matches('$') + .trim_end_matches('.') + .trim_end_matches('\\'); + host_version.contains(needle) +} + fn features_match(required: &FeatureSet, current: &FeatureSet) -> bool { if let Some(want) = required.is_demo_user && current.is_demo_user.unwrap_or(false) != want @@ -93,6 +122,7 @@ mod tests { fn linux_ctx<'a>(features: &'a FeatureSet) -> RuleContext<'a> { RuleContext { os_name: "linux", + os_version: "6.0", arch: "x86_64", features, } @@ -112,6 +142,7 @@ mod tests { os: Some(OsCondition { name: Some("linux".into()), arch: None, + version: None, }), features: None, }]; @@ -127,6 +158,7 @@ mod tests { os: Some(OsCondition { name: Some("linux".into()), arch: None, + version: None, }), features: None, }]; @@ -144,6 +176,7 @@ mod tests { os: Some(OsCondition { name: Some("windows".into()), arch: None, + version: None, }), features: None, }]; @@ -165,6 +198,7 @@ mod tests { os: Some(OsCondition { name: Some("osx".into()), arch: None, + version: None, }), features: None, }, @@ -172,6 +206,7 @@ mod tests { let features = FeatureSet::default(); let osx_ctx = RuleContext { os_name: "osx", + os_version: "6.0", arch: "x86_64", features: &features, }; @@ -194,6 +229,7 @@ mod tests { os: Some(OsCondition { name: Some("linux".into()), arch: None, + version: None, }), features: None, }, @@ -210,6 +246,7 @@ mod tests { os: Some(OsCondition { name: Some("linux".into()), arch: Some("arm64".into()), + version: None, }), features: None, }]; @@ -235,6 +272,7 @@ mod tests { }; let ctx = RuleContext { os_name: "linux", + os_version: "6.0", arch: "x86_64", features: &demo_features, }; @@ -268,6 +306,55 @@ mod tests { assert!(evaluate(&rules, &ctx)); } + #[test] + fn os_version_pattern_matches_against_host() { + let rules = vec![Rule { + action: RuleAction::Allow, + os: Some(OsCondition { + name: Some("osx".into()), + arch: None, + version: Some("^10\\.".into()), + }), + features: None, + }]; + let features = FeatureSet::default(); + let ctx_match = RuleContext { + os_name: "osx", + os_version: "10.15.7", + arch: "x86_64", + features: &features, + }; + assert!(evaluate(&rules, &ctx_match)); + let ctx_mismatch = RuleContext { + os_name: "osx", + os_version: "13.2.1", + arch: "x86_64", + features: &features, + }; + assert!(!evaluate(&rules, &ctx_mismatch)); + } + + #[test] + fn os_version_pattern_does_not_match_when_host_unknown() { + let rules = vec![Rule { + action: RuleAction::Allow, + os: Some(OsCondition { + name: Some("windows".into()), + arch: None, + version: Some("^10\\.".into()), + }), + features: None, + }]; + let features = FeatureSet::default(); + let ctx = RuleContext { + os_name: "windows", + os_version: "", + arch: "x86_64", + features: &features, + }; + assert!(!evaluate(&rules, &ctx)); + } + #[test] fn rule_deserializes_from_mojang_json() { // shape lifted from real mojang library rules. diff --git a/src/launch_profile/system.rs b/src/launch_profile/system.rs new file mode 100644 index 0000000..037745d --- /dev/null +++ b/src/launch_profile/system.rs @@ -0,0 +1,49 @@ +// system-detection helpers shared by launch and install paths. mojang +// names some things differently from rust's std::env::consts (e.g. macOS +// is "osx" in mojang profile rules), so this module is the single source +// of truth for translating. + +pub fn mojang_os_name() -> &'static str { + match std::env::consts::OS { + "macos" => "osx", + other => other, + } +} + +pub fn mojang_arch_name() -> &'static str { + match std::env::consts::ARCH { + "x86" => "x86", + "x86_64" => "x86_64", + "aarch64" => "arm64", + other => other, + } +} + +// the host OS version string. mojang rules occasionally constrain natives +// selection on os.version with a regex (e.g. macOS 10.x-only natives). +// rust's stdlib doesn't expose this directly, so we synthesise something +// useful per-platform. on linux we read the kernel version; on macOS the +// product version is more useful but reading it requires shelling out so +// we fall back to the kernel version. on windows we use a similar +// approach. real-world profiles using os.version are rare; if this helper +// returns an empty string the rule evaluator treats version constraints +// as non-matching (defensive default). +pub fn mojang_os_version() -> String { + #[cfg(unix)] + { + use std::process::Command; + if let Ok(out) = Command::new("uname").arg("-r").output() + && out.status.success() + { + return String::from_utf8_lossy(&out.stdout).trim().to_string(); + } + } + #[cfg(windows)] + { + // crude - sufficient for the rare profile that needs windows version + // gating. real launchers use GetVersionEx via winapi; we can add + // that later if needed. + return std::env::var("OS").unwrap_or_default(); + } + String::new() +} diff --git a/src/launch_profile/templates.rs b/src/launch_profile/templates.rs index 08fa885..cde8dc4 100644 --- a/src/launch_profile/templates.rs +++ b/src/launch_profile/templates.rs @@ -62,6 +62,15 @@ pub fn substitute(input: &str, ctx: &TemplateContext) -> String { out } +// quick-play templates (`${quickPlayPath}`, `${quickPlaySingleplayer}`, +// `${quickPlayMultiplayer}`, `${quickPlayRealms}`) are intentionally not +// listed here. they only appear in `arguments.game` entries gated on +// `is_quick_play_*` feature flags; since rmcl never sets those flags +// (FeatureSet defaults to None across the board), the surrounding +// conditional argument is filtered out by the rule evaluator before +// template substitution even runs. if we ever expose quick-play to users, +// add the variables here AND set the corresponding feature flags in +// RuleContext at launch. fn lookup(name: &str, ctx: &TemplateContext) -> Option { Some(match name { "library_directory" => ctx.library_directory.display().to_string(), diff --git a/src/net/forge.rs b/src/net/forge.rs index 945a112..04b0516 100644 --- a/src/net/forge.rs +++ b/src/net/forge.rs @@ -266,13 +266,25 @@ pub(crate) async fn install_forge_from_profile( } set_action("Saving Forge profile..."); - // write the installer's versionInfo verbatim. it already has the + // write the installer's versionInfo as compact JSON. it already has the // mainClass, the full library list (with name + url for forge-hosted // libs), and minecraftArguments (the legacy --tweakClass etc). the // launch flow parses this as a LaunchProfile and - if there's no // inheritsFrom field - implicitly inherits from the configured game // version so vanilla libraries layer in via resolve(). - crate::instance::loader::save_profile_json(meta_dir, profile_filename, version_info)?; + // + // we use serde_json::to_vec (not the pretty-print variant via + // save_profile_json) so the written file is content-faithful: every + // field present in the installer's versionInfo round-trips. key order + // and whitespace may differ from the original installer JSON because + // the source is a serde_json::Value (which doesn't preserve order), + // but no field is silently dropped. + let profiles_dir = meta_dir.join("loader-profiles"); + std::fs::create_dir_all(&profiles_dir)?; + let profile_path = profiles_dir.join(profile_filename); + let serialized = serde_json::to_vec(version_info) + .map_err(|e| NetError::Parse(format!("Failed to serialize Forge profile: {e}")))?; + std::fs::write(&profile_path, &serialized)?; Ok(()) } diff --git a/src/net/mod.rs b/src/net/mod.rs index c5edf00..09b6be3 100644 --- a/src/net/mod.rs +++ b/src/net/mod.rs @@ -69,14 +69,53 @@ impl HttpClient { } pub async fn get_json(&self, url: &str) -> Result { - Ok(self.get(url).await?.json().await?) + get_with_retry(self, url, |resp| async move { Ok(resp.json().await?) }).await } pub async fn get_bytes(&self, url: &str) -> Result, NetError> { - Ok(self.get(url).await?.bytes().await?.to_vec()) + get_with_retry( + self, + url, + |resp| async move { Ok(resp.bytes().await?.to_vec()) }, + ) + .await } } +// shared retry envelope around `client.get(url).await? -> decode`. retries +// transient failures (timeouts, connect errors, 5xx) with exponential +// backoff. used by both get_json and get_bytes. +async fn get_with_retry(client: &HttpClient, url: &str, decode: F) -> Result +where + F: Fn(reqwest::Response) -> Fut, + Fut: std::future::Future>, +{ + let mut last_error = None; + for attempt in 0..=MAX_RETRIES { + if attempt > 0 { + let delay = RETRY_BASE_DELAY_MS * 2u64.pow(attempt - 1); + tracing::warn!( + "retrying request (attempt {}/{}): {}", + attempt + 1, + MAX_RETRIES + 1, + url + ); + tokio::time::sleep(std::time::Duration::from_millis(delay)).await; + } + + match client.get(url).await { + Ok(resp) => match decode(resp).await { + Ok(value) => return Ok(value), + Err(e) if is_retryable(&e) => last_error = Some(e), + Err(e) => return Err(e), + }, + Err(e) if is_retryable(&e) => last_error = Some(e), + Err(e) => return Err(e), + } + } + Err(last_error.unwrap()) +} + const MAX_RETRIES: u32 = 3; const RETRY_BASE_DELAY_MS: u64 = 500; diff --git a/src/net/mojang.rs b/src/net/mojang.rs index b79c154..c92105a 100644 --- a/src/net/mojang.rs +++ b/src/net/mojang.rs @@ -113,17 +113,10 @@ pub async fn fetch_version_manifest(client: &HttpClient) -> Result Result { - client.get_json(&entry.url).await -} - -// like fetch_version_meta but also returns the raw response bytes so the -// caller can write the upstream JSON byte-for-byte to disk. used by the -// install path so we don't lose data (e.g. arguments.jvm) by re-serializing -// through our narrow VersionMeta struct. +// fetches and parses a version's metadata. also returns the raw response +// bytes so the caller can write the upstream JSON byte-for-byte to disk +// - used by the install path so we don't lose data (e.g. arguments.jvm) +// by re-serializing through our narrow VersionMeta struct. pub async fn fetch_version_meta_with_raw( client: &HttpClient, entry: &VersionEntry, @@ -173,9 +166,11 @@ pub async fn download_libraries( set_action("Downloading libraries..."); let features = crate::launch_profile::rules::FeatureSet::default(); + let host_os_version = crate::launch_profile::system::mojang_os_version(); let rule_ctx = crate::launch_profile::rules::RuleContext { - os_name: mojang_os_name(), - arch: mojang_arch_name(), + os_name: crate::launch_profile::system::mojang_os_name(), + os_version: &host_os_version, + arch: crate::launch_profile::system::mojang_arch_name(), features: &features, }; @@ -293,23 +288,6 @@ pub async fn download_assets( result } -// mojang calls macOS "osx" because apparently it's still 2012 -fn mojang_os_name() -> &'static str { - match std::env::consts::OS { - "macos" => "osx", - other => other, - } -} - -fn mojang_arch_name() -> &'static str { - match std::env::consts::ARCH { - "x86" => "x86", - "x86_64" => "x86_64", - "aarch64" => "arm64", - other => other, - } -} - // bounded parallel downloader. spawns up to MAX_CONCURRENT_DOWNLOADS tasks // and feeds new ones in as each completes. collects errors but keeps going // so it downloads as much as possible before reporting the first failure.