use crate::encode::supported_media_types;
use axum::Json;
use axum::http::{StatusCode, header};
use axum::response::{IntoResponse, Response};
use serde_json::json;
use thiserror::Error;
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum Error {
#[error("{message}")]
Body {
status: StatusCode,
message: String,
},
#[error("expected a JSON request body, got Content-Type {found:?}")]
ContentType {
found: String,
},
#[error("expected a JSON request body, but the request has no Content-Type")]
MissingContentType,
#[error("the request body is not a valid AG-UI RunAgentInput: {0}")]
Decode(#[from] serde_json::Error),
#[error("the request body is empty; expected an AG-UI RunAgentInput object")]
EmptyBody,
#[error(
"cannot produce any media type this request accepts ({accept:?}); \
this endpoint emits: {}",
supported_media_types().join(", ")
)]
NotAcceptable {
accept: String,
},
}
impl Error {
pub const fn status(&self) -> StatusCode {
match self {
Self::Body { status, .. } => *status,
Self::ContentType { .. } | Self::MissingContentType => {
StatusCode::UNSUPPORTED_MEDIA_TYPE
}
Self::Decode(_) | Self::EmptyBody => StatusCode::BAD_REQUEST,
Self::NotAcceptable { .. } => StatusCode::NOT_ACCEPTABLE,
}
}
pub const fn code(&self) -> &'static str {
match self {
Self::Body { .. } => "INVALID_BODY",
Self::ContentType { .. } | Self::MissingContentType => "UNSUPPORTED_MEDIA_TYPE",
Self::Decode(_) | Self::EmptyBody => "INVALID_INPUT",
Self::NotAcceptable { .. } => "NOT_ACCEPTABLE",
}
}
}
impl IntoResponse for Error {
fn into_response(self) -> Response {
let body = Json(json!({ "code": self.code(), "message": self.to_string() }));
let mut response = (self.status(), body).into_response();
response
.headers_mut()
.insert(header::VARY, header::HeaderValue::from_static("accept"));
response
}
}
pub type Result<T, E = Error> = core::result::Result<T, E>;