From 5fc99606f776b718aaa2eee4e67f3a60aeb7c8c0 Mon Sep 17 00:00:00 2001 From: ZhuchkaTriplesix Date: Sun, 18 Oct 2026 19:01:35 +0300 Subject: [PATCH] perf(dispatch): call model_validate_json directly and stream JSON into Python objects --- src/dispatch.rs | 105 ++++++++++++++-------- src/lib.rs | 4 +- src/schema.rs | 182 +++++++++++++++++++++++++++++++++++++++ tests/test_validation.py | 86 ++++++++++++++++++ 4 files changed, 338 insertions(+), 39 deletions(-) diff --git a/src/dispatch.rs b/src/dispatch.rs index f25bf1f..f3c56fe 100644 --- a/src/dispatch.rs +++ b/src/dispatch.rs @@ -935,30 +935,10 @@ pub async fn run_rsgi( } else { HashMap::new() }; - let body_json: Option = if read_json_body + let has_json_body = read_json_body && !read_form_body && (method == "POST" || method == "PUT" || method == "PATCH" || method == "DELETE") - { - if body_bytes.is_empty() { - None - } else { - match serde_json::from_slice::(&body_bytes) { - Ok(v) => Some(v), - Err(e) => { - let err_body = serde_json::json!({ "error": format!("json: {e}") }).to_string(); - return response::send_text( - &protocol, - 400, - &err_body, - "application/json; charset=utf-8", - ) - .await; - } - } - } - } else { - None - }; + && !body_bytes.is_empty(); let (form_map, form_files): (HashMap, Vec) = if read_form_body && (method == "POST" || method == "PUT" || method == "PATCH" || method == "DELETE") { @@ -1210,7 +1190,7 @@ pub async fn run_rsgi( let should_pass_files = read_form_body && (handler_varkw || handler_param_names.contains("files")); let should_pass_protocol = handler_varkw || handler_param_names.contains("protocol"); - let should_pass_body = !read_form_body && !body_bytes.is_empty() && body_json.is_none(); + let should_pass_body = !read_form_body && !body_bytes.is_empty() && !has_json_body; let has_dep_kwargs = dependencies.iter().enumerate().any(|(i, dep)| { dep_out.get(i).is_some() && (handler_varkw || handler_param_names.contains(&dep.name)) }); @@ -1218,7 +1198,7 @@ pub async fn run_rsgi( || !query_map.is_empty() || has_dep_kwargs || claims_val.is_some() - || body_json.is_some() + || has_json_body || should_pass_form || should_pass_files || should_pass_body @@ -1226,6 +1206,7 @@ pub async fn run_rsgi( enum RunHandlerResult { Ok((PyObject, bool)), ValidationError(String), + JsonParseError(String), } let (res, run_async) = match Python::with_gil(|py| -> PyResult { @@ -1263,10 +1244,39 @@ pub async fn run_rsgi( let pyv = json_to_py(py, c)?; kwargs.set_item("claims", pyv)?; } - if let Some(ref j) = body_json { - let pyv = json_to_py(py, j)?; + if has_json_body { if let Some(ref bm) = body_model { - match bm.bind(py).call_method1("model_validate", (&pyv,)) { + let bound_bm = bm.bind(py); + let py_bytes_bound = match body_py_obj { + Some(ref obj) => obj.bind(py).clone(), + None => pyo3::types::PyBytes::new(py, body_bytes.as_bytes()).into_any(), + }; + let validated_res = if bound_bm + .hasattr(pyo3::intern!(py, "model_validate_json")) + .unwrap_or(false) + { + bound_bm + .call_method1(pyo3::intern!(py, "model_validate_json"), (&py_bytes_bound,)) + } else { + match crate::schema::json_bytes_to_py(py, body_bytes.as_bytes()) { + Ok(pyv) => { + if bound_bm + .hasattr(pyo3::intern!(py, "model_validate")) + .unwrap_or(false) + { + bound_bm.call_method1(pyo3::intern!(py, "model_validate"), (&pyv,)) + } else { + bound_bm.call1((&pyv,)) + } + } + Err(e) => { + let err_body = + serde_json::json!({ "error": format!("json: {e}") }).to_string(); + return Ok(RunHandlerResult::JsonParseError(err_body)); + } + } + }; + match validated_res { Ok(validated) => { let target_name = if body_param_name.is_empty() { "json" @@ -1279,24 +1289,34 @@ pub async fn run_rsgi( } } Err(e) => { - let err_str: String = - if let Ok(exc_obj) = e.clone_ref(py).into_bound_py_any(py) { - if let Ok(j_method) = exc_obj.call_method0("json") { - j_method - .extract::() - .unwrap_or_else(|_| "[]".to_string()) - } else { - "[]".to_string() - } + let err_str: String = if let Ok(exc_obj) = + e.clone_ref(py).into_bound_py_any(py) + { + if let Ok(j_method) = exc_obj.call_method0(pyo3::intern!(py, "json")) { + j_method + .extract::() + .unwrap_or_else(|_| "[]".to_string()) } else { "[]".to_string() - }; + } + } else { + "[]".to_string() + }; let err_json = format!(r#"{{"detail":{err_str}}}"#); return Ok(RunHandlerResult::ValidationError(err_json)); } } } else { - kwargs.set_item("json", pyv)?; + match crate::schema::json_bytes_to_py(py, body_bytes.as_bytes()) { + Ok(pyv) => { + kwargs.set_item(pyo3::intern!(py, "json"), pyv)?; + } + Err(e) => { + let err_body = + serde_json::json!({ "error": format!("json: {e}") }).to_string(); + return Ok(RunHandlerResult::JsonParseError(err_body)); + } + } } } if read_form_body { @@ -1336,6 +1356,15 @@ pub async fn run_rsgi( Ok(RunHandlerResult::Ok((res, is_async))) }) { Ok(RunHandlerResult::Ok((res, is_async))) => (res, is_async), + Ok(RunHandlerResult::JsonParseError(err_body)) => { + return response::send_text( + &protocol, + 400, + &err_body, + "application/json; charset=utf-8", + ) + .await; + } Ok(RunHandlerResult::ValidationError(err_json)) => { return response::send_text( &protocol, diff --git a/src/lib.rs b/src/lib.rs index a68245d..f21a5f0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -34,7 +34,9 @@ pub mod microbench { use pyo3::prelude::*; pub use crate::params::header_get_lax; - pub use crate::schema::{json_to_py, py_to_json_bytes, py_to_json_bytes_or_fallback}; + pub use crate::schema::{ + json_bytes_to_py, json_to_py, py_to_json_bytes, py_to_json_bytes_or_fallback, + }; pub use crate::state::{match_route_compiled, CompiledRouters}; /// Build a compiled GET router with one static and one param route for matching benches. diff --git a/src/schema.rs b/src/schema.rs index 3571927..84eeca3 100644 --- a/src/schema.rs +++ b/src/schema.rs @@ -52,6 +52,188 @@ pub fn json_to_py(py: Python<'_>, v: &JsonValue) -> PyResult> { json_value_to_py(py, v) } +struct PyStringVisitor<'py>(Python<'py>); + +impl<'de, 'py> serde::de::Visitor<'de> for PyStringVisitor<'py> { + type Value = Py; + + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + formatter.write_str("a string key") + } + + fn visit_str(self, v: &str) -> Result + where + E: serde::de::Error, + { + Ok(PyString::new(self.0, v).unbind()) + } + + fn visit_borrowed_str(self, v: &'de str) -> Result + where + E: serde::de::Error, + { + Ok(PyString::new(self.0, v).unbind()) + } + + fn visit_string(self, v: String) -> Result + where + E: serde::de::Error, + { + Ok(PyString::new(self.0, &v).unbind()) + } +} + +struct PyStringSeed<'py>(Python<'py>); + +impl<'de, 'py> serde::de::DeserializeSeed<'de> for PyStringSeed<'py> { + type Value = Py; + + fn deserialize(self, deserializer: D) -> Result + where + D: serde::de::Deserializer<'de>, + { + deserializer.deserialize_str(PyStringVisitor(self.0)) + } +} + +struct PyJsonVisitor<'py>(Python<'py>); + +impl<'de, 'py> serde::de::Visitor<'de> for PyJsonVisitor<'py> { + type Value = Py; + + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + formatter.write_str("any valid JSON value") + } + + fn visit_bool(self, v: bool) -> Result + where + E: serde::de::Error, + { + v.into_py_any(self.0).map_err(serde::de::Error::custom) + } + + fn visit_i64(self, v: i64) -> Result + where + E: serde::de::Error, + { + v.into_py_any(self.0).map_err(serde::de::Error::custom) + } + + fn visit_u64(self, v: u64) -> Result + where + E: serde::de::Error, + { + v.into_py_any(self.0).map_err(serde::de::Error::custom) + } + + fn visit_i128(self, v: i128) -> Result + where + E: serde::de::Error, + { + v.into_py_any(self.0).map_err(serde::de::Error::custom) + } + + fn visit_u128(self, v: u128) -> Result + where + E: serde::de::Error, + { + v.into_py_any(self.0).map_err(serde::de::Error::custom) + } + + fn visit_f64(self, v: f64) -> Result + where + E: serde::de::Error, + { + Ok(PyFloat::new(self.0, v).into_any().unbind()) + } + + fn visit_str(self, v: &str) -> Result + where + E: serde::de::Error, + { + Ok(PyString::new(self.0, v).into_any().unbind()) + } + + fn visit_borrowed_str(self, v: &'de str) -> Result + where + E: serde::de::Error, + { + Ok(PyString::new(self.0, v).into_any().unbind()) + } + + fn visit_string(self, v: String) -> Result + where + E: serde::de::Error, + { + Ok(PyString::new(self.0, &v).into_any().unbind()) + } + + fn visit_unit(self) -> Result + where + E: serde::de::Error, + { + Ok(self.0.None()) + } + + fn visit_none(self) -> Result + where + E: serde::de::Error, + { + Ok(self.0.None()) + } + + fn visit_seq(self, mut seq: A) -> Result + where + A: serde::de::SeqAccess<'de>, + { + let py = self.0; + let list = PyList::empty(py); + while let Some(elem) = seq.next_element_seed(PyJsonSeed(py))? { + list.append(elem.bind(py)) + .map_err(serde::de::Error::custom)?; + } + Ok(list.into_any().unbind()) + } + + fn visit_map(self, mut access: M) -> Result + where + M: serde::de::MapAccess<'de>, + { + let py = self.0; + let dict = PyDict::new(py); + while let Some(k) = access.next_key_seed(PyStringSeed(py))? { + let v = access.next_value_seed(PyJsonSeed(py))?; + dict.set_item(k.bind(py), v.bind(py)) + .map_err(serde::de::Error::custom)?; + } + Ok(dict.into_any().unbind()) + } +} + +pub struct PyJsonSeed<'py>(pub Python<'py>); + +impl<'de, 'py> serde::de::DeserializeSeed<'de> for PyJsonSeed<'py> { + type Value = Py; + + fn deserialize(self, deserializer: D) -> Result + where + D: serde::de::Deserializer<'de>, + { + deserializer.deserialize_any(PyJsonVisitor(self.0)) + } +} + +/// Deserialize raw JSON bytes directly into Python objects (`dict`, `list`, `str`, `int`, +/// `float`, `bool`, `None`) in a single pass without intermediate `serde_json::Value` AST +/// allocations. +pub fn json_bytes_to_py(py: Python<'_>, bytes: &[u8]) -> Result, serde_json::Error> { + use serde::de::DeserializeSeed; + let mut de = serde_json::Deserializer::from_slice(bytes); + let val = PyJsonSeed(py).deserialize(&mut de)?; + de.end()?; + Ok(val) +} + fn write_py_json(obj: &Bound<'_, PyAny>, writer: &mut W, depth: usize) -> PyResult<()> { if depth > 128 { return Err(pyo3::exceptions::PyValueError::new_err( diff --git a/tests/test_validation.py b/tests/test_validation.py index d1cf68f..d744ca8 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -1,4 +1,5 @@ import asyncio +from typing import Any, ClassVar import httpx from oxyroute import App @@ -107,3 +108,88 @@ async def _run() -> None: up = seen["updated"] assert isinstance(up, UserBody) assert up.name == "David" + + +def test_model_validate_json_called_directly() -> None: + """Issue #255: verify Pydantic model_validate_json is called directly with raw bytes.""" + app = App() + + class SpyModel(BaseModel): + name: str + score: int + direct_bytes_called: ClassVar[bool] = False + + @classmethod + def model_validate_json(cls, json_data: Any, *args: Any, **kwargs: Any) -> Any: + cls.direct_bytes_called = True + assert isinstance(json_data, (bytes, bytearray)) + return super().model_validate_json(json_data, *args, **kwargs) + + @app.post("/spy", body_model=SpyModel) + def handle_spy(json: SpyModel) -> str: + return f"{json.name}:{json.score}" + + async def _run() -> None: + transport = httpx.ASGITransport(app=asgi_test_app(app)) + async with httpx.AsyncClient(transport=transport, base_url="http://test") as c: + r = await c.post("/spy", json={"name": "agent", "score": 100}) + assert r.status_code == 200, r.text + assert r.text == "agent:100" + + asyncio.run(_run()) + assert SpyModel.direct_bytes_called is True + + +def test_body_model_fallback_without_model_validate_json() -> None: + """Issue #255: fallback when model class does not have model_validate_json.""" + app = App() + + class LegacyValidator: + def __init__(self, data: dict[str, Any]) -> None: + self.data = data + + @classmethod + def model_validate(cls, data: Any) -> Any: + assert isinstance(data, dict) + return cls(data) + + @classmethod + def model_json_schema(cls) -> dict[str, Any]: + return {"type": "object"} + + @app.post("/legacy", body_model=LegacyValidator) + def handle_legacy(json: LegacyValidator) -> str: + return f"legacy:{json.data.get('k')}" + + async def _run() -> None: + transport = httpx.ASGITransport(app=asgi_test_app(app)) + async with httpx.AsyncClient(transport=transport, base_url="http://test") as c: + r = await c.post("/legacy", json={"k": "v1"}) + assert r.status_code == 200, r.text + assert r.text == "legacy:v1" + + asyncio.run(_run()) + + +def test_body_model_malformed_json_returns_422() -> None: + """Issue #255: malformed JSON to body_model endpoint returns 422 with json_invalid.""" + app = App() + + @app.post("/user", body_model=UserBody) + def create_user(json: UserBody) -> str: + return json.name + + async def _run() -> None: + transport = httpx.ASGITransport(app=asgi_test_app(app)) + async with httpx.AsyncClient(transport=transport, base_url="http://test") as c: + r = await c.post( + "/user", + content=b'{"name": "Alice", "age": }', + headers={"content-type": "application/json"}, + ) + assert r.status_code == 422 + data = r.json() + assert "detail" in data + assert any(d.get("type") == "json_invalid" for d in data["detail"]) + + asyncio.run(_run())