diff --git a/AGENTS.md b/AGENTS.md index 543bb198de0..ca7be1dcac5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,7 +7,7 @@ This is the Modrinth monorepo — it contains all Modrinth projects, both fronte - **Monorepo tooling:** [Turborepo](https://turbo.build/) (`turbo.jsonc`) + [pnpm workspaces](https://pnpm.io/workspaces) (`pnpm-workspace.yaml`) - **Frontend:** Vue 3 / Nuxt 3, Tailwind CSS v3 - **Backend:** Rust (Labrinth API), Postgres, Clickhouse -- **Indentation:** Use TAB everywhere, never spaces +- **Indentation:** follow what `.editorconfig` says; tabs for frontend, spaces for backend ### Apps (`apps/`) diff --git a/apps/meta-generator/.env.local b/apps/meta-generator/.env.local index 21715db5374..31e5593d688 100644 --- a/apps/meta-generator/.env.local +++ b/apps/meta-generator/.env.local @@ -1,4 +1,5 @@ MR_DATABASE_URL=postgresql://launchermeta:launchermeta@localhost:5433/launchermeta +MR_DOWNLOADS__MAX_ATTEMPTS_PER_HOSTNAME=100 MR_CONCURRENCY__DOWNLOAD=8 MR_CONCURRENCY__EXTRACT_FILES=8 AWS_ACCESS_KEY_ID=minecraftmeta diff --git a/apps/meta-generator/src/config.rs b/apps/meta-generator/src/config.rs index 47d15f8c79d..6118da3d0d0 100644 --- a/apps/meta-generator/src/config.rs +++ b/apps/meta-generator/src/config.rs @@ -7,6 +7,7 @@ use url::Url; #[derive(Debug, Clone, Deserialize)] pub struct Config { pub database_url: Url, + pub downloads: Downloads, pub concurrency: Concurrency, #[serde(default)] pub sentry: Option, @@ -42,6 +43,16 @@ pub struct S3 { pub path_style: bool, } +#[derive(Debug, Clone, Deserialize)] +pub struct Downloads { + #[serde(default = "default_max_attempts_per_hostname")] + pub max_attempts_per_hostname: NonZero, +} + +pub(crate) fn default_max_attempts_per_hostname() -> NonZero { + NonZero::new(100).unwrap() +} + #[derive(Debug, Clone, Deserialize)] pub struct Concurrency { pub download: NonZero, diff --git a/apps/meta-generator/src/import/download.rs b/apps/meta-generator/src/import/download.rs index 2cc4cf14721..e477f3d1eba 100644 --- a/apps/meta-generator/src/import/download.rs +++ b/apps/meta-generator/src/import/download.rs @@ -15,8 +15,8 @@ use crate::{ store::BlobCas, upstream::Upstreams, util::{ - ErrorAccumulator, ResponseExt, Sha256, TaskContext, from_json_str, - from_json_value, + ErrorAccumulator, RequestExt, ResponseExt, Sha256, TaskContext, + from_json_str, from_json_value, }, }; @@ -143,7 +143,7 @@ impl<'cx> DownloadRunContext<'cx> { let bytes = async { self.http .get(url.clone()) - .send() + .send_retry() .await? .error_for_status_ext() .await? @@ -166,7 +166,7 @@ impl<'cx> DownloadRunContext<'cx> { let text = async { self.http .get(url.clone()) - .send() + .send_retry() .await? .error_for_status_ext() .await? diff --git a/apps/meta-generator/src/import/extract/fabriclike.rs b/apps/meta-generator/src/import/extract/fabriclike.rs index c96eca4ad19..814a7a96bed 100644 --- a/apps/meta-generator/src/import/extract/fabriclike.rs +++ b/apps/meta-generator/src/import/extract/fabriclike.rs @@ -1,7 +1,7 @@ use std::collections::{HashMap, HashSet}; use anyhow::{Context, Result, anyhow, ensure}; -use futures::{StreamExt, TryStreamExt, stream}; +use futures::{StreamExt, stream}; use indexmap::IndexMap; use tracing::{debug, info, info_span, warn}; use tracing_anyhow::FutureContext; @@ -13,7 +13,7 @@ use crate::{ FabriclikeLoader, FabriclikeStoredArtifact, GAME_VERSION_PLACEHOLDER, }, util::{ - MavenCoordinate, ResponseExt, Sha1, Sha256, TaskContext, + MavenCoordinate, RequestExt, ResponseExt, Sha1, Sha256, TaskContext, from_json_slice, }, }; @@ -147,6 +147,10 @@ pub async fn extract_catalogs( .with_context(|| { format!("normalizing profile {} from {source}", version.id) })?; + let profile_dependencies = dependencies + .iter() + .map(|artifact| artifact.coordinate.clone()) + .collect(); for mut artifact in dependencies { artifact.source = Some(format!("{source} (profile SHA256 {sha256})")); @@ -162,14 +166,13 @@ pub async fn extract_catalogs( source_sha256: sha256, template: template.to_owned(), metadata: profile, + dependencies: profile_dependencies, }); } drop(blobs); validate_groups(&games, &groups)?; drop(conn); - // store dependencies before committing profiles which reference them; - // a failed download leaves the previous extracted dataset intact let num_total = artifacts.len(); let mut num_done = 0usize; info!(num_artifacts = num_total, "downloading loader dependencies"); @@ -181,23 +184,36 @@ pub async fn extract_catalogs( || info_span!("downloading Maven artifact", %coordinate), ) .await + .inspect_err(|error| { + warn!(%coordinate, error = ?error, "skipping loader dependency after download failure"); + }) + .ok() .map(|artifact| (index, artifact)) }) .buffer_unordered(app.concurrency.download.get()) - .inspect_ok(|_| { + .inspect(|_| { num_done += 1; if num_done.is_multiple_of(100) || num_done == num_total { - info!("downloaded {num_done}/{num_total} dependencies"); + info!("processed {num_done}/{num_total} dependencies"); } }) - .try_collect::>() - .context(info_span!("downloading loader dependencies")) - .await?; + .filter_map(futures::future::ready) + .collect::>() + .await; artifacts.sort_unstable_by_key(|(index, _)| *index); let artifacts = artifacts .into_iter() .map(|(_, artifact)| artifact) .collect::>(); + let available_artifacts = artifacts + .iter() + .map(|stored| stored.artifact.coordinate.to_maven_path()) + .collect::>(); + retain_complete_profiles(&mut profiles, &available_artifacts); + ensure!( + !profiles.is_empty(), + "no complete {loader:?} profiles; keeping previous extracted dataset" + ); let mut conn = app .db @@ -299,14 +315,14 @@ async fn download_artifact( let mut checksum_url = url.clone(); checksum_url.set_path(&format!("{}.sha256", url.path())); - let response = app.http.get(checksum_url.clone()).send() + let response = app.http.get(checksum_url.clone()).send_retry() .context(info_span!("fetching Maven artifact checksum", url = %checksum_url, coordinate = %artifact.coordinate)) .await?; let use_sha1 = response.status() == reqwest::StatusCode::NOT_FOUND; let response = if use_sha1 { debug!(%url, coordinate = %artifact.coordinate, "Maven artifact SHA256 checksum unavailable; using SHA1"); checksum_url.set_path(&format!("{}.sha1", url.path())); - app.http.get(checksum_url.clone()).send() + app.http.get(checksum_url.clone()).send_retry() .context(info_span!("fetching Maven artifact SHA1 checksum", url = %checksum_url, coordinate = %artifact.coordinate)) .await? } else { @@ -374,7 +390,7 @@ async fn download_artifact( let bytes = async { app.http .get(url.clone()) - .send() + .send_retry() .await? .error_for_status_ext() .await? @@ -573,6 +589,33 @@ struct SelectedProfile { source_sha256: Sha256, template: String, metadata: ProfileMetadata, + dependencies: Vec, +} + +fn retain_complete_profiles( + profiles: &mut Vec, + available_artifacts: &HashSet, +) { + profiles.retain(|profile| { + let missing = profile + .dependencies + .iter() + .filter(|coordinate| { + !available_artifacts.contains(&coordinate.to_maven_path()) + }) + .map(ToString::to_string) + .collect::>(); + if missing.is_empty() { + return true; + } + warn!( + loader_version = %profile.loader_version, + group = %profile.version_group, + missing_dependencies = ?missing, + "skipping loader profile with missing dependencies" + ); + false + }); } fn profile_source( @@ -618,6 +661,119 @@ mod tests { use super::*; use serde_json::{Value, json}; + fn selected_profile( + version: &str, + libraries: &[&str], + games: &[String], + ) -> SelectedProfile { + let profile = serde_json::from_value(json!({ + "id": "loader-GAME", + "inheritsFrom": "GAME", + "releaseTime": "2026-01-01T00:00:00Z", + "time": "2026-01-01T00:00:00Z", + "type": "release", + "libraries": libraries.iter().map(|name| json!({"name": name})).collect::>() + })).unwrap(); + let (metadata, artifacts) = normalize_profile( + profile, + "GAME", + games, + &"https://maven.example.com/".parse().unwrap(), + ) + .unwrap(); + SelectedProfile { + loader_version: version.into(), + version_group: String::new(), + stable: true, + source_url: "https://meta.example.com/profile.json".into(), + source_sha256: Sha256::from_digest(b"profile"), + template: "GAME".into(), + metadata, + dependencies: artifacts + .into_iter() + .map(|artifact| artifact.coordinate) + .collect(), + } + } + + fn artifact_paths(names: &[&str]) -> HashSet { + names + .iter() + .map(|name| { + name.parse::().unwrap().to_maven_path() + }) + .collect() + } + + #[test] + fn retains_complete_profiles_in_original_order() { + let mut profiles = vec![ + selected_profile("2", &["loader:main:2"], &[]), + selected_profile("1", &["loader:main:1"], &[]), + ]; + retain_complete_profiles( + &mut profiles, + &artifact_paths(&["loader:main:1@jar", "loader:main:2"]), + ); + assert_eq!( + profiles + .iter() + .map(|profile| profile.loader_version.as_str()) + .collect::>(), + vec!["2", "1"] + ); + } + + #[test] + fn excludes_only_profiles_with_missing_dependencies() { + let mut profiles = vec![ + selected_profile("1", &["loader:main:1"], &[]), + selected_profile("2", &["loader:main:2", "org.ow2.asm:asm:9"], &[]), + ]; + retain_complete_profiles( + &mut profiles, + &artifact_paths(&["loader:main:1", "loader:main:2"]), + ); + assert_eq!(profiles.len(), 1); + assert_eq!(profiles[0].loader_version, "1"); + } + + #[test] + fn checks_concrete_mappings_for_every_game_before_importing() { + let games = vec!["1.21".into(), "1.22".into()]; + for mapping in ["net.fabricmc:intermediary", "org.quiltmc:hashed"] { + let library = format!("{mapping}:GAME:v2@jar"); + let first = format!("{mapping}:1.21:v2"); + let second = format!("{mapping}:1.22:v2"); + let mut incomplete = + vec![selected_profile("1", &[&library], &games)]; + retain_complete_profiles( + &mut incomplete, + &artifact_paths(&[&first]), + ); + assert!(incomplete.is_empty()); + let mut complete = vec![selected_profile("1", &[&library], &games)]; + retain_complete_profiles( + &mut complete, + &artifact_paths(&[&first, &second]), + ); + assert_eq!(complete.len(), 1); + } + } + + #[test] + fn missing_shared_dependency_excludes_all_affected_profiles() { + let mut profiles = vec![ + selected_profile("1", &["loader:main:1", "org.ow2.asm:asm:9"], &[]), + selected_profile("2", &["loader:main:2", "org.ow2.asm:asm:9"], &[]), + ]; + retain_complete_profiles( + &mut profiles, + &artifact_paths(&["loader:main:1", "loader:main:2"]), + ); + assert!(profiles.is_empty()); + } + fn group(id: Option<&str>, template: &str, games: &[&str]) -> ProfileGroup { ProfileGroup { id: id.map(str::to_owned), diff --git a/apps/meta-generator/src/import/forgelike/mod.rs b/apps/meta-generator/src/import/forgelike/mod.rs index a99a4ff5fa3..cf00f399a34 100644 --- a/apps/meta-generator/src/import/forgelike/mod.rs +++ b/apps/meta-generator/src/import/forgelike/mod.rs @@ -17,8 +17,8 @@ use crate::{ AppState, model, upstream::{self, mojang}, util::{ - MavenCoordinate, ResponseExt, Sha1, TaskContext, from_json_slice, - from_json_value, + MavenCoordinate, RequestExt, ResponseExt, Sha1, TaskContext, + from_json_slice, from_json_value, }, }; @@ -521,7 +521,7 @@ async fn download_library( let bytes = app .http .get(url.clone()) - .send() + .send_retry() .await? .error_for_status_ext() .await? diff --git a/apps/meta-generator/src/lib.rs b/apps/meta-generator/src/lib.rs index b2162fc9664..6b82944ae97 100644 --- a/apps/meta-generator/src/lib.rs +++ b/apps/meta-generator/src/lib.rs @@ -114,6 +114,9 @@ pub fn main() -> Result<()> { async fn main_(config: Config) -> Result<()> { static MIGRATIONS: MigrationSet = toasty::embed_migrations!(); + util::configure_hostname_attempt_limit( + config.downloads.max_attempts_per_hostname, + )?; let cli = ::parse(); let http = reqwest::Client::builder() .timeout(Duration::from_secs(30)) diff --git a/apps/meta-generator/src/util/fastly.rs b/apps/meta-generator/src/util/fastly.rs index 3069bc5ca73..0809686d79e 100644 --- a/apps/meta-generator/src/util/fastly.rs +++ b/apps/meta-generator/src/util/fastly.rs @@ -4,7 +4,7 @@ use reqwest::{IntoUrl, header::HeaderValue}; use secrecy::{ExposeSecret, SecretString}; use url::Url; -use crate::util::ResponseExt; +use crate::util::{RequestExt, ResponseExt}; #[derive(Debug)] pub struct Client { @@ -51,7 +51,7 @@ impl Client { .post(endpoint) .header("Fastly-Key", &self.fastly_key) .header("Fastly-Soft-Purge", "1") - .send() + .send_retry() .await? .error_for_status_ext() .await?; diff --git a/apps/meta-generator/src/util/http.rs b/apps/meta-generator/src/util/http.rs index 30f676d4867..d5f21b55f24 100644 --- a/apps/meta-generator/src/util/http.rs +++ b/apps/meta-generator/src/util/http.rs @@ -1,5 +1,111 @@ +use std::{ + collections::HashMap, + num::NonZero, + sync::{LazyLock, Mutex, OnceLock}, + time::Duration, +}; + use anyhow::{Result, anyhow}; -use reqwest::Response; +use reqwest::{RequestBuilder, Response, StatusCode}; +use tracing::warn; + +static FAILED_HOSTNAMES: LazyLock>> = + LazyLock::new(|| Mutex::new(HashMap::new())); +static MAX_ATTEMPTS_PER_HOSTNAME: OnceLock> = OnceLock::new(); + +pub fn configure_hostname_attempt_limit(limit: NonZero) -> Result<()> { + MAX_ATTEMPTS_PER_HOSTNAME + .set(limit) + .map_err(|_| anyhow!("hostname attempt limit already configured")) +} + +fn check_hostname_limit(hostname: &str, limit: usize) -> Result<()> { + let failures = FAILED_HOSTNAMES.lock().unwrap(); + let count = failures.get(hostname).copied().unwrap_or_default(); + anyhow::ensure!( + count < limit, + "hostname {hostname} reached its failed request attempt limit ({count}/{limit})" + ); + Ok(()) +} + +fn record_hostname_failure(hostname: &str) { + let mut failures = FAILED_HOSTNAMES.lock().unwrap(); + let count = failures.entry(hostname.to_owned()).or_default(); + *count = count.saturating_add(1); +} + +pub trait RequestExt: Sized { + /// Sends a request, retrying the request if it fails. + /// + /// If too many requests for the same hostname fail, all future requests + /// to that hostname will instantly fail. + async fn send_retry(self) -> Result; +} + +impl RequestExt for RequestBuilder { + async fn send_retry(self) -> Result { + let built = self + .try_clone() + .ok_or_else(|| { + anyhow!("request cannot be cloned for hostname validation") + })? + .build()?; + let hostname = built + .url() + .host_str() + .ok_or_else(|| anyhow!("request URL has no hostname"))? + .to_owned(); + let limit = MAX_ATTEMPTS_PER_HOSTNAME + .get() + .copied() + .unwrap_or_else(crate::config::default_max_attempts_per_hostname) + .get(); + let mut request = self; + for attempt in 0..=3 { + check_hostname_limit(&hostname, limit)?; + let next = request.try_clone(); + let result = request.send().await; + if result.as_ref().map_or(true, |response| { + response.status().is_client_error() + || response.status().is_server_error() + }) { + record_hostname_failure(&hostname); + } + let retryable = match &result { + Ok(response) => { + response.status() == StatusCode::TOO_MANY_REQUESTS + || response.status().is_server_error() + } + Err(error) => { + error.is_timeout() + || error.is_connect() + || error.is_request() + } + }; + if !retryable || attempt == 3 { + return result.map_err(anyhow::Error::from); + } + let Some(next) = next else { + return result.map_err(anyhow::Error::from); + }; + check_hostname_limit(&hostname, limit)?; + let delay = Duration::from_secs(1 << attempt); + match &result { + Ok(response) => { + warn!(url = %response.url(), status = %response.status(), retry = attempt + 1, delay_seconds = delay.as_secs(), "retrying HTTP request") + } + Err(error) => { + warn!(%error, retry = attempt + 1, delay_seconds = delay.as_secs(), "retrying HTTP request") + } + } + drop(result); + tokio::time::sleep(delay).await; + request = next; + } + unreachable!() + } +} pub trait ResponseExt: Sized { async fn error_for_status_ext(self) -> Result; @@ -22,3 +128,75 @@ impl ResponseExt for Response { } } } + +#[cfg(test)] +mod tests { + use super::*; + use std::{ + io::{BufRead, BufReader, Write}, + net::TcpListener, + }; + + #[test] + fn failures_accumulate_per_hostname() { + let host = "failure-counter.test"; + assert!(check_hostname_limit(host, 2).is_ok()); + record_hostname_failure(host); + assert!(check_hostname_limit(host, 2).is_ok()); + record_hostname_failure(host); + assert!(check_hostname_limit(host, 2).is_err()); + assert!(check_hostname_limit("other-host.test", 2).is_ok()); + } + + #[tokio::test] + async fn blocked_hostname_fails_without_sending() { + let host = "blocked-host.invalid"; + for _ in 0..crate::config::default_max_attempts_per_hostname().get() { + record_hostname_failure(host); + } + let error = reqwest::Client::new() + .get(format!("http://{host}/")) + .send_retry() + .await + .unwrap_err(); + assert!( + error + .to_string() + .contains("reached its failed request attempt limit") + ); + } + + #[tokio::test] + async fn counts_http_failures_without_resetting_on_success() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let server = std::thread::spawn(move || { + for status in [404, 200] { + let (mut stream, _) = listener.accept().unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + let mut reader = BufReader::new(&mut stream); + loop { + let mut line = String::new(); + assert!(reader.read_line(&mut line).unwrap() > 0); + if line == "\r\n" { + break; + } + } + write!(stream, "HTTP/1.1 {status} Test\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").unwrap(); + } + }); + let client = reqwest::Client::new(); + assert_eq!( + client.get(&url).send_retry().await.unwrap().status(), + StatusCode::NOT_FOUND + ); + assert_eq!( + client.get(&url).send_retry().await.unwrap().status(), + StatusCode::OK + ); + assert_eq!(FAILED_HOSTNAMES.lock().unwrap().get("127.0.0.1"), Some(&1)); + server.join().unwrap(); + } +}