use adk_core::{AdkError, ErrorCategory, ErrorComponent};
use crate::rules::RuleViolation;
pub type Result<T> = std::result::Result<T, SurfaceError>;
#[derive(Debug, thiserror::Error)]
pub enum SurfaceError {
#[error("{what} was not found among your sessions and decisions")]
NotFound {
what: String,
},
#[error(transparent)]
Rule(#[from] RuleViolation),
#[error("{0}")]
NotHere(String),
#[error(
"stopping and resuming every agent needs the `{group}` group: they freeze and unfreeze \
every run this server makes"
)]
OperatorOnly {
group: String,
},
#[error(
"{what} is not available from this source; run the surface on a kernel or harness that provides it"
)]
Unsupported {
what: String,
},
#[error("{0}")]
Invalid(String),
#[error(transparent)]
Source(#[from] AdkError),
}
impl SurfaceError {
pub fn not_found(what: impl Into<String>) -> Self {
Self::NotFound { what: what.into() }
}
pub fn unsupported(what: impl Into<String>) -> Self {
Self::Unsupported { what: what.into() }
}
pub fn code(&self) -> String {
match self {
Self::NotFound { .. } => "surface.not_found".to_string(),
Self::Rule(rule) => rule.code().to_string(),
Self::NotHere(_) => "surface.not_here".to_string(),
Self::OperatorOnly { .. } => "surface.operator_only".to_string(),
Self::Unsupported { .. } => "surface.unsupported".to_string(),
Self::Invalid(_) => "surface.invalid".to_string(),
Self::Source(error) => error.code.to_string(),
}
}
}
impl From<adk_kernel::KernelError> for SurfaceError {
fn from(error: adk_kernel::KernelError) -> Self {
Self::Source(AdkError::from(error))
}
}
impl From<SurfaceError> for AdkError {
fn from(error: SurfaceError) -> Self {
let error = match error {
SurfaceError::Source(inner) => return inner,
other => other,
};
let (category, code) = match &error {
SurfaceError::NotFound { .. } => (ErrorCategory::NotFound, "surface.not_found"),
SurfaceError::Rule(rule) => (ErrorCategory::Forbidden, rule.code()),
SurfaceError::NotHere(_) => (ErrorCategory::Forbidden, "surface.not_here"),
SurfaceError::OperatorOnly { .. } => {
(ErrorCategory::Forbidden, "surface.operator_only")
}
SurfaceError::Unsupported { .. } => (ErrorCategory::Unsupported, "surface.unsupported"),
SurfaceError::Invalid(_) => (ErrorCategory::InvalidInput, "surface.invalid"),
SurfaceError::Source(_) => (ErrorCategory::Internal, "surface.source"),
};
AdkError::new(ErrorComponent::Server, category, code, error.to_string())
}
}