use std::fmt;
use std::ops::{Deref, DerefMut};
use crate::error::Error as JshiftError;
use crate::typed_doc::TypedDoc;
use crate::view::JsonView;
use axum::body::Bytes;
use axum::extract::{FromRequest, Request};
use axum::http::{header, HeaderMap, HeaderValue, StatusCode};
use axum::response::{IntoResponse, Response};
#[derive(Debug, Clone)]
pub struct JshiftJson<T> {
pub value: T,
raw: Option<Vec<u8>>,
}
impl<T> JshiftJson<T> {
#[inline]
pub const fn new(value: T) -> Self {
Self { value, raw: None }
}
#[inline]
pub const fn closed(value: T) -> Self {
Self::new(value)
}
#[inline]
pub fn from_parts(value: T, raw: Option<Vec<u8>>) -> Self {
Self { value, raw }
}
#[inline]
pub fn into_inner(self) -> T {
self.value
}
#[inline]
pub fn into_parts(self) -> (T, Option<Vec<u8>>) {
(self.value, self.raw)
}
#[inline]
pub fn raw(&self) -> Option<&[u8]> {
self.raw.as_deref()
}
#[inline]
pub fn has_raw(&self) -> bool {
self.raw.is_some()
}
#[inline]
pub fn into_closed(self) -> Self {
Self {
value: self.value,
raw: None,
}
}
#[inline]
pub fn map_value<U>(self, f: impl FnOnce(T) -> U) -> JshiftJson<U> {
JshiftJson {
value: f(self.value),
raw: self.raw,
}
}
}
impl<T: Default> Default for JshiftJson<T> {
#[inline]
fn default() -> Self {
Self::new(T::default())
}
}
impl<T> From<T> for JshiftJson<T> {
#[inline]
fn from(value: T) -> Self {
Self::new(value)
}
}
impl<T> Deref for JshiftJson<T> {
type Target = T;
#[inline]
fn deref(&self) -> &Self::Target {
&self.value
}
}
impl<T> DerefMut for JshiftJson<T> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.value
}
}
#[derive(Debug, Clone)]
pub struct JshiftDoc(pub TypedDoc);
impl JshiftDoc {
#[inline]
pub fn new(doc: TypedDoc) -> Self {
Self(doc)
}
#[inline]
pub fn into_inner(self) -> TypedDoc {
self.0
}
}
impl From<TypedDoc> for JshiftDoc {
#[inline]
fn from(doc: TypedDoc) -> Self {
Self(doc)
}
}
impl Deref for JshiftDoc {
type Target = TypedDoc;
#[inline]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for JshiftDoc {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[derive(Debug)]
pub enum JshiftRejection {
MissingJsonContentType,
Body(String),
Decode(JshiftError),
}
impl fmt::Display for JshiftRejection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
JshiftRejection::MissingJsonContentType => {
f.write_str("Expected request with `Content-Type: application/json`")
}
JshiftRejection::Body(e) => write!(f, "Failed to read request body: {e}"),
JshiftRejection::Decode(e) => write!(f, "Failed to decode JSON body: {e}"),
}
}
}
impl std::error::Error for JshiftRejection {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
JshiftRejection::Decode(e) => Some(e),
_ => None,
}
}
}
impl IntoResponse for JshiftRejection {
fn into_response(self) -> Response {
let status = match &self {
JshiftRejection::MissingJsonContentType => StatusCode::UNSUPPORTED_MEDIA_TYPE,
JshiftRejection::Body(_) => StatusCode::BAD_REQUEST,
JshiftRejection::Decode(_) => StatusCode::UNPROCESSABLE_ENTITY,
};
let mut body = Vec::with_capacity(64 + self.to_string().len());
body.extend_from_slice(br#"{"error":"#);
crate::convert::write_json_string(&mut body, &self.to_string());
body.push(b'}');
let mut res = (status, body).into_response();
res.headers_mut().insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/json"),
);
res
}
}
#[inline]
fn json_content_type(headers: &HeaderMap) -> bool {
let Some(ct) = headers.get(header::CONTENT_TYPE) else {
return false;
};
let Ok(s) = ct.to_str() else {
return false;
};
let mime = s.split(';').next().unwrap_or("").trim();
if mime.eq_ignore_ascii_case("application/json") {
return true;
}
let b = mime.as_bytes();
b.len() >= 5 && b[b.len() - 5..].eq_ignore_ascii_case(b"+json")
}
#[inline]
fn bytes_into_vec(bytes: Bytes) -> Vec<u8> {
Vec::from(bytes)
}
fn json_response(bytes: Vec<u8>) -> Response {
let mut res = bytes.into_response();
res.headers_mut().insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/json"),
);
res
}
fn encode_error_response(e: impl fmt::Display) -> Response {
let mut body = Vec::new();
body.extend_from_slice(br#"{"error":"#);
crate::convert::write_json_string(&mut body, &format!("jshift response encode failed: {e}"));
body.push(b'}');
let mut res = (StatusCode::INTERNAL_SERVER_ERROR, body).into_response();
res.headers_mut().insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/json"),
);
res
}
impl<S, T> FromRequest<S> for JshiftJson<T>
where
T: JsonView,
S: Send + Sync,
{
type Rejection = JshiftRejection;
async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
if !json_content_type(req.headers()) {
return Err(JshiftRejection::MissingJsonContentType);
}
let bytes = Bytes::from_request(req, state)
.await
.map_err(|e| JshiftRejection::Body(e.to_string()))?;
let raw = bytes_into_vec(bytes);
let value = T::read_from(&raw).map_err(JshiftRejection::Decode)?;
Ok(JshiftJson {
value,
raw: Some(raw),
})
}
}
impl<S> FromRequest<S> for JshiftDoc
where
S: Send + Sync,
{
type Rejection = JshiftRejection;
async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
if !json_content_type(req.headers()) {
return Err(JshiftRejection::MissingJsonContentType);
}
let bytes = Bytes::from_request(req, state)
.await
.map_err(|e| JshiftRejection::Body(e.to_string()))?;
Ok(JshiftDoc(TypedDoc::from_vec(bytes_into_vec(bytes))))
}
}
impl<T: JsonView> IntoResponse for JshiftJson<T> {
fn into_response(self) -> Response {
match self.raw {
Some(mut buf) => match self.value.write_into(&mut buf) {
Ok(()) => json_response(buf),
Err(e) => encode_error_response(e),
},
None => match self.value.to_schema_bytes() {
Ok(bytes) => json_response(bytes),
Err(e) => encode_error_response(e),
},
}
}
}
impl IntoResponse for JshiftDoc {
fn into_response(self) -> Response {
json_response(self.0.into_bytes())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{find_value, parse_path, FromJsonSlice, ProjectPlan, ToJsonBytes};
use axum::body::Body;
use axum::http::{Request, StatusCode};
use http_body_util::BodyExt;
use tower::ServiceExt;
struct IdOnly {
id: u64,
}
impl JsonView for IdOnly {
fn read_from(json: &[u8]) -> Result<Self, crate::Error> {
let slice = find_value(json, &parse_path("id"))?;
Ok(Self {
id: u64::from_json_slice(slice).ok_or(crate::Error::TypeMismatch {
expected: "u64",
found: "bad",
})?,
})
}
fn write_into(&self, json: &mut Vec<u8>) -> Result<(), crate::Error> {
crate::upsert_at_path(json, &parse_path("id"), &self.id.to_json_bytes())
}
fn project_plan() -> ProjectPlan {
ProjectPlan::from_paths(&["id"]).unwrap()
}
}
#[tokio::test(flavor = "current_thread")]
async fn jshift_json_open_response_preserves_unknowns() {
async fn handler(mut req: JshiftJson<IdOnly>) -> JshiftJson<IdOnly> {
req.value.id += 1;
req
}
let app = axum::Router::new().route("/", axum::routing::post(handler));
let res = app
.oneshot(
Request::builder()
.method("POST")
.uri("/")
.header(header::CONTENT_TYPE, "application/json; charset=utf-8")
.body(Body::from(r#"{"id":7,"noise":true}"#))
.unwrap(),
)
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
let body = res.into_body().collect().await.unwrap().to_bytes();
let s = std::str::from_utf8(&body).unwrap();
assert!(s.contains("\"id\":8"), "{s}");
assert!(s.contains("\"noise\""), "unknowns must survive open response: {s}");
}
#[tokio::test(flavor = "current_thread")]
async fn jshift_json_closed_response_is_schema_only() {
async fn handler(req: JshiftJson<IdOnly>) -> JshiftJson<IdOnly> {
JshiftJson::closed(IdOnly {
id: req.value.id + 1,
})
}
let app = axum::Router::new().route("/", axum::routing::post(handler));
let res = app
.oneshot(
Request::builder()
.method("POST")
.uri("/")
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(r#"{"id":7,"noise":true}"#))
.unwrap(),
)
.await
.unwrap();
let body = res.into_body().collect().await.unwrap().to_bytes();
let s = std::str::from_utf8(&body).unwrap();
assert!(s.contains("\"id\":8"));
assert!(!s.contains("noise"), "closed must drop unknowns: {s}");
}
#[tokio::test(flavor = "current_thread")]
async fn accepts_json_suffix_and_case() {
async fn handler(req: JshiftJson<IdOnly>) -> JshiftJson<IdOnly> {
req
}
let app = axum::Router::new().route("/", axum::routing::post(handler));
let res = app
.oneshot(
Request::builder()
.method("POST")
.uri("/")
.header(header::CONTENT_TYPE, "Application/vnd.api+JSON")
.body(Body::from(r#"{"id":1}"#))
.unwrap(),
)
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
}
#[tokio::test(flavor = "current_thread")]
async fn rejects_non_json_content_type() {
async fn handler(req: JshiftJson<IdOnly>) -> JshiftJson<IdOnly> {
req
}
let app = axum::Router::new().route("/", axum::routing::post(handler));
let res = app
.oneshot(
Request::builder()
.method("POST")
.uri("/")
.header(header::CONTENT_TYPE, "text/plain")
.body(Body::from(r#"{"id":1}"#))
.unwrap(),
)
.await
.unwrap();
assert_eq!(res.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
let body = res.into_body().collect().await.unwrap().to_bytes();
assert!(body.starts_with(b"{\"error\":"));
}
#[tokio::test(flavor = "current_thread")]
async fn decode_error_is_422() {
async fn handler(req: JshiftJson<IdOnly>) -> JshiftJson<IdOnly> {
req
}
let app = axum::Router::new().route("/", axum::routing::post(handler));
let res = app
.oneshot(
Request::builder()
.method("POST")
.uri("/")
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(r#"{"nope":true}"#))
.unwrap(),
)
.await
.unwrap();
assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY);
}
#[tokio::test(flavor = "current_thread")]
async fn jshift_doc_preserves_unknowns() {
async fn handler(JshiftDoc(mut doc): JshiftDoc) -> JshiftDoc {
let _ = doc.mutate().upsert("seen", &true);
JshiftDoc(doc)
}
let app = axum::Router::new().route("/", axum::routing::post(handler));
let res = app
.oneshot(
Request::builder()
.method("POST")
.uri("/")
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(r#"{"keep":1}"#))
.unwrap(),
)
.await
.unwrap();
let body = res.into_body().collect().await.unwrap().to_bytes();
let s = std::str::from_utf8(&body).unwrap();
assert!(s.contains("\"keep\""));
assert!(s.contains("\"seen\""));
}
#[test]
fn content_type_helpers() {
let mut h = HeaderMap::new();
h.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("APPLICATION/JSON"),
);
assert!(json_content_type(&h));
h.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/vnd.api+json"),
);
assert!(json_content_type(&h));
h.insert(header::CONTENT_TYPE, HeaderValue::from_static("text/json"));
assert!(!json_content_type(&h));
}
}