footing 0.6.4

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 URI-reference length in bytes.
pub const MAX_PROBLEM_URI_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 {
    /// Validates a dynamic code after trimming surrounding Unicode whitespace.
    ///
    /// Codes contain 1 to [`MAX_PROBLEM_CODE_LENGTH`] bytes and only ASCII
    /// letters, digits, `-`, `_`, `.`, or `:`. Case is preserved.
    /// Use [`Self::from_static`] for codes declared in source code.
    pub fn try_new(value: impl Into<String>) -> Result<Self, ProblemIdentifierError> {
        let value = value.into();
        let trimmed = value.trim();
        validate_problem_code(trimmed)?;
        let value = if trimmed.len() == value.len() {
            value
        } else {
            trimmed.to_owned()
        };
        Ok(Self(Cow::Owned(value)))
    }

    /// Validates and borrows a static code without allocating, including when cloned.
    ///
    /// The code must already be normalized: unlike [`Self::try_new`], this
    /// constructor does not trim whitespace. Using it in a `const` or `static`
    /// declaration validates the code at compile time.
    ///
    /// ```
    /// use footing::http::{ApiProblem, ProblemCode};
    ///
    /// const USER_EXISTS: ProblemCode = ProblemCode::from_static("user_exists");
    /// let problem = ApiProblem::conflict(USER_EXISTS, "User already exists");
    /// assert_eq!(problem.body().code(), "user_exists");
    /// ```
    ///
    /// ```compile_fail
    /// use footing::http::ProblemCode;
    ///
    /// const INVALID: ProblemCode = ProblemCode::from_static("invalid code");
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the code is empty, exceeds [`MAX_PROBLEM_CODE_LENGTH`] bytes,
    /// or contains characters other than ASCII letters, digits, `-`, `_`, `.`,
    /// or `:`. In a constant declaration this is a compilation error. Use
    /// [`Self::try_new`] for input that may be invalid.
    #[must_use]
    pub const fn from_static(value: &'static str) -> Self {
        assert!(
            validate_problem_code(value).is_ok(),
            "invalid static problem code"
        );
        Self(Cow::Borrowed(value))
    }

    pub(crate) const UNAUTHENTICATED: Self = Self::from_static("unauthenticated");
    pub(crate) const FORBIDDEN: Self = Self::from_static("forbidden");
    pub(crate) const PERMISSION_UNAVAILABLE: Self = Self::from_static("permission_unavailable");
    pub(crate) const INVALID_PRINCIPAL: Self = Self::from_static("invalid_principal");
    pub(crate) const INVALID_QUERY: Self = Self::from_static("invalid_query");
    pub(crate) const INVALID_PATH: Self = Self::from_static("invalid_path");
    #[cfg(feature = "pagination")]
    pub(crate) const INVALID_PAGINATION: Self = Self::from_static("invalid_pagination");
    pub(crate) const INTERNAL_ERROR: Self = Self::from_static("internal_error");
    pub(crate) const UNSUPPORTED_MEDIA_TYPE: Self = Self::from_static("unsupported_media_type");
    pub(crate) const PAYLOAD_TOO_LARGE: Self = Self::from_static("payload_too_large");
    pub(crate) const INVALID_JSON: Self = Self::from_static("invalid_json");

    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::from_static(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()
    }
}

#[cfg(feature = "http-stack")]
impl ProblemCode {
    pub(crate) const RATE_LIMITED: Self = Self::from_static("rate_limited");
    pub(crate) const RATE_LIMIT_KEY_UNAVAILABLE: Self =
        Self::from_static("rate_limit_key_unavailable");
    pub(crate) const RATE_LIMIT_UNAVAILABLE: Self = Self::from_static("rate_limit_unavailable");
    pub(crate) const INVALID_IDEMPOTENCY_KEY: Self = Self::from_static("invalid_idempotency_key");
    pub(crate) const IDEMPOTENCY_REQUEST_PROCESSING: Self =
        Self::from_static("idempotency_request_processing");
    pub(crate) const IDEMPOTENCY_KEY_CONFLICT: Self = Self::from_static("idempotency_key_conflict");
    pub(crate) const IDEMPOTENCY_REQUEST_BODY_TOO_LARGE: Self =
        Self::from_static("idempotency_request_body_too_large");
    pub(crate) const IDEMPOTENCY_AUTHENTICATION_SCOPE_REQUIRED: Self =
        Self::from_static("idempotency_authentication_scope_required");
    pub(crate) const IDEMPOTENCY_STORE_UNAVAILABLE: Self =
        Self::from_static("idempotency_store_unavailable");
    pub(crate) const IDEMPOTENCY_KEY_REQUIRED: Self = Self::from_static("idempotency_key_required");
    pub(crate) const IDEMPOTENCY_REQUEST_BODY_READ_FAILED: Self =
        Self::from_static("idempotency_request_body_read_failed");
    pub(crate) const REQUEST_BODY_TOO_LARGE: Self = Self::from_static("request_body_too_large");
    pub(crate) const RESPONSE_TIMEOUT: Self = Self::from_static("response_timeout");
    pub(crate) const REQUEST_OVERLOADED: Self = Self::from_static("request_overloaded");
}

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 RFC 3986 URI reference for a problem's `type` or `instance`.
///
/// Absolute URIs, relative references and the empty reference are accepted up to
/// [`MAX_PROBLEM_URI_LENGTH`] bytes. Whitespace and malformed percent escapes are
/// rejected; spelling, case and percent encoding are preserved exactly.
/// Prefer an absolute URI or an absolute path for `instance`, as recommended by
/// [RFC 9457 ยง3.1.5](https://www.rfc-editor.org/rfc/rfc9457.html#section-3.1.5).
pub struct ProblemUri(Cow<'static, str>);

impl ProblemUri {
    /// Validates the identifier's length and RFC 3986 URI-reference syntax.
    ///
    /// Does not trim, encode or normalize the supplied reference.
    pub fn try_new(value: impl Into<String>) -> Result<Self, ProblemIdentifierError> {
        let value = value.into();
        validate_problem_uri(&value)?;
        Ok(Self(Cow::Owned(value)))
    }

    #[must_use]
    /// Uses the HTTP status itself as the problem type (`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 ProblemUri {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for ProblemUri {
    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",
        })
    }
}

const 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,
        });
    }

    let bytes = value.as_bytes();
    let mut index = 0;
    while index < bytes.len() {
        let byte = bytes[index];
        if !byte.is_ascii_alphanumeric() && !matches!(byte, b'-' | b'_' | b'.' | b':') {
            return Err(ProblemIdentifierError::InvalidCharacters);
        }
        index += 1;
    }

    Ok(())
}

fn validate_problem_uri(value: &str) -> Result<(), ProblemIdentifierError> {
    if value.len() > MAX_PROBLEM_URI_LENGTH {
        return Err(ProblemIdentifierError::TooLong {
            max: MAX_PROBLEM_URI_LENGTH,
        });
    }

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