#![forbid(unsafe_code)]
pub mod check;
mod doc;
mod executor;
pub use doc::*;
pub use executor::{BoxFuture, Executor, Swept};
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Error {
Invalid(String),
SpaceNotFound,
SchemaConflict {
current: Option<i64>,
},
RequestIdConflict,
RequestExpired,
Contention,
Unavailable(String),
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::Invalid(m) => write!(f, "invalid: {m}"),
Error::SpaceNotFound => write!(f, "space not found"),
Error::SchemaConflict { current } => {
write!(f, "schema conflict (current version {current:?})")
}
Error::RequestIdConflict => write!(f, "request id reused with a different program"),
Error::RequestExpired => write!(f, "request expired"),
Error::Contention => write!(f, "contention"),
Error::Unavailable(m) => write!(f, "unavailable: {m}"),
}
}
}
impl std::error::Error for Error {}
pub mod unavailable {
pub const SUPERSEDED: &str = "instance superseded";
pub const BUSY: &str = "space busy";
pub const RATE_LIMITED: &str = "rate limited";
}
impl Error {
fn unavailable_with(&self, prefix: &str) -> bool {
matches!(self, Error::Unavailable(m) if m.starts_with(prefix))
}
pub fn is_superseded(&self) -> bool {
self.unavailable_with(unavailable::SUPERSEDED)
}
pub fn is_busy(&self) -> bool {
self.unavailable_with(unavailable::BUSY)
}
pub fn is_rate_limited(&self) -> bool {
self.unavailable_with(unavailable::RATE_LIMITED)
}
pub fn is_retryable(&self) -> bool {
match self {
Error::Contention => true,
Error::Unavailable(_) => !self.is_superseded(),
_ => false,
}
}
}
pub type Result<T> = std::result::Result<T, Error>;
pub(crate) fn invalid<T>(msg: impl Into<String>) -> Result<T> {
Err(Error::Invalid(msg.into()))
}
pub fn from_yaml<T: serde::de::DeserializeOwned>(text: &str) -> Result<T> {
let v: serde_json::Value =
serde_norway::from_str(text).map_err(|e| Error::Invalid(e.to_string()))?;
serde_json::from_value(v).map_err(|e| Error::Invalid(e.to_string()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn errors_classify_the_same_on_every_backend() {
let superseded = Error::Unavailable(format!("{}: x", unavailable::SUPERSEDED));
let limited = Error::Unavailable(format!("{}: x", unavailable::RATE_LIMITED));
let busy = Error::Unavailable(format!("{}: x", unavailable::BUSY));
let db = Error::Unavailable("08006: connection failure".into());
assert!(superseded.is_superseded() && !superseded.is_retryable());
assert!(limited.is_rate_limited() && limited.is_retryable());
assert!(busy.is_busy() && busy.is_retryable());
assert!(db.is_retryable() && !db.is_superseded());
assert!(Error::Contention.is_retryable());
for e in [
Error::Invalid("x".into()),
Error::SpaceNotFound,
Error::SchemaConflict { current: None },
Error::RequestIdConflict,
Error::RequestExpired,
] {
assert!(!e.is_retryable(), "{e}");
}
}
}