use askama::Template;
use axum::async_trait;
use axum::extract::FromRequestParts;
use axum::http::request::Parts;
use axum::http::{header, HeaderValue, StatusCode};
use axum::response::{IntoResponse, Response};
use schemars::{schema_for, JsonSchema};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::convert::Infallible;
use crate::discovery::discovery_link_header;
use crate::error::AppError;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResponseFormat {
Html,
Json,
Ai,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Format(pub ResponseFormat);
impl Format {
pub fn negotiate(path: &str, headers: &axum::http::HeaderMap) -> ResponseFormat {
if path.ends_with(".json") {
return ResponseFormat::Json;
}
if path.ends_with(".ai") || path == "/ai" || path.starts_with("/ai/") {
return ResponseFormat::Ai;
}
if path.ends_with(".html") {
return ResponseFormat::Html;
}
if let Some(val) = headers.get("x-agent-mode").and_then(|v| v.to_str().ok()) {
if val.eq_ignore_ascii_case("true") || val == "1" {
return ResponseFormat::Ai;
}
}
if let Some(accept) = headers.get(header::ACCEPT).and_then(|v| v.to_str().ok()) {
let lower = accept.to_ascii_lowercase();
if lower.contains("text/markdown") {
return ResponseFormat::Ai;
}
if lower.contains("application/json") && !lower.contains("text/html") {
return ResponseFormat::Json;
}
}
ResponseFormat::Html
}
}
#[async_trait]
impl<S> FromRequestParts<S> for Format
where
S: Send + Sync,
{
type Rejection = Infallible;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
Ok(Format(Self::negotiate(parts.uri.path(), &parts.headers)))
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ActionAffordance {
pub name: String,
pub method: String,
pub path: String,
pub description: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub input_schema: Option<Value>,
}
impl ActionAffordance {
pub fn new(
name: impl Into<String>,
method: impl Into<String>,
path: impl Into<String>,
description: impl Into<String>,
) -> Self {
Self {
name: name.into(),
method: method.into(),
path: path.into(),
description: description.into(),
input_schema: None,
}
}
pub fn with_schema<D: JsonSchema>(
name: impl Into<String>,
method: impl Into<String>,
path: impl Into<String>,
description: impl Into<String>,
) -> Self {
let schema = serde_json::to_value(schema_for!(D)).ok();
Self {
name: name.into(),
method: method.into(),
path: path.into(),
description: description.into(),
input_schema: schema,
}
}
}
#[derive(Debug, Clone, Serialize)]
struct AiFrontmatter {
canonical_url: String,
title: String,
status: String,
#[serde(skip_serializing_if = "Option::is_none")]
pagination: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
flash: Option<String>,
}
pub struct ActionResponse<T: Serialize> {
pub data: T,
pub format: ResponseFormat,
pub status: StatusCode,
pub html: Option<String>,
pub html_redirect: Option<String>,
pub canonical_url: String,
pub title: String,
pub ai_alternate_url: Option<String>,
pub actions: Vec<ActionAffordance>,
pub flash: Option<String>,
pub pagination: Option<Value>,
}
impl<T: Serialize> ActionResponse<T> {
pub fn new(format: ResponseFormat, data: T) -> Self {
Self {
data,
format,
status: StatusCode::OK,
html: None,
html_redirect: None,
canonical_url: "/".to_string(),
title: "Ferrik".to_string(),
ai_alternate_url: None,
actions: Vec::new(),
flash: None,
pagination: None,
}
}
pub fn with_html(mut self, html: impl Into<String>) -> Self {
self.html = Some(html.into());
self
}
pub fn with_template<Tmpl: Template>(mut self, template: &Tmpl) -> Result<Self, AppError> {
if self.format == ResponseFormat::Html {
self.html = Some(template.render()?);
}
Ok(self)
}
pub fn with_html_redirect(mut self, location: impl Into<String>) -> Self {
self.html_redirect = Some(location.into());
self
}
pub fn with_status(mut self, status: StatusCode) -> Self {
self.status = status;
self
}
pub fn with_title(mut self, title: impl Into<String>) -> Self {
self.title = title.into();
self
}
pub fn with_canonical_url(mut self, url: impl Into<String>) -> Self {
self.canonical_url = url.into();
self
}
pub fn with_ai_alternate(mut self, url: impl Into<String>) -> Self {
self.ai_alternate_url = Some(url.into());
self
}
pub fn with_action(mut self, action: ActionAffordance) -> Self {
self.actions.push(action);
self
}
pub fn with_actions(mut self, actions: Vec<ActionAffordance>) -> Self {
self.actions.extend(actions);
self
}
pub fn with_flash(mut self, flash: impl Into<String>) -> Self {
self.flash = Some(flash.into());
self
}
pub fn with_pagination(mut self, pagination: Value) -> Self {
self.pagination = Some(pagination);
self
}
pub fn render_ai_markdown(&self) -> String {
let frontmatter = AiFrontmatter {
canonical_url: self.canonical_url.clone(),
title: self.title.clone(),
status: if self.status.is_success() {
"ok".to_string()
} else {
format!("error_{}", self.status.as_u16())
},
pagination: self.pagination.clone(),
flash: self.flash.clone(),
};
let yaml = serde_yaml::to_string(&frontmatter).unwrap_or_default();
let mut out = String::new();
out.push_str("---\n");
out.push_str(&yaml);
out.push_str("---\n\n");
out.push_str(&format!("# {}\n\n", self.title));
out.push_str("## Data\n\n");
let value = serde_json::to_value(&self.data).unwrap_or(Value::Null);
out.push_str(&render_json_as_markdown(&value));
out.push_str("\n## Available Actions\n\n");
if self.actions.is_empty() {
out.push_str("No actions available.\n");
} else {
for action in &self.actions {
out.push_str(&format!(
"- **{}** (`{} {}`): {}\n",
action.name, action.method, action.path, action.description
));
if let Some(schema) = &action.input_schema {
if let Ok(pretty) = serde_json::to_string_pretty(schema) {
out.push_str(" ```json\n");
for line in pretty.lines() {
out.push_str(" ");
out.push_str(line);
out.push('\n');
}
out.push_str(" ```\n");
}
}
}
}
out
}
fn resolved_ai_alternate(&self) -> String {
if let Some(url) = &self.ai_alternate_url {
return url.clone();
}
if self.canonical_url == "/" {
"/ai".to_string()
} else {
format!("{}.ai", self.canonical_url.trim_end_matches('/'))
}
}
}
impl<T: Serialize> IntoResponse for ActionResponse<T> {
fn into_response(self) -> Response {
match self.format {
ResponseFormat::Json => {
let body = serde_json::to_string(&self.data).unwrap_or_else(|_| "{}".to_string());
(
self.status,
[(header::CONTENT_TYPE, "application/json; charset=utf-8")],
body,
)
.into_response()
}
ResponseFormat::Ai => {
let md = self.render_ai_markdown();
(
self.status,
[(header::CONTENT_TYPE, "text/markdown; charset=utf-8")],
md,
)
.into_response()
}
ResponseFormat::Html => {
if let Some(location) = self.html_redirect {
return axum::response::Redirect::to(&location).into_response();
}
let html = self.html.clone().unwrap_or_else(|| {
format!(
"<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\"><title>{}</title></head><body><main><h1>{}</h1></main></body></html>",
self.title, self.title
)
});
let link_header = discovery_link_header(&self.resolved_ai_alternate());
let mut resp = (
self.status,
[(header::CONTENT_TYPE, "text/html; charset=utf-8")],
html,
)
.into_response();
if let Ok(hv) = HeaderValue::from_str(&link_header) {
resp.headers_mut().insert(header::LINK, hv);
}
resp
}
}
}
}
fn render_json_as_markdown(value: &Value) -> String {
match value {
Value::Object(map) => {
if map.is_empty() {
return "_Empty object._\n".to_string();
}
let mut out = String::from("| Field | Value |\n| :--- | :--- |\n");
for (k, v) in map {
out.push_str(&format!("| {} | {} |\n", escape_md_cell(k), format_scalar(v)));
}
out
}
Value::Array(items) => {
if items.is_empty() {
return "_No records found._\n".to_string();
}
if let Some(Value::Object(first)) = items.first() {
let columns: Vec<&String> = first.keys().collect();
let mut out = String::new();
out.push('|');
for col in &columns {
out.push_str(&format!(" {} |", escape_md_cell(col)));
}
out.push('\n');
out.push('|');
for _ in &columns {
out.push_str(" :--- |");
}
out.push('\n');
for item in items {
if let Value::Object(obj) = item {
out.push('|');
for col in &columns {
let cell = obj.get(*col).map(format_scalar).unwrap_or_default();
out.push_str(&format!(" {} |", cell));
}
out.push('\n');
}
}
out
} else {
let mut out = String::new();
for item in items {
out.push_str(&format!("- {}\n", format_scalar(item)));
}
out
}
}
other => format!("{}\n", format_scalar(other)),
}
}
fn format_scalar(value: &Value) -> String {
match value {
Value::Null => "null".to_string(),
Value::Bool(b) => b.to_string(),
Value::Number(n) => n.to_string(),
Value::String(s) => escape_md_cell(s),
Value::Array(_) | Value::Object(_) => {
escape_md_cell(&serde_json::to_string(value).unwrap_or_default())
}
}
}
fn escape_md_cell(input: &str) -> String {
input.replace('|', "\\|").replace('\n', " ")
}
#[cfg(test)]
mod tests {
use super::*;
use axum::http::HeaderMap;
use http_body_util::BodyExt;
#[derive(Serialize, JsonSchema)]
struct SamplePost {
id: i32,
title: String,
}
#[derive(Template)]
#[template(source = "<main><h1>{{ title }}</h1></main>", ext = "html")]
struct SampleTemplate {
title: String,
}
async fn read_body(resp: Response) -> String {
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
String::from_utf8(bytes.to_vec()).unwrap()
}
#[test]
fn negotiates_format_from_url_and_headers() {
let empty = HeaderMap::new();
assert_eq!(Format::negotiate("/posts", &empty), ResponseFormat::Html);
assert_eq!(Format::negotiate("/posts.html", &empty), ResponseFormat::Html);
assert_eq!(Format::negotiate("/posts.json", &empty), ResponseFormat::Json);
assert_eq!(Format::negotiate("/posts.ai", &empty), ResponseFormat::Ai);
assert_eq!(Format::negotiate("/ai", &empty), ResponseFormat::Ai);
assert_eq!(Format::negotiate("/ai/posts", &empty), ResponseFormat::Ai);
let mut agent_headers = HeaderMap::new();
agent_headers.insert("x-agent-mode", HeaderValue::from_static("true"));
assert_eq!(Format::negotiate("/posts", &agent_headers), ResponseFormat::Ai);
let mut md_headers = HeaderMap::new();
md_headers.insert(header::ACCEPT, HeaderValue::from_static("text/markdown"));
assert_eq!(Format::negotiate("/posts", &md_headers), ResponseFormat::Ai);
let mut json_headers = HeaderMap::new();
json_headers.insert(header::ACCEPT, HeaderValue::from_static("application/json"));
assert_eq!(Format::negotiate("/posts", &json_headers), ResponseFormat::Json);
}
#[tokio::test]
async fn renders_html_with_askama_and_link_header() {
let tmpl = SampleTemplate {
title: "Hello".into(),
};
let resp = ActionResponse::new(
ResponseFormat::Html,
SamplePost {
id: 1,
title: "Hello".into(),
},
)
.with_title("Hello")
.with_canonical_url("/posts/1")
.with_template(&tmpl)
.unwrap()
.into_response();
assert_eq!(resp.status(), StatusCode::OK);
let link = resp.headers().get(header::LINK).unwrap().to_str().unwrap();
assert!(link.contains("/.well-known/ferrik-agent.json"));
assert!(link.contains("/posts/1.ai"));
let body = read_body(resp).await;
assert_eq!(body, "<main><h1>Hello</h1></main>");
}
#[tokio::test]
async fn renders_json_payload() {
let resp = ActionResponse::new(
ResponseFormat::Json,
SamplePost {
id: 42,
title: "Ferrik".into(),
},
)
.with_status(StatusCode::CREATED)
.into_response();
assert_eq!(resp.status(), StatusCode::CREATED);
let body = read_body(resp).await;
let parsed: Value = serde_json::from_str(&body).unwrap();
assert_eq!(parsed["id"], 42);
assert_eq!(parsed["title"], "Ferrik");
}
#[tokio::test]
async fn renders_ai_markdown_with_frontmatter_table_and_affordances() {
let posts = vec![
SamplePost {
id: 1,
title: "First".into(),
},
SamplePost {
id: 2,
title: "Second".into(),
},
];
let resp = ActionResponse::new(ResponseFormat::Ai, posts)
.with_title("Posts")
.with_canonical_url("/posts")
.with_flash("Loaded 2 posts")
.with_pagination(serde_json::json!({ "page": 1, "per_page": 20 }))
.with_action(ActionAffordance::with_schema::<SamplePost>(
"create_post",
"POST",
"/posts",
"Create a new post",
))
.into_response();
assert_eq!(resp.status(), StatusCode::OK);
let body = read_body(resp).await;
assert!(body.starts_with("---\n"));
assert!(body.contains("canonical_url: /posts"));
assert!(body.contains("title: Posts"));
assert!(body.contains("flash: Loaded 2 posts"));
assert!(body.contains("| id | title |"));
assert!(body.contains("| 1 | First |"));
assert!(body.contains("## Available Actions"));
assert!(body.contains("**create_post** (`POST /posts`)"));
assert!(body.contains("\"SamplePost\""));
}
#[test]
fn renders_empty_and_scalar_markdown_cases() {
assert_eq!(render_json_as_markdown(&serde_json::json!([])), "_No records found._\n");
assert_eq!(render_json_as_markdown(&serde_json::json!({})), "_Empty object._\n");
assert_eq!(
render_json_as_markdown(&serde_json::json!(["a", "b"])),
"- a\n- b\n"
);
assert_eq!(render_json_as_markdown(&serde_json::json!(123)), "123\n");
}
}