soaprs-http 0.3.0

Transport-neutral HTTP contracts and policies for soaprs
Documentation
//! Validated identifiers shared by HTTP declarations and extension packages.

use std::fmt;

use soaprs_core::{SoapError, SoapResult};

macro_rules! identifier {
    ($name:ident, $description:literal) => {
        #[doc = $description]
        #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
        pub struct $name(String);

        impl $name {
            /// Validates and wraps a stable logical identifier.
            pub fn new(value: impl Into<String>) -> SoapResult<Self> {
                let value = value.into();
                validate_identifier(stringify!($name), &value)?;
                Ok(Self(value))
            }

            /// Returns the identifier as text.
            pub fn as_str(&self) -> &str {
                &self.0
            }
        }

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

        impl TryFrom<String> for $name {
            type Error = SoapError;

            fn try_from(value: String) -> Result<Self, Self::Error> {
                Self::new(value)
            }
        }

        impl TryFrom<&str> for $name {
            type Error = SoapError;

            fn try_from(value: &str) -> Result<Self, Self::Error> {
                Self::new(value)
            }
        }
    };
}

identifier!(
    EndpointId,
    "Stable endpoint identity used by adapters, documentation, and telemetry."
);
identifier!(
    ContractId,
    "Logical request or response contract identity resolved by validation and schema adapters."
);
fn validate_identifier(kind: &str, value: &str) -> SoapResult<()> {
    if value.is_empty()
        || !value.chars().all(|character| {
            character == '.'
                || character == '_'
                || character == '-'
                || character == ':'
                || character.is_ascii_alphanumeric()
        })
    {
        return Err(SoapError::validation(format!("invalid {kind} `{value}`")));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{ContractId, EndpointId};

    #[test]
    fn identifiers_accept_logical_names_and_reject_transport_fragments() {
        assert!(EndpointId::new("users.get-by-id").is_ok());
        assert!(ContractId::new("users:create:request").is_ok());
        assert!(EndpointId::new("GET /users").is_err());
        assert!(ContractId::new("").is_err());
    }
}