From 7a7fad93d676fddaff00ab5a4434e1365fc38731 Mon Sep 17 00:00:00 2001 From: ZhuchkaTriplesix Date: Sun, 18 Oct 2026 17:57:36 +0300 Subject: [PATCH] perf(dispatch): enable sync short-circuit for sync routes with path parameters --- src/dispatch.rs | 56 +++++++++++- src/lib.rs | 35 ++++++- tests/test_sync_rsgi_short_circuit.py | 126 ++++++++++++++++++++++++++ 3 files changed, 210 insertions(+), 7 deletions(-) diff --git a/src/dispatch.rs b/src/dispatch.rs index 62f9906..f25bf1f 100644 --- a/src/dispatch.rs +++ b/src/dispatch.rs @@ -218,6 +218,7 @@ fn run_trivial_sync_route( path: &str, is_head: bool, entry: &RouteEntry, + params: &matchit::Params<'_, '_>, scope: &pyo3::Bound<'_, PyAny>, state: &std::sync::Arc>, snapshot: &HotSnapshot, @@ -228,10 +229,54 @@ fn run_trivial_sync_route( entry.extra.path_template.clone(), ); let handler = entry.handler.bind(py); - let out = match handler.call0() { - Ok(x) => x.unbind(), - Err(e) => { - return send_python_error_sync(py, protocol, method, path, e, Some(scope), Some(state)); + let out = if params.is_empty() { + match handler.call0() { + Ok(x) => x.unbind(), + Err(e) => { + return send_python_error_sync( + py, + protocol, + method, + path, + e, + Some(scope), + Some(state), + ); + } + } + } else { + let kwargs = PyDict::new(py); + for (k, v) in params.iter() { + let vpy = if entry.extra.wildcard_params.contains(k) { + pyo3::types::PyString::new(py, v).into_any().unbind() + } else { + value_for_path_param(py, v) + }; + if let Err(e) = kwargs.set_item(k, vpy) { + return send_python_error_sync( + py, + protocol, + method, + path, + e, + Some(scope), + Some(state), + ); + } + } + match handler.call((), Some(&kwargs)) { + Ok(x) => x.unbind(), + Err(e) => { + return send_python_error_sync( + py, + protocol, + method, + path, + e, + Some(scope), + Some(state), + ); + } } }; let mapped = match map_handler_return(py, &out) { @@ -443,7 +488,7 @@ pub fn try_rsgi_sync_short_circuit<'py>( Some(m) => m, }; match route_out { - Some((idx, _)) => { + Some((idx, params)) => { let has_uncompiled_cfg = (snapshot.cors.is_some() && snapshot.compiled_cors.is_none()) || (snapshot.security_headers.is_some() && snapshot.compiled_security_headers.is_none()); @@ -462,6 +507,7 @@ pub fn try_rsgi_sync_short_circuit<'py>( path, is_head, entry, + ¶ms, scope, state, &snapshot, diff --git a/src/lib.rs b/src/lib.rs index 3a809ab..a68245d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -115,6 +115,29 @@ fn wildcard_param_names(path: &str) -> HashSet { out } +/// All parameter names (`:name` and `*name`) declared in a matchit-style route template. +fn all_path_param_names(path: &str) -> HashSet { + let mut out = HashSet::new(); + let chars: Vec = path.chars().collect(); + let mut i = 0; + while i < chars.len() { + if chars[i] == ':' || chars[i] == '*' { + i += 1; + let start = i; + while i < chars.len() && (chars[i].is_ascii_alphanumeric() || chars[i] == '_') { + i += 1; + } + let name: String = chars[start..i].iter().collect(); + if !name.is_empty() { + out.insert(name); + } + } else { + i += 1; + } + } + out +} + fn parse_algorithm(s: &str) -> PyResult { jsonwebtoken::Algorithm::from_str(s).map_err(|_| { pyo3::exceptions::PyValueError::new_err( @@ -484,13 +507,21 @@ impl App { .getattr(pyo3::intern!(py, "__name__"))? .extract()?; let (handler_param_names, handler_varkw) = handler_signature_kinds(py, handler.bind(py))?; + let path_params = all_path_param_names(&path); + let reserved_names = [ + "query", "request", "scope", "proto", "protocol", "body", "form", "files", "claims", + ]; + let has_reserved = handler_param_names + .iter() + .any(|n| reserved_names.contains(&n.as_str())); + let params_compatible = + !handler_varkw && !has_reserved && handler_param_names == path_params; let trivial_sync = !is_async && !require_jwt && !read_json_body && !read_form_body && dependencies.is_empty() - && !handler_varkw - && handler_param_names.is_empty() + && params_compatible && !has_rate_limit; let mut st = self.state.write(); let routes = Arc::make_mut(&mut st.routes); diff --git a/tests/test_sync_rsgi_short_circuit.py b/tests/test_sync_rsgi_short_circuit.py index 718e829..d3623b6 100644 --- a/tests/test_sync_rsgi_short_circuit.py +++ b/tests/test_sync_rsgi_short_circuit.py @@ -8,6 +8,7 @@ import asyncio import inspect from types import SimpleNamespace +from typing import Any from oxyroute import App @@ -19,6 +20,9 @@ def __init__(self) -> None: self.sent: list[tuple[int, str, str]] = [] self.headers: list[list[tuple[str, str]]] = [] + async def __call__(self) -> bytes: + return b"" + def response_str(self, status: int, headers: list, body: str) -> None: self.sent.append((status, body, "str")) self.headers.append(headers) @@ -193,3 +197,125 @@ def test_handle_rsgi_cors_preflight_on_sync_path() -> None: hdrs = {k.lower(): v for k, v in proto.headers[0]} assert hdrs.get("access-control-allow-origin") == "https://example.com" assert "POST" in hdrs.get("access-control-allow-methods", "") + + +def test_handle_rsgi_sync_route_with_path_param_short_circuits() -> None: + """Issue #254: sync routes with path parameters should short-circuit synchronously.""" + app = App() + + @app.get("/items/:id") + def get_item(id: int) -> str: + return f"item:{id}:{type(id).__name__}" + + scope = SimpleNamespace( + proto="http", + method="GET", + path="/items/123", + query_string="", + headers={}, + ) + proto = _ProtoText() + r = app.handle_rsgi(scope, proto) + assert r is None + assert not inspect.isawaitable(r) + assert proto.sent and proto.sent[0][0] == 200 + assert proto.sent[0][1] == "item:123:int" + + +def test_handle_rsgi_sync_route_with_multiple_path_params() -> None: + """Issue #254: sync routes with multiple path parameters.""" + app = App() + + @app.get("/users/:user_id/posts/:slug") + def get_post(user_id: int, slug: str) -> str: + return f"{user_id}/{slug}" + + scope = SimpleNamespace( + proto="http", + method="GET", + path="/users/99/posts/hello-world", + query_string="", + headers={}, + ) + proto = _ProtoText() + r = app.handle_rsgi(scope, proto) + assert r is None + assert not inspect.isawaitable(r) + assert proto.sent and proto.sent[0][0] == 200 + assert proto.sent[0][1] == "99/hello-world" + + +def test_handle_rsgi_sync_route_with_wildcard_param() -> None: + """Issue #254: sync routes with wildcard catch-all parameter (*path).""" + app = App() + + @app.get("/static/*filepath") + def static_file(filepath: str) -> str: + return f"file:{filepath}" + + scope = SimpleNamespace( + proto="http", + method="GET", + path="/static/css/main.css", + query_string="", + headers={}, + ) + proto = _ProtoText() + r = app.handle_rsgi(scope, proto) + assert r is None + assert not inspect.isawaitable(r) + assert proto.sent and proto.sent[0][0] == 200 + assert proto.sent[0][1] == "file:css/main.css" + + +def test_handle_rsgi_sync_route_with_varkw_defers_to_async() -> None: + """Issue #254: sync route with **kwargs defers to async to allow query/scope injection.""" + app = App() + + @app.get("/varkw/:id") + def varkw_handler(**kwargs: Any) -> str: + return f"id={kwargs['id']}" + + scope = SimpleNamespace( + proto="http", + method="GET", + path="/varkw/abc", + query_string="", + headers={}, + ) + proto = _ProtoText() + + async def check() -> None: + r = app.handle_rsgi(scope, proto) + assert inspect.isawaitable(r) + await r + assert proto.sent and proto.sent[0][0] == 200 + assert proto.sent[0][1] == "id=abc" + + asyncio.run(check()) + + +def test_handle_rsgi_sync_route_with_extra_query_param_defers_to_async() -> None: + """Issue #254: sync route with non-path parameter defers to async.""" + app = App() + + @app.get("/search/:category") + def search(category: str, q: str = "") -> str: + return f"{category}:{q}" + + scope = SimpleNamespace( + proto="http", + method="GET", + path="/search/books", + query_string="", + headers={}, + ) + proto = _ProtoText() + + async def check() -> None: + r = app.handle_rsgi(scope, proto) + assert inspect.isawaitable(r) + await r + assert proto.sent and proto.sent[0][0] == 200 + + asyncio.run(check())