mcapi 0.2.0

Unified async Rust client for the Minecraft ecosystem (Mojang, Modrinth, CurseForge, Yggdrasil, Blessing Skin, Loaders, Java Runtimes, and SLP)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
use std::sync::Arc;
use std::time::Duration;

use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
use reqwest::{Client, RequestBuilder, Response, StatusCode};
use serde::Serialize;
use serde::de::DeserializeOwned;

use crate::error::{Error, Result, extract_api_error_message, parse_rate_limit_headers};
use crate::mirror::Mirror;

/// Default resilience policy controlling rate-limit retries, transient 5xx retries,
/// and mirror-to-official fallback behavior.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ResiliencePolicy {
    /// Whether HTTP 429 responses should automatically sleep and retry.
    /// Defaults to `false` (fast-fail with `Error::RateLimitExceeded`).
    pub auto_retry_rate_limit: bool,
    /// Maximum number of retry attempts on rate limits or transient 5xx errors.
    pub max_retries: u32,
    /// Whether HTTP 5xx responses should automatically retry with exponential backoff.
    pub retry_5xx: bool,
    /// Whether a rewritten mirror request that fails with transport error, 404, 5xx,
    /// or body decode/parse error should fall back once to the original official URL.
    pub fallback_to_official: bool,
    /// Maximum backoff wait for automatic rate-limit retries.
    pub max_retry_wait: Duration,
}

impl Default for ResiliencePolicy {
    fn default() -> Self {
        Self {
            auto_retry_rate_limit: false,
            max_retries: 2,
            retry_5xx: false,
            fallback_to_official: false,
            max_retry_wait: Duration::from_secs(30),
        }
    }
}

/// Configuration snapshot used to construct an [`HttpCore`].
#[derive(Clone, Debug)]
pub struct HttpConfig {
    pub user_agent: String,
    pub mirror: Mirror,
    pub resilience: ResiliencePolicy,
    pub timeout: Duration,
}

impl Default for HttpConfig {
    fn default() -> Self {
        Self {
            user_agent: concat!("mcapi/", env!("CARGO_PKG_VERSION")).to_string(),
            mirror: Mirror::Official,
            resilience: ResiliencePolicy::default(),
            timeout: Duration::from_secs(30),
        }
    }
}

/// Builder for [`HttpCore`].
#[derive(Clone, Debug)]
pub struct HttpCoreBuilder {
    config: HttpConfig,
    client: Option<Client>,
    default_headers: HeaderMap,
}

impl Default for HttpCoreBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl HttpCoreBuilder {
    /// Creates a new builder with default settings.
    pub fn new() -> Self {
        Self {
            config: HttpConfig::default(),
            client: None,
            default_headers: HeaderMap::new(),
        }
    }

    /// Sets the `User-Agent` header used when building an internal `reqwest::Client`.
    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
        self.config.user_agent = user_agent.into();
        self
    }

    /// Configures mirror URL rewriting.
    pub fn mirror(mut self, mirror: Mirror) -> Self {
        self.config.mirror = mirror;
        self
    }

    /// Configures retry and mirror-fallback policies.
    pub fn resilience(mut self, resilience: ResiliencePolicy) -> Self {
        self.config.resilience = resilience;
        self
    }

    /// Sets the request timeout when building an internal `reqwest::Client`.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.config.timeout = timeout;
        self
    }

    /// Adds a default header when building an internal `reqwest::Client`.
    pub fn default_header(mut self, name: HeaderName, value: HeaderValue) -> Self {
        self.default_headers.insert(name, value);
        self
    }

    /// Injects a pre-configured `reqwest::Client` (for connection pool sharing or custom TLS).
    ///
    /// Note: `user_agent`, `timeout`, and `default_header` configure the internally constructed
    /// `reqwest::Client` and are bypassed when an external `reqwest::Client` is provided.
    pub fn with_client(mut self, client: Client) -> Self {
        self.client = Some(client);
        self
    }

    /// Builds the [`HttpCore`] instance.
    pub fn build(self) -> Result<HttpCore> {
        let client = match self.client {
            Some(client) => client,
            None => Client::builder()
                .user_agent(self.config.user_agent.clone())
                .timeout(self.config.timeout)
                .default_headers(self.default_headers)
                .redirect(safe_redirect_policy())
                .build()?,
        };

        Ok(HttpCore {
            inner: Arc::new(HttpCoreInner {
                client,
                mirror: self.config.mirror,
                resilience: self.config.resilience,
                user_agent: self.config.user_agent,
            }),
        })
    }
}

#[derive(Debug)]
struct HttpCoreInner {
    client: Client,
    mirror: Mirror,
    resilience: ResiliencePolicy,
    user_agent: String,
}

/// Shared, cheaply cloneable (`Arc`-backed) HTTP client wrapper adding mirror routing,
/// rate-limit inspection, optional retries, and official-origin fallback on top of `reqwest::Client`.
#[derive(Clone, Debug)]
pub struct HttpCore {
    inner: Arc<HttpCoreInner>,
}

impl HttpCore {
    /// Builds an [`HttpCore`] using default settings.
    pub fn new() -> Result<Self> {
        HttpCoreBuilder::new().build()
    }

    /// Returns an [`HttpCoreBuilder`].
    pub fn builder() -> HttpCoreBuilder {
        HttpCoreBuilder::new()
    }

    /// Returns the underlying `reqwest::Client`.
    pub fn client(&self) -> &Client {
        &self.inner.client
    }

    /// Returns the configured [`Mirror`].
    pub fn mirror(&self) -> &Mirror {
        &self.inner.mirror
    }

    /// Returns the configured [`ResiliencePolicy`].
    pub fn resilience(&self) -> &ResiliencePolicy {
        &self.inner.resilience
    }

    /// Returns the configured `User-Agent` string.
    pub fn user_agent(&self) -> &str {
        &self.inner.user_agent
    }

    /// Resolves `official_url` through the active [`Mirror`].
    pub fn resolve_url(&self, official_url: &str) -> String {
        self.inner.mirror.rewrite_url(official_url)
    }

    /// Sends a replayable request built by `build_req` and returns the raw successful [`Response`].
    pub async fn send_with<F>(&self, official_url: &str, build_req: F) -> Result<Response>
    where
        F: FnMut(&Client, &str) -> RequestBuilder,
    {
        self.send_and_map(official_url, build_req, |resp| std::future::ready(Ok(resp)))
            .await
    }

    /// Sends a one-shot request (such as multipart uploads) that cannot be cloned/replayed.
    pub async fn send_oneshot<F>(&self, official_url: &str, build_req: F) -> Result<Response>
    where
        F: FnOnce(&Client, &str) -> RequestBuilder,
    {
        let target_url = self.inner.mirror.rewrite_url(official_url);
        let response = build_req(&self.inner.client, &target_url).send().await?;
        check_response_status(response, &target_url).await
    }

    /// Sends a replayable request directly to `url`, bypassing [`Mirror`] URL rewriting and
    /// mirror fallback. Use this for authenticated or mutating endpoints so credentials are
    /// never sent to third-party mirrors.
    pub async fn send_direct<F>(&self, url: &str, mut build_req: F) -> Result<Response>
    where
        F: FnMut(&Client, &str) -> RequestBuilder,
    {
        self.execute_with_retries(url, &mut build_req).await
    }

    /// Sends a one-shot request directly to `url`, bypassing [`Mirror`] URL rewriting.
    pub async fn send_direct_oneshot<F>(&self, url: &str, build_req: F) -> Result<Response>
    where
        F: FnOnce(&Client, &str) -> RequestBuilder,
    {
        let response = build_req(&self.inner.client, url).send().await?;
        check_response_status(response, url).await
    }

    /// Sends a `POST` JSON request directly to `url` (bypassing [`Mirror`] rewriting)
    /// and deserializes the JSON body.
    pub async fn post_direct_json<B: Serialize + ?Sized, T: DeserializeOwned>(
        &self,
        url: &str,
        body: &B,
    ) -> Result<T> {
        let resp = self
            .send_direct(url, |client, target| client.post(target).json(body))
            .await?;
        Ok(resp.json::<T>().await?)
    }

    /// Sends a replayable request built by `build_req` and deserializes the JSON body,
    /// falling back to `official_url` if mirror transport, status, or JSON parsing fails.
    pub async fn send_json_with<F, T>(&self, official_url: &str, build_req: F) -> Result<T>
    where
        F: FnMut(&Client, &str) -> RequestBuilder,
        T: DeserializeOwned,
    {
        self.send_and_map(official_url, build_req, |resp| async move {
            Ok(resp.json::<T>().await?)
        })
        .await
    }

    /// Sends a `GET` request and deserializes the JSON body.
    pub async fn get_json<T: DeserializeOwned>(&self, official_url: &str) -> Result<T> {
        self.send_json_with(official_url, |client, url| client.get(url))
            .await
    }

    /// Sends a `GET` request with query parameters and deserializes the JSON body.
    pub async fn get_json_query<Q: Serialize + ?Sized, T: DeserializeOwned>(
        &self,
        official_url: &str,
        query: &Q,
    ) -> Result<T> {
        self.send_json_with(official_url, |client, url| client.get(url).query(query))
            .await
    }

    /// Sends a `POST` JSON request and deserializes the JSON body.
    pub async fn post_json<B: Serialize + ?Sized, T: DeserializeOwned>(
        &self,
        official_url: &str,
        body: &B,
    ) -> Result<T> {
        self.send_json_with(official_url, |client, url| client.post(url).json(body))
            .await
    }

    /// Sends a `GET` request and returns plain text.
    pub async fn get_text(&self, official_url: &str) -> Result<String> {
        self.send_and_map(
            official_url,
            |client, url| client.get(url),
            |resp| async move { Ok(resp.text().await?) },
        )
        .await
    }

    /// Sends a `GET` request, reads the body as text, and parses it with `parse`.
    ///
    /// If reading or parsing the mirror response fails with a fallback-eligible error
    /// (such as malformed JSON/XML from a mirror HTML page), retries against `official_url`
    /// when `fallback_to_official` is enabled.
    pub async fn get_text_parsed<P, T>(&self, official_url: &str, parse: P) -> Result<T>
    where
        P: Fn(&str) -> Result<T>,
    {
        self.send_and_map(
            official_url,
            |client, url| client.get(url),
            |resp| {
                let parse = &parse;
                async move { parse(&resp.text().await?) }
            },
        )
        .await
    }

    /// Issues a mirror-aware `GET` request and returns the raw [`reqwest::Response`] stream.
    pub async fn get_stream(&self, official_url: &str) -> Result<Response> {
        self.send_with(official_url, |client, target| client.get(target))
            .await
    }

    /// Reads a JSON response or returns `Ok(None)` when the status is `204 No Content` or `404 Not Found`.
    pub async fn send_optional_json<F, T>(
        &self,
        official_url: &str,
        build_req: F,
    ) -> Result<Option<T>>
    where
        F: FnMut(&Client, &str) -> RequestBuilder,
        T: DeserializeOwned,
    {
        let res = self
            .send_and_map(official_url, build_req, |resp| async move {
                if resp.status() == StatusCode::NO_CONTENT {
                    return Ok(None);
                }
                let text = resp.text().await?;
                if text.trim().is_empty() {
                    return Ok(None);
                }
                Ok(Some(serde_json::from_str(&text)?))
            })
            .await;

        match res {
            Ok(val) => Ok(val),
            Err(Error::ApiStatus { status: 404, .. }) => Ok(None),
            Err(err) => Err(err),
        }
    }

    async fn send_and_map<F, M, Fut, T>(
        &self,
        official_url: &str,
        mut build_req: F,
        mut map_resp: M,
    ) -> Result<T>
    where
        F: FnMut(&Client, &str) -> RequestBuilder,
        M: FnMut(Response) -> Fut,
        Fut: std::future::Future<Output = Result<T>>,
    {
        let primary_url = self.inner.mirror.rewrite_url(official_url);
        let rewritten = primary_url != official_url;

        let primary_res = match self
            .execute_with_retries(&primary_url, &mut build_req)
            .await
        {
            Ok(resp) => map_resp(resp).await,
            Err(err) => Err(err),
        };

        match primary_res {
            Ok(val) => Ok(val),
            Err(err)
                if rewritten
                    && self.inner.resilience.fallback_to_official
                    && should_fallback(&err) =>
            {
                let resp = self
                    .execute_with_retries(official_url, &mut build_req)
                    .await?;
                map_resp(resp).await
            }
            Err(err) => Err(err),
        }
    }

    async fn execute_with_retries<F>(&self, target_url: &str, build_req: &mut F) -> Result<Response>
    where
        F: FnMut(&Client, &str) -> RequestBuilder,
    {
        let mut attempt: u32 = 0;
        let resilience = self.inner.resilience;
        loop {
            let response = build_req(&self.inner.client, target_url).send().await?;
            match check_response_status(response, target_url).await {
                Ok(resp) => return Ok(resp),
                Err(Error::RateLimitExceeded {
                    retry_after_secs,
                    limit,
                    remaining,
                }) => {
                    if resilience.auto_retry_rate_limit && attempt < resilience.max_retries {
                        let wait = Duration::from_secs(retry_after_secs.max(1))
                            .min(resilience.max_retry_wait);
                        tokio::time::sleep(wait).await;
                        attempt += 1;
                        continue;
                    }
                    return Err(Error::RateLimitExceeded {
                        retry_after_secs,
                        limit,
                        remaining,
                    });
                }
                Err(Error::ApiStatus { status, .. })
                    if resilience.retry_5xx
                        && (500..600).contains(&status)
                        && attempt < resilience.max_retries =>
                {
                    let backoff = Duration::from_millis(200 * (1_u64 << attempt.min(5)));
                    tokio::time::sleep(backoff).await;
                    attempt += 1;
                }
                Err(err) => return Err(err),
            }
        }
    }
}

/// Validates HTTP status, mapping `429` into [`Error::RateLimitExceeded`] and
/// other non-success codes into [`Error::ApiStatus`].
pub async fn check_response_status(response: Response, url: &str) -> Result<Response> {
    let status = response.status();
    if status.is_success() {
        return Ok(response);
    }

    if status == StatusCode::TOO_MANY_REQUESTS {
        let info = parse_rate_limit_headers(response.headers());
        return Err(Error::RateLimitExceeded {
            retry_after_secs: info.retry_after_secs.unwrap_or(60),
            limit: info.limit,
            remaining: info.remaining,
        });
    }

    let body = response.text().await.unwrap_or_default();
    let message = extract_api_error_message(&body, status);
    Err(Error::ApiStatus {
        status: status.as_u16(),
        url: url.to_string(),
        message,
        body,
    })
}

fn safe_redirect_policy() -> reqwest::redirect::Policy {
    reqwest::redirect::Policy::custom(|attempt| {
        if attempt.previous().len() >= 10 {
            attempt.error("too many redirects")
        } else if attempt
            .previous()
            .last()
            .is_some_and(|prev| prev.scheme() == "https")
            && attempt.url().scheme() == "http"
        {
            attempt.error("refusing HTTPS to HTTP redirect downgrade")
        } else {
            attempt.follow()
        }
    })
}

fn should_fallback(err: &Error) -> bool {
    match err {
        Error::Http(_) | Error::Json(_) => true,
        #[cfg(feature = "loaders")]
        Error::Xml(_) => true,
        Error::ApiStatus { status, .. } => *status == 404 || *status >= 500,
        _ => false,
    }
}