diff --git a/oxyroute/_ws.py b/oxyroute/_ws.py new file mode 100644 index 0000000..91246c0 --- /dev/null +++ b/oxyroute/_ws.py @@ -0,0 +1,69 @@ +"""Internal asyncio coroutine helpers for native RSGI WebSocket transport. + +These coroutines run directly on Granian's Python asyncio event loop without +crossing the Tokio future bridge, avoiding task scheduling and context switching +overhead on every WebSocket frame (issue #257). +""" + +from __future__ import annotations + +import json +from typing import Any + + +async def ws_accept(proto: Any, ws: Any) -> None: + transport = await proto.accept() + ws._set_transport(transport) + + +async def ws_receive(transport: Any, ws: Any) -> Any: + msg = await transport.receive() + if msg.kind == 0: + ws._mark_closed() + raise RuntimeError("WebSocket closed by peer") + return msg.data + + +async def ws_receive_text(transport: Any, ws: Any) -> str: + msg = await transport.receive() + if msg.kind == 0: + ws._mark_closed() + raise RuntimeError("WebSocket closed by peer") + if msg.kind != 2: + raise ValueError("expected text frame") + if not isinstance(msg.data, str): + raise ValueError("expected text frame") + return msg.data + + +async def ws_receive_bytes(transport: Any, ws: Any) -> bytes: + msg = await transport.receive() + if msg.kind == 0: + ws._mark_closed() + raise RuntimeError("WebSocket closed by peer") + if msg.kind != 1: + raise ValueError("expected binary frame") + data = msg.data + if not isinstance(data, (bytes, bytearray, memoryview)): + raise ValueError("expected binary frame") + return bytes(data) if not isinstance(data, bytes) else data + + +async def ws_send_text(transport: Any, lock: Any, data: str) -> None: + async with lock: + await transport.send_str(data) + + +async def ws_send_bytes(transport: Any, lock: Any, data: bytes) -> None: + async with lock: + await transport.send_bytes(data) + + +async def ws_send_json(transport: Any, lock: Any, data: Any) -> None: + dumped = json.dumps(data) + async with lock: + await transport.send_str(dumped) + + +async def ws_close_noop() -> None: + return None diff --git a/src/dispatch.rs b/src/dispatch.rs index d2082ea..e03a568 100644 --- a/src/dispatch.rs +++ b/src/dispatch.rs @@ -2113,7 +2113,7 @@ async fn run_rsgi_websocket( }; let call_result = Python::with_gil(|py| -> PyResult<(PyObject, bool)> { - let ws = WebSocket::new(protocol.clone_ref(py), scope.clone_ref(py), path_params); + let ws = WebSocket::new(py, protocol.clone_ref(py), scope.clone_ref(py), path_params)?; let py_ws = Py::new(py, ws)?; let res = handler.bind(py).call1((py_ws,))?.unbind(); Ok((res, is_async)) diff --git a/src/websocket.rs b/src/websocket.rs index d41830d..983139c 100644 --- a/src/websocket.rs +++ b/src/websocket.rs @@ -7,11 +7,45 @@ //! it would have awaited natively — no extra Tokio future bridge, no scheduling cost. //! //! [1]: https://github.com/emmett-framework/granian — see `granian/rsgi.py`. -use std::sync::Arc; +use std::sync::OnceLock; use parking_lot::Mutex; use pyo3::prelude::*; -use pyo3::types::{PyBytes, PyDict, PyString, PyTuple}; +use pyo3::types::PyDict; + +struct WsHelpers { + accept: Py, + receive: Py, + receive_text: Py, + receive_bytes: Py, + send_text: Py, + send_bytes: Py, + send_json: Py, + close_noop: Py, +} + +static WS_HELPERS: OnceLock = OnceLock::new(); + +impl WsHelpers { + fn get(py: Python<'_>) -> PyResult<&'static WsHelpers> { + if let Some(helpers) = WS_HELPERS.get() { + return Ok(helpers); + } + let m = py.import("oxyroute._ws")?; + let helpers = WsHelpers { + accept: m.getattr("ws_accept")?.unbind(), + receive: m.getattr("ws_receive")?.unbind(), + receive_text: m.getattr("ws_receive_text")?.unbind(), + receive_bytes: m.getattr("ws_receive_bytes")?.unbind(), + send_text: m.getattr("ws_send_text")?.unbind(), + send_bytes: m.getattr("ws_send_bytes")?.unbind(), + send_json: m.getattr("ws_send_json")?.unbind(), + close_noop: m.getattr("ws_close_noop")?.unbind(), + }; + let _ = WS_HELPERS.set(helpers); + Ok(WS_HELPERS.get().expect("just set")) + } +} /// Thin async wrapper around a Granian RSGI WebSocket connection. /// @@ -28,37 +62,45 @@ use pyo3::types::{PyBytes, PyDict, PyString, PyTuple}; pub struct WebSocket { protocol: Py, scope: Py, - transport: Arc>>>, + transport: Mutex>>, path_params: Vec<(String, String)>, - closed: Arc>, - write_lock: Arc>, + closed: Mutex, + write_lock: Py, } impl WebSocket { - pub fn new(protocol: Py, scope: Py, path_params: Vec<(String, String)>) -> Self { - Self { + pub fn new( + py: Python<'_>, + protocol: Py, + scope: Py, + path_params: Vec<(String, String)>, + ) -> PyResult { + let asyncio = py.import("asyncio")?; + let write_lock = asyncio.call_method0("Lock")?.unbind(); + Ok(Self { protocol, scope, - transport: Arc::new(Mutex::new(None)), + transport: Mutex::new(None), path_params, - closed: Arc::new(Mutex::new(false)), - write_lock: Arc::new(tokio::sync::Mutex::new(())), - } - } - - fn transport_clone(&self, py: Python<'_>) -> PyResult> { - let g = self.transport.lock(); - match g.as_ref() { - Some(t) => Ok(t.clone_ref(py)), - None => Err(pyo3::exceptions::PyRuntimeError::new_err( - "WebSocket: call accept() before send/receive", - )), - } + closed: Mutex::new(false), + write_lock, + }) } } #[pymethods] impl WebSocket { + #[new] + #[pyo3(signature = (protocol, scope, path_params=None))] + fn py_new( + py: Python<'_>, + protocol: Py, + scope: Py, + path_params: Option>, + ) -> PyResult { + Self::new(py, protocol, scope, path_params.unwrap_or_default()) + } + /// The Granian RSGI scope (proto = ``"websocket"``). #[getter] fn scope(&self, py: Python<'_>) -> Py { @@ -91,173 +133,148 @@ impl WebSocket { Ok(crate::params::header_get_lax(&headers, "origin")) } + /// Internal callback from `ws_accept` coroutine to store the Granian transport. + fn _set_transport(&self, transport: Py) { + *self.transport.lock() = Some(transport); + } + + /// Internal callback from `ws_receive_*` coroutines when close frame (kind = 0) is encountered. + fn _mark_closed(&self) { + *self.closed.lock() = true; + } + /// Perform the handshake. Stores the transport for subsequent send/receive calls. - fn accept<'py>(&self, py: Python<'py>) -> PyResult> { - let proto = self.protocol.clone_ref(py); - let transport_slot = self.transport.clone(); - let coro = proto.bind(py).call_method0("accept")?; - let fut = pyo3_async_runtimes::tokio::into_future(coro)?; - pyo3_async_runtimes::tokio::future_into_py(py, async move { - let result = fut.await?; - Python::with_gil(|py| { - *transport_slot.lock() = Some(result); - Ok(py.None()) - }) - }) + fn accept<'py>(this: Bound<'py, Self>) -> PyResult> { + let py = this.py(); + let proto = this.borrow().protocol.clone_ref(py); + let helpers = WsHelpers::get(py)?; + helpers.accept.bind(py).call1((proto, this)) } /// Receive the next WebSocket message; returns ``str`` or ``bytes``. Raises ``RuntimeError`` /// if the peer has closed the connection (Granian close kind = 0). - fn receive<'py>(&self, py: Python<'py>) -> PyResult> { - let transport = self.transport_clone(py)?; - let coro = transport.bind(py).call_method0("receive")?; - let fut = pyo3_async_runtimes::tokio::into_future(coro)?; - let closed_flag = self.closed.clone(); - pyo3_async_runtimes::tokio::future_into_py(py, async move { - let msg = fut.await?; - Python::with_gil(|py| -> PyResult> { - let m = msg.bind(py); - let kind: i64 = m.getattr("kind")?.extract()?; - if kind == 0 { - *closed_flag.lock() = true; - return Err(pyo3::exceptions::PyRuntimeError::new_err( - "WebSocket closed by peer", - )); - } - let data = m.getattr("data")?; - Ok(data.unbind()) - }) - }) + fn receive<'py>(this: Bound<'py, Self>) -> PyResult> { + let py = this.py(); + let transport = this + .borrow() + .transport + .lock() + .as_ref() + .map(|t| t.clone_ref(py)); + let transport = match transport { + Some(t) => t, + None => { + return Err(pyo3::exceptions::PyRuntimeError::new_err( + "WebSocket: call accept() before send/receive", + )); + } + }; + let helpers = WsHelpers::get(py)?; + helpers.receive.bind(py).call1((transport, this)) } /// Receive the next message as ``str``; raises ``ValueError`` if a binary frame arrives. - fn receive_text<'py>(&self, py: Python<'py>) -> PyResult> { - let transport = self.transport_clone(py)?; - let coro = transport.bind(py).call_method0("receive")?; - let fut = pyo3_async_runtimes::tokio::into_future(coro)?; - let closed_flag = self.closed.clone(); - pyo3_async_runtimes::tokio::future_into_py(py, async move { - let msg = fut.await?; - Python::with_gil(|py| -> PyResult> { - let m = msg.bind(py); - let kind: i64 = m.getattr("kind")?.extract()?; - if kind == 0 { - *closed_flag.lock() = true; - return Err(pyo3::exceptions::PyRuntimeError::new_err( - "WebSocket closed by peer", - )); - } - if kind != 2 { - return Err(pyo3::exceptions::PyValueError::new_err( - "expected text frame", - )); - } - let data = m.getattr("data")?; - let s = data.downcast::()?; - Ok(s.clone().unbind().into()) - }) - }) + fn receive_text<'py>(this: Bound<'py, Self>) -> PyResult> { + let py = this.py(); + let transport = this + .borrow() + .transport + .lock() + .as_ref() + .map(|t| t.clone_ref(py)); + let transport = match transport { + Some(t) => t, + None => { + return Err(pyo3::exceptions::PyRuntimeError::new_err( + "WebSocket: call accept() before send/receive", + )); + } + }; + let helpers = WsHelpers::get(py)?; + helpers.receive_text.bind(py).call1((transport, this)) } /// Receive the next message as ``bytes``; raises ``ValueError`` if a text frame arrives. - fn receive_bytes<'py>(&self, py: Python<'py>) -> PyResult> { - let transport = self.transport_clone(py)?; - let coro = transport.bind(py).call_method0("receive")?; - let fut = pyo3_async_runtimes::tokio::into_future(coro)?; - let closed_flag = self.closed.clone(); - pyo3_async_runtimes::tokio::future_into_py(py, async move { - let msg = fut.await?; - Python::with_gil(|py| -> PyResult> { - let m = msg.bind(py); - let kind: i64 = m.getattr("kind")?.extract()?; - if kind == 0 { - *closed_flag.lock() = true; - return Err(pyo3::exceptions::PyRuntimeError::new_err( - "WebSocket closed by peer", - )); - } - if kind != 1 { - return Err(pyo3::exceptions::PyValueError::new_err( - "expected binary frame", - )); - } - let data = m.getattr("data")?; - let b = data.downcast::()?; - Ok(b.clone().unbind().into()) - }) - }) + fn receive_bytes<'py>(this: Bound<'py, Self>) -> PyResult> { + let py = this.py(); + let transport = this + .borrow() + .transport + .lock() + .as_ref() + .map(|t| t.clone_ref(py)); + let transport = match transport { + Some(t) => t, + None => { + return Err(pyo3::exceptions::PyRuntimeError::new_err( + "WebSocket: call accept() before send/receive", + )); + } + }; + let helpers = WsHelpers::get(py)?; + helpers.receive_bytes.bind(py).call1((transport, this)) } /// Send a text frame. Concurrent send calls are serialized to prevent frame interleaving. fn send_text<'py>(&self, py: Python<'py>, data: String) -> PyResult> { - let transport_slot = self.transport.clone(); - let write_lock = self.write_lock.clone(); - pyo3_async_runtimes::tokio::future_into_py(py, async move { - let _guard = write_lock.lock().await; - let fut = Python::with_gil(|py| -> PyResult<_> { - let g = transport_slot.lock(); - let transport = g.as_ref().ok_or_else(|| { - pyo3::exceptions::PyRuntimeError::new_err( - "WebSocket: call accept() before send/receive", - ) - })?; - let coro = transport - .bind(py) - .call_method1("send_str", PyTuple::new(py, [data])?)?; - pyo3_async_runtimes::tokio::into_future(coro) - })?; - fut.await?; - Python::with_gil(|py| Ok(py.None())) - }) + let transport = self.transport.lock().as_ref().map(|t| t.clone_ref(py)); + let transport = match transport { + Some(t) => t, + None => { + return Err(pyo3::exceptions::PyRuntimeError::new_err( + "WebSocket: call accept() before send/receive", + )); + } + }; + let helpers = WsHelpers::get(py)?; + helpers + .send_text + .bind(py) + .call1((transport, self.write_lock.clone_ref(py), data)) } /// Send a binary frame. Concurrent send calls are serialized to prevent frame interleaving. - fn send_bytes<'py>(&self, py: Python<'py>, data: Vec) -> PyResult> { - let transport_slot = self.transport.clone(); - let write_lock = self.write_lock.clone(); - pyo3_async_runtimes::tokio::future_into_py(py, async move { - let _guard = write_lock.lock().await; - let fut = Python::with_gil(|py| -> PyResult<_> { - let g = transport_slot.lock(); - let transport = g.as_ref().ok_or_else(|| { - pyo3::exceptions::PyRuntimeError::new_err( - "WebSocket: call accept() before send/receive", - ) - })?; - let pb = PyBytes::new(py, &data); - let coro = transport - .bind(py) - .call_method1("send_bytes", PyTuple::new(py, [pb])?)?; - pyo3_async_runtimes::tokio::into_future(coro) - })?; - fut.await?; - Python::with_gil(|py| Ok(py.None())) - }) + fn send_bytes<'py>( + &self, + py: Python<'py>, + data: Bound<'py, PyAny>, + ) -> PyResult> { + let transport = self.transport.lock().as_ref().map(|t| t.clone_ref(py)); + let transport = match transport { + Some(t) => t, + None => { + return Err(pyo3::exceptions::PyRuntimeError::new_err( + "WebSocket: call accept() before send/receive", + )); + } + }; + let helpers = WsHelpers::get(py)?; + helpers + .send_bytes + .bind(py) + .call1((transport, self.write_lock.clone_ref(py), data)) } /// Send a JSON-serialised object as a text frame. Concurrent send calls are serialized. - fn send_json<'py>(&self, py: Python<'py>, data: Py) -> PyResult> { - let transport_slot = self.transport.clone(); - let write_lock = self.write_lock.clone(); - pyo3_async_runtimes::tokio::future_into_py(py, async move { - let _guard = write_lock.lock().await; - let fut = Python::with_gil(|py| -> PyResult<_> { - let g = transport_slot.lock(); - let transport = g.as_ref().ok_or_else(|| { - pyo3::exceptions::PyRuntimeError::new_err( - "WebSocket: call accept() before send/receive", - ) - })?; - let json_mod = py.import("json")?; - let dumped = json_mod.call_method1("dumps", (data.bind(py),))?; - let coro = transport - .bind(py) - .call_method1("send_str", PyTuple::new(py, [dumped])?)?; - pyo3_async_runtimes::tokio::into_future(coro) - })?; - fut.await?; - Python::with_gil(|py| Ok(py.None())) - }) + fn send_json<'py>( + &self, + py: Python<'py>, + data: Bound<'py, PyAny>, + ) -> PyResult> { + let transport = self.transport.lock().as_ref().map(|t| t.clone_ref(py)); + let transport = match transport { + Some(t) => t, + None => { + return Err(pyo3::exceptions::PyRuntimeError::new_err( + "WebSocket: call accept() before send/receive", + )); + } + }; + let helpers = WsHelpers::get(py)?; + helpers + .send_json + .bind(py) + .call1((transport, self.write_lock.clone_ref(py), data)) } /// Close the connection. ``code`` defaults to 1000 (normal closure). @@ -283,8 +300,7 @@ impl WebSocket { e }); } - pyo3_async_runtimes::tokio::future_into_py(py, async { - Python::with_gil(|py| Ok(py.None())) - }) + let helpers = WsHelpers::get(py)?; + helpers.close_noop.bind(py).call0() } } diff --git a/tests/test_granian_e2e.py b/tests/test_granian_e2e.py index baddb43..7ce4bb3 100644 --- a/tests/test_granian_e2e.py +++ b/tests/test_granian_e2e.py @@ -219,6 +219,12 @@ def echo(json: dict) -> str: with httpx.Client(timeout=1.0) as c: r = c.post(f"http://127.0.0.1:{port}/echo", json={"n": 42}) if r.status_code == 200 and r.text == "n:42": + for _ in range(50): + if os.path.exists(log_file): + with open(log_file, encoding="utf-8") as lf: + if "200:/echo" in lf.read(): + return + time.sleep(0.05) with open(log_file, encoding="utf-8") as lf: lines = lf.read() assert "200:/echo" in lines