-
Notifications
You must be signed in to change notification settings - Fork 3.2k
refactor: connect-first stream lifecycle for sse and streamable_http #2292
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
Open
maxisbey
wants to merge
1
commit into
main
Choose a base branch
from
marcelo-async-with-followup
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+144
−150
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -57,108 +57,107 @@ async def sse_client( | |
| write_stream: MemoryObjectSendStream[SessionMessage] | ||
| write_stream_reader: MemoryObjectReceiveStream[SessionMessage] | ||
|
|
||
| read_stream_writer, read_stream = anyio.create_memory_object_stream(0) | ||
| write_stream, write_stream_reader = anyio.create_memory_object_stream(0) | ||
|
|
||
| async with anyio.create_task_group() as tg: | ||
| try: | ||
| logger.debug(f"Connecting to SSE endpoint: {remove_request_params(url)}") | ||
| async with httpx_client_factory( | ||
| headers=headers, auth=auth, timeout=httpx.Timeout(timeout, read=sse_read_timeout) | ||
| ) as client: | ||
| async with aconnect_sse( | ||
| client, | ||
| "GET", | ||
| url, | ||
| ) as event_source: | ||
| event_source.response.raise_for_status() | ||
| logger.debug("SSE connection established") | ||
|
|
||
| async def sse_reader(task_status: TaskStatus[str] = anyio.TASK_STATUS_IGNORED): | ||
| try: | ||
| async for sse in event_source.aiter_sse(): # pragma: no branch | ||
| logger.debug(f"Received SSE event: {sse.event}") | ||
| match sse.event: | ||
| case "endpoint": | ||
| endpoint_url = urljoin(url, sse.data) | ||
| logger.debug(f"Received endpoint URL: {endpoint_url}") | ||
|
|
||
| url_parsed = urlparse(url) | ||
| endpoint_parsed = urlparse(endpoint_url) | ||
| if ( # pragma: no cover | ||
| url_parsed.netloc != endpoint_parsed.netloc | ||
| or url_parsed.scheme != endpoint_parsed.scheme | ||
| ): | ||
| error_msg = ( # pragma: no cover | ||
| f"Endpoint origin does not match connection origin: {endpoint_url}" | ||
| ) | ||
| logger.error(error_msg) # pragma: no cover | ||
| raise ValueError(error_msg) # pragma: no cover | ||
|
|
||
| if on_session_created: | ||
| session_id = _extract_session_id_from_endpoint(endpoint_url) | ||
| if session_id: | ||
| on_session_created(session_id) | ||
|
|
||
| task_status.started(endpoint_url) | ||
|
|
||
| case "message": | ||
| # Skip empty data (keep-alive pings) | ||
| if not sse.data: | ||
| continue | ||
| try: | ||
| message = types.jsonrpc_message_adapter.validate_json( | ||
| sse.data, by_name=False | ||
| ) | ||
| logger.debug(f"Received server message: {message}") | ||
| except Exception as exc: # pragma: no cover | ||
| logger.exception("Error parsing server message") # pragma: no cover | ||
| await read_stream_writer.send(exc) # pragma: no cover | ||
| continue # pragma: no cover | ||
|
|
||
| session_message = SessionMessage(message) | ||
| await read_stream_writer.send(session_message) | ||
| case _: # pragma: no cover | ||
| logger.warning(f"Unknown SSE event: {sse.event}") # pragma: no cover | ||
| except SSEError as sse_exc: # pragma: lax no cover | ||
| logger.exception("Encountered SSE exception") | ||
| raise sse_exc | ||
| except Exception as exc: # pragma: lax no cover | ||
| logger.exception("Error in sse_reader") | ||
| await read_stream_writer.send(exc) | ||
| finally: | ||
| await read_stream_writer.aclose() | ||
|
|
||
| async def post_writer(endpoint_url: str): | ||
| try: | ||
| async with write_stream_reader: | ||
| async for session_message in write_stream_reader: | ||
| logger.debug(f"Sending client message: {session_message}") | ||
| response = await client.post( | ||
| endpoint_url, | ||
| json=session_message.message.model_dump( | ||
| by_alias=True, | ||
| mode="json", | ||
| exclude_unset=True, | ||
| ), | ||
| logger.debug(f"Connecting to SSE endpoint: {remove_request_params(url)}") | ||
| async with httpx_client_factory( | ||
| headers=headers, auth=auth, timeout=httpx.Timeout(timeout, read=sse_read_timeout) | ||
| ) as client: | ||
| async with aconnect_sse( | ||
| client, | ||
| "GET", | ||
| url, | ||
| ) as event_source: | ||
| event_source.response.raise_for_status() | ||
| logger.debug("SSE connection established") | ||
|
|
||
| read_stream_writer, read_stream = anyio.create_memory_object_stream(0) | ||
| write_stream, write_stream_reader = anyio.create_memory_object_stream(0) | ||
|
|
||
| async def sse_reader(task_status: TaskStatus[str] = anyio.TASK_STATUS_IGNORED): | ||
| try: | ||
| async for sse in event_source.aiter_sse(): # pragma: no branch | ||
| logger.debug(f"Received SSE event: {sse.event}") | ||
| match sse.event: | ||
| case "endpoint": | ||
| endpoint_url = urljoin(url, sse.data) | ||
| logger.debug(f"Received endpoint URL: {endpoint_url}") | ||
|
|
||
| url_parsed = urlparse(url) | ||
| endpoint_parsed = urlparse(endpoint_url) | ||
| if ( # pragma: no cover | ||
| url_parsed.netloc != endpoint_parsed.netloc | ||
| or url_parsed.scheme != endpoint_parsed.scheme | ||
| ): | ||
| error_msg = ( # pragma: no cover | ||
| f"Endpoint origin does not match connection origin: {endpoint_url}" | ||
| ) | ||
| response.raise_for_status() | ||
| logger.debug(f"Client message sent successfully: {response.status_code}") | ||
| except Exception: # pragma: lax no cover | ||
| logger.exception("Error in post_writer") | ||
| finally: | ||
| await write_stream.aclose() | ||
|
|
||
| endpoint_url = await tg.start(sse_reader) | ||
| logger.debug(f"Starting post writer with endpoint URL: {endpoint_url}") | ||
| tg.start_soon(post_writer, endpoint_url) | ||
|
|
||
| try: | ||
| yield read_stream, write_stream | ||
| finally: | ||
| tg.cancel_scope.cancel() | ||
| finally: | ||
| await read_stream_writer.aclose() | ||
| await write_stream.aclose() | ||
| await read_stream.aclose() | ||
| await write_stream_reader.aclose() | ||
| logger.error(error_msg) # pragma: no cover | ||
| raise ValueError(error_msg) # pragma: no cover | ||
|
|
||
| if on_session_created: | ||
| session_id = _extract_session_id_from_endpoint(endpoint_url) | ||
| if session_id: | ||
| on_session_created(session_id) | ||
|
|
||
| task_status.started(endpoint_url) | ||
|
|
||
| case "message": | ||
| # Skip empty data (keep-alive pings) | ||
| if not sse.data: | ||
| continue | ||
| try: | ||
| message = types.jsonrpc_message_adapter.validate_json(sse.data, by_name=False) | ||
| logger.debug(f"Received server message: {message}") | ||
| except Exception as exc: # pragma: no cover | ||
| logger.exception("Error parsing server message") # pragma: no cover | ||
| await read_stream_writer.send(exc) # pragma: no cover | ||
| continue # pragma: no cover | ||
|
|
||
| session_message = SessionMessage(message) | ||
| await read_stream_writer.send(session_message) | ||
| case _: # pragma: no cover | ||
| logger.warning(f"Unknown SSE event: {sse.event}") # pragma: no cover | ||
| except SSEError as sse_exc: # pragma: lax no cover | ||
| logger.exception("Encountered SSE exception") | ||
| raise sse_exc | ||
| except Exception as exc: # pragma: lax no cover | ||
| logger.exception("Error in sse_reader") | ||
| await read_stream_writer.send(exc) | ||
| finally: | ||
| await read_stream_writer.aclose() | ||
|
Comment on lines
+125
to
+126
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is this still neecessary? |
||
|
|
||
| async def post_writer(endpoint_url: str): | ||
| try: | ||
| async with write_stream_reader: | ||
| async for session_message in write_stream_reader: | ||
| logger.debug(f"Sending client message: {session_message}") | ||
| response = await client.post( | ||
| endpoint_url, | ||
| json=session_message.message.model_dump( | ||
| by_alias=True, | ||
| mode="json", | ||
| exclude_unset=True, | ||
| ), | ||
| ) | ||
| response.raise_for_status() | ||
| logger.debug(f"Client message sent successfully: {response.status_code}") | ||
| except Exception: # pragma: lax no cover | ||
| logger.exception("Error in post_writer") | ||
| finally: | ||
| await write_stream.aclose() | ||
|
|
||
| # On Python 3.14, coverage.py reports a phantom branch arc on this | ||
| # line (->yield) when nested two async-with levels deep. The branch | ||
| # is the unreachable "did __aexit__ suppress?" arm for memory streams. | ||
| async with ( # pragma: no branch | ||
| read_stream_writer, | ||
| read_stream, | ||
| write_stream, | ||
| write_stream_reader, | ||
| anyio.create_task_group() as tg, | ||
| ): | ||
| endpoint_url = await tg.start(sse_reader) | ||
| logger.debug(f"Starting post writer with endpoint URL: {endpoint_url}") | ||
| tg.start_soon(post_writer, endpoint_url) | ||
|
|
||
| yield read_stream, write_stream | ||
| tg.cancel_scope.cancel() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.