Skip to main content

mcapi/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2//! Unified async Rust client for the Minecraft ecosystem.
3//!
4//! All HTTP platform clients can share a single `Arc`-backed [`HttpClient`] (and its connection
5//! pool, [`Mirror`] routing, and [`ResiliencePolicy`]) either directly via `::from_http(http)`
6//! or through the lightweight [`McApi`] entry point (`McApi::builder()`).
7//!
8//! Every module returns the unified [`Error`] and [`Result`] types, uses [`McUuid`] for Minecraft
9//! UUIDs, and re-exports public dependency crates under [`reexports`].
10//!
11//! Enable only the modules you need via Cargo features (`mojang`, `modrinth`, `modrinth-write`,
12//! `curseforge`, `curseforge-cdn-fallback`, `yggdrasil`, `yggdrasil-authlib`,
13//! `yggdrasil-verify`, `blessing`, `loaders`, `bmclapi`, `java`, `stream`, `tracing`) or keep
14//! the default `full` feature set. When any HTTP feature is enabled, select exactly one TLS
15//! backend: `tls-aws-lc` (default), `tls-native`, `tls-native-vendored`, or
16//! `tls-rustls-no-provider`.
17
18pub mod error;
19#[cfg(feature = "http")]
20#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
21pub mod http;
22#[cfg(feature = "http")]
23#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
24pub mod mirror;
25#[cfg(feature = "profile")]
26#[cfg_attr(docsrs, doc(cfg(feature = "profile")))]
27pub mod profile;
28#[cfg(all(test, feature = "http"))]
29#[path = "../tests/common/mod.rs"]
30pub(crate) mod test_common;
31#[cfg(feature = "http")]
32pub(crate) mod util;
33pub mod uuid;
34
35#[cfg(feature = "curseforge")]
36#[cfg_attr(docsrs, doc(cfg(feature = "curseforge")))]
37pub mod curseforge;
38
39#[cfg(feature = "modrinth")]
40#[cfg_attr(docsrs, doc(cfg(feature = "modrinth")))]
41pub mod modrinth;
42
43#[cfg(feature = "mojang")]
44#[cfg_attr(docsrs, doc(cfg(feature = "mojang")))]
45pub mod mojang;
46
47#[cfg(feature = "yggdrasil")]
48#[cfg_attr(docsrs, doc(cfg(feature = "yggdrasil")))]
49pub mod yggdrasil;
50
51#[cfg(feature = "blessing")]
52#[cfg_attr(docsrs, doc(cfg(feature = "blessing")))]
53pub mod blessing;
54
55#[cfg(feature = "loaders")]
56#[cfg_attr(docsrs, doc(cfg(feature = "loaders")))]
57pub mod loaders;
58
59#[cfg(feature = "bmclapi")]
60#[cfg_attr(docsrs, doc(cfg(feature = "bmclapi")))]
61pub mod bmclapi;
62
63#[cfg(feature = "java")]
64#[cfg_attr(docsrs, doc(cfg(feature = "java")))]
65pub mod java;
66
67#[cfg(feature = "http")]
68#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
69pub use error::ApiStatusError;
70#[cfg(feature = "yggdrasil")]
71#[cfg_attr(docsrs, doc(cfg(feature = "yggdrasil")))]
72pub use error::YggdrasilError;
73pub use error::{Error, Result};
74#[cfg(feature = "http")]
75#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
76pub use http::{HttpClient, HttpClientBuilder, ResiliencePolicy};
77#[cfg(feature = "http")]
78#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
79pub use mirror::{Mirror, RewriteRule};
80pub use uuid::McUuid;
81
82/// Re-exports of upstream dependency crates exposed in `mcapi` public types and signatures.
83///
84/// Using these re-exports prevents Cargo semver/version-mismatch issues when callers accept
85/// or construct types such as [`reqwest::Client`], [`url::Url`], [`jiff::Timestamp`],
86/// [`uuid::Uuid`], [`rsa::RsaPublicKey`], or [`serde_json::Value`].
87pub mod reexports {
88    /// Re-export of the `uuid` crate used by [`McUuid`](crate::McUuid).
89    pub use ::uuid;
90    /// Re-export of the `jiff` crate used for timestamps.
91    #[cfg(any(
92        feature = "curseforge",
93        feature = "modrinth",
94        feature = "mojang",
95        feature = "java"
96    ))]
97    #[cfg_attr(
98        docsrs,
99        doc(cfg(any(
100            feature = "curseforge",
101            feature = "modrinth",
102            feature = "mojang",
103            feature = "java"
104        )))
105    )]
106    pub use jiff;
107    /// Re-export of the `reqwest` crate used by [`HttpClient`](crate::HttpClient).
108    #[cfg(feature = "http")]
109    #[cfg_attr(docsrs, doc(cfg(feature = "http")))]
110    pub use reqwest;
111    /// Re-export of the `rsa` crate used by `yggdrasil-verify`.
112    #[cfg(feature = "yggdrasil-verify")]
113    #[cfg_attr(docsrs, doc(cfg(feature = "yggdrasil-verify")))]
114    pub use rsa;
115    /// Re-export of the `serde_json` crate used in [`Error::Json`](crate::Error::Json) and extensible model fields.
116    pub use serde_json;
117    /// Re-export of the `url` crate used for endpoint and asset URLs.
118    #[cfg(any(feature = "http", feature = "profile"))]
119    #[cfg_attr(docsrs, doc(cfg(any(feature = "http", feature = "profile"))))]
120    pub use url;
121}
122
123/// Builder for [`McApi`].
124#[cfg(feature = "http")]
125#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
126#[derive(Clone, Debug, Default)]
127pub struct McApiBuilder {
128    http: HttpClientBuilder,
129}
130
131#[cfg(feature = "http")]
132impl McApiBuilder {
133    /// Creates a new [`McApiBuilder`] with default [`HttpClient`] settings.
134    #[must_use]
135    pub fn new() -> Self {
136        Self {
137            http: HttpClientBuilder::new(),
138        }
139    }
140
141    /// Sets the `User-Agent` header used when building an internal `reqwest::Client`.
142    #[must_use]
143    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
144        self.http = self.http.user_agent(user_agent);
145        self
146    }
147
148    /// Configures the [`Mirror`] routing strategy shared across clients.
149    #[must_use]
150    pub fn mirror(mut self, mirror: Mirror) -> Self {
151        self.http = self.http.mirror(mirror);
152        self
153    }
154
155    /// Configures the [`ResiliencePolicy`] (retries, backoff, and official fallback).
156    #[must_use]
157    pub fn resilience(mut self, resilience: ResiliencePolicy) -> Self {
158        self.http = self.http.resilience(resilience);
159        self
160    }
161
162    /// Sets the request timeout when building an internal `reqwest::Client`.
163    #[must_use]
164    pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
165        self.http = self.http.timeout(timeout);
166        self
167    }
168
169    /// Adds a default header when building an internal `reqwest::Client`.
170    #[must_use]
171    pub fn default_header(
172        mut self,
173        name: reqwest::header::HeaderName,
174        value: reqwest::header::HeaderValue,
175    ) -> Self {
176        self.http = self.http.default_header(name, value);
177        self
178    }
179
180    /// Injects a pre-configured `reqwest::Client` (for connection pool sharing or custom TLS).
181    #[must_use]
182    pub fn reqwest_client(mut self, client: reqwest::Client) -> Self {
183        self.http = self.http.reqwest_client(client);
184        self
185    }
186
187    /// Builds a [`McApi`] facade backed by the configured [`HttpClient`].
188    pub fn build(self) -> Result<McApi> {
189        Ok(McApi::from_http(self.http.build()?))
190    }
191}
192
193/// Lightweight shared entry point holding a single [`HttpClient`] (one `reqwest::Client`
194/// connection pool, [`Mirror`], and [`ResiliencePolicy`]) and vending zero-cost platform clients.
195#[cfg(feature = "http")]
196#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
197#[derive(Clone, Debug)]
198pub struct McApi {
199    http: HttpClient,
200}
201
202#[cfg(feature = "http")]
203impl McApi {
204    /// Creates a new [`McApi`] with default [`HttpClient`] settings.
205    pub fn new() -> Result<Self> {
206        Ok(Self {
207            http: HttpClient::new()?,
208        })
209    }
210
211    /// Returns a [`McApiBuilder`] for configuring mirrors, resilience policies, and headers.
212    #[must_use]
213    pub fn builder() -> McApiBuilder {
214        McApiBuilder::new()
215    }
216
217    /// Wraps an existing shared [`HttpClient`].
218    #[must_use]
219    pub const fn from_http(http: HttpClient) -> Self {
220        Self { http }
221    }
222
223    /// Returns a reference to the underlying shared [`HttpClient`].
224    #[must_use]
225    pub fn http(&self) -> &HttpClient {
226        &self.http
227    }
228
229    /// Returns a [`mojang::MojangClient`] sharing this instance's [`HttpClient`].
230    #[cfg(feature = "mojang")]
231    #[cfg_attr(docsrs, doc(cfg(feature = "mojang")))]
232    #[must_use]
233    pub fn mojang(&self) -> mojang::MojangClient {
234        mojang::MojangClient::from_http(self.http.clone())
235    }
236
237    /// Returns a [`modrinth::ModrinthClient`] sharing this instance's [`HttpClient`].
238    #[cfg(feature = "modrinth")]
239    #[cfg_attr(docsrs, doc(cfg(feature = "modrinth")))]
240    #[must_use]
241    pub fn modrinth(&self) -> modrinth::ModrinthClient {
242        modrinth::ModrinthClient::from_http(self.http.clone())
243    }
244
245    /// Returns a [`curseforge::CurseForgeClient`] sharing this instance's [`HttpClient`].
246    ///
247    /// - When `api_key` is `Some(key)` (non-blank), attaches `x-api-key` only for direct
248    ///   unrewritten requests (never forwarded to third-party mirrors).
249    /// - When `api_key` is `None` (or blank) and the active [`Mirror`] rewrites
250    ///   `https://api.curseforge.com`, constructs a keyless mirror client (skipping official
251    ///   fallback).
252    /// - Otherwise returns [`Error::InvalidInput`].
253    #[cfg(feature = "curseforge")]
254    #[cfg_attr(docsrs, doc(cfg(feature = "curseforge")))]
255    pub fn curseforge(&self, api_key: Option<&str>) -> Result<curseforge::CurseForgeClient> {
256        curseforge::CurseForgeClient::from_http(self.http.clone(), api_key)
257    }
258
259    /// Returns a [`yggdrasil::YggdrasilClient`] targeting `api_root` and sharing this instance's [`HttpClient`].
260    #[cfg(feature = "yggdrasil")]
261    #[cfg_attr(docsrs, doc(cfg(feature = "yggdrasil")))]
262    pub fn yggdrasil(&self, api_root: impl AsRef<str>) -> Result<yggdrasil::YggdrasilClient> {
263        yggdrasil::YggdrasilClient::from_http(self.http.clone(), api_root)
264    }
265
266    /// Returns an [`AuthlibInjectorClient`](yggdrasil::authlib_injector::AuthlibInjectorClient) sharing this instance's [`HttpClient`].
267    #[cfg(feature = "yggdrasil-authlib")]
268    #[cfg_attr(docsrs, doc(cfg(feature = "yggdrasil-authlib")))]
269    #[must_use]
270    pub fn authlib_injector(&self) -> yggdrasil::authlib_injector::AuthlibInjectorClient {
271        yggdrasil::authlib_injector::AuthlibInjectorClient::from_http(self.http.clone())
272    }
273
274    /// Returns a [`blessing::BlessingClient`] targeting `site_url` and sharing this instance's [`HttpClient`].
275    #[cfg(feature = "blessing")]
276    #[cfg_attr(docsrs, doc(cfg(feature = "blessing")))]
277    pub fn blessing(&self, site_url: impl AsRef<str>) -> Result<blessing::BlessingClient> {
278        blessing::BlessingClient::from_http(self.http.clone(), site_url)
279    }
280
281    /// Returns a [`loaders::LoadersClient`] sharing this instance's [`HttpClient`].
282    #[cfg(feature = "loaders")]
283    #[cfg_attr(docsrs, doc(cfg(feature = "loaders")))]
284    #[must_use]
285    pub fn loaders(&self) -> loaders::LoadersClient {
286        loaders::LoadersClient::from_http(self.http.clone())
287    }
288
289    /// Returns a [`bmclapi::BmclapiClient`] sharing this instance's [`HttpClient`].
290    #[cfg(feature = "bmclapi")]
291    #[cfg_attr(docsrs, doc(cfg(feature = "bmclapi")))]
292    #[must_use]
293    pub fn bmclapi(&self) -> bmclapi::BmclapiClient {
294        bmclapi::BmclapiClient::from_http(self.http.clone())
295    }
296
297    /// Returns a [`java::JavaClient`] sharing this instance's [`HttpClient`].
298    #[cfg(feature = "java")]
299    #[cfg_attr(docsrs, doc(cfg(feature = "java")))]
300    #[must_use]
301    pub fn java(&self) -> java::JavaClient {
302        java::JavaClient::from_http(self.http.clone())
303    }
304}
305
306#[cfg(feature = "http")]
307impl From<HttpClient> for McApi {
308    fn from(http: HttpClient) -> Self {
309        Self { http }
310    }
311}