pactum-annotations 0.7.0

Declarative field normalization and validation for pactum contracts
Documentation
use serde::{Deserialize, Serialize};

/// One field (or whole-model) invariant that failed.
///
/// The text field is `reason` so UniFFI Kotlin exceptions never collide with
/// `Throwable.message`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FieldIssue {
    /// JSON / MessagePack key, or `"body"` for a whole-object failure.
    pub field: String,
    /// Stable machine code (`INVALID_EMAIL`, `STRING_TOO_LONG`, …).
    pub code: String,
    /// Human-readable explanation.
    pub reason: String,
}

impl FieldIssue {
    pub fn new(
        field: impl Into<String>,
        code: impl Into<String>,
        reason: impl Into<String>,
    ) -> Self {
        Self {
            field: field.into(),
            code: code.into(),
            reason: reason.into(),
        }
    }
}

impl std::fmt::Display for FieldIssue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: {} ({})", self.field, self.reason, self.code)
    }
}

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

/// Infrastructure / host-resolver failure (distinct from domain [`FieldIssue`] validation errors).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HostError {
    pub code: String,
    pub reason: String,
}

impl HostError {
    pub fn new(code: impl Into<String>, reason: impl Into<String>) -> Self {
        Self {
            code: code.into(),
            reason: reason.into(),
        }
    }
}

impl std::fmt::Display for HostError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: {}", self.code, self.reason)
    }
}

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

/// Failure returned by [`crate::AsyncValidate`]: either domain field issues or a host/IO failure.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum AsyncValidationError {
    Issues(Vec<FieldIssue>),
    Host(HostError),
}

impl From<FieldIssue> for AsyncValidationError {
    fn from(issue: FieldIssue) -> Self {
        Self::Issues(vec![issue])
    }
}

impl From<Vec<FieldIssue>> for AsyncValidationError {
    fn from(issues: Vec<FieldIssue>) -> Self {
        Self::Issues(issues)
    }
}

impl From<HostError> for AsyncValidationError {
    fn from(err: HostError) -> Self {
        Self::Host(err)
    }
}

impl std::fmt::Display for AsyncValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Issues(issues) => match issues.as_slice() {
                [] => write!(f, "validation failed"),
                [only] => write!(f, "{only}"),
                [first, rest @ ..] => {
                    write!(f, "{first}")?;
                    for issue in rest {
                        write!(f, "; {issue}")?;
                    }
                    Ok(())
                }
            },
            Self::Host(err) => write!(f, "{err}"),
        }
    }
}

impl std::error::Error for AsyncValidationError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Issues(issues) => issues
                .first()
                .map(|issue| issue as &(dyn std::error::Error + 'static)),
            Self::Host(err) => Some(err),
        }
    }
}

impl crate::traits::Normalize for HostError {
    fn normalize(&mut self) {}
}

impl crate::traits::Validate for HostError {
    fn validate_with(&self, _ctx: &crate::context::ValidationContext) -> Result<(), Vec<FieldIssue>> {
        Ok(())
    }
}

impl<S> crate::traits::ScopedValidate<S> for HostError {
    fn validate_scoped_with(
        &self,
        _ctx: &crate::context::ValidationContext,
    ) -> Result<(), Vec<FieldIssue>> {
        Ok(())
    }
}

#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
impl<R: ?Sized + Sync, S> crate::traits::AsyncValidate<R, S> for HostError {
    async fn validate_async_with(
        &self,
        _ctx: &crate::context::ValidationContext,
        _resolver: &R,
    ) -> Result<(), AsyncValidationError> {
        Ok(())
    }
}

impl crate::traits::Normalize for FieldIssue {
    fn normalize(&mut self) {}
}

impl crate::traits::Validate for FieldIssue {
    fn validate_with(&self, _ctx: &crate::context::ValidationContext) -> Result<(), Vec<FieldIssue>> {
        Ok(())
    }
}

impl<S> crate::traits::ScopedValidate<S> for FieldIssue {
    fn validate_scoped_with(
        &self,
        _ctx: &crate::context::ValidationContext,
    ) -> Result<(), Vec<FieldIssue>> {
        Ok(())
    }
}

#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
impl<R: ?Sized + Sync, S> crate::traits::AsyncValidate<R, S> for FieldIssue {
    async fn validate_async_with(
        &self,
        _ctx: &crate::context::ValidationContext,
        _resolver: &R,
    ) -> Result<(), AsyncValidationError> {
        Ok(())
    }
}