footing 0.5.3

Feature-gated foundations for Rust backend services
Documentation
use std::fmt;

use crate::result::{ClassifyError, ErrorCode, ErrorKind};

/// Invalid presence inputs or a failed database operation.
///
/// Display and Debug omit identities and database error details. The original
/// database error remains available through [`std::error::Error::source`].
#[derive(thiserror::Error)]
#[non_exhaustive]
pub enum PresenceError {
    /// The scope is empty, too long, or contains control characters.
    #[error("presence scope must contain 1 to 256 UTF-8 bytes without control characters")]
    InvalidScope,
    /// A user ID or pagination boundary is invalid.
    #[error("presence user ID must contain 1 to 256 UTF-8 bytes without control characters")]
    InvalidUserId,
    /// The timeout is zero, exceeds the supported range, or loses precision.
    #[error(
        "presence timeout must be a whole number of milliseconds between 1 millisecond and 2147483647 seconds"
    )]
    InvalidTimeout,
    /// A query or cleanup batch size is outside the supported range.
    #[error("presence limit must be between 1 and 1000")]
    InvalidLimit,
    /// The database failed; an interrupted write can have an unknown commit outcome.
    #[error("presence database operation failed")]
    Database(#[from] sqlx::Error),
}

impl fmt::Debug for PresenceError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("PresenceError")
            .field("code", &self.error_code())
            .finish_non_exhaustive()
    }
}

impl ClassifyError for PresenceError {
    fn error_kind(&self) -> ErrorKind {
        match self {
            Self::Database(_) => ErrorKind::Dependency,
            Self::InvalidScope
            | Self::InvalidUserId
            | Self::InvalidTimeout
            | Self::InvalidLimit => ErrorKind::Validation,
        }
    }

    fn error_code(&self) -> ErrorCode {
        ErrorCode::internal(match self {
            Self::InvalidScope => "presence_invalid_scope",
            Self::InvalidUserId => "presence_invalid_user_id",
            Self::InvalidTimeout => "presence_invalid_timeout",
            Self::InvalidLimit => "presence_invalid_limit",
            Self::Database(_) => "presence_database_failed",
        })
    }
}