use thiserror::Error;
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum ForgeError {
#[error("{source}")]
Context {
operation: String,
backend: Option<String>,
#[source]
source: Box<ForgeError>,
},
#[error("configuration error: {0}")]
Config(String),
#[error("not configured: {0}")]
NotConfigured(String),
#[error("backend unavailable: {0}")]
Unavailable(String),
#[error("not found")]
NotFound,
#[error("precondition failed: {0}")]
Precondition(String),
#[error("limit exceeded: {0}")]
Limit(String),
#[error("invalid input: {0}")]
Invalid(String),
#[error("backend error: {context}")]
Backend {
context: String,
retryable: bool,
#[source]
source: Option<Box<dyn std::error::Error + Send + Sync>>,
},
}
impl ForgeError {
pub fn with_context(self, operation: impl Into<String>, backend: Option<String>) -> Self {
Self::Context {
operation: operation.into(),
backend,
source: Box::new(self),
}
}
pub fn code(&self) -> &'static str {
match self {
Self::Context { source, .. } => source.code(),
Self::Config(_) => "CONFIG",
Self::NotConfigured(_) => "NOT_CONFIGURED",
Self::Unavailable(_) => "UNAVAILABLE",
Self::NotFound => "NOT_FOUND",
Self::Precondition(_) => "PRECONDITION",
Self::Limit(_) => "LIMIT",
Self::Invalid(_) => "INVALID",
Self::Backend { .. } => "BACKEND",
}
}
pub fn operation(&self) -> Option<&str> {
match self {
Self::Context { operation, .. } => Some(operation),
_ => None,
}
}
pub fn backend_id(&self) -> Option<&str> {
match self {
Self::Context {
backend, source, ..
} => backend.as_deref().or_else(|| source.backend_id()),
_ => None,
}
}
pub fn safe_message(&self) -> String {
self.to_string()
}
pub fn config(msg: impl Into<String>) -> Self {
Self::Config(msg.into())
}
pub fn unavailable(msg: impl Into<String>) -> Self {
Self::Unavailable(msg.into())
}
pub fn not_configured(msg: impl Into<String>) -> Self {
Self::NotConfigured(msg.into())
}
pub fn precondition(msg: impl Into<String>) -> Self {
Self::Precondition(msg.into())
}
pub fn limit(msg: impl Into<String>) -> Self {
Self::Limit(msg.into())
}
pub fn invalid(msg: impl Into<String>) -> Self {
Self::Invalid(msg.into())
}
pub fn backend(context: impl Into<String>) -> Self {
Self::Backend {
context: context.into(),
retryable: false,
source: None,
}
}
pub fn backend_with(
context: impl Into<String>,
retryable: bool,
source: impl std::error::Error + Send + Sync + 'static,
) -> Self {
Self::Backend {
context: context.into(),
retryable,
source: Some(Box::new(source)),
}
}
pub fn is_retryable(&self) -> bool {
match self {
Self::Context { source, .. } => source.is_retryable(),
Self::Unavailable(_) => true,
Self::Backend { retryable, .. } => *retryable,
_ => false,
}
}
pub fn from_sqlx(err: sqlx::Error) -> Self {
if is_transient_sqlx_error(&err) {
Self::Unavailable("database temporarily unavailable".to_string())
} else {
Self::Backend {
context: "database error".to_string(),
retryable: false,
source: Some(Box::new(err)),
}
}
}
}
impl From<sqlx::Error> for ForgeError {
fn from(err: sqlx::Error) -> Self {
Self::from_sqlx(err)
}
}
fn is_transient_sqlx_error(err: &sqlx::Error) -> bool {
match err {
sqlx::Error::PoolTimedOut | sqlx::Error::PoolClosed | sqlx::Error::WorkerCrashed => true,
sqlx::Error::Io(_) => true,
sqlx::Error::Database(db_err) => db_err
.code()
.map(|c| c.starts_with("08") || c == "57014" || c == "57P03")
.unwrap_or(false),
_ => false,
}
}
pub type Result<T> = std::result::Result<T, ForgeError>;
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::indexing_slicing, clippy::panic)]
mod tests {
use super::*;
use std::error::Error as _;
#[test]
fn display_is_generic_and_secret_free() {
assert_eq!(
ForgeError::config("bad dsn").to_string(),
"configuration error: bad dsn"
);
assert_eq!(
ForgeError::not_configured("PostgreSQL is unavailable in memory mode").to_string(),
"not configured: PostgreSQL is unavailable in memory mode"
);
assert_eq!(ForgeError::NotFound.to_string(), "not found");
assert_eq!(
ForgeError::precondition("lease lost").to_string(),
"precondition failed: lease lost"
);
assert_eq!(
ForgeError::limit("value > 1 MiB").to_string(),
"limit exceeded: value > 1 MiB"
);
assert_eq!(
ForgeError::invalid("key contains ':'").to_string(),
"invalid input: key contains ':'"
);
}
#[test]
fn backend_display_hides_source() {
let secret = std::io::Error::other("table forge_secret_tokens constraint uq_x");
let err = ForgeError::backend_with("database error", false, secret);
assert_eq!(err.to_string(), "backend error: database error");
assert!(err.source().is_some());
assert!(
err.source()
.expect("source present")
.to_string()
.contains("forge_secret_tokens")
);
}
#[test]
fn retryability_matches_contract() {
assert!(ForgeError::unavailable("x").is_retryable());
assert!(!ForgeError::NotFound.is_retryable());
assert!(!ForgeError::not_configured("x").is_retryable());
assert!(!ForgeError::invalid("x").is_retryable());
assert!(!ForgeError::limit("x").is_retryable());
assert!(!ForgeError::precondition("x").is_retryable());
assert!(ForgeError::backend_with("x", true, std::io::Error::other("e")).is_retryable());
assert!(!ForgeError::backend("x").is_retryable());
}
#[test]
fn error_is_send_and_sync() {
fn assert_send<T: Send>() {}
fn assert_sync<T: Sync>() {}
assert_send::<ForgeError>();
assert_sync::<ForgeError>();
}
#[test]
fn transient_sqlx_classifies_to_unavailable() {
let e = ForgeError::from_sqlx(sqlx::Error::PoolTimedOut);
assert!(matches!(e, ForgeError::Unavailable(_)));
assert!(e.is_retryable());
}
#[test]
fn non_transient_sqlx_classifies_to_backend() {
let e = ForgeError::from_sqlx(sqlx::Error::RowNotFound);
assert!(matches!(
e,
ForgeError::Backend {
retryable: false,
..
}
));
assert!(!e.is_retryable());
}
#[test]
fn transient_sqlx_pool_and_worker_errors_retry() {
assert!(is_transient_sqlx_error(&sqlx::Error::PoolTimedOut));
assert!(is_transient_sqlx_error(&sqlx::Error::PoolClosed));
assert!(is_transient_sqlx_error(&sqlx::Error::WorkerCrashed));
}
#[test]
fn transient_sqlx_io_error_retries() {
let io = std::io::Error::new(std::io::ErrorKind::ConnectionReset, "reset");
assert!(is_transient_sqlx_error(&sqlx::Error::Io(io)));
}
#[test]
fn transient_sqlx_connection_family_and_timeouts_retry() {
assert!(is_transient_sqlx_error(&db(FakeDbError::with_code(
"08006"
))));
assert!(is_transient_sqlx_error(&db(FakeDbError::with_code(
"08003"
))));
assert!(is_transient_sqlx_error(&db(FakeDbError::with_code(
"57014"
))));
assert!(is_transient_sqlx_error(&db(FakeDbError::with_code(
"57P03"
))));
}
#[test]
fn non_transient_sqlx_logical_errors_do_not_retry() {
assert!(!is_transient_sqlx_error(&db(FakeDbError::with_code(
"23505"
)))); assert!(!is_transient_sqlx_error(&db(FakeDbError::with_code(
"23503"
)))); assert!(!is_transient_sqlx_error(&db(FakeDbError::with_code(
"57000"
)))); assert!(!is_transient_sqlx_error(&db(FakeDbError::no_code())));
assert!(!is_transient_sqlx_error(&sqlx::Error::RowNotFound));
}
fn db(err: FakeDbError) -> sqlx::Error {
sqlx::Error::Database(Box::new(err))
}
#[derive(Debug)]
struct FakeDbError {
code: Option<String>,
}
impl FakeDbError {
fn with_code(code: &str) -> Self {
Self {
code: Some(code.to_string()),
}
}
fn no_code() -> Self {
Self { code: None }
}
}
impl std::fmt::Display for FakeDbError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "fake db error ({:?})", self.code)
}
}
impl std::error::Error for FakeDbError {}
impl sqlx::error::DatabaseError for FakeDbError {
fn message(&self) -> &str {
"fake db error"
}
fn code(&self) -> Option<std::borrow::Cow<'_, str>> {
self.code.as_deref().map(std::borrow::Cow::Borrowed)
}
fn as_error(&self) -> &(dyn std::error::Error + Send + Sync + 'static) {
self
}
fn as_error_mut(&mut self) -> &mut (dyn std::error::Error + Send + Sync + 'static) {
self
}
fn into_error(self: Box<Self>) -> Box<dyn std::error::Error + Send + Sync + 'static> {
self
}
fn kind(&self) -> sqlx::error::ErrorKind {
sqlx::error::ErrorKind::Other
}
}
}