use std::{
borrow::Cow,
error::Error,
fmt::{self, Display, Formatter},
};
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
use serde::{Deserialize, Deserializer, Serialize, de::Error as _};
use super::{UriReference, UriReferenceError};
pub const MAX_CORRELATION_ID_BYTES: usize = 128;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(transparent)]
pub struct CorrelationId(String);
impl CorrelationId {
pub fn new(value: impl Into<String>) -> Result<Self, CorrelationIdError> {
let value = value.into();
if value.is_empty() {
return Err(CorrelationIdError::Empty);
}
if value.len() > MAX_CORRELATION_ID_BYTES {
return Err(CorrelationIdError::TooLong {
actual_bytes: value.len(),
});
}
if let Some((byte_index, byte)) = value
.bytes()
.enumerate()
.find(|(_, byte)| !(b'!'..=b'~').contains(byte))
{
return Err(CorrelationIdError::InvalidByte { byte_index, byte });
}
Ok(Self(value))
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn to_uri_path_segment(&self) -> String {
const HEX: &[u8; 16] = b"0123456789ABCDEF";
let mut encoded = String::with_capacity(self.0.len());
for byte in self.0.bytes() {
if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'~') {
encoded.push(char::from(byte));
} else {
encoded.push('%');
encoded.push(char::from(HEX[usize::from(byte >> 4)]));
encoded.push(char::from(HEX[usize::from(byte & 0x0f)]));
}
}
encoded
}
}
impl Display for CorrelationId {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0)
}
}
impl<'de> Deserialize<'de> for CorrelationId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
Self::new(value).map_err(D::Error::custom)
}
}
impl JsonSchema for CorrelationId {
fn schema_name() -> Cow<'static, str> {
"CorrelationId".into()
}
fn json_schema(_generator: &mut SchemaGenerator) -> Schema {
json_schema!({
"type": "string",
"minLength": 1,
"maxLength": MAX_CORRELATION_ID_BYTES,
"pattern": "^[!-~]+$"
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum CorrelationIdError {
Empty,
TooLong {
actual_bytes: usize,
},
InvalidByte {
byte_index: usize,
byte: u8,
},
}
impl Display for CorrelationIdError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::Empty => formatter.write_str("correlation ID must not be empty"),
Self::TooLong { actual_bytes } => write!(
formatter,
"correlation ID is {actual_bytes} bytes; maximum is {MAX_CORRELATION_ID_BYTES}"
),
Self::InvalidByte { byte_index, byte } => write!(
formatter,
"correlation ID has invalid byte {byte:#04x} at index {byte_index}"
),
}
}
}
impl Error for CorrelationIdError {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProblemOccurrence {
correlation_id: CorrelationId,
instance: UriReference,
}
impl ProblemOccurrence {
pub fn new(
correlation_id: CorrelationId,
instance: impl AsRef<str>,
) -> Result<Self, ProblemOccurrenceError> {
let instance = UriReference::new(instance.as_ref())
.map_err(ProblemOccurrenceError::InvalidInstance)?;
Ok(Self {
correlation_id,
instance,
})
}
pub const fn correlation_id(&self) -> &CorrelationId {
&self.correlation_id
}
pub const fn instance(&self) -> &UriReference {
&self.instance
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ProblemOccurrenceError {
InvalidInstance(UriReferenceError),
}
impl Display for ProblemOccurrenceError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidInstance(error) => write!(formatter, "invalid Problem instance: {error}"),
}
}
}
impl Error for ProblemOccurrenceError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::InvalidInstance(error) => Some(error),
}
}
}