use crate::RunAgentInput;
use axum::body::Bytes;
use axum::extract::{FromRequest, Request};
use axum::http::{HeaderMap, header};
use crate::axum::error::{Error, Result};
#[derive(Clone, Debug, PartialEq)]
pub struct AgUiInput(pub RunAgentInput);
impl AgUiInput {
pub fn into_inner(self) -> RunAgentInput {
self.0
}
pub(crate) async fn read<S>(
request: Request,
state: &S,
allow_missing_content_type: bool,
) -> Result<(Self, Vec<String>)>
where
S: Send + Sync,
{
check_content_type(request.headers(), allow_missing_content_type)?;
let bytes = Bytes::from_request(request, state)
.await
.map_err(|rejection| Error::Body {
status: rejection.status(),
message: rejection.body_text(),
})?;
let (input, warnings) = decode_with_warnings(&bytes)?;
Ok((Self(input), warnings))
}
}
impl<S> FromRequest<S> for AgUiInput
where
S: Send + Sync,
{
type Rejection = Error;
async fn from_request(request: Request, state: &S) -> Result<Self> {
let (input, _warnings) = Self::read(request, state, false).await?;
Ok(input)
}
}
pub fn decode(body: &[u8]) -> Result<RunAgentInput> {
decode_with_warnings(body).map(|(input, _warnings)| input)
}
pub fn decode_with_warnings(body: &[u8]) -> Result<(RunAgentInput, Vec<String>)> {
if body.iter().all(u8::is_ascii_whitespace) {
return Err(Error::EmptyBody);
}
let value = serde_json::from_slice(body)?;
let mut warnings = Vec::new();
let value = crate::protocol::input(value, &mut warnings)
.map_err(<serde_json::Error as serde::de::Error>::custom)?;
Ok((serde_json::from_value(value)?, warnings))
}
fn check_content_type(headers: &HeaderMap, allow_missing: bool) -> Result<()> {
let Some(value) = headers.get(header::CONTENT_TYPE) else {
return if allow_missing {
Ok(())
} else {
Err(Error::MissingContentType)
};
};
let found = String::from_utf8_lossy(value.as_bytes());
if is_json(&found) {
return Ok(());
}
Err(Error::ContentType {
found: found.into_owned(),
})
}
fn is_json(value: &str) -> bool {
let essence = value.split(';').next().unwrap_or(value).trim();
essence.eq_ignore_ascii_case("application/json")
|| essence.eq_ignore_ascii_case("text/json")
|| essence
.rsplit_once('+')
.is_some_and(|(_, suffix)| suffix.eq_ignore_ascii_case("json"))
}
#[cfg(test)]
mod tests {
use super::*;
use axum::http::StatusCode;
fn headers(content_type: &str) -> HeaderMap {
let mut headers = HeaderMap::new();
headers.insert(
header::CONTENT_TYPE,
content_type.parse().expect("a valid header value"),
);
headers
}
#[test]
fn json_content_types_are_accepted() {
for value in [
"application/json",
"application/json; charset=utf-8",
"APPLICATION/JSON",
"text/json",
"application/vnd.acme.run+json",
] {
for allow_missing in [false, true] {
assert!(
check_content_type(&headers(value), allow_missing).is_ok(),
"should accept {value:?}"
);
}
}
}
#[test]
fn a_missing_content_type_is_refused_with_415() {
let error = check_content_type(&HeaderMap::new(), false)
.expect_err("an unlabelled body is not assumed to be JSON");
assert!(matches!(error, Error::MissingContentType), "{error}");
assert_eq!(error.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
assert_eq!(error.code(), "UNSUPPORTED_MEDIA_TYPE");
}
#[test]
fn a_missing_content_type_passes_only_when_allowed() {
assert!(check_content_type(&HeaderMap::new(), true).is_ok());
}
#[test]
fn a_form_post_is_refused_with_415() {
for allow_missing in [false, true] {
let error =
check_content_type(&headers("application/x-www-form-urlencoded"), allow_missing)
.expect_err("should refuse a form body");
assert_eq!(error.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
assert!(
error.to_string().contains("x-www-form-urlencoded"),
"{error}"
);
}
}
#[test]
fn a_media_type_that_only_mentions_json_is_refused() {
for value in [
"text/plain; application/json",
"text/plain;charset=application/json",
"application/json, text/plain",
"application/jsonx",
"",
] {
assert!(
check_content_type(&headers(value), true).is_err(),
"should refuse {value:?}"
);
}
}
#[test]
fn a_missing_field_names_itself() {
let error = decode(br#"{"threadId":"t","runId":"r"}"#).expect_err("should not decode");
assert_eq!(error.status(), StatusCode::BAD_REQUEST);
assert!(error.to_string().contains("messages"), "{error}");
}
#[test]
fn whitespace_only_bodies_read_as_empty() {
assert!(matches!(decode(b" \n\t"), Err(Error::EmptyBody)));
}
}