Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 51 additions & 5 deletions src/dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<parking_lot::RwLock<crate::state::AppState>>,
snapshot: &HotSnapshot,
Expand All @@ -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) {
Expand Down Expand Up @@ -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());
Expand All @@ -462,6 +507,7 @@ pub fn try_rsgi_sync_short_circuit<'py>(
path,
is_head,
entry,
&params,
scope,
state,
&snapshot,
Expand Down
35 changes: 33 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,29 @@ fn wildcard_param_names(path: &str) -> HashSet<String> {
out
}

/// All parameter names (`:name` and `*name`) declared in a matchit-style route template.
fn all_path_param_names(path: &str) -> HashSet<String> {
let mut out = HashSet::new();
let chars: Vec<char> = 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> {
jsonwebtoken::Algorithm::from_str(s).map_err(|_| {
pyo3::exceptions::PyValueError::new_err(
Expand Down Expand Up @@ -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);
Expand Down
126 changes: 126 additions & 0 deletions tests/test_sync_rsgi_short_circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import asyncio
import inspect
from types import SimpleNamespace
from typing import Any

from oxyroute import App

Expand All @@ -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)
Expand Down Expand Up @@ -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())
Loading