#![forbid(unsafe_code)]
pub trait Validate {
fn validate(&self) -> Result<(), ValidationError>;
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ValidationError {
pub message: String,
}
impl ValidationError {
pub fn new(message: impl Into<String>) -> Self {
Self {
message: message.into(),
}
}
}
impl std::fmt::Display for ValidationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for ValidationError {}
use std::sync::atomic::{AtomicBool, Ordering};
use http::StatusCode;
use seiva_ports::BoxError;
static EXPOSE_ERROR_DETAILS: AtomicBool = AtomicBool::new(false);
pub fn set_expose_error_details(expose: bool) {
EXPOSE_ERROR_DETAILS.store(expose, Ordering::Relaxed);
}
#[must_use]
pub fn expose_error_details() -> bool {
EXPOSE_ERROR_DETAILS.load(Ordering::Relaxed)
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Problem {
pub type_uri: Box<str>,
pub title: Box<str>,
pub status: StatusCode,
pub detail: Option<Box<str>>,
pub instance: Option<Box<str>>,
pub request_id: Option<Box<str>>,
}
impl Problem {
pub fn new(status: StatusCode, title: impl Into<String>) -> Self {
Self {
type_uri: "about:blank".into(),
title: title.into().into_boxed_str(),
status,
detail: None,
instance: None,
request_id: None,
}
}
pub fn unauthorized(detail: impl Into<String>) -> Self {
Self::new(StatusCode::UNAUTHORIZED, "Unauthorized").with_detail(detail)
}
pub fn forbidden(detail: impl Into<String>) -> Self {
Self::new(StatusCode::FORBIDDEN, "Forbidden").with_detail(detail)
}
pub fn not_found(detail: impl Into<String>) -> Self {
Self::new(StatusCode::NOT_FOUND, "Not Found").with_detail(detail)
}
pub fn unprocessable_entity(detail: impl Into<String>) -> Self {
Self::new(StatusCode::UNPROCESSABLE_ENTITY, "Unprocessable Entity").with_detail(detail)
}
pub fn too_many_requests(detail: impl Into<String>) -> Self {
Self::new(StatusCode::TOO_MANY_REQUESTS, "Too Many Requests").with_detail(detail)
}
pub fn internal(detail: impl Into<String>) -> Self {
Self::new(StatusCode::INTERNAL_SERVER_ERROR, "Internal Server Error").with_detail(detail)
}
#[must_use]
pub fn with_type(mut self, type_uri: impl Into<String>) -> Self {
self.type_uri = type_uri.into().into_boxed_str();
self
}
#[must_use]
pub fn with_detail(mut self, detail: impl Into<String>) -> Self {
self.detail = Some(detail.into().into_boxed_str());
self
}
#[must_use]
pub fn with_instance(mut self, instance: impl Into<String>) -> Self {
self.instance = Some(instance.into().into_boxed_str());
self
}
#[must_use]
pub fn with_request_id(mut self, request_id: impl Into<String>) -> Self {
self.request_id = Some(request_id.into().into_boxed_str());
self
}
#[must_use]
pub fn with_request_id_opt(mut self, request_id: Option<String>) -> Self {
self.request_id = request_id.map(String::into_boxed_str);
self
}
#[must_use]
pub fn to_json(&self) -> serde_json::Value {
let mut map = serde_json::Map::new();
map.insert("type".to_owned(), self.type_uri.as_ref().into());
map.insert("title".to_owned(), self.title.as_ref().into());
map.insert("status".to_owned(), self.status.as_u16().into());
if let Some(detail) = &self.detail {
map.insert("detail".to_owned(), detail.as_ref().into());
}
if let Some(instance) = &self.instance {
map.insert("instance".to_owned(), instance.as_ref().into());
}
if let Some(request_id) = &self.request_id {
map.insert("request_id".to_owned(), request_id.as_ref().into());
}
serde_json::Value::Object(map)
}
}
impl std::fmt::Display for Problem {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} {}", self.status.as_u16(), self.title)?;
if let Some(detail) = &self.detail {
write!(f, ": {detail}")?;
}
Ok(())
}
}
impl std::error::Error for Problem {}
impl From<BoxError> for Problem {
fn from(error: BoxError) -> Self {
match error.downcast::<Problem>() {
Ok(problem) => *problem,
Err(error) => {
if expose_error_details() {
Problem::internal(error.to_string())
} else {
tracing::error!(error = %error, "internal error mapped to 500");
Problem::internal("an internal error occurred")
}
}
}
}
}
const _: () = assert!(
std::mem::size_of::<Problem>() <= 112,
"Problem must stay small enough that Result<_, Problem> does not trip \
clippy::result_large_err; box or restructure a field before growing it",
);
#[cfg(test)]
mod tests {
use super::*;
struct Name(String);
impl Validate for Name {
fn validate(&self) -> Result<(), ValidationError> {
if self.0.trim().is_empty() {
return Err(ValidationError::new("name must not be empty"));
}
Ok(())
}
}
#[test]
fn validate_rejects_and_accepts() {
assert!(Name(" ".into()).validate().is_err());
assert!(Name("ada".into()).validate().is_ok());
}
#[test]
fn validation_error_carries_the_message_as_display() {
let error = ValidationError::new("bad");
assert_eq!(error.message, "bad");
assert_eq!(error.to_string(), "bad");
}
}