rust-umami 0.1.1

An ergonomic Rust client for Umami Analytics event ingestion
Documentation
use reqwest::StatusCode;
use serde_json::Value;
use std::fmt;

/// Result type used throughout the crate.
pub type Result<T> = std::result::Result<T, Error>;

/// An error returned by Umami for a non-successful HTTP response.
#[derive(Clone, Debug)]
pub struct ApiError {
    /// HTTP status returned by Umami.
    pub status: StatusCode,
    /// Stable Umami error code, when provided.
    pub code: Option<String>,
    /// Human-readable error message.
    pub message: String,
    /// Complete JSON response body.
    pub body: Value,
}

impl fmt::Display for ApiError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Umami returned {}: {}", self.status, self.message)
    }
}

impl std::error::Error for ApiError {}

/// Errors produced while configuring the client or sending analytics.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// An endpoint URL could not be parsed.
    #[error("invalid Umami endpoint URL: {0}")]
    InvalidUrl(#[from] url::ParseError),

    /// The endpoint URL is not an HTTP(S) URL or cannot be used as a base URL.
    #[error("invalid Umami endpoint: {0}")]
    InvalidEndpoint(String),

    /// The website ID is not a UUID accepted by Umami.
    #[error("invalid Umami website ID `{value}`")]
    InvalidWebsiteId {
        /// The rejected value.
        value: String,
        /// UUID parsing error.
        #[source]
        source: uuid::Error,
    },

    /// The configured HTTP user-agent is not a valid header value.
    #[error("invalid HTTP user-agent")]
    InvalidUserAgent(#[from] reqwest::header::InvalidHeaderValue),

    /// Umami requires a non-empty HTTP user-agent.
    #[error("HTTP user-agent cannot be empty")]
    EmptyUserAgent,

    /// A cache value returned by Umami could not be represented as a header.
    #[error("invalid Umami cache header")]
    InvalidCacheHeader(reqwest::header::InvalidHeaderValue),

    /// Event properties could not be represented as a JSON object.
    #[error("invalid event properties: {0}")]
    InvalidProperties(String),

    /// A custom event name is invalid.
    #[error("invalid event name: {0}")]
    InvalidEventName(String),

    /// A performance metric is outside Umami's accepted range.
    #[error("invalid performance metric `{name}`: expected {expected}, got {value}")]
    InvalidMetric {
        /// Metric name.
        name: &'static str,
        /// Accepted range.
        expected: &'static str,
        /// Rejected value.
        value: f64,
    },

    /// A track contains fields that do not apply to its kind.
    #[error("{0}")]
    InvalidTrack(String),

    /// Umami accepts at most 500 items in one batch.
    #[error("analytics batch has {len} items; Umami accepts at most {max}")]
    BatchTooLarge {
        /// Submitted item count.
        len: usize,
        /// Umami's maximum item count.
        max: usize,
    },

    /// A batch received an event created by another client or session.
    #[error("an analytics batch can only contain tracks from the same client and session")]
    MismatchedBatch,

    /// The HTTP client failed to build or send a request.
    #[error(transparent)]
    Http(#[from] reqwest::Error),

    /// Umami returned a non-successful HTTP status.
    #[error(transparent)]
    Api(#[from] ApiError),

    /// A successful response was not valid JSON for the expected response type.
    #[error("could not decode Umami response with status {status}: {source}")]
    Decode {
        /// HTTP status returned by Umami.
        status: StatusCode,
        /// JSON decoding error.
        #[source]
        source: serde_json::Error,
        /// A bounded, lossy response-body excerpt useful for diagnostics.
        body: String,
    },
}

impl Error {
    /// Returns the HTTP status when this error came from an Umami response.
    #[must_use]
    pub fn status(&self) -> Option<StatusCode> {
        match self {
            Self::Api(error) => Some(error.status),
            Self::Decode { status, .. } => Some(*status),
            Self::Http(error) => error.status(),
            _ => None,
        }
    }

    /// Returns whether this error is retryable under a conservative policy.
    ///
    /// Timeouts, connection failures, HTTP 429, and server errors are
    /// considered retryable. The crate does not retry automatically because a
    /// retry can duplicate an analytics event.
    #[must_use]
    pub fn is_retryable(&self) -> bool {
        match self {
            Self::Http(error) => error.is_timeout() || error.is_connect(),
            Self::Api(error) => {
                error.status == StatusCode::TOO_MANY_REQUESTS || error.status.is_server_error()
            }
            _ => false,
        }
    }
}