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
}
}
impl<S> FromRequest<S> for AgUiInput
where
S: Send + Sync,
{
type Rejection = Error;
async fn from_request(request: Request, state: &S) -> Result<Self> {
check_content_type(request.headers())?;
let bytes = Bytes::from_request(request, state)
.await
.map_err(|rejection| Error::Body {
status: rejection.status(),
message: rejection.body_text(),
})?;
Ok(Self(decode(&bytes)?))
}
}
pub fn decode(body: &[u8]) -> Result<RunAgentInput> {
if body.iter().all(u8::is_ascii_whitespace) {
return Err(Error::EmptyBody);
}
Ok(serde_json::from_slice(body)?)
}
fn check_content_type(headers: &HeaderMap) -> Result<()> {
let Some(value) = headers.get(header::CONTENT_TYPE) else {
return Ok(());
};
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",
] {
assert!(
check_content_type(&headers(value)).is_ok(),
"should accept {value:?}"
);
}
}
#[test]
fn a_missing_content_type_is_accepted() {
assert!(check_content_type(&HeaderMap::new()).is_ok());
}
#[test]
fn a_form_post_is_refused_with_415() {
let error = check_content_type(&headers("application/x-www-form-urlencoded"))
.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_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)));
}
}