-
Notifications
You must be signed in to change notification settings - Fork 198
Raise StreamDisconnectedError on SSE error frames #596
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
mistralai-nfau
wants to merge
7
commits into
main
Choose a base branch
from
nicolasfaurie/wfl-1679-python-sdk-raise-streamdisconnectederror-on-sse-error-frames
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.
+467
−1
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
77bcbe7
feat(workflows): raise StreamDisconnectedError on SSE error frames
mistralai-nfau 874a593
refactor(workflows): move StreamDisconnectedError into extra/exceptio…
mistralai-nfau a7d9e33
test: narrow hook result to Response before iterating (pyright)
mistralai-nfau 472daf2
refactor(workflows): move stream error hook into _hooks and cover log…
mistralai-nfau 6a711e1
refactor: rename to STREAM_OPERATIONS_WITH_ERROR_EVENT for clarity
mistralai-nfau 584fab7
refactor: drop redundant content-encoding strip; test hook composition
mistralai-nfau e49af8e
fix: parse error frames with data split across multiple SSE data lines
mistralai-nfau 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
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 |
|---|---|---|
| @@ -0,0 +1,188 @@ | ||
| import json | ||
| import re | ||
| from typing import Any, AsyncIterator, Dict, Iterator, Optional, Tuple, Union, get_args | ||
|
|
||
| import httpx | ||
| from httpx._types import AsyncByteStream, SyncByteStream | ||
|
|
||
| from .types import AfterSuccessContext, AfterSuccessHook | ||
| from mistralai.extra.exceptions import ( | ||
| StreamDisconnectReason, | ||
| StreamDisconnectedError, | ||
| ) | ||
|
|
||
| # Operation IDs of the SSE-backed workflow stream endpoints that can emit a | ||
| # terminal ``event: error`` frame (event, execution, and logs streams). | ||
| STREAM_OPERATIONS_WITH_ERROR_EVENT = { | ||
| "get_stream_events_v1_workflows_events_stream_get", | ||
| "stream_v1_workflows_executions__execution_id__stream_get", | ||
| "stream_deployment_logs", | ||
| "stream_workflow_execution_logs", | ||
| } | ||
|
|
||
| _ERROR_EVENT = "error" | ||
| _VALID_REASONS = get_args(StreamDisconnectReason) | ||
| _DEFAULT_REASON: StreamDisconnectReason = "stream_error" | ||
|
|
||
| # SSE frame boundaries (blank line), longest first so the full separator is consumed. | ||
| _BOUNDARIES = [ | ||
| b"\r\n\r\n", | ||
| b"\r\n\r", | ||
| b"\r\n\n", | ||
| b"\r\r\n", | ||
| b"\n\r\n", | ||
| b"\r\r", | ||
| b"\n\r", | ||
| b"\n\n", | ||
| ] | ||
|
|
||
|
|
||
| def _find_boundary(buffer: bytearray) -> Optional[Tuple[int, int]]: | ||
| """Return (index, length) of the earliest frame boundary, or None if incomplete.""" | ||
| best: Optional[Tuple[int, int]] = None | ||
| for boundary in _BOUNDARIES: | ||
| idx = buffer.find(boundary) | ||
| if idx == -1: | ||
| continue | ||
| if ( | ||
| best is None | ||
| or idx < best[0] | ||
| or (idx == best[0] and len(boundary) > best[1]) | ||
| ): | ||
| best = (idx, len(boundary)) | ||
| return best | ||
|
|
||
|
|
||
| def _parse_error_payload(data: str) -> Tuple[str, StreamDisconnectReason]: | ||
| payload: Dict[str, Any] = {} | ||
| try: | ||
| # strict=False: SSE joins multi-line data with "\n", so a value spanning | ||
| # several data: lines contains literal newlines that strict JSON rejects. | ||
| parsed = json.loads(data.strip(), strict=False) | ||
| if isinstance(parsed, dict): | ||
| payload = parsed | ||
| except json.JSONDecodeError: | ||
| pass | ||
| error = str(payload.get("error", data.strip())) | ||
| reason = payload.get("reason", _DEFAULT_REASON) | ||
| if reason not in _VALID_REASONS: | ||
| reason = _DEFAULT_REASON | ||
| return error, reason | ||
|
|
||
|
|
||
| def _raise_if_error_frame(block: bytes) -> None: | ||
| """Raise StreamDisconnectedError if the SSE frame is an ``event: error`` frame.""" | ||
| event_name: Optional[str] = None | ||
| data = "" | ||
| for line in re.split(r"\r?\n|\r", block.decode("utf-8", errors="replace")): | ||
| if not line or line.startswith(":"): | ||
| continue | ||
| field, _, value = line.partition(":") | ||
| if value.startswith(" "): | ||
| value = value[1:] | ||
| if field == "event": | ||
| event_name = value | ||
| elif field == "data": | ||
| data += value + "\n" | ||
|
|
||
| if event_name != _ERROR_EVENT: | ||
| return | ||
|
|
||
| error, reason = _parse_error_payload(data) | ||
| raise StreamDisconnectedError(reason=reason, error=error) | ||
|
|
||
|
|
||
| class _FrameScanner: | ||
| """Buffers raw SSE bytes, raising on error frames and passing others through.""" | ||
|
|
||
| def __init__(self) -> None: | ||
| self._buffer = bytearray() | ||
|
|
||
| def feed(self, chunk: bytes) -> Iterator[bytes]: | ||
| self._buffer += chunk | ||
| while True: | ||
| found = _find_boundary(self._buffer) | ||
| if found is None: | ||
| return | ||
| idx, length = found | ||
| block = bytes(self._buffer[:idx]) | ||
| frame = bytes(self._buffer[: idx + length]) | ||
| del self._buffer[: idx + length] | ||
| _raise_if_error_frame(block) | ||
| yield frame | ||
|
|
||
| def flush(self) -> Iterator[bytes]: | ||
|
mistralai-nfau marked this conversation as resolved.
|
||
| if not self._buffer: | ||
| return | ||
| block = bytes(self._buffer) | ||
| self._buffer.clear() | ||
| _raise_if_error_frame(block) | ||
| yield block | ||
|
|
||
|
|
||
| class _ErrorDetectingSyncByteStream(SyncByteStream): | ||
| def __init__(self, original: SyncByteStream) -> None: | ||
| self._original = original | ||
| self._scanner = _FrameScanner() | ||
|
|
||
| def __iter__(self) -> Iterator[bytes]: | ||
| for chunk in self._original: | ||
| yield from self._scanner.feed(chunk) | ||
| yield from self._scanner.flush() | ||
|
|
||
| def close(self) -> None: | ||
| self._original.close() | ||
|
|
||
|
|
||
| class _ErrorDetectingAsyncByteStream(AsyncByteStream): | ||
| def __init__(self, original: AsyncByteStream) -> None: | ||
| self._original = original | ||
| self._scanner = _FrameScanner() | ||
|
|
||
| async def __aiter__(self) -> AsyncIterator[bytes]: | ||
| async for chunk in self._original: | ||
| for frame in self._scanner.feed(chunk): | ||
| yield frame | ||
| for frame in self._scanner.flush(): | ||
| yield frame | ||
|
|
||
| async def aclose(self) -> None: | ||
| await self._original.aclose() | ||
|
|
||
|
|
||
| class WorkflowStreamErrorHook(AfterSuccessHook): | ||
| """Raise StreamDisconnectedError when a workflow SSE stream sends an error frame. | ||
|
|
||
| Wraps the response byte stream for the workflow SSE operations so that an | ||
| ``event: error`` frame raises during iteration, terminating the consumer's | ||
| ``for event in stream`` loop instead of yielding the error as a normal event. | ||
| """ | ||
|
|
||
| def after_success( | ||
| self, | ||
| hook_ctx: AfterSuccessContext, | ||
| response: httpx.Response, | ||
| ) -> Union[httpx.Response, Exception]: | ||
| if hook_ctx.operation_id not in STREAM_OPERATIONS_WITH_ERROR_EVENT: | ||
| return response | ||
| if "text/event-stream" not in response.headers.get("content-type", ""): | ||
| return response | ||
|
|
||
| stream = response.stream | ||
| wrapped: Union[SyncByteStream, AsyncByteStream] | ||
| if isinstance(stream, AsyncByteStream): | ||
| wrapped = _ErrorDetectingAsyncByteStream(stream) | ||
| elif isinstance(stream, SyncByteStream): | ||
| wrapped = _ErrorDetectingSyncByteStream(stream) | ||
| else: | ||
| return response | ||
|
|
||
| # Keep the original headers: this hook forwards the raw stream unchanged, | ||
| # so httpx still applies any Content-Encoding when the consumer iterates. | ||
| return httpx.Response( | ||
| status_code=response.status_code, | ||
| headers=response.headers, | ||
| stream=wrapped, | ||
| request=response.request, | ||
| extensions=response.extensions, | ||
| ) | ||
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.
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.
Uh oh!
There was an error while loading. Please reload this page.