Skip to content
Open
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
26 changes: 26 additions & 0 deletions integration_tests/base_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1636,6 +1636,32 @@ async def async_event_generator():
return SSEResponse(async_event_generator())


sse_disconnect_state = {"cleaned_up": False}


@app.get("/sse/disconnect_cleanup")
async def sse_disconnect_cleanup(request):
"""Endless async SSE stream with an awaiting ``finally``; a test disconnects
mid-stream and checks the cleanup still runs to completion."""
sse_disconnect_state["cleaned_up"] = False

async def event_generator():
try:
while True:
yield SSEMessage("tick")
await asyncio.sleep(0.05)
finally:
await asyncio.sleep(0) # async cleanup, e.g. `await session.close()`
sse_disconnect_state["cleaned_up"] = True

return SSEResponse(event_generator())


@app.get("/sse/disconnect_cleanup/status")
def sse_disconnect_cleanup_status():
return {"cleaned_up": sse_disconnect_state["cleaned_up"]}


@app.get("/stream/bytes")
def stream_bytes(request):
"""Stream raw binary chunks (sync generator) — regression test for #1236."""
Expand Down
17 changes: 17 additions & 0 deletions integration_tests/test_sse.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
import time

import pytest
import requests
Expand Down Expand Up @@ -148,6 +149,22 @@ def test_sse_async_endpoint(session):
assert f"Async message {i}" in data_lines


def test_sse_disconnect_runs_async_generator_cleanup(session):
"""A client disconnecting mid-stream must not skip ``await``s in the async
generator's ``finally`` (e.g. returning a DB connection to its pool)."""
with requests.get(f"{BASE_URL}/sse/disconnect_cleanup", stream=True, timeout=5) as response:
response.raise_for_status()
assert next(response.iter_lines(decode_unicode=True)) == "data: tick"
# Leaving the block closes the connection mid-stream.

deadline = time.time() + 5
while time.time() < deadline:
if requests.get(f"{BASE_URL}/sse/disconnect_cleanup/status", timeout=5).json()["cleaned_up"]:
return
time.sleep(0.1)
pytest.fail("async generator cleanup did not complete after the client disconnected")


@pytest.mark.benchmark
def test_sse_single_message(session):
"""Test SSE endpoint that sends only one message"""
Expand Down
30 changes: 18 additions & 12 deletions robyn/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,6 @@ def __init__(self, async_gen: AsyncGenerator[Union[str, bytes], None]):
self._exhausted = False
self._owns_loop = False
self._thread: Optional[threading.Thread] = None
self._finalizer: Optional[weakref.finalize] = None
try:
# Constructed inside an async handler -> reuse its running loop.
self._loop = asyncio.get_running_loop()
Expand All @@ -99,10 +98,13 @@ def __init__(self, async_gen: AsyncGenerator[Union[str, bytes], None]):
self._owns_loop = True
self._thread = threading.Thread(target=self._run_loop, args=(self._loop,), daemon=True)
self._thread.start()
# Guarantee the background loop is stopped even if iteration ends
# early (client disconnect, unsupported chunk type) and _finish() is
# never reached — otherwise the daemon loop thread would leak.
self._finalizer = weakref.finalize(self, self._stop_loop, self._loop)
# If iteration ends early (client disconnect, unsupported chunk type) and
# _finish() is never reached, close the generator on its loop so that
# ``await``s in its ``finally`` / ``async with`` cleanup can run, then
# stop the background loop if we own it. Otherwise the generator is
# finalized synchronously on whichever thread drops it, its cleanup
# aborts at the first ``await``, and an owned loop thread would leak.
self._finalizer = weakref.finalize(self, self._close, async_gen, self._loop, self._owns_loop)

@staticmethod
def _run_loop(loop):
Expand All @@ -113,9 +115,14 @@ def _run_loop(loop):
loop.close()

@staticmethod
def _stop_loop(loop):
if not loop.is_closed():
loop.call_soon_threadsafe(loop.stop)
def _close(async_gen, loop, owns_loop):
if loop.is_closed():
return
# Don't wait for the result: this can run on any thread, including the
# loop's own. aclose() is a no-op for an exhausted generator.
future = asyncio.run_coroutine_threadsafe(async_gen.aclose(), loop)
if owns_loop:
future.add_done_callback(lambda _: loop.call_soon_threadsafe(loop.stop))

def __iter__(self):
return self
Expand Down Expand Up @@ -143,10 +150,9 @@ def __next__(self):

def _finish(self):
self._exhausted = True
if self._finalizer is not None:
# Stops the background loop now; idempotent and also runs on GC if
# the stream is dropped before exhaustion.
self._finalizer()
# Stops the background loop now; idempotent and also runs on GC if the
# stream is dropped before exhaustion.
self._finalizer()


class StreamingResponse:
Expand Down
62 changes: 62 additions & 0 deletions unit_tests/test_streaming_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,65 @@ async def gen():

thread.join(timeout=3)
assert not thread.is_alive()


def test_abandoned_stream_runs_async_cleanup_on_handler_loop():
"""A client disconnect drops the wrapper before the generator is exhausted.
The generator's ``finally`` must still run to completion on the handler's
loop, including any ``await`` in it (e.g. returning a DB connection)."""

async def main():
handler_loop = asyncio.get_running_loop()
cleaned_up = asyncio.Event()
cleanup_loop = {}

async def gen():
try:
yield "a"
yield "b"
finally:
await asyncio.sleep(0) # async cleanup, e.g. `await session.close()`
cleanup_loop["loop"] = asyncio.get_running_loop()
cleaned_up.set()

holder = [AsyncGeneratorWrapper(gen())]

def consume_one_then_disconnect():
# Like the Rust driver: the worker thread holds the only reference
# and drops it after the client goes away.
wrapper = holder.pop()
assert next(wrapper) == "a"

await asyncio.to_thread(consume_one_then_disconnect)
await asyncio.wait_for(cleaned_up.wait(), timeout=3)
return handler_loop, cleanup_loop["loop"]

handler_loop, cleanup_loop = asyncio.run(main())
assert cleanup_loop is handler_loop


def test_abandoned_stream_runs_async_cleanup_on_background_loop():
"""Same as above for sync handlers: the generator's async cleanup completes
on the background loop before that loop is stopped."""
import gc
import threading

cleaned_up = threading.Event()

async def gen():
try:
yield "a"
yield "b"
finally:
await asyncio.sleep(0)
cleaned_up.set()

wrapper = AsyncGeneratorWrapper(gen()) # sync context -> owns a background loop
thread = wrapper._thread
assert next(wrapper) == "a"
del wrapper
gc.collect()

assert cleaned_up.wait(timeout=3)
thread.join(timeout=3)
assert not thread.is_alive()