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
53 changes: 52 additions & 1 deletion oxyroute/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,38 @@ def _unwrap_dep(f: Dep) -> Any:
return f


class _ProtocolWrapper:
__slots__ = ("__oxyroute_path_template__", "_inner", "status")

def __init__(self, inner: Any) -> None:
self._inner = inner
self.status: int = 500
self.__oxyroute_path_template__: str = ""

def __oxyroute_set_path_template__(self, template: str) -> None:
self.__oxyroute_path_template__ = template

def response_empty(self, status: int, headers: list[tuple[str, str]]) -> None:
self.status = status
self._inner.response_empty(status, headers)

def response_str(self, status: int, headers: list[tuple[str, str]], body: str) -> None:
self.status = status
self._inner.response_str(status, headers, body)

def response_bytes(self, status: int, headers: list[tuple[str, str]], body: bytes) -> None:
self.status = status
self._inner.response_bytes(status, headers, body)

def response_file(self, status: int, headers: list[tuple[str, str]], file_path: str) -> None:
self.status = status
self._inner.response_file(status, headers, file_path)

def response_stream(self, status: int, headers: list[tuple[str, str]]) -> Any:
self.status = status
return self._inner.response_stream(status, headers)


def _norm_dependencies(
deps: list[tuple[str, Dep]] | None,
) -> list[tuple[str, Any]] | None:
Expand All @@ -43,10 +75,17 @@ class App:
Granian worker processes.
"""

def __init__(self, title: str = "OxyRoute", *, include_openapi: bool = True) -> None:
def __init__(
self,
title: str = "OxyRoute",
*,
include_openapi: bool = True,
access_log_hook: Callable[[Any, int, float, str], None] | None = None,
) -> None:
self._app = _oxyroute.App(include_openapi=include_openapi)
self._app.set_openapi_title(title)
self.title = title
self.access_log_hook = access_log_hook
# Per-process mutable bag for ``__rsgi_init__`` / factory setup (DB pool, clients, …).
self.state: SimpleNamespace = SimpleNamespace()

Expand Down Expand Up @@ -413,6 +452,18 @@ async def __rsgi__(self, scope: Any, protocol: Any) -> Any:
Granian awaits this coroutine. Native ``handle_rsgi`` may return ``None`` immediately
(sync short-circuit for openapi / 404 / 405) or an awaitable (full async path).
"""
if self.access_log_hook:
import time

start = time.perf_counter_ns()
p = _ProtocolWrapper(protocol)
r = self._app.handle_rsgi(scope, p)
if r is not None and inspect.isawaitable(r):
await r
dur = (time.perf_counter_ns() - start) / 1000000.0
self.access_log_hook(scope, p.status, dur, p.__oxyroute_path_template__)
return r

r = self._app.handle_rsgi(scope, protocol)
if r is None or not inspect.isawaitable(r):
return r
Expand Down
18 changes: 18 additions & 0 deletions src/dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,11 @@ fn run_trivial_sync_route(
scope: &pyo3::Bound<'_, PyAny>,
state: &std::sync::Arc<parking_lot::RwLock<crate::state::AppState>>,
) -> PyResult<()> {
let _ = protocol.setattr(
py,
"__oxyroute_path_template__",
entry.path_template.clone(),
);
let handler = entry.handler.bind(py);
let out = match handler.call0() {
Ok(x) => x.unbind(),
Expand Down Expand Up @@ -348,6 +353,7 @@ pub fn try_rsgi_sync_short_circuit(
}
if (method == "GET" || method == "HEAD") && path == "/openapi.json" && snapshot.include_openapi
{
let _ = protocol_py.setattr(py, "__oxyroute_path_template__", "/openapi.json");
let doc = state.read().openapi.lock().to_string();
if is_head {
response::send_head_simple_sync(
Expand Down Expand Up @@ -475,6 +481,9 @@ pub async fn run_rsgi(
});
if (method == "GET" || method == "HEAD") && path == "/openapi.json" && snapshot.include_openapi
{
let _ = Python::with_gil(|py| {
protocol.setattr(py, "__oxyroute_path_template__", "/openapi.json")
});
let doc = state.read().openapi.lock().to_string();
if is_head {
return response::send_head_simple(
Expand All @@ -489,6 +498,8 @@ pub async fn run_rsgi(
}
// Prototype: Issue 55 (sqlx integration benchmark path)
if method == "GET" && path == "/test_db" {
let _ =
Python::with_gil(|py| protocol.setattr(py, "__oxyroute_path_template__", "/test_db"));
if let Some(pool) = snapshot.db_pool.as_ref() {
use sqlx::Row;
match sqlx::query("SELECT 1 as num").fetch_one(pool).await {
Expand Down Expand Up @@ -677,6 +688,13 @@ pub async fn run_rsgi(
})?;
let may_need_raw_body = handler_varkw || handler_param_names.contains("body");
let should_read_body = read_json_body || read_form_body || may_need_raw_body;
let _ = Python::with_gil(|py| {
protocol.setattr(
py,
"__oxyroute_path_template__",
routes_arc[route_idx].path_template.clone(),
)
});
let mut body_bytes: Vec<u8> = if should_read_body {
let read_fut = Python::with_gil(|py| {
let p = protocol.bind(py);
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,7 @@ impl App {
let routes = Arc::make_mut(&mut st.routes);
let idx = routes.len();
routes.push(state::RouteEntry {
path_template: path.to_string(),
handler,
is_async,
require_jwt,
Expand Down
1 change: 1 addition & 0 deletions src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ pub struct WebsocketRoute {

#[derive(Clone)]
pub struct RouteEntry {
pub path_template: String,
pub handler: Py<PyAny>,
pub is_async: bool,
pub require_jwt: bool,
Expand Down
Loading