use serde::Serialize;
pub mod code {
pub const NOT_SET: &str = "not_set";
pub const NOT_FOUND: &str = "not_found";
}
#[derive(Clone, PartialEq, Eq)]
pub struct HostError {
pub code: String,
pub message: String,
}
impl HostError {
pub(crate) fn new(message: impl Into<String>) -> Self {
Self { code: String::new(), message: message.into() }
}
pub fn is_not_found(&self) -> bool {
self.code == code::NOT_FOUND
}
}
impl std::fmt::Display for HostError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.code.is_empty() {
write!(f, "{}", self.message)
} else {
write!(f, "{} ({})", self.message, self.code)
}
}
}
impl std::fmt::Debug for HostError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "HostError({self})")
}
}
impl std::error::Error for HostError {}
pub enum OpError {
NotConfigured,
TicketTypeNotEnabled,
NotFound,
EndOfCollection(String),
RateLimited { retry_after: Option<String> },
Transient(String),
Other(String),
}
impl std::fmt::Display for OpError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
OpError::NotConfigured => write!(f, "not configured"),
OpError::TicketTypeNotEnabled => write!(f, "context is not enabled for this ticket type"),
OpError::NotFound => write!(f, "not found"),
OpError::EndOfCollection(message) => write!(f, "end of collection: {message}"),
OpError::RateLimited { retry_after } => match retry_after {
Some(after) => write!(f, "rate limited (retry after {after})"),
None => write!(f, "rate limited"),
},
OpError::Transient(message) => write!(f, "transient failure: {message}"),
OpError::Other(message) => write!(f, "{message}"),
}
}
}
impl std::fmt::Debug for OpError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "OpError({self})")
}
}
impl std::error::Error for OpError {}
impl From<HostError> for OpError {
fn from(e: HostError) -> Self {
if e.is_not_found() {
return OpError::NotFound;
}
OpError::Other(e.to_string())
}
}
#[derive(Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub(crate) enum Outcome<T> {
Ok { data: T },
NotFound,
EndOfCollection { message: String },
RateLimited { retry_after: Option<String> },
Transient { message: String },
Error { message: String },
}