use std::fmt;
use crate::EventType;
use thiserror::Error;
pub type Result<T, E = Error> = core::result::Result<T, E>;
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum Error {
#[error(transparent)]
Protocol(#[from] crate::Error),
#[error("JSON conversion failed: {0}")]
Json(#[from] serde_json::Error),
#[error(transparent)]
Verification(#[from] VerificationError),
#[error("the run was cancelled")]
Cancelled,
#[error("the event stream was dropped by the consumer")]
Disconnected,
#[error("agent error: {0}")]
Agent(Box<dyn std::error::Error + Send + Sync>),
}
impl Error {
pub fn agent<E>(error: E) -> Self
where
E: Into<Box<dyn std::error::Error + Send + Sync>>,
{
Self::Agent(error.into())
}
pub const fn code(&self) -> &'static str {
match self {
Self::Protocol(_) => "PROTOCOL",
Self::Json(_) => "SERIALIZATION",
Self::Verification(_) => "PROTOCOL_VIOLATION",
Self::Cancelled => "CANCELLED",
Self::Disconnected => "DISCONNECTED",
Self::Agent(_) => "AGENT_ERROR",
}
}
pub const fn is_cancelled(&self) -> bool {
matches!(self, Self::Cancelled)
}
pub const fn is_disconnected(&self) -> bool {
matches!(self, Self::Disconnected)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Rule {
RunEnded,
DuplicateRunStarted,
DuplicateStart,
NotOpen,
UnknownId,
OpenAtFinish,
OutOfOrder,
OwnerMismatch,
}
impl Rule {
pub const fn as_str(&self) -> &'static str {
match self {
Self::RunEnded => "run-ended",
Self::DuplicateRunStarted => "duplicate-run-started",
Self::DuplicateStart => "duplicate-start",
Self::NotOpen => "not-open",
Self::UnknownId => "unknown-id",
Self::OpenAtFinish => "open-at-finish",
Self::OutOfOrder => "out-of-order",
Self::OwnerMismatch => "owner-mismatch",
}
}
pub const fn describe(&self) -> &'static str {
match self {
Self::RunEnded => "a run emits nothing after RUN_FINISHED or RUN_ERROR",
Self::DuplicateRunStarted => "a run emits RUN_STARTED exactly once",
Self::DuplicateStart => "an id may only be opened once",
Self::NotOpen => "content and terminators require a matching start",
Self::UnknownId => "an event may only reference an id it has seen",
Self::OpenAtFinish => "everything opened must be closed before RUN_FINISHED",
Self::OutOfOrder => "the event arrived before the event it depends on",
Self::OwnerMismatch => "an event names the subagent that opened its entity",
}
}
}
impl fmt::Display for Rule {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Error)]
#[error("{event} breaks rule `{rule}` ({}): {detail}", rule.describe())]
pub struct VerificationError {
pub event: EventType,
pub rule: Rule,
pub detail: String,
}
impl VerificationError {
pub fn new(event: EventType, rule: Rule, detail: impl Into<String>) -> Self {
Self {
event,
rule,
detail: detail.into(),
}
}
}