ag_ui/axum/error.rs
1//! What can go wrong before the stream starts, and what the client sees.
2//!
3//! Everything here happens *before* `RUN_STARTED`. Once the SSE body is open
4//! the status line is already sent, so execution failures from then on are
5//! `RUN_ERROR` events inside a `200` stream — that is [`crate::server`]'s job, not this
6//! module's. Independent delivery failures end the HTTP body without claiming
7//! that execution failed. What is left is how a request can be refused:
8//! a body that is not AG-UI JSON, and an `Accept` header this build cannot
9//! satisfy.
10//!
11//! A refusal answers with a JSON object rather than a bare status line, because
12//! the caller is a program:
13//!
14//! ```json
15//! {"code": "INVALID_INPUT", "message": "missing field `messages` at line 1 column 34"}
16//! ```
17
18use crate::encode::supported_media_types;
19use axum::Json;
20use axum::http::{StatusCode, header};
21use axum::response::{IntoResponse, Response};
22use serde_json::json;
23use thiserror::Error;
24
25/// A request this endpoint refused, before any events were produced.
26///
27/// Implements [`IntoResponse`], so it doubles as the rejection type of
28/// [`AgUiInput`](crate::axum::AgUiInput) — a handler can take
29/// `Result<AgUiInput, Error>` and inspect the failure, or take `AgUiInput` and
30/// let axum answer with the response below.
31#[derive(Debug, Error)]
32#[non_exhaustive]
33pub enum Error {
34 /// The request body could not be read at all — a connection that died
35 /// mid-body, or a payload over the configured
36 /// [`DefaultBodyLimit`](axum::extract::DefaultBodyLimit).
37 ///
38 /// Carries the status axum's own extractor chose, so a body limit stays a
39 /// `413` rather than being flattened into a `400`.
40 #[error("{message}")]
41 Body {
42 /// The status to answer with.
43 status: StatusCode,
44 /// What axum said about it.
45 message: String,
46 },
47
48 /// The `Content-Type` was set to something that is not JSON.
49 ///
50 /// Refused rather than sniffed. See
51 /// [`AgUiInput`](crate::axum::AgUiInput#the-content-type-is-required) for
52 /// what requiring a JSON media type does and does not protect.
53 #[error("expected a JSON request body, got Content-Type {found:?}")]
54 ContentType {
55 /// The offending header value.
56 found: String,
57 },
58
59 /// The request carried no `Content-Type` at all.
60 ///
61 /// An unlabelled body is not assumed to be JSON.
62 /// [`AgentEndpoint::allow_missing_content_type`](crate::axum::AgentEndpoint::allow_missing_content_type)
63 /// accepts one, for clients that cannot be changed to send the header.
64 #[error("expected a JSON request body, but the request has no Content-Type")]
65 MissingContentType,
66
67 /// The body was JSON, but not a
68 /// [`RunAgentInput`](crate::input::RunAgentInput).
69 ///
70 /// Schema failures name the field path; malformed JSON names the offset.
71 #[error("the request body is not a valid AG-UI RunAgentInput: {0}")]
72 Decode(#[from] serde_json::Error),
73
74 /// The request body was empty.
75 #[error("the request body is empty; expected an AG-UI RunAgentInput object")]
76 EmptyBody,
77
78 /// Content negotiation found nothing this build can emit.
79 ///
80 /// See [`negotiate`](crate::axum::respond::negotiate).
81 #[error(
82 "cannot produce any media type this request accepts ({accept:?}); \
83 this endpoint emits: {}",
84 supported_media_types().join(", ")
85 )]
86 NotAcceptable {
87 /// The `Accept` header that could not be satisfied.
88 accept: String,
89 },
90}
91
92impl Error {
93 /// The status this error answers with.
94 pub const fn status(&self) -> StatusCode {
95 match self {
96 Self::Body { status, .. } => *status,
97 Self::ContentType { .. } | Self::MissingContentType => {
98 StatusCode::UNSUPPORTED_MEDIA_TYPE
99 }
100 Self::Decode(_) | Self::EmptyBody => StatusCode::BAD_REQUEST,
101 Self::NotAcceptable { .. } => StatusCode::NOT_ACCEPTABLE,
102 }
103 }
104
105 /// The machine-readable code placed in the response body.
106 ///
107 /// Deliberately not derived from the status: a client that wants to branch
108 /// should not have to distinguish two `400`s by parsing prose.
109 pub const fn code(&self) -> &'static str {
110 match self {
111 Self::Body { .. } => "INVALID_BODY",
112 Self::ContentType { .. } | Self::MissingContentType => "UNSUPPORTED_MEDIA_TYPE",
113 Self::Decode(_) | Self::EmptyBody => "INVALID_INPUT",
114 Self::NotAcceptable { .. } => "NOT_ACCEPTABLE",
115 }
116 }
117}
118
119impl IntoResponse for Error {
120 fn into_response(self) -> Response {
121 let body = Json(json!({ "code": self.code(), "message": self.to_string() }));
122 let mut response = (self.status(), body).into_response();
123 // The answer depends on `Accept`, including when the answer is a 406.
124 // Without this a shared cache can serve one client's refusal to another
125 // client that would have been served happily.
126 response
127 .headers_mut()
128 .insert(header::VARY, header::HeaderValue::from_static("accept"));
129 response
130 }
131}
132
133/// Result alias for this crate.
134pub type Result<T, E = Error> = core::result::Result<T, E>;