Skip to content

Add an explicit HTTP input closed event #94

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 5, 2025
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
9 changes: 1 addition & 8 deletions python/restate/server_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,14 +318,7 @@ async def leave(self):
# {'type': 'http.request', 'body': b'', 'more_body': True}
# {'type': 'http.request', 'body': b'', 'more_body': False}
# {'type': 'http.disconnect'}
while True:
event = await self.receive()
if event is None:
break
if event.get('type') == 'http.disconnect':
break
if event.get('type') == 'http.request' and event.get('more_body', False) is False:
break
await self.receive.block_until_http_input_closed()
# finally, we close our side
# it is important to do it, after the other side has closed his side,
# because some asgi servers (like hypercorn) will remove the stream
Expand Down
17 changes: 14 additions & 3 deletions python/restate/server_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,14 +98,19 @@ class ReceiveChannel:

def __init__(self, receive: Receive) -> None:
self._queue = asyncio.Queue[Union[ASGIReceiveEvent, RestateEvent]]()
self._http_input_closed = asyncio.Event()
self._disconnected = asyncio.Event()

async def loop():
"""Receive loop."""
while True:
while not self._disconnected.is_set():
event = await receive()
if event.get('type') == 'http.request' and not event.get('more_body', False):
self._http_input_closed.set()
elif event.get('type') == 'http.disconnect':
self._http_input_closed.set()
self._disconnected.set()
await self._queue.put(event)
if event.get('type') == 'http.disconnect':
break

self._task = asyncio.create_task(loop())

Expand All @@ -115,12 +120,18 @@ async def __call__(self) -> ASGIReceiveEvent | RestateEvent:
self._queue.task_done()
return what

async def block_until_http_input_closed(self) -> None:
"""Wait until the HTTP input is closed"""
await self._http_input_closed.wait()

async def enqueue_restate_event(self, what: RestateEvent):
"""Add a message."""
await self._queue.put(what)

async def close(self):
"""Close the channel."""
self._http_input_closed.set()
self._disconnected.set()
if self._task.done():
return
self._task.cancel()
Expand Down