mcapi 0.2.0

Unified async Rust client for the Minecraft ecosystem (Mojang, Modrinth, CurseForge, Yggdrasil, Blessing Skin, Loaders, Java Runtimes, and SLP)
Documentation
#[cfg(feature = "http")]
use std::time::{SystemTime, UNIX_EPOCH};

#[cfg(feature = "http")]
use reqwest::header::HeaderMap;
use thiserror::Error;

/// Rate-limit metadata extracted from HTTP response headers.
#[cfg(feature = "http")]
#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct RateLimitInfo {
    /// Seconds to wait before retrying (`Retry-After` or `X-Ratelimit-Reset`).
    pub retry_after_secs: Option<u64>,
    /// Maximum requests allowed in the current window (`X-Ratelimit-Limit`).
    pub limit: Option<u32>,
    /// Remaining requests in the current window (`X-Ratelimit-Remaining`).
    pub remaining: Option<u32>,
}

/// Unified error type returned across all `mcapi` modules.
#[derive(Debug, Error)]
pub enum Error {
    #[cfg(feature = "http")]
    #[cfg_attr(docsrs, doc(cfg(feature = "http")))]
    #[error("HTTP request failed: {0}")]
    Http(#[from] reqwest::Error),

    #[error("failed to serialize or deserialize JSON: {0}")]
    Json(#[from] serde_json::Error),

    #[cfg(feature = "http")]
    #[cfg_attr(docsrs, doc(cfg(feature = "http")))]
    #[error("invalid URL: {0}")]
    Url(#[from] url::ParseError),

    #[cfg(feature = "http")]
    #[cfg_attr(docsrs, doc(cfg(feature = "http")))]
    #[error("invalid HTTP header value: {0}")]
    InvalidHeader(#[from] reqwest::header::InvalidHeaderValue),

    #[cfg(feature = "http")]
    #[cfg_attr(docsrs, doc(cfg(feature = "http")))]
    #[error("rate limit exceeded, retry after {retry_after_secs}s")]
    RateLimitExceeded {
        retry_after_secs: u64,
        limit: Option<u32>,
        remaining: Option<u32>,
    },

    #[cfg(feature = "http")]
    #[cfg_attr(docsrs, doc(cfg(feature = "http")))]
    #[error("API returned HTTP {status} for {url}: {message}")]
    ApiStatus {
        status: u16,
        url: String,
        message: String,
        body: String,
    },

    #[error("invalid input: {0}")]
    InvalidInput(String),

    #[cfg(any(feature = "yggdrasil", feature = "slp"))]
    #[cfg_attr(docsrs, doc(cfg(any(feature = "yggdrasil", feature = "slp"))))]
    #[error("base64 decode error: {0}")]
    Base64(#[from] base64::DecodeError),

    #[cfg(feature = "loaders")]
    #[cfg_attr(docsrs, doc(cfg(feature = "loaders")))]
    #[error("XML parse error: {0}")]
    Xml(#[from] quick_xml::DeError),

    #[cfg(feature = "modrinth")]
    #[cfg_attr(docsrs, doc(cfg(feature = "modrinth")))]
    #[error("invalid Modrinth project/version/user ID or slug: {0}")]
    InvalidIdOrSlug(String),

    #[cfg(feature = "modrinth")]
    #[cfg_attr(docsrs, doc(cfg(feature = "modrinth")))]
    #[error("invalid {algorithm} hash: {hash}")]
    InvalidHash {
        algorithm: &'static str,
        hash: String,
    },

    #[cfg(feature = "mojang")]
    #[cfg_attr(docsrs, doc(cfg(feature = "mojang")))]
    #[error("XSTS rejected ({:?}, XErr={}): {}", .0.kind, .0.xerr, .0.message)]
    XstsRejected(crate::mojang::XstsError),

    #[cfg(feature = "mojang")]
    #[cfg_attr(docsrs, doc(cfg(feature = "mojang")))]
    #[error("missing Xbox user hash (uhs) in XBL/XSTS DisplayClaims")]
    MissingUserHash,

    #[cfg(feature = "mojang")]
    #[cfg_attr(docsrs, doc(cfg(feature = "mojang")))]
    #[error("Microsoft device code expired before authorization")]
    DeviceCodeExpired,

    #[cfg(feature = "mojang")]
    #[cfg_attr(docsrs, doc(cfg(feature = "mojang")))]
    #[error("Microsoft device code authorization was declined by the user")]
    DeviceCodeDeclined,

    #[cfg(feature = "mojang")]
    #[cfg_attr(docsrs, doc(cfg(feature = "mojang")))]
    #[error("Microsoft account does not own Minecraft: Java Edition")]
    DoesNotOwnMinecraft,

    #[cfg(any(feature = "mojang", feature = "yggdrasil"))]
    #[cfg_attr(docsrs, doc(cfg(any(feature = "mojang", feature = "yggdrasil"))))]
    #[error("profile has no textures property")]
    MissingTexturesProperty,

    #[cfg(feature = "yggdrasil")]
    #[cfg_attr(docsrs, doc(cfg(feature = "yggdrasil")))]
    #[error("Yggdrasil error ({error}): {error_message}")]
    Yggdrasil {
        error: String,
        error_message: String,
        cause: Option<String>,
    },

    #[cfg(feature = "yggdrasil")]
    #[cfg_attr(docsrs, doc(cfg(feature = "yggdrasil")))]
    #[error("invalid X-Authlib-Injector-API-Location header")]
    InvalidAliLocation,

    #[cfg(feature = "yggdrasil")]
    #[cfg_attr(docsrs, doc(cfg(feature = "yggdrasil")))]
    #[error("profile property '{0}' is missing a signature")]
    MissingSignature(String),

    #[cfg(feature = "yggdrasil")]
    #[cfg_attr(docsrs, doc(cfg(feature = "yggdrasil")))]
    #[error("invalid profile signature or public key: {0}")]
    InvalidSignature(String),

    #[cfg(feature = "blessing")]
    #[cfg_attr(docsrs, doc(cfg(feature = "blessing")))]
    #[error("Blessing Skin API returned code {code}: {message}")]
    BlessingApi { code: i32, message: String },

    #[cfg(feature = "blessing")]
    #[cfg_attr(docsrs, doc(cfg(feature = "blessing")))]
    #[error("Blessing Skin API response missing expected data field")]
    MissingData,

    #[cfg(feature = "slp")]
    #[cfg_attr(docsrs, doc(cfg(feature = "slp")))]
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),

    #[cfg(feature = "slp")]
    #[cfg_attr(docsrs, doc(cfg(feature = "slp")))]
    #[error("operation timed out")]
    Timeout,

    #[cfg(feature = "slp")]
    #[cfg_attr(docsrs, doc(cfg(feature = "slp")))]
    #[error("malformed VarInt in Minecraft protocol frame")]
    MalformedVarInt,

    #[cfg(feature = "slp")]
    #[cfg_attr(docsrs, doc(cfg(feature = "slp")))]
    #[error("unexpected Minecraft packet ID: 0x{0:02X}")]
    UnexpectedPacketId(i32),

    #[cfg(feature = "slp")]
    #[cfg_attr(docsrs, doc(cfg(feature = "slp")))]
    #[error("packet frame too large: {0} bytes")]
    FrameTooLarge(usize),

    #[cfg(feature = "slp")]
    #[cfg_attr(docsrs, doc(cfg(feature = "slp")))]
    #[error("invalid server status response: {0}")]
    InvalidResponse(String),
}

impl Error {
    /// Returns the HTTP status code associated with this error, if any.
    ///
    /// Returns `Some(status)` for [`Error::ApiStatus`] and `Some(429)` for
    /// [`Error::RateLimitExceeded`].
    pub fn status_code(&self) -> Option<u16> {
        match self {
            #[cfg(feature = "http")]
            Error::ApiStatus { status, .. } => Some(*status),
            #[cfg(feature = "http")]
            Error::RateLimitExceeded { .. } => Some(429),
            _ => None,
        }
    }

    /// Returns `true` if this error represents an HTTP `404 Not Found` response.
    pub fn is_not_found(&self) -> bool {
        self.status_code() == Some(404)
    }

    /// Returns `true` if this error represents an HTTP `429 Too Many Requests` response.
    pub fn is_rate_limited(&self) -> bool {
        self.status_code() == Some(429)
    }
}

/// Unified result alias for `mcapi`.
pub type Result<T> = std::result::Result<T, Error>;

/// Parses `Retry-After` (RFC 9110 ยง10.2.3, <https://datatracker.ietf.org/doc/html/rfc9110#section-10.2.3>)
/// and `X-Ratelimit-*` headers (Modrinth style, <https://docs.modrinth.com/api/#ratelimits>)
/// from an HTTP response.
#[cfg(feature = "http")]
#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
pub fn parse_rate_limit_headers(headers: &HeaderMap) -> RateLimitInfo {
    let retry_after_secs = parse_header::<u64>(headers, "retry-after").or_else(|| {
        parse_header::<u64>(headers, "x-ratelimit-reset").map(|val| {
            if val >= 1_000_000_000 {
                let now = SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .map(|d| d.as_secs())
                    .unwrap_or(0);
                val.saturating_sub(now)
            } else {
                val
            }
        })
    });
    let limit = parse_header::<u32>(headers, "x-ratelimit-limit");
    let remaining = parse_header::<u32>(headers, "x-ratelimit-remaining");

    RateLimitInfo {
        retry_after_secs,
        limit,
        remaining,
    }
}

#[cfg(feature = "http")]
fn parse_header<T: std::str::FromStr>(headers: &HeaderMap, name: &str) -> Option<T> {
    headers.get(name)?.to_str().ok()?.trim().parse::<T>().ok()
}

/// Extracts a human-readable error message from a JSON response body when possible.
#[cfg(feature = "http")]
pub(crate) fn extract_api_error_message(body: &str, status: reqwest::StatusCode) -> String {
    if let Ok(value) = serde_json::from_str::<serde_json::Value>(body) {
        for key in [
            "errorMessage",
            "description",
            "message",
            "error_description",
            "error",
        ] {
            if let Some(msg) = value.get(key).and_then(|v| v.as_str())
                && !msg.trim().is_empty()
            {
                return msg.to_string();
            }
        }
    }
    let trimmed = body.trim();
    if trimmed.is_empty() {
        status
            .canonical_reason()
            .unwrap_or("unexpected status")
            .to_string()
    } else if trimmed.len() > 240 {
        let end = (0..=240)
            .rev()
            .find(|&i| trimmed.is_char_boundary(i))
            .unwrap_or(0);
        format!("{}...", &trimmed[..end])
    } else {
        trimmed.to_string()
    }
}