grow-graylog 0.2.0

Rust SDK for Graylog Open by Grow Codes
Documentation
// Generated by sdk-kit 0.3.0 — do not edit; change sdk-kit and run "sdk-kit sync"
//! Error type shared by every module of the SDK (SPEC §2.1).

use std::fmt;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;

/// Result alias used by every fallible SDK function.
pub type Result<T> = std::result::Result<T, Error>;

/// Canonical error codes. The wire value (`as_str`) is the same in every language.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum ErrorCode {
    /// Invalid or missing configuration.
    Config,
    /// Bad credentials (HTTP 401).
    Authentication,
    /// Credentials lack permission (HTTP 403).
    PermissionDenied,
    /// Missing resource (HTTP 404).
    NotFound,
    /// Conflict or failed precondition (HTTP 409, 412, CAS mismatch).
    Conflict,
    /// Throttled (HTTP 429).
    RateLimited,
    /// Rejected input (HTTP 400, 413, 422, other 4xx, client-side validation).
    Validation,
    /// Network failure or server error (HTTP 500, 502, 503).
    Unavailable,
    /// A deadline was exceeded (HTTP 408, 504).
    Timeout,
    /// The service or deployment does not offer the capability (HTTP 501).
    Unsupported,
    /// The caller cancelled the operation.
    Cancelled,
}

impl ErrorCode {
    /// Every code, in declaration order.
    pub const ALL: [ErrorCode; 11] = [
        ErrorCode::Config,
        ErrorCode::Authentication,
        ErrorCode::PermissionDenied,
        ErrorCode::NotFound,
        ErrorCode::Conflict,
        ErrorCode::RateLimited,
        ErrorCode::Validation,
        ErrorCode::Unavailable,
        ErrorCode::Timeout,
        ErrorCode::Unsupported,
        ErrorCode::Cancelled,
    ];

    /// Wire value, e.g. `"NOT_FOUND"`.
    pub fn as_str(self) -> &'static str {
        match self {
            ErrorCode::Config => "CONFIG",
            ErrorCode::Authentication => "AUTHENTICATION",
            ErrorCode::PermissionDenied => "PERMISSION_DENIED",
            ErrorCode::NotFound => "NOT_FOUND",
            ErrorCode::Conflict => "CONFLICT",
            ErrorCode::RateLimited => "RATE_LIMITED",
            ErrorCode::Validation => "VALIDATION",
            ErrorCode::Unavailable => "UNAVAILABLE",
            ErrorCode::Timeout => "TIMEOUT",
            ErrorCode::Unsupported => "UNSUPPORTED",
            ErrorCode::Cancelled => "CANCELLED",
        }
    }

    /// Whether errors with this code are retryable by default.
    pub fn default_retryable(self) -> bool {
        matches!(
            self,
            ErrorCode::RateLimited | ErrorCode::Unavailable | ErrorCode::Timeout
        )
    }

    /// Short human reason used in error messages, e.g. `"not found"`.
    pub fn reason(self) -> &'static str {
        match self {
            ErrorCode::Config => "invalid configuration",
            ErrorCode::Authentication => "authentication failed",
            ErrorCode::PermissionDenied => "permission denied",
            ErrorCode::NotFound => "not found",
            ErrorCode::Conflict => "conflict",
            ErrorCode::RateLimited => "rate limited",
            ErrorCode::Validation => "invalid request",
            ErrorCode::Unavailable => "service unavailable",
            ErrorCode::Timeout => "timed out",
            ErrorCode::Unsupported => "not supported",
            ErrorCode::Cancelled => "cancelled",
        }
    }

    /// Code for an HTTP status according to SPEC §2.1 (`None` for 1xx–3xx).
    pub fn from_http_status(status: u16) -> Option<ErrorCode> {
        Some(match status {
            401 => ErrorCode::Authentication,
            403 => ErrorCode::PermissionDenied,
            404 => ErrorCode::NotFound,
            409 | 412 => ErrorCode::Conflict,
            429 => ErrorCode::RateLimited,
            408 | 504 => ErrorCode::Timeout,
            501 => ErrorCode::Unsupported,
            400..=499 => ErrorCode::Validation,
            500..=599 => ErrorCode::Unavailable,
            _ => return None,
        })
    }
}

impl fmt::Display for ErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for ErrorCode {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self> {
        ErrorCode::ALL
            .into_iter()
            .find(|c| c.as_str() == s)
            .ok_or_else(|| Error::validation(format!("unknown error code {s:?}")))
    }
}

/// Details carried by every [`Error`] variant.
#[derive(Clone)]
pub struct ErrorContext {
    message: String,
    http_status: Option<u16>,
    request_id: Option<String>,
    retryable: bool,
    retry_after: Option<Duration>,
    source: Option<Arc<dyn std::error::Error + Send + Sync + 'static>>,
}

impl fmt::Debug for ErrorContext {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ErrorContext")
            .field("message", &self.message)
            .field("http_status", &self.http_status)
            .field("request_id", &self.request_id)
            .field("retryable", &self.retryable)
            .field("retry_after", &self.retry_after)
            .field("source", &self.source.as_ref().map(|s| s.to_string()))
            .finish()
    }
}

/// The SDK error. Match on the variant or use [`Error::code`].
///
/// Messages never contain secrets, tokens, request bodies or unfiltered response bodies.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum Error {
    /// `CONFIG`: invalid or missing configuration.
    Config(Box<ErrorContext>),
    /// `AUTHENTICATION`: HTTP 401.
    Authentication(Box<ErrorContext>),
    /// `PERMISSION_DENIED`: HTTP 403.
    PermissionDenied(Box<ErrorContext>),
    /// `NOT_FOUND`: HTTP 404 or a missing record.
    NotFound(Box<ErrorContext>),
    /// `CONFLICT`: HTTP 409, 412 or a CAS mismatch.
    Conflict(Box<ErrorContext>),
    /// `RATE_LIMITED`: HTTP 429 (see [`Error::retry_after`]).
    RateLimited(Box<ErrorContext>),
    /// `VALIDATION`: rejected input.
    Validation(Box<ErrorContext>),
    /// `UNAVAILABLE`: network error or HTTP 500/502/503.
    Unavailable(Box<ErrorContext>),
    /// `TIMEOUT`: a deadline was exceeded.
    Timeout(Box<ErrorContext>),
    /// `UNSUPPORTED`: capability not offered by the service.
    Unsupported(Box<ErrorContext>),
    /// `CANCELLED`: the caller cancelled.
    Cancelled(Box<ErrorContext>),
}

impl Error {
    /// Creates an error with the given code; `retryable` defaults per code.
    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
        let ctx = Box::new(ErrorContext {
            message: message.into(),
            http_status: None,
            request_id: None,
            retryable: code.default_retryable(),
            retry_after: None,
            source: None,
        });
        match code {
            ErrorCode::Config => Error::Config(ctx),
            ErrorCode::Authentication => Error::Authentication(ctx),
            ErrorCode::PermissionDenied => Error::PermissionDenied(ctx),
            ErrorCode::NotFound => Error::NotFound(ctx),
            ErrorCode::Conflict => Error::Conflict(ctx),
            ErrorCode::RateLimited => Error::RateLimited(ctx),
            ErrorCode::Validation => Error::Validation(ctx),
            ErrorCode::Unavailable => Error::Unavailable(ctx),
            ErrorCode::Timeout => Error::Timeout(ctx),
            ErrorCode::Unsupported => Error::Unsupported(ctx),
            ErrorCode::Cancelled => Error::Cancelled(ctx),
        }
    }

    /// Error for an HTTP status (SPEC §2.1 mapping); non-error statuses map to `UNAVAILABLE`.
    pub fn from_status(status: u16, message: impl Into<String>) -> Self {
        let code = ErrorCode::from_http_status(status).unwrap_or(ErrorCode::Unavailable);
        Error::new(code, message).with_status(status)
    }

    /// `CONFIG` error.
    pub fn config(message: impl Into<String>) -> Self {
        Error::new(ErrorCode::Config, message)
    }
    /// `VALIDATION` error.
    pub fn validation(message: impl Into<String>) -> Self {
        Error::new(ErrorCode::Validation, message)
    }
    /// `NOT_FOUND` error.
    pub fn not_found(message: impl Into<String>) -> Self {
        Error::new(ErrorCode::NotFound, message)
    }
    /// `CONFLICT` error.
    pub fn conflict(message: impl Into<String>) -> Self {
        Error::new(ErrorCode::Conflict, message)
    }
    /// `TIMEOUT` error.
    pub fn timeout(message: impl Into<String>) -> Self {
        Error::new(ErrorCode::Timeout, message)
    }
    /// `UNAVAILABLE` error.
    pub fn unavailable(message: impl Into<String>) -> Self {
        Error::new(ErrorCode::Unavailable, message)
    }
    /// `UNSUPPORTED` error.
    pub fn unsupported(message: impl Into<String>) -> Self {
        Error::new(ErrorCode::Unsupported, message)
    }
    /// `CANCELLED` error.
    pub fn cancelled(message: impl Into<String>) -> Self {
        Error::new(ErrorCode::Cancelled, message)
    }

    fn ctx(&self) -> &ErrorContext {
        match self {
            Error::Config(c)
            | Error::Authentication(c)
            | Error::PermissionDenied(c)
            | Error::NotFound(c)
            | Error::Conflict(c)
            | Error::RateLimited(c)
            | Error::Validation(c)
            | Error::Unavailable(c)
            | Error::Timeout(c)
            | Error::Unsupported(c)
            | Error::Cancelled(c) => c,
        }
    }

    fn ctx_mut(&mut self) -> &mut ErrorContext {
        match self {
            Error::Config(c)
            | Error::Authentication(c)
            | Error::PermissionDenied(c)
            | Error::NotFound(c)
            | Error::Conflict(c)
            | Error::RateLimited(c)
            | Error::Validation(c)
            | Error::Unavailable(c)
            | Error::Timeout(c)
            | Error::Unsupported(c)
            | Error::Cancelled(c) => c,
        }
    }

    /// Sets the HTTP status.
    pub fn with_status(mut self, status: u16) -> Self {
        self.ctx_mut().http_status = Some(status);
        self
    }
    /// Sets the vendor request id.
    pub fn with_request_id(mut self, request_id: impl Into<String>) -> Self {
        self.ctx_mut().request_id = Some(request_id.into());
        self
    }
    /// Overrides whether the error is retryable.
    pub fn with_retryable(mut self, retryable: bool) -> Self {
        self.ctx_mut().retryable = retryable;
        self
    }
    /// Sets the server-requested wait before a retry.
    pub fn with_retry_after(mut self, retry_after: Duration) -> Self {
        self.ctx_mut().retry_after = Some(retry_after);
        self
    }
    /// Sets the underlying cause (it must not expose secrets).
    pub fn with_source(mut self, source: impl std::error::Error + Send + Sync + 'static) -> Self {
        self.ctx_mut().source = Some(Arc::new(source));
        self
    }
    /// Replaces the message.
    pub fn with_message(mut self, message: impl Into<String>) -> Self {
        self.ctx_mut().message = message.into();
        self
    }

    /// Canonical code.
    pub fn code(&self) -> ErrorCode {
        match self {
            Error::Config(_) => ErrorCode::Config,
            Error::Authentication(_) => ErrorCode::Authentication,
            Error::PermissionDenied(_) => ErrorCode::PermissionDenied,
            Error::NotFound(_) => ErrorCode::NotFound,
            Error::Conflict(_) => ErrorCode::Conflict,
            Error::RateLimited(_) => ErrorCode::RateLimited,
            Error::Validation(_) => ErrorCode::Validation,
            Error::Unavailable(_) => ErrorCode::Unavailable,
            Error::Timeout(_) => ErrorCode::Timeout,
            Error::Unsupported(_) => ErrorCode::Unsupported,
            Error::Cancelled(_) => ErrorCode::Cancelled,
        }
    }
    /// Human-readable message (redacted).
    pub fn message(&self) -> &str {
        &self.ctx().message
    }
    /// HTTP status when the error came from a response.
    pub fn http_status(&self) -> Option<u16> {
        self.ctx().http_status
    }
    /// Vendor request id when the response carried one.
    pub fn request_id(&self) -> Option<&str> {
        self.ctx().request_id.as_deref()
    }
    /// Whether retrying the same call may succeed.
    pub fn is_retryable(&self) -> bool {
        self.ctx().retryable
    }
    /// Server-requested wait (`Retry-After`) when known.
    pub fn retry_after(&self) -> Option<Duration> {
        self.ctx().retry_after
    }
    /// Whether this error has the given code.
    pub fn is(&self, code: ErrorCode) -> bool {
        self.code() == code
    }
    /// The underlying cause, when any.
    pub fn cause(&self) -> Option<&(dyn std::error::Error + Send + Sync + 'static)> {
        self.ctx().source.as_deref()
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.ctx().message)
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.ctx()
            .source
            .as_deref()
            .map(|s| s as &(dyn std::error::Error + 'static))
    }
}

impl From<serde_json::Error> for Error {
    fn from(err: serde_json::Error) -> Self {
        Error::validation(format!("invalid JSON: {}", err.classify_name())).with_source(err)
    }
}

/// Small helper so `serde_json::Error` can describe itself without echoing input.
trait ClassifyName {
    fn classify_name(&self) -> &'static str;
}

impl ClassifyName for serde_json::Error {
    fn classify_name(&self) -> &'static str {
        match self.classify() {
            serde_json::error::Category::Io => "I/O error",
            serde_json::error::Category::Syntax => "syntax error",
            serde_json::error::Category::Data => "unexpected data",
            serde_json::error::Category::Eof => "unexpected end of input",
        }
    }
}