use std::borrow::Cow;
use serde::{Deserialize, Deserializer, Serialize};
use thiserror::Error;
use crate::result::{ClassifyError, ErrorKind};
pub const DEFAULT_PROBLEM_CODE: &str = "unknown_error";
pub const MAX_PROBLEM_CODE_LENGTH: usize = 128;
pub const MAX_PROBLEM_URI_LENGTH: usize = 2048;
const DEFAULT_PROBLEM_TYPE: &str = "about:blank";
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[non_exhaustive]
pub struct ProblemCode(Cow<'static, str>);
impl ProblemCode {
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)))
}
#[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]
pub const fn unknown() -> Self {
Self::from_static(DEFAULT_PROBLEM_CODE)
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
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]
pub struct ProblemUri(Cow<'static, str>);
impl ProblemUri {
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]
pub const fn about_blank() -> Self {
Self(Cow::Borrowed(DEFAULT_PROBLEM_TYPE))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
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]
pub enum ProblemIdentifierError {
#[error("problem identifier must not be empty")]
Empty,
#[error("problem identifier must be less than or equal to {max} bytes")]
TooLong {
#[doc = "The configured upper bound."]
max: usize,
},
#[error("problem identifier contains unsupported characters")]
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)
}