mcapi 0.3.0

Unified async Rust client for the Minecraft ecosystem (Mojang, Modrinth, CurseForge, Yggdrasil, Blessing Skin, Loaders, BMCLAPI, and Java Runtimes)
Documentation
//! Unified error and result types returned across all `mcapi` modules.

use thiserror::Error;

/// Structured HTTP non-success error details carried by [`Error::ApiStatus`].
#[cfg(feature = "http")]
#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
#[non_exhaustive]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ApiStatusError {
    /// HTTP status code returned by the upstream server.
    pub status: u16,
    /// Target URL that produced the error status.
    pub url: String,
    /// Extracted human-readable summary message.
    pub message: String,
    /// Bounded raw response body (truncated safely on UTF-8 boundaries).
    pub body: String,
}

#[cfg(feature = "http")]
impl ApiStatusError {
    /// Creates a new [`ApiStatusError`] payload.
    #[must_use]
    pub fn new(
        status: u16,
        url: impl Into<String>,
        message: impl Into<String>,
        body: impl Into<String>,
    ) -> Self {
        Self {
            status,
            url: url.into(),
            message: message.into(),
            body: body.into(),
        }
    }
}

/// Structured Yggdrasil protocol error payload carried by [`Error::Yggdrasil`].
#[cfg(feature = "yggdrasil")]
#[cfg_attr(docsrs, doc(cfg(feature = "yggdrasil")))]
#[non_exhaustive]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct YggdrasilError {
    /// Machine-readable Yggdrasil error identifier (e.g. `"ForbiddenOperationException"`).
    pub error: String,
    /// Human-readable error description from the Yggdrasil server.
    pub error_message: String,
    /// Optional underlying cause reported by the server.
    pub cause: Option<String>,
}

#[cfg(feature = "yggdrasil")]
impl YggdrasilError {
    /// Creates a new [`YggdrasilError`] payload.
    #[must_use]
    pub fn new(
        error: impl Into<String>,
        error_message: impl Into<String>,
        cause: Option<String>,
    ) -> Self {
        Self {
            error: error.into(),
            error_message: error_message.into(),
            cause,
        }
    }
}

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

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

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

    /// Invalid HTTP header value supplied by caller or server response.
    #[cfg(feature = "http")]
    #[cfg_attr(docsrs, doc(cfg(feature = "http")))]
    #[error("invalid HTTP header value: {0}")]
    InvalidHeader(#[from] reqwest::header::InvalidHeaderValue),

    /// HTTP `429 Too Many Requests` response when rate-limit retries are disabled or exhausted.
    #[cfg(feature = "http")]
    #[cfg_attr(docsrs, doc(cfg(feature = "http")))]
    #[error("{}", format_rate_limit(*retry_after_secs))]
    RateLimitExceeded {
        /// Parsed wait duration in seconds from `Retry-After` / `X-Ratelimit-Reset`.
        retry_after_secs: Option<u64>,
        /// Upstream rate-limit bucket capacity from `X-Ratelimit-Limit`, if present.
        limit: Option<u32>,
        /// Remaining requests in the current window from `X-Ratelimit-Remaining`, if present.
        remaining: Option<u32>,
    },

    /// Non-success HTTP status response returned by an API endpoint.
    #[cfg(feature = "http")]
    #[cfg_attr(docsrs, doc(cfg(feature = "http")))]
    #[error("API returned HTTP {} for {}: {}", .0.status, .0.url, .0.message)]
    ApiStatus(Box<ApiStatusError>),

    /// Caller-supplied argument failed validation or precondition checks.
    #[error("invalid input: {0}")]
    InvalidInput(String),

    /// Filesystem or stream I/O failure.
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),

    /// Opaque Base64 decoding failure (e.g. malformed `textures` property or signature).
    #[cfg(feature = "profile")]
    #[cfg_attr(docsrs, doc(cfg(feature = "profile")))]
    #[error("base64 decode error: {0}")]
    Base64(#[source] Box<dyn std::error::Error + Send + Sync>),

    /// Opaque XML parsing failure (e.g. malformed Maven metadata XML).
    #[cfg(feature = "loaders")]
    #[cfg_attr(docsrs, doc(cfg(feature = "loaders")))]
    #[error("XML parse error: {0}")]
    Xml(#[source] Box<dyn std::error::Error + Send + Sync>),

    /// Xbox Live XSTS authorization rejected with an `XErr` code.
    #[cfg(feature = "mojang")]
    #[cfg_attr(docsrs, doc(cfg(feature = "mojang")))]
    #[error("XSTS rejected ({:?}, XErr={}): {}", .0.kind, .0.xerr, .0.message)]
    XstsRejected(Box<crate::mojang::XstsError>),

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

    /// Microsoft OAuth2 device code expired before the user completed authorization.
    #[cfg(feature = "mojang")]
    #[cfg_attr(docsrs, doc(cfg(feature = "mojang")))]
    #[error("Microsoft device code expired before authorization")]
    DeviceCodeExpired,

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

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

    /// Profile properties did not contain a `"textures"` entry.
    #[cfg(any(feature = "mojang", feature = "yggdrasil"))]
    #[cfg_attr(docsrs, doc(cfg(any(feature = "mojang", feature = "yggdrasil"))))]
    #[error("profile has no textures property")]
    MissingTexturesProperty,

    /// Yggdrasil server returned a structured JSON error response.
    #[cfg(feature = "yggdrasil")]
    #[cfg_attr(docsrs, doc(cfg(feature = "yggdrasil")))]
    #[error("Yggdrasil error ({}): {}", .0.error, .0.error_message)]
    Yggdrasil(Box<YggdrasilError>),

    /// `X-Authlib-Injector-API-Location` header was invalid, circular, or attempted an HTTPS-to-HTTP downgrade.
    #[cfg(feature = "yggdrasil")]
    #[cfg_attr(docsrs, doc(cfg(feature = "yggdrasil")))]
    #[error("invalid X-Authlib-Injector-API-Location header")]
    InvalidAliLocation,

    /// Required RSA signature was absent from a profile property.
    #[cfg(feature = "yggdrasil-verify")]
    #[cfg_attr(docsrs, doc(cfg(feature = "yggdrasil-verify")))]
    #[error("profile property '{0}' is missing a signature")]
    MissingSignature(String),

    /// RSA public key PEM or property signature verification failed.
    #[cfg(feature = "yggdrasil-verify")]
    #[cfg_attr(docsrs, doc(cfg(feature = "yggdrasil-verify")))]
    #[error("invalid profile signature or public key: {0}")]
    InvalidSignature(String),

    /// Blessing Skin API returned a non-zero error code, or `code == 0` with a missing
    /// expected `data` payload.
    #[cfg(feature = "blessing")]
    #[cfg_attr(docsrs, doc(cfg(feature = "blessing")))]
    #[error("Blessing Skin API returned code {code}: {message}")]
    BlessingApi {
        /// Numeric status code from the Blessing Skin JSON envelope.
        code: i32,
        /// Human-readable message from the Blessing Skin JSON envelope.
        message: String,
    },
}

impl Error {
    #[cfg(feature = "http")]
    pub(crate) fn api_status(
        status: u16,
        url: impl Into<String>,
        message: impl Into<String>,
        body: impl Into<String>,
    ) -> Self {
        Self::ApiStatus(Box::new(ApiStatusError::new(status, url, message, body)))
    }

    #[cfg(feature = "profile")]
    pub(crate) fn base64(err: impl std::error::Error + Send + Sync + 'static) -> Self {
        Self::Base64(Box::new(err))
    }

    #[cfg(feature = "loaders")]
    pub(crate) fn xml(err: impl std::error::Error + Send + Sync + 'static) -> Self {
        Self::Xml(Box::new(err))
    }

    #[cfg(feature = "yggdrasil")]
    pub(crate) fn yggdrasil(
        error: impl Into<String>,
        error_message: impl Into<String>,
        cause: Option<String>,
    ) -> Self {
        Self::Yggdrasil(Box::new(YggdrasilError::new(error, error_message, cause)))
    }

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

    /// Returns the structured [`ApiStatusError`] payload if this is [`Error::ApiStatus`].
    #[cfg(feature = "http")]
    #[cfg_attr(docsrs, doc(cfg(feature = "http")))]
    #[must_use]
    pub fn api_status_error(&self) -> Option<&ApiStatusError> {
        match self {
            Error::ApiStatus(err) => Some(err),
            _ => None,
        }
    }

    /// Returns the structured [`YggdrasilError`] payload if this is [`Error::Yggdrasil`].
    #[cfg(feature = "yggdrasil")]
    #[cfg_attr(docsrs, doc(cfg(feature = "yggdrasil")))]
    #[must_use]
    pub fn yggdrasil_error(&self) -> Option<&YggdrasilError> {
        match self {
            Error::Yggdrasil(err) => Some(err),
            _ => None,
        }
    }

    /// Returns the structured [`XstsError`](crate::mojang::XstsError) payload if this is [`Error::XstsRejected`].
    #[cfg(feature = "mojang")]
    #[cfg_attr(docsrs, doc(cfg(feature = "mojang")))]
    #[must_use]
    pub fn xsts_error(&self) -> Option<&crate::mojang::XstsError> {
        match self {
            Error::XstsRejected(err) => Some(err),
            _ => None,
        }
    }

    /// Returns `true` if this error represents an HTTP `404 Not Found` response.
    #[must_use]
    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.
    #[must_use]
    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>;

#[cfg(feature = "http")]
fn format_rate_limit(retry_after_secs: Option<u64>) -> String {
    match retry_after_secs {
        Some(secs) => format!("rate limit exceeded, retry after {secs}s"),
        None => "rate limit exceeded".to_string(),
    }
}