|
| 1 | +# This file was auto-generated by Fern from our API Definition. |
| 2 | + |
| 3 | +import re |
| 4 | +from contextlib import asynccontextmanager, contextmanager |
| 5 | +from typing import Any, AsyncGenerator, AsyncIterator, Iterator, cast |
| 6 | + |
| 7 | +import httpx |
| 8 | +from ._decoders import SSEDecoder |
| 9 | +from ._exceptions import SSEError |
| 10 | +from ._models import ServerSentEvent |
| 11 | + |
| 12 | + |
| 13 | +class EventSource: |
| 14 | + def __init__(self, response: httpx.Response) -> None: |
| 15 | + self._response = response |
| 16 | + |
| 17 | + def _check_content_type(self) -> None: |
| 18 | + content_type = self._response.headers.get("content-type", "").partition(";")[0] |
| 19 | + if "text/event-stream" not in content_type: |
| 20 | + raise SSEError( |
| 21 | + f"Expected response header Content-Type to contain 'text/event-stream', got {content_type!r}" |
| 22 | + ) |
| 23 | + |
| 24 | + def _get_charset(self) -> str: |
| 25 | + """Extract charset from Content-Type header, fallback to UTF-8.""" |
| 26 | + content_type = self._response.headers.get("content-type", "") |
| 27 | + |
| 28 | + # Parse charset parameter using regex |
| 29 | + charset_match = re.search(r"charset=([^;\s]+)", content_type, re.IGNORECASE) |
| 30 | + if charset_match: |
| 31 | + charset = charset_match.group(1).strip("\"'") |
| 32 | + # Validate that it's a known encoding |
| 33 | + try: |
| 34 | + # Test if the charset is valid by trying to encode/decode |
| 35 | + "test".encode(charset).decode(charset) |
| 36 | + return charset |
| 37 | + except (LookupError, UnicodeError): |
| 38 | + # If charset is invalid, fall back to UTF-8 |
| 39 | + pass |
| 40 | + |
| 41 | + # Default to UTF-8 if no charset specified or invalid charset |
| 42 | + return "utf-8" |
| 43 | + |
| 44 | + @property |
| 45 | + def response(self) -> httpx.Response: |
| 46 | + return self._response |
| 47 | + |
| 48 | + def iter_sse(self) -> Iterator[ServerSentEvent]: |
| 49 | + self._check_content_type() |
| 50 | + decoder = SSEDecoder() |
| 51 | + charset = self._get_charset() |
| 52 | + |
| 53 | + buffer = "" |
| 54 | + for chunk in self._response.iter_bytes(): |
| 55 | + # Decode chunk using detected charset |
| 56 | + text_chunk = chunk.decode(charset, errors="replace") |
| 57 | + buffer += text_chunk |
| 58 | + |
| 59 | + # Process complete lines |
| 60 | + while "\n" in buffer: |
| 61 | + line, buffer = buffer.split("\n", 1) |
| 62 | + line = line.rstrip("\r") |
| 63 | + sse = decoder.decode(line) |
| 64 | + # when we reach a "\n\n" => line = '' |
| 65 | + # => decoder will attempt to return an SSE Event |
| 66 | + if sse is not None: |
| 67 | + yield sse |
| 68 | + |
| 69 | + # Process any remaining data in buffer |
| 70 | + if buffer.strip(): |
| 71 | + line = buffer.rstrip("\r") |
| 72 | + sse = decoder.decode(line) |
| 73 | + if sse is not None: |
| 74 | + yield sse |
| 75 | + |
| 76 | + async def aiter_sse(self) -> AsyncGenerator[ServerSentEvent, None]: |
| 77 | + self._check_content_type() |
| 78 | + decoder = SSEDecoder() |
| 79 | + lines = cast(AsyncGenerator[str, None], self._response.aiter_lines()) |
| 80 | + try: |
| 81 | + async for line in lines: |
| 82 | + line = line.rstrip("\n") |
| 83 | + sse = decoder.decode(line) |
| 84 | + if sse is not None: |
| 85 | + yield sse |
| 86 | + finally: |
| 87 | + await lines.aclose() |
| 88 | + |
| 89 | + |
| 90 | +@contextmanager |
| 91 | +def connect_sse(client: httpx.Client, method: str, url: str, **kwargs: Any) -> Iterator[EventSource]: |
| 92 | + headers = kwargs.pop("headers", {}) |
| 93 | + headers["Accept"] = "text/event-stream" |
| 94 | + headers["Cache-Control"] = "no-store" |
| 95 | + |
| 96 | + with client.stream(method, url, headers=headers, **kwargs) as response: |
| 97 | + yield EventSource(response) |
| 98 | + |
| 99 | + |
| 100 | +@asynccontextmanager |
| 101 | +async def aconnect_sse( |
| 102 | + client: httpx.AsyncClient, |
| 103 | + method: str, |
| 104 | + url: str, |
| 105 | + **kwargs: Any, |
| 106 | +) -> AsyncIterator[EventSource]: |
| 107 | + headers = kwargs.pop("headers", {}) |
| 108 | + headers["Accept"] = "text/event-stream" |
| 109 | + headers["Cache-Control"] = "no-store" |
| 110 | + |
| 111 | + async with client.stream(method, url, headers=headers, **kwargs) as response: |
| 112 | + yield EventSource(response) |
0 commit comments