use axum::http::{header, HeaderMap, HeaderValue, StatusCode};
use axum::response::{IntoResponse, Response};
use chrono::{DateTime, Utc};
use littlegraph_core::QueryResult;
use serde_json::{json, Map};
use crate::error::HttpError;
use crate::value::{encode, ValueView};
const PLAIN_JSON: &str = "application/json";
const TYPED_JSON: &str = "application/vnd.neo4j.query";
const TYPED_JSON_V10: &str = "application/vnd.neo4j.query.v1.0";
const TYPED_JSON_V11: &str = "application/vnd.neo4j.query.v1.1";
const PLAIN_JSONL: &str = "application/jsonl";
const TYPED_JSONL_V10: &str = "application/vnd.neo4j.query.v1.0+jsonl";
const TYPED_JSONL_V11: &str = "application/vnd.neo4j.query.v1.1+jsonl";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct ResponseFormat {
json_lines: bool,
view: ValueView,
content_type: &'static str,
}
#[derive(Debug)]
pub(crate) struct QueryResponse {
pub(crate) result: Option<QueryResult>,
pub(crate) transaction: Option<TransactionInfo>,
}
#[derive(Clone, Debug)]
pub(crate) struct TransactionInfo {
pub(crate) id: String,
pub(crate) expires: DateTime<Utc>,
}
impl ResponseFormat {
pub(crate) fn negotiate(headers: &HeaderMap) -> Result<Self, HttpError> {
let mut values = headers.get_all(header::ACCEPT).iter();
let Some(first_value) = values.next() else {
return Ok(Self::plain_json());
};
let mut ranges = Vec::new();
let mut position = 0;
for value in std::iter::once(first_value).chain(values) {
let value = value
.to_str()
.map_err(|_| HttpError::invalid("Accept header is not valid ASCII"))?;
for item in value.split(',') {
let item_position = position;
position += 1;
let mut parts = item.split(';');
let media_type = parts.next().unwrap_or_default().trim().to_ascii_lowercase();
let specificity = match media_type.as_str() {
"*/*" => 0,
"application/*" => 1,
media_type if is_supported_media_type(media_type) => 2,
_ => continue,
};
if media_type.is_empty() {
continue;
}
let mut quality = 1000;
let mut valid = true;
for parameter in parts {
let Some((name, value)) = parameter.trim().split_once('=') else {
continue;
};
if name.trim().eq_ignore_ascii_case("q") {
match parse_quality(value.trim()) {
Some(parsed) => quality = parsed,
None => valid = false,
}
}
}
if !valid {
continue;
}
ranges.push(AcceptRange {
media_type,
quality,
specificity,
position: item_position,
});
}
}
let mut selected = None;
for (server_position, format) in supported_formats().into_iter().enumerate() {
let matching_range = ranges
.iter()
.filter(|range| range.matches(format.content_type))
.max_by_key(|range| (range.specificity, std::cmp::Reverse(range.position)));
let Some(range) = matching_range.filter(|range| range.quality > 0) else {
continue;
};
let key = (
range.quality,
range.specificity,
std::cmp::Reverse(range.position),
std::cmp::Reverse(server_position),
);
if selected
.as_ref()
.is_none_or(|(best_key, _)| key > *best_key)
{
selected = Some((key, format));
}
}
selected.map(|(_, format)| format).ok_or_else(|| {
HttpError::new(
StatusCode::NOT_ACCEPTABLE,
"Neo.ClientError.Request.Invalid",
"Not Acceptable",
)
})
}
pub(crate) fn validate_content_type(headers: &HeaderMap) -> Result<bool, HttpError> {
let Some(value) = headers.get(header::CONTENT_TYPE) else {
return Err(unsupported_content_type());
};
let value = value
.to_str()
.map_err(|_| HttpError::invalid("Content-Type header is not valid ASCII"))?;
let media_type = value
.split(';')
.next()
.unwrap_or_default()
.trim()
.to_ascii_lowercase();
match media_type.as_str() {
PLAIN_JSON => Ok(false),
TYPED_JSON | TYPED_JSON_V10 | TYPED_JSON_V11 => Ok(true),
_ => Err(unsupported_content_type()),
}
}
fn plain_json() -> Self {
Self {
json_lines: false,
view: ValueView::Plain,
content_type: PLAIN_JSON,
}
}
fn typed_json(content_type: &'static str) -> Self {
Self {
json_lines: false,
view: ValueView::Typed,
content_type,
}
}
fn jsonl(view: ValueView, content_type: &'static str) -> Self {
Self {
json_lines: true,
view,
content_type,
}
}
pub(crate) fn for_error(headers: &HeaderMap) -> Self {
Self::negotiate(headers).unwrap_or_else(|_| Self::plain_json())
}
pub(crate) fn render_error(self, error: HttpError) -> Response {
error.into_formatted_response(self.content_type, self.json_lines)
}
pub(crate) fn render(
self,
response: QueryResponse,
status: StatusCode,
max_bytes: usize,
) -> Result<Response, HttpError> {
let body = if self.json_lines {
render_json_lines(response, self.view)?
} else {
serde_json::to_vec(&render_json(response, self.view)?)
.map_err(|error| HttpError::invalid(error.to_string()))?
};
if body.len() > max_bytes {
return Err(HttpError::new(
StatusCode::PAYLOAD_TOO_LARGE,
"Neo.TransientError.General.MemoryPoolOutOfMemoryError",
"query result exceeds the configured response limit",
));
}
Ok((
status,
[(
header::CONTENT_TYPE,
HeaderValue::from_static(self.content_type),
)],
body,
)
.into_response())
}
}
#[derive(Debug)]
struct AcceptRange {
media_type: String,
quality: u16,
specificity: u8,
position: usize,
}
impl AcceptRange {
fn matches(&self, content_type: &str) -> bool {
self.media_type == "*/*"
|| self.media_type == "application/*"
|| self.media_type == content_type
}
}
fn is_supported_media_type(media_type: &str) -> bool {
matches!(
media_type,
PLAIN_JSON
| TYPED_JSON
| TYPED_JSON_V10
| TYPED_JSON_V11
| PLAIN_JSONL
| TYPED_JSONL_V10
| TYPED_JSONL_V11
)
}
fn supported_formats() -> [ResponseFormat; 7] {
[
ResponseFormat::plain_json(),
ResponseFormat::typed_json(TYPED_JSON),
ResponseFormat::typed_json(TYPED_JSON_V10),
ResponseFormat::typed_json(TYPED_JSON_V11),
ResponseFormat::jsonl(ValueView::Plain, PLAIN_JSONL),
ResponseFormat::jsonl(ValueView::Typed, TYPED_JSONL_V10),
ResponseFormat::jsonl(ValueView::Typed, TYPED_JSONL_V11),
]
}
fn parse_quality(value: &str) -> Option<u16> {
let (whole, fraction) = value.split_once('.').unwrap_or((value, ""));
if fraction.len() > 3 || !fraction.bytes().all(|byte| byte.is_ascii_digit()) {
return None;
}
match whole {
"0" => {
let fraction = if fraction.is_empty() {
0
} else {
fraction.parse::<u16>().ok()? * 10_u16.pow((3 - fraction.len()) as u32)
};
Some(fraction)
}
"1" if fraction.bytes().all(|byte| byte == b'0') => Some(1000),
_ => None,
}
}
fn unsupported_content_type() -> HttpError {
HttpError::new(
StatusCode::UNSUPPORTED_MEDIA_TYPE,
"Neo.ClientError.Request.Invalid",
"Unsupported Media Type",
)
}
fn render_json(response: QueryResponse, view: ValueView) -> Result<serde_json::Value, HttpError> {
let mut root = Map::new();
if let Some(result) = response.result {
let values = result
.rows
.iter()
.map(|record| {
record
.values
.iter()
.map(|value| encode(value, view))
.collect::<Result<Vec<_>, _>>()
.map(serde_json::Value::Array)
})
.collect::<Result<Vec<_>, _>>()?;
root.insert(
"data".into(),
json!({"fields": result.columns, "values": values}),
);
}
if let Some(transaction) = response.transaction {
root.insert(
"transaction".into(),
json!({"id": transaction.id, "expires": transaction.expires.to_rfc3339()}),
);
}
Ok(serde_json::Value::Object(root))
}
fn render_json_lines(response: QueryResponse, view: ValueView) -> Result<Vec<u8>, HttpError> {
let mut lines = Vec::new();
if let Some(result) = response.result {
push_line(
&mut lines,
&json!({"$event": "Header", "_body": {"fields": result.columns}}),
)?;
for record in result.rows {
let values = record
.values
.iter()
.map(|value| encode(value, view))
.collect::<Result<Vec<_>, _>>()?;
push_line(&mut lines, &json!({"$event": "Record", "_body": values}))?;
}
} else {
push_line(&mut lines, &json!({"$event": "Header", "_body": {}}))?;
}
let summary = response.transaction.map_or_else(
|| json!({}),
|transaction| {
json!({"transaction": {
"id": transaction.id,
"expires": transaction.expires.to_rfc3339()
}})
},
);
push_line(&mut lines, &json!({"$event": "Summary", "_body": summary}))?;
Ok(lines)
}
fn push_line(output: &mut Vec<u8>, value: &serde_json::Value) -> Result<(), HttpError> {
serde_json::to_writer(&mut *output, value)
.map_err(|error| HttpError::invalid(error.to_string()))?;
output.push(b'\n');
Ok(())
}
#[cfg(test)]
mod tests {
use http_body_util::BodyExt;
use littlegraph_core::{QueryResult, Record, Value};
use super::*;
fn result() -> QueryResult {
QueryResult {
columns: vec!["answer".into()],
rows: vec![Record {
values: vec![Value::Integer(42)],
}],
}
}
async fn body(response: Response) -> Vec<u8> {
response
.into_body()
.collect()
.await
.unwrap()
.to_bytes()
.to_vec()
}
#[tokio::test]
async fn renders_typed_json_values() {
let response = ResponseFormat::typed_json(TYPED_JSON_V11)
.render(
QueryResponse {
result: Some(result()),
transaction: None,
},
StatusCode::ACCEPTED,
4096,
)
.unwrap();
let json: serde_json::Value = serde_json::from_slice(&body(response).await).unwrap();
assert_eq!(
json["data"]["values"][0][0],
json!({"$type": "Integer", "_value": "42"})
);
}
#[tokio::test]
async fn renders_json_lines_events() {
let response = ResponseFormat::jsonl(ValueView::Plain, PLAIN_JSONL)
.render(
QueryResponse {
result: Some(result()),
transaction: None,
},
StatusCode::ACCEPTED,
4096,
)
.unwrap();
let bytes = body(response).await;
let events = std::str::from_utf8(&bytes)
.unwrap()
.lines()
.map(|line| serde_json::from_str::<serde_json::Value>(line).unwrap())
.collect::<Vec<_>>();
assert_eq!(events.len(), 3);
assert_eq!(events[0]["$event"], "Header");
assert_eq!(events[1]["$event"], "Record");
assert_eq!(events[1]["_body"], json!([42]));
assert_eq!(events[2]["$event"], "Summary");
}
#[tokio::test]
async fn renders_empty_json_lines_header_before_transaction_summary() {
let expires = Utc::now();
let response = ResponseFormat::jsonl(ValueView::Plain, PLAIN_JSONL)
.render(
QueryResponse {
result: None,
transaction: Some(TransactionInfo {
id: "abcdef".into(),
expires,
}),
},
StatusCode::ACCEPTED,
4096,
)
.unwrap();
let bytes = body(response).await;
let events = std::str::from_utf8(&bytes)
.unwrap()
.lines()
.map(|line| serde_json::from_str::<serde_json::Value>(line).unwrap())
.collect::<Vec<_>>();
assert_eq!(
events,
vec![
json!({"$event": "Header", "_body": {}}),
json!({
"$event": "Summary",
"_body": {
"transaction": {
"id": "abcdef",
"expires": expires.to_rfc3339()
}
}
}),
]
);
}
#[tokio::test]
async fn renders_json_lines_errors_as_one_event() {
let response = ResponseFormat::jsonl(ValueView::Typed, TYPED_JSONL_V11)
.render_error(HttpError::invalid("bad request"));
assert_eq!(response.headers()[header::CONTENT_TYPE], TYPED_JSONL_V11);
let bytes = body(response).await;
assert_eq!(bytes.last(), Some(&b'\n'));
assert_eq!(
serde_json::from_slice::<serde_json::Value>(&bytes).unwrap(),
json!({
"$event": "Error",
"_body": {
"errors": [{
"code": "Neo.ClientError.Request.Invalid",
"message": "bad request"
}]
}
})
);
}
#[test]
fn negotiates_accept_quality_specificity_and_parameters() {
let mut headers = HeaderMap::new();
headers.insert(
header::ACCEPT,
HeaderValue::from_static(
"application/json; q=0.1, application/jsonl; charset=utf-8; q=0.9",
),
);
assert_eq!(
ResponseFormat::negotiate(&headers).unwrap(),
ResponseFormat::jsonl(ValueView::Plain, PLAIN_JSONL)
);
headers.insert(
header::ACCEPT,
HeaderValue::from_static("*/*, application/vnd.neo4j.query.v1.1"),
);
assert_eq!(
ResponseFormat::negotiate(&headers).unwrap(),
ResponseFormat::typed_json(TYPED_JSON_V11)
);
headers.insert(
header::ACCEPT,
HeaderValue::from_static("application/json;q=0, application/jsonl;q=0"),
);
assert_eq!(
ResponseFormat::negotiate(&headers).unwrap_err().status,
StatusCode::NOT_ACCEPTABLE
);
headers.insert(header::ACCEPT, HeaderValue::from_static(TYPED_JSON));
assert_eq!(
ResponseFormat::negotiate(&headers).unwrap(),
ResponseFormat::typed_json(TYPED_JSON)
);
headers.remove(header::ACCEPT);
headers.append(
header::ACCEPT,
HeaderValue::from_static("application/json;q=0.1"),
);
headers.append(
header::ACCEPT,
HeaderValue::from_static("application/jsonl;q=0.9"),
);
assert_eq!(
ResponseFormat::negotiate(&headers).unwrap(),
ResponseFormat::jsonl(ValueView::Plain, PLAIN_JSONL)
);
headers.insert(
header::ACCEPT,
HeaderValue::from_static("application/json;q=0, application/*;q=1"),
);
assert_eq!(
ResponseFormat::negotiate(&headers).unwrap(),
ResponseFormat::typed_json(TYPED_JSON)
);
}
#[test]
fn requires_a_supported_request_content_type() {
let error = ResponseFormat::validate_content_type(&HeaderMap::new()).unwrap_err();
assert_eq!(error.status, StatusCode::UNSUPPORTED_MEDIA_TYPE);
}
}