use std::{borrow::Cow, error::Error, fmt};
pub type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
pub type Result<T, E = BoxError> = std::result::Result<T, E>;
pub const DEFAULT_ERROR_CODE: &str = "unknown_error";
pub const MAX_ERROR_CODE_LENGTH: usize = 128;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorKind {
Validation,
Authentication,
Authorization,
NotFound,
Conflict,
RateLimit,
Timeout,
Dependency,
Unavailable,
Internal,
}
impl ErrorKind {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Validation => "validation",
Self::Authentication => "authentication",
Self::Authorization => "authorization",
Self::NotFound => "not_found",
Self::Conflict => "conflict",
Self::RateLimit => "rate_limit",
Self::Timeout => "timeout",
Self::Dependency => "dependency",
Self::Unavailable => "unavailable",
Self::Internal => "internal",
}
}
#[must_use]
pub const fn retryable(self) -> bool {
matches!(
self,
Self::RateLimit | Self::Timeout | Self::Dependency | Self::Unavailable
)
}
#[must_use]
pub const fn client_fault(self) -> bool {
matches!(
self,
Self::Validation
| Self::Authentication
| Self::Authorization
| Self::NotFound
| Self::Conflict
| Self::RateLimit
)
}
}
impl fmt::Display for ErrorKind {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "config", derive(serde::Serialize))]
pub struct ErrorCode(Cow<'static, str>);
impl ErrorCode {
pub fn try_new(value: impl Into<String>) -> std::result::Result<Self, ErrorCodeError> {
let value = value.into().trim().to_owned();
validate_error_code(&value)?;
Ok(Self(Cow::Owned(value)))
}
pub fn from_parts(
parts: impl IntoIterator<Item = impl AsRef<str>>,
) -> std::result::Result<Self, ErrorCodeError> {
let mut code = String::new();
for part in parts {
let part = part.as_ref().trim();
if part.is_empty() {
return Err(ErrorCodeError::Empty);
}
if !code.is_empty() {
code.push('_');
}
code.push_str(part);
}
Self::try_new(code)
}
pub(crate) const fn internal(value: &'static str) -> Self {
Self(Cow::Borrowed(value))
}
#[must_use]
pub const fn unknown() -> Self {
Self(Cow::Borrowed(DEFAULT_ERROR_CODE))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn into_string(self) -> String {
self.0.into_owned()
}
}
impl fmt::Display for ErrorCode {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
impl PartialEq<&str> for ErrorCode {
fn eq(&self, other: &&str) -> bool {
self.as_str() == *other
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ErrorCodeError {
Empty,
TooLong {
#[doc = "The configured upper bound."]
max: usize,
},
InvalidCharacters,
}
impl fmt::Display for ErrorCodeError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Empty => formatter.write_str("error code must not be empty"),
Self::TooLong { max } => {
write!(
formatter,
"error code must be less than or equal to {max} bytes"
)
}
Self::InvalidCharacters => {
formatter.write_str("error code contains unsupported characters")
}
}
}
}
impl Error for ErrorCodeError {}
impl ClassifyError for ErrorCodeError {
fn error_kind(&self) -> ErrorKind {
ErrorKind::Validation
}
fn error_code(&self) -> ErrorCode {
ErrorCode::internal(match self {
Self::Empty => "error_code_empty",
Self::TooLong { .. } => "error_code_too_long",
Self::InvalidCharacters => "error_code_invalid_characters",
})
}
}
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ErrorDescriptor {
kind: ErrorKind,
code: ErrorCode,
message: String,
retryable: bool,
visibility: ErrorVisibility,
}
impl fmt::Debug for ErrorDescriptor {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ErrorDescriptor")
.field("kind", &self.kind)
.field("code", &self.code)
.field("message", &"[REDACTED]")
.field("retryable", &self.retryable)
.field("visibility", &self.visibility)
.finish()
}
}
impl ErrorDescriptor {
#[must_use]
pub fn new(kind: ErrorKind, code: ErrorCode, message: impl Into<String>) -> Self {
Self {
kind,
code,
message: normalize_error_message(kind, message),
retryable: kind.retryable(),
visibility: ErrorVisibility::default_for_kind(kind),
}
}
pub fn try_new(
kind: ErrorKind,
code: impl Into<String>,
message: impl Into<String>,
) -> std::result::Result<Self, ErrorCodeError> {
Ok(Self::new(kind, ErrorCode::try_new(code)?, message))
}
#[must_use]
pub const fn kind(&self) -> ErrorKind {
self.kind
}
#[must_use]
pub fn code(&self) -> &ErrorCode {
&self.code
}
#[must_use]
pub fn message(&self) -> &str {
&self.message
}
#[must_use]
pub const fn retryable(&self) -> bool {
self.retryable
}
#[must_use]
pub const fn visibility(&self) -> ErrorVisibility {
self.visibility
}
#[must_use]
pub fn public_message(&self) -> Cow<'_, str> {
if self.visibility.exposes_message() {
Cow::Borrowed(self.message())
} else {
Cow::Borrowed(generic_error_message(self.kind))
}
}
#[must_use]
pub const fn with_retryable(mut self, retryable: bool) -> Self {
self.retryable = retryable;
self
}
#[must_use]
pub const fn with_visibility(mut self, visibility: ErrorVisibility) -> Self {
self.visibility = visibility;
self
}
#[must_use]
pub const fn with_public_message(self) -> Self {
self.with_visibility(ErrorVisibility::Public)
}
#[must_use]
pub const fn with_private_message(self) -> Self {
self.with_visibility(ErrorVisibility::Private)
}
}
fn normalize_error_message(kind: ErrorKind, message: impl Into<String>) -> String {
let message = message.into().trim().to_owned();
if message.is_empty() {
generic_error_message(kind).to_owned()
} else {
message
}
}
impl fmt::Display for ErrorDescriptor {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.public_message())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorVisibility {
Public,
Private,
}
impl ErrorVisibility {
#[must_use]
pub const fn default_for_kind(kind: ErrorKind) -> Self {
if kind.client_fault() {
Self::Public
} else {
Self::Private
}
}
#[must_use]
pub const fn exposes_message(self) -> bool {
matches!(self, Self::Public)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorLogLevel {
Debug,
Info,
Warn,
Error,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ErrorBoundaryDecision {
descriptor: ErrorDescriptor,
log_level: ErrorLogLevel,
alert: bool,
}
impl ErrorBoundaryDecision {
#[must_use]
pub const fn descriptor(&self) -> &ErrorDescriptor {
&self.descriptor
}
#[must_use]
pub const fn log_level(&self) -> ErrorLogLevel {
self.log_level
}
#[must_use]
pub const fn alert(&self) -> bool {
self.alert
}
#[must_use]
pub fn public_message(&self) -> Cow<'_, str> {
self.descriptor.public_message()
}
#[must_use]
pub fn into_descriptor(self) -> ErrorDescriptor {
self.descriptor
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct ErrorBoundaryPolicy {
expose_server_error_messages: bool,
alert_internal_errors: bool,
}
impl Default for ErrorBoundaryPolicy {
fn default() -> Self {
Self {
expose_server_error_messages: false,
alert_internal_errors: true,
}
}
}
impl ErrorBoundaryPolicy {
#[must_use]
pub const fn new() -> Self {
Self {
expose_server_error_messages: false,
alert_internal_errors: true,
}
}
#[must_use]
pub const fn http_api() -> Self {
Self {
expose_server_error_messages: false,
alert_internal_errors: true,
}
}
#[must_use]
pub const fn worker() -> Self {
Self {
expose_server_error_messages: false,
alert_internal_errors: true,
}
}
#[must_use]
pub const fn cli() -> Self {
Self {
expose_server_error_messages: true,
alert_internal_errors: false,
}
}
#[must_use]
pub const fn trusted_internal() -> Self {
Self {
expose_server_error_messages: true,
alert_internal_errors: true,
}
}
#[must_use]
pub const fn exposes_server_error_messages(self) -> bool {
self.expose_server_error_messages
}
#[must_use]
pub const fn alerts_internal_errors(self) -> bool {
self.alert_internal_errors
}
#[must_use]
pub const fn with_server_error_messages(mut self, expose: bool) -> Self {
self.expose_server_error_messages = expose;
self
}
#[must_use]
pub const fn with_internal_error_alerts(mut self, alert: bool) -> Self {
self.alert_internal_errors = alert;
self
}
#[must_use]
pub fn decide<E>(&self, error: &E) -> ErrorBoundaryDecision
where
E: ClassifyError + ?Sized,
{
self.decide_descriptor(error.error_descriptor())
}
#[must_use]
pub fn decide_descriptor(&self, descriptor: ErrorDescriptor) -> ErrorBoundaryDecision {
let kind = descriptor.kind();
let descriptor = if self.expose_server_error_messages {
descriptor.with_public_message()
} else {
descriptor
};
ErrorBoundaryDecision {
descriptor,
log_level: log_level_for_kind(kind),
alert: self.alert_internal_errors && matches!(kind, ErrorKind::Internal),
}
}
}
#[must_use]
pub const fn generic_error_message(kind: ErrorKind) -> &'static str {
match kind {
ErrorKind::Validation => "request validation failed",
ErrorKind::Authentication => "authentication is required",
ErrorKind::Authorization => "permission is denied",
ErrorKind::NotFound => "resource was not found",
ErrorKind::Conflict => "resource conflict",
ErrorKind::RateLimit => "too many requests",
ErrorKind::Timeout | ErrorKind::Dependency | ErrorKind::Unavailable => {
"service is unavailable"
}
ErrorKind::Internal => "internal server error",
}
}
const fn log_level_for_kind(kind: ErrorKind) -> ErrorLogLevel {
match kind {
ErrorKind::Validation
| ErrorKind::Authentication
| ErrorKind::Authorization
| ErrorKind::NotFound
| ErrorKind::Conflict => ErrorLogLevel::Info,
ErrorKind::RateLimit => ErrorLogLevel::Debug,
ErrorKind::Timeout | ErrorKind::Dependency | ErrorKind::Unavailable => ErrorLogLevel::Warn,
ErrorKind::Internal => ErrorLogLevel::Error,
}
}
pub trait ClassifyError: fmt::Display {
fn error_kind(&self) -> ErrorKind;
fn error_code(&self) -> ErrorCode;
fn error_descriptor(&self) -> ErrorDescriptor {
ErrorDescriptor::new(self.error_kind(), self.error_code(), self.to_string())
}
}
impl ClassifyError for ErrorDescriptor {
fn error_kind(&self) -> ErrorKind {
self.kind
}
fn error_code(&self) -> ErrorCode {
self.code.clone()
}
fn error_descriptor(&self) -> ErrorDescriptor {
self.clone()
}
}
fn validate_error_code(value: &str) -> std::result::Result<(), ErrorCodeError> {
if value.is_empty() {
return Err(ErrorCodeError::Empty);
}
if value.len() > MAX_ERROR_CODE_LENGTH {
return Err(ErrorCodeError::TooLong {
max: MAX_ERROR_CODE_LENGTH,
});
}
if !value
.bytes()
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
{
return Err(ErrorCodeError::InvalidCharacters);
}
Ok(())
}