use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Category {
NotFound,
LeaseHeld,
LeaseFenced,
EngineIncompatible,
ProtocolUnsupported,
Corrupt,
ClassificationRefused,
SecretRefused,
Engine,
Backend,
Timeout,
CommitAmbiguous,
LimitExceeded,
Closed,
}
impl Category {
pub fn as_str(self) -> &'static str {
match self {
Self::NotFound => "not_found",
Self::LeaseHeld => "lease_held",
Self::LeaseFenced => "lease_fenced",
Self::EngineIncompatible => "engine_incompatible",
Self::ProtocolUnsupported => "protocol_unsupported",
Self::Corrupt => "corrupt",
Self::ClassificationRefused => "classification_refused",
Self::SecretRefused => "secret_refused",
Self::Engine => "engine",
Self::Backend => "backend",
Self::Timeout => "timeout",
Self::CommitAmbiguous => "commit_ambiguous",
Self::LimitExceeded => "limit_exceeded",
Self::Closed => "closed",
}
}
}
impl fmt::Display for Category {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug)]
pub struct Error {
category: Category,
message: String,
source: Option<Box<dyn std::error::Error + Send + Sync>>,
details: Option<Box<Details>>,
}
#[derive(Debug, Default)]
struct Details {
owner: Option<String>,
key: Option<String>,
features: Vec<String>,
expected: Option<String>,
actual: Option<String>,
limit: Option<u64>,
observed: Option<u64>,
}
impl Error {
pub fn new(category: Category, message: impl Into<String>) -> Self {
Self {
category,
message: message.into(),
source: None,
details: None,
}
}
fn details(&mut self) -> &mut Details {
self.details.get_or_insert_with(Box::default)
}
pub fn wrap(
category: Category,
cause: impl std::error::Error + Send + Sync + 'static,
message: impl Into<String>,
) -> Self {
Self::new(category, message).with_source(cause)
}
pub fn with_source(mut self, cause: impl std::error::Error + Send + Sync + 'static) -> Self {
self.source = Some(Box::new(cause));
self
}
pub(crate) fn with_owner(mut self, owner: impl Into<String>) -> Self {
self.details().owner = Some(owner.into());
self
}
pub(crate) fn with_key(mut self, key: impl Into<String>) -> Self {
self.details().key = Some(key.into());
self
}
pub(crate) fn with_features(mut self, features: Vec<String>) -> Self {
self.details().features = features;
self
}
pub(crate) fn with_bounds(
mut self,
expected: impl Into<String>,
actual: impl Into<String>,
) -> Self {
let details = self.details();
details.expected = Some(expected.into());
details.actual = Some(actual.into());
self
}
pub(crate) fn with_limit(mut self, limit: u64, observed: u64) -> Self {
let details = self.details();
details.limit = Some(limit);
details.observed = Some(observed);
self
}
pub fn category(&self) -> Category {
self.category
}
pub fn owner(&self) -> Option<&str> {
self.details.as_ref()?.owner.as_deref()
}
pub fn key(&self) -> Option<&str> {
self.details.as_ref()?.key.as_deref()
}
pub fn features(&self) -> &[String] {
self.details.as_ref().map_or(&[], |d| &d.features)
}
pub fn expected(&self) -> Option<&str> {
self.details.as_ref()?.expected.as_deref()
}
pub fn actual(&self) -> Option<&str> {
self.details.as_ref()?.actual.as_deref()
}
pub fn limit(&self) -> Option<(u64, u64)> {
let details = self.details.as_ref()?;
details.limit.zip(details.observed)
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.source {
Some(cause) => write!(f, "{}: {cause}", self.message),
None => f.write_str(&self.message),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.source.as_ref().map(|e| e.as_ref() as _)
}
}
pub type Result<T> = std::result::Result<T, Error>;
pub(crate) fn err(category: Category, message: impl Into<String>) -> Error {
Error::new(category, message)
}
pub(crate) fn engine_err(cause: crate::error::Error, message: impl Into<String>) -> Error {
Error::wrap(Category::Engine, cause, message)
}
pub(crate) fn backend_err(cause: std::io::Error, message: impl Into<String>) -> Error {
Error::wrap(Category::Backend, cause, message)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn a_durable_error_crosses_into_the_crate_result_with_question_mark() {
fn durable_call() -> Result<()> {
Err(Error::new(Category::NotFound, "no such object"))
}
fn crate_level() -> crate::error::Result<()> {
durable_call()?;
Ok(())
}
let err = crate_level().expect_err("the durable failure must propagate");
match err {
crate::error::Error::Durable(inner) => {
assert_eq!(inner.category(), Category::NotFound);
assert!(inner.to_string().contains("no such object"));
}
other => panic!("expected Error::Durable, got {other:?}"),
}
}
#[test]
fn every_frozen_category_keeps_its_wire_name() {
let names: Vec<&str> = [
Category::NotFound,
Category::LeaseHeld,
Category::LeaseFenced,
Category::EngineIncompatible,
Category::ProtocolUnsupported,
Category::Corrupt,
Category::ClassificationRefused,
Category::SecretRefused,
Category::Engine,
Category::Backend,
Category::Timeout,
Category::CommitAmbiguous,
Category::LimitExceeded,
Category::Closed,
]
.iter()
.map(|c| c.as_str())
.collect();
assert_eq!(
names,
vec![
"not_found",
"lease_held",
"lease_fenced",
"engine_incompatible",
"protocol_unsupported",
"corrupt",
"classification_refused",
"secret_refused",
"engine",
"backend",
"timeout",
"commit_ambiguous",
"limit_exceeded",
"closed",
]
);
}
#[test]
fn a_wrapped_cause_shows_in_the_message_and_the_source_chain() {
let cause = std::io::Error::other("disk on fire");
let error = Error::wrap(Category::Backend, cause, "durable: cannot read head.json");
assert_eq!(error.category(), Category::Backend);
assert_eq!(
error.to_string(),
"durable: cannot read head.json: disk on fire"
);
assert!(std::error::Error::source(&error).is_some());
}
}