use std::fmt;
use crate::StoredEvent;
pub type BoxError = Box<dyn std::error::Error + Send + Sync>;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Rejected {
pub code: String,
pub message: String,
pub key: Option<String>,
pub requirement: Option<Box<crate::Requirement>>,
}
impl Rejected {
pub fn new(message: impl Into<String>) -> Rejected {
Rejected {
code: "rejected".into(),
message: message.into(),
key: None,
requirement: None,
}
}
pub fn code(mut self, code: impl Into<String>) -> Rejected {
self.code = code.into();
self
}
pub(crate) fn from_wire(r: kernable_core::proto::Rejected) -> Rejected {
Rejected {
code: r.code,
message: r.message,
key: Some(r.key).filter(|k| !k.is_empty()),
requirement: r
.requirement
.map(|q| Box::new(crate::Requirement::from_wire(*q))),
}
}
pub(crate) fn to_wire(&self) -> kernable_core::proto::Rejected {
kernable_core::proto::Rejected {
code: self.code.clone(),
message: self.message.clone(),
..Default::default()
}
}
pub(crate) fn of(err: &BoxError, code: &str) -> Rejected {
if let Some(r) = err.downcast_ref::<Rejected>() {
return r.clone();
}
if let Some(Error::Rejected(r)) = err.downcast_ref::<Error>() {
return r.clone();
}
Rejected::new(err.to_string()).code(code)
}
}
impl fmt::Display for Rejected {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for Rejected {}
#[derive(Debug)]
pub enum Error {
Rejected(Rejected),
NotSettled(Vec<StoredEvent>),
NotDue(String),
Status(tonic::Status),
Config(String),
Json(serde_json::Error),
Store(rusqlite::Error),
}
impl Error {
pub fn waits_for_switch(&self) -> bool {
matches!(self, Error::Status(s) if s.code() == tonic::Code::FailedPrecondition
&& ["not_caught_up", "not_serving", "served_before"]
.iter()
.any(|reason| s.message().starts_with(reason)))
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Rejected(r) => write!(f, "{} ({})", r.message, r.code),
Error::NotSettled(_) => f.write_str(
"command committed, but not all listeners have processed its events yet",
),
Error::NotDue(id) => write!(
f,
"command {id} is scheduled and not due yet: ask again after its time"
),
Error::Status(s) => write!(f, "{}: {}", s.code(), s.message()),
Error::Config(m) => f.write_str(m),
Error::Json(e) => write!(f, "JSON: {e}"),
Error::Store(e) => write!(f, "store: {e}"),
}
}
}
impl std::error::Error for Error {}
impl From<tonic::Status> for Error {
fn from(s: tonic::Status) -> Error {
Error::Status(s)
}
}
impl From<serde_json::Error> for Error {
fn from(e: serde_json::Error) -> Error {
Error::Json(e)
}
}
impl From<rusqlite::Error> for Error {
fn from(e: rusqlite::Error) -> Error {
Error::Store(e)
}
}
impl From<Rejected> for Error {
fn from(r: Rejected) -> Error {
Error::Rejected(r)
}
}