footing 0.5.1

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

use serde::{Deserialize, Deserializer, Serialize};
use thiserror::Error;

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

/// Default problem code.
pub const DEFAULT_PROBLEM_CODE: &str = "unknown_error";
/// Maximum supported problem code length.
pub const MAX_PROBLEM_CODE_LENGTH: usize = 128;
/// Maximum supported problem type length.
pub const MAX_PROBLEM_TYPE_LENGTH: usize = 2048;
const DEFAULT_PROBLEM_TYPE: &str = "about:blank";

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[non_exhaustive]
/// Validated machine-readable problem identifier.
pub struct ProblemCode(Cow<'static, str>);

impl ProblemCode {
    /// Attempts to create and validate a problem code.
    pub fn try_new(value: impl Into<String>) -> Result<Self, ProblemIdentifierError> {
        let value = value.into().trim().to_owned();
        validate_problem_code(&value)?;
        Ok(Self(Cow::Owned(value)))
    }

    pub(crate) const UNAUTHENTICATED: Self = Self::known("unauthenticated");
    pub(crate) const FORBIDDEN: Self = Self::known("forbidden");
    pub(crate) const PERMISSION_UNAVAILABLE: Self = Self::known("permission_unavailable");
    pub(crate) const INVALID_PRINCIPAL: Self = Self::known("invalid_principal");
    pub(crate) const INVALID_QUERY: Self = Self::known("invalid_query");
    pub(crate) const INVALID_PAGINATION: Self = Self::known("invalid_pagination");
    pub(crate) const RATE_LIMITED: Self = Self::known("rate_limited");
    pub(crate) const RATE_LIMIT_KEY_UNAVAILABLE: Self = Self::known("rate_limit_key_unavailable");
    pub(crate) const RATE_LIMIT_UNAVAILABLE: Self = Self::known("rate_limit_unavailable");
    pub(crate) const INVALID_IDEMPOTENCY_KEY: Self = Self::known("invalid_idempotency_key");
    pub(crate) const IDEMPOTENCY_REQUEST_PROCESSING: Self =
        Self::known("idempotency_request_processing");
    pub(crate) const IDEMPOTENCY_KEY_CONFLICT: Self = Self::known("idempotency_key_conflict");
    pub(crate) const IDEMPOTENCY_REQUEST_BODY_TOO_LARGE: Self =
        Self::known("idempotency_request_body_too_large");
    pub(crate) const IDEMPOTENCY_AUTHENTICATION_SCOPE_REQUIRED: Self =
        Self::known("idempotency_authentication_scope_required");
    pub(crate) const IDEMPOTENCY_STORE_UNAVAILABLE: Self =
        Self::known("idempotency_store_unavailable");
    pub(crate) const IDEMPOTENCY_KEY_REQUIRED: Self = Self::known("idempotency_key_required");
    pub(crate) const REQUEST_BODY_TOO_LARGE: Self = Self::known("request_body_too_large");
    pub(crate) const IDEMPOTENCY_REQUEST_BODY_READ_FAILED: Self =
        Self::known("idempotency_request_body_read_failed");
    pub(crate) const INTERNAL_ERROR: Self = Self::known("internal_error");
    pub(crate) const UNSUPPORTED_MEDIA_TYPE: Self = Self::known("unsupported_media_type");
    pub(crate) const PAYLOAD_TOO_LARGE: Self = Self::known("payload_too_large");
    pub(crate) const INVALID_JSON: Self = Self::known("invalid_json");

    const fn known(value: &'static str) -> Self {
        Self(Cow::Borrowed(value))
    }

    pub(crate) fn from_error_code(value: crate::result::ErrorCode) -> Self {
        Self(Cow::Owned(value.into_string()))
    }

    #[must_use]
    /// Creates unknown.
    pub const fn unknown() -> Self {
        Self(Cow::Borrowed(DEFAULT_PROBLEM_CODE))
    }

    #[must_use]
    /// Returns this value as str.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    #[must_use]
    /// Consumes this value and returns string.
    pub fn into_string(self) -> String {
        self.0.into_owned()
    }
}

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

impl<'de> Deserialize<'de> for ProblemCode {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Self::try_new(value).map_err(serde::de::Error::custom)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[non_exhaustive]
/// Validated URI reference identifying a problem type.
pub struct ProblemType(Cow<'static, str>);

impl ProblemType {
    /// Validates the identifier's length and RFC 3986 URI-reference syntax.
    ///
    /// Trims surrounding whitespace without otherwise normalizing the identifier.
    pub fn try_new(value: impl Into<String>) -> Result<Self, ProblemIdentifierError> {
        let value = value.into().trim().to_owned();
        validate_problem_type(&value)?;
        Ok(Self(Cow::Owned(value)))
    }

    #[must_use]
    /// Creates about blank.
    pub const fn about_blank() -> Self {
        Self(Cow::Borrowed(DEFAULT_PROBLEM_TYPE))
    }

    #[must_use]
    /// Returns this value as str.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    #[must_use]
    /// Consumes this value and returns string.
    pub fn into_string(self) -> String {
        self.0.into_owned()
    }
}

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

impl<'de> Deserialize<'de> for ProblemType {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Self::try_new(value).map_err(serde::de::Error::custom)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
/// Errors that can occur while handling problem identifier.
pub enum ProblemIdentifierError {
    #[error("problem identifier must not be empty")]
    /// Indicates empty.
    Empty,
    #[error("problem identifier must be less than or equal to {max} bytes")]
    /// The value exceeds the supported length.
    TooLong {
        #[doc = "The configured upper bound."]
        max: usize,
    },
    #[error("problem identifier contains unsupported characters")]
    /// The characters is invalid.
    InvalidCharacters,
}

impl ClassifyError for ProblemIdentifierError {
    fn error_kind(&self) -> ErrorKind {
        ErrorKind::Validation
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal(match self {
            Self::Empty => "problem_identifier_empty",
            Self::TooLong { .. } => "problem_identifier_too_long",
            Self::InvalidCharacters => "problem_identifier_invalid_characters",
        })
    }
}

fn validate_problem_code(value: &str) -> Result<(), ProblemIdentifierError> {
    if value.is_empty() {
        return Err(ProblemIdentifierError::Empty);
    }

    if value.len() > MAX_PROBLEM_CODE_LENGTH {
        return Err(ProblemIdentifierError::TooLong {
            max: MAX_PROBLEM_CODE_LENGTH,
        });
    }

    if !value
        .bytes()
        .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':'))
    {
        return Err(ProblemIdentifierError::InvalidCharacters);
    }

    Ok(())
}

fn validate_problem_type(value: &str) -> Result<(), ProblemIdentifierError> {
    if value.is_empty() {
        return Err(ProblemIdentifierError::Empty);
    }

    if value.len() > MAX_PROBLEM_TYPE_LENGTH {
        return Err(ProblemIdentifierError::TooLong {
            max: MAX_PROBLEM_TYPE_LENGTH,
        });
    }

    fluent_uri::UriRef::parse(value)
        .map(|_| ())
        .map_err(|_| ProblemIdentifierError::InvalidCharacters)
}