| 1 |
|
| 2 |
|
| 3 |
import codecs |
| 4 |
import re |
| 5 |
import time |
| 6 |
from contextlib import asynccontextmanager, contextmanager |
| 7 |
from typing import ( |
| 8 |
Any, |
| 9 |
AsyncContextManager, |
| 10 |
AsyncGenerator, |
| 11 |
AsyncIterator, |
| 12 |
Callable, |
| 13 |
ContextManager, |
| 14 |
Iterator, |
| 15 |
Optional, |
| 16 |
) |
| 17 |
|
| 18 |
import anyio |
| 19 |
import httpx |
| 20 |
from ._decoders import SSEDecoder |
| 21 |
from ._exceptions import SSEError |
| 22 |
from ._models import ServerSentEvent |
| 23 |
|
| 24 |
MAX_LINE_SIZE: int = 1_048_576 |
| 25 |
|
| 26 |
|
| 27 |
DEFAULT_MAX_RECONNECTION_ATTEMPTS: int = 5 |
| 28 |
DEFAULT_RECONNECT_DELAY_MS: int = 1_000 |
| 29 |
MAX_RECONNECT_DELAY_MS: int = 30_000 |
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
class EventSource: |
| 37 |
def __init__( |
| 38 |
self, |
| 39 |
response: httpx.Response, |
| 40 |
*, |
| 41 |
resumable: bool = False, |
| 42 |
stream_reconnection_enabled: bool = True, |
| 43 |
max_stream_reconnection_attempts: Optional[int] = None, |
| 44 |
stream_terminator: Optional[str] = None, |
| 45 |
reconnect: Optional[Callable[[str], Any]] = None, |
| 46 |
) -> None: |
| 47 |
self._response = response |
| 48 |
self._resumable = resumable |
| 49 |
self._stream_reconnection_enabled = stream_reconnection_enabled |
| 50 |
self._max_stream_reconnection_attempts = max_stream_reconnection_attempts |
| 51 |
self._stream_terminator = stream_terminator |
| 52 |
self._reconnect = reconnect |
| 53 |
|
| 54 |
@staticmethod |
| 55 |
def _is_event_stream(response: httpx.Response) -> bool: |
| 56 |
content_type = response.headers.get("content-type", "").partition(";")[0] |
| 57 |
return "text/event-stream" in content_type |
| 58 |
|
| 59 |
def _check_content_type(self) -> None: |
| 60 |
if not self._is_event_stream(self._response): |
| 61 |
content_type = self._response.headers.get("content-type", "").partition(";")[0] |
| 62 |
raise SSEError( |
| 63 |
f"Expected response header Content-Type to contain 'text/event-stream', got {content_type!r}" |
| 64 |
) |
| 65 |
|
| 66 |
def _is_reconnect_response_usable(self, response: httpx.Response) -> bool: |
| 67 |
"""Whether a reconnected response can be resumed as an SSE stream. |
| 68 |
|
| 69 |
``httpx.stream`` does not raise on non-success status, so a resume that |
| 70 |
returns an error page (e.g. ``200 text/html`` or a ``500`` body) would |
| 71 |
otherwise be parsed as SSE and yield garbage/zero events. Such a |
| 72 |
response is treated as a failed attempt (back off and retry) instead. |
| 73 |
""" |
| 74 |
return response.status_code < 400 and self._is_event_stream(response) |
| 75 |
|
| 76 |
def _get_charset(self, response: Optional[httpx.Response] = None) -> str: |
| 77 |
"""Extract charset from Content-Type header, fallback to UTF-8.""" |
| 78 |
resolved = response if response is not None else self._response |
| 79 |
content_type = resolved.headers.get("content-type", "") |
| 80 |
|
| 81 |
|
| 82 |
charset_match = re.search(r"charset=([^;\s]+)", content_type, re.IGNORECASE) |
| 83 |
if charset_match: |
| 84 |
charset = charset_match.group(1).strip("\"'") |
| 85 |
|
| 86 |
try: |
| 87 |
|
| 88 |
"test".encode(charset).decode(charset) |
| 89 |
return charset |
| 90 |
except (LookupError, UnicodeError): |
| 91 |
|
| 92 |
pass |
| 93 |
|
| 94 |
|
| 95 |
return "utf-8" |
| 96 |
|
| 97 |
@property |
| 98 |
def response(self) -> httpx.Response: |
| 99 |
return self._response |
| 100 |
|
| 101 |
@staticmethod |
| 102 |
def _normalize_sse_line_endings(buf: str) -> str: |
| 103 |
"""Normalize line endings per the SSE spec (\\r\\n → \\n, bare \\r → \\n). |
| 104 |
|
| 105 |
A trailing \\r is preserved because it may pair with a leading \\n in |
| 106 |
the next chunk to form a single \\r\\n terminator. |
| 107 |
""" |
| 108 |
buf = buf.replace("\r\n", "\n") |
| 109 |
if buf.endswith("\r"): |
| 110 |
return buf[:-1].replace("\r", "\n") + "\r" |
| 111 |
return buf.replace("\r", "\n") |
| 112 |
|
| 113 |
def _new_text_decoder(self, response: Optional[httpx.Response] = None) -> "codecs.IncrementalDecoder": |
| 114 |
return codecs.getincrementaldecoder(self._get_charset(response))(errors="replace") |
| 115 |
|
| 116 |
def _reconnect_applicable(self) -> bool: |
| 117 |
"""Whether reconnection is configured for this stream at all. |
| 118 |
|
| 119 |
This is the terminator-gating half of the reconnect decision, kept |
| 120 |
separate from :meth:`_should_reconnect` (which additionally requires a |
| 121 |
last *dispatched* id and an unexhausted attempt budget). The split lets |
| 122 |
a mid-stream transport error terminate consistently: |
| 123 |
- a stream that can never reconnect (non-resumable, no terminator, |
| 124 |
disabled, or no callback) must re-raise the error to the caller, so a |
| 125 |
truncated stream is not mistaken for a clean completion; |
| 126 |
- a resumable stream that has merely run out of attempts (or has no id |
| 127 |
to resume from) ends cleanly — the same way an exhausted empty/error |
| 128 |
-body resume already does, matching the TypeScript ``return``. |
| 129 |
""" |
| 130 |
return ( |
| 131 |
self._resumable |
| 132 |
and self._stream_terminator is not None |
| 133 |
and self._stream_reconnection_enabled |
| 134 |
and self._reconnect is not None |
| 135 |
) |
| 136 |
|
| 137 |
def _should_reconnect(self, last_dispatched_id: Optional[str], reconnect_attempts: int) -> bool: |
| 138 |
"""Decide whether a prematurely-ended stream should be reconnected. |
| 139 |
|
| 140 |
Mirrors the TypeScript ``shouldReconnect`` gating: |
| 141 |
- only resumable SSE endpoints with a configured terminator, reconnect |
| 142 |
enabled, and a reconnect callback are eligible (see |
| 143 |
:meth:`_reconnect_applicable`); |
| 144 |
- a last *dispatched* event id must exist to resume from; |
| 145 |
- the consecutive-failed-attempt cap must not be exceeded. |
| 146 |
""" |
| 147 |
if not self._reconnect_applicable(): |
| 148 |
return False |
| 149 |
if not last_dispatched_id: |
| 150 |
return False |
| 151 |
max_attempts = ( |
| 152 |
self._max_stream_reconnection_attempts |
| 153 |
if self._max_stream_reconnection_attempts is not None |
| 154 |
else DEFAULT_MAX_RECONNECTION_ATTEMPTS |
| 155 |
) |
| 156 |
if reconnect_attempts >= max_attempts: |
| 157 |
return False |
| 158 |
return True |
| 159 |
|
| 160 |
def _reconnect_delay_seconds(self, last_retry: Optional[int]) -> float: |
| 161 |
"""Backoff before a reconnect. |
| 162 |
|
| 163 |
Uses the server's most recent ``retry:`` directive (milliseconds) when |
| 164 |
present, otherwise a default of ``DEFAULT_RECONNECT_DELAY_MS``, clamped |
| 165 |
to ``MAX_RECONNECT_DELAY_MS``. |
| 166 |
""" |
| 167 |
base_ms = last_retry if (last_retry is not None and last_retry > 0) else DEFAULT_RECONNECT_DELAY_MS |
| 168 |
return min(base_ms, MAX_RECONNECT_DELAY_MS) / 1000.0 |
| 169 |
|
| 170 |
def _sleep_before_reconnect(self, last_retry: Optional[int]) -> None: |
| 171 |
|
| 172 |
|
| 173 |
|
| 174 |
time.sleep(self._reconnect_delay_seconds(last_retry)) |
| 175 |
|
| 176 |
async def _asleep_before_reconnect(self, last_retry: Optional[int]) -> None: |
| 177 |
|
| 178 |
|
| 179 |
|
| 180 |
await anyio.sleep(self._reconnect_delay_seconds(last_retry)) |
| 181 |
|
| 182 |
def _decode_response( |
| 183 |
self, |
| 184 |
response: httpx.Response, |
| 185 |
decoder: SSEDecoder, |
| 186 |
text_decoder: "codecs.IncrementalDecoder", |
| 187 |
) -> Iterator[ServerSentEvent]: |
| 188 |
buf = "" |
| 189 |
for chunk in response.iter_bytes(): |
| 190 |
buf += text_decoder.decode(chunk) |
| 191 |
buf = self._normalize_sse_line_endings(buf) |
| 192 |
|
| 193 |
while "\n" in buf: |
| 194 |
line, buf = buf.split("\n", 1) |
| 195 |
sse = decoder.decode(line) |
| 196 |
if sse is not None: |
| 197 |
yield sse |
| 198 |
|
| 199 |
if len(buf) > MAX_LINE_SIZE: |
| 200 |
raise SSEError( |
| 201 |
f"SSE line exceeded maximum size of {MAX_LINE_SIZE} characters without encountering a newline" |
| 202 |
) |
| 203 |
|
| 204 |
yield from self._flush_decoder(buf, decoder, text_decoder) |
| 205 |
|
| 206 |
async def _adecode_response( |
| 207 |
self, |
| 208 |
response: httpx.Response, |
| 209 |
decoder: SSEDecoder, |
| 210 |
text_decoder: "codecs.IncrementalDecoder", |
| 211 |
) -> AsyncGenerator[ServerSentEvent, None]: |
| 212 |
buf = "" |
| 213 |
async for chunk in response.aiter_bytes(): |
| 214 |
buf += text_decoder.decode(chunk) |
| 215 |
buf = self._normalize_sse_line_endings(buf) |
| 216 |
|
| 217 |
while "\n" in buf: |
| 218 |
line, buf = buf.split("\n", 1) |
| 219 |
sse = decoder.decode(line) |
| 220 |
if sse is not None: |
| 221 |
yield sse |
| 222 |
|
| 223 |
if len(buf) > MAX_LINE_SIZE: |
| 224 |
raise SSEError( |
| 225 |
f"SSE line exceeded maximum size of {MAX_LINE_SIZE} characters without encountering a newline" |
| 226 |
) |
| 227 |
|
| 228 |
for sse in self._flush_decoder(buf, decoder, text_decoder): |
| 229 |
yield sse |
| 230 |
|
| 231 |
def _flush_decoder( |
| 232 |
self, |
| 233 |
buf: str, |
| 234 |
decoder: SSEDecoder, |
| 235 |
text_decoder: "codecs.IncrementalDecoder", |
| 236 |
) -> Iterator[ServerSentEvent]: |
| 237 |
|
| 238 |
buf += text_decoder.decode(b"", final=True) |
| 239 |
buf = buf.replace("\r\n", "\n").replace("\r", "\n") |
| 240 |
|
| 241 |
if len(buf) > MAX_LINE_SIZE: |
| 242 |
raise SSEError( |
| 243 |
f"SSE line exceeded maximum size of {MAX_LINE_SIZE} characters without encountering a newline" |
| 244 |
) |
| 245 |
|
| 246 |
while "\n" in buf: |
| 247 |
line, buf = buf.split("\n", 1) |
| 248 |
sse = decoder.decode(line) |
| 249 |
if sse is not None: |
| 250 |
yield sse |
| 251 |
|
| 252 |
if buf.strip(): |
| 253 |
sse = decoder.decode(buf) |
| 254 |
if sse is not None: |
| 255 |
yield sse |
| 256 |
|
| 257 |
def iter_sse(self) -> Iterator[ServerSentEvent]: |
| 258 |
self._check_content_type() |
| 259 |
decoder = SSEDecoder() |
| 260 |
text_decoder = self._new_text_decoder() |
| 261 |
|
| 262 |
last_dispatched_id: Optional[str] = None |
| 263 |
last_retry: Optional[int] = None |
| 264 |
|
| 265 |
er |
| 266 |
|
| 267 |
|
| 268 |
reconnect_attempts = 0 |
| 269 |
|
| 270 |
|
| 271 |
|
| 272 |
|
| 273 |
response: Optional[httpx.Response] = self._response |
| 274 |
|
| 275 |
|
| 276 |
owned_cm: Optional[ContextManager[httpx.Response]] = None |
| 277 |
try: |
| 278 |
while True: |
| 279 |
if response is not None: |
| 280 |
events = self._decode_response(response, decoder, text_decoder) |
| 281 |
while True: |
| 282 |
try: |
| 283 |
sse = next(events) |
| 284 |
except StopIteration: |
| 285 |
break |
| 286 |
except SSEError: |
| 287 |
|
| 288 |
|
| 289 |
|
| 290 |
|
| 291 |
raise |
| 292 |
except httpx.TransportError: |
| 293 |
|
| 294 |
|
| 295 |
|
| 296 |
|
| 297 |
|
| 298 |
|
| 299 |
|
| 300 |
he |
| 301 |
|
| 302 |
|
| 303 |
|
| 304 |
|
| 305 |
if not self._reconnect_applicable(): |
| 306 |
raise |
| 307 |
break |
| 308 |
yield sse |
| 309 |
if sse.id: |
| 310 |
last_dispatched_id = sse.id |
| 311 |
if sse.retry is not None: |
| 312 |
last_retry = sse.retry |
| 313 |
reconnect_attempts = 0 |
| 314 |
|
| 315 |
if not self._should_reconnect(last_dispatched_id, reconnect_attempts): |
| 316 |
return |
| 317 |
reconnect_attempts += 1 |
| 318 |
|
| 319 |
self._sleep_before_reconnect(last_retry) |
| 320 |
|
| 321 |
|
| 322 |
|
| 323 |
if owned_cm is not None: |
| 324 |
owned_cm.__exit__(None, None, None) |
| 325 |
owned_cm = None |
| 326 |
|
| 327 |
assert self._reconnect is not None |
| 328 |
try: |
| 329 |
cm: ContextManager[httpx.Response] = self._reconnect(last_dispatched_id or "") |
| 330 |
new_response = cm.__enter__() |
| 331 |
except Exception: |
| 332 |
|
| 333 |
response = None |
| 334 |
continue |
| 335 |
owned_cm = cm |
| 336 |
if new_response is None or not self._is_reconnect_response_usable(new_response): |
| 337 |
|
| 338 |
|
| 339 |
response = None |
| 340 |
continue |
| 341 |
|
| 342 |
response = new_response |
| 343 |
|
| 344 |
|
| 345 |
|
| 346 |
decoder.reset_in_progress_event() |
| 347 |
text_decoder = self._new_text_decoder(new_response) |
| 348 |
finally: |
| 349 |
if owned_cm is not None: |
| 350 |
owned_cm.__exit__(None, None, None) |
| 351 |
|
| 352 |
async def aiter_sse(self) -> AsyncGenerator[ServerSentEvent, None]: |
| 353 |
self._check_content_type() |
| 354 |
decoder = SSEDecoder() |
| 355 |
text_decoder = self._new_text_decoder() |
| 356 |
|
| 357 |
last_dispatched_id: Optional[str] = None |
| 358 |
last_retry: Optional[int] = None |
| 359 |
reconnect_attempts = 0 |
| 360 |
|
| 361 |
response: Optional[httpx.Response] = self._response |
| 362 |
owned_cm: Optional[AsyncContextManager[httpx.Response]] = None |
| 363 |
try: |
| 364 |
while True: |
| 365 |
if response is not None: |
| 366 |
events = self._adecode_response(response, decoder, text_decoder) |
| 367 |
while True: |
| 368 |
try: |
| 369 |
sse = await events.__anext__() |
| 370 |
except StopAsyncIteration: |
| 371 |
break |
| 372 |
except SSEError: |
| 373 |
|
| 374 |
|
| 375 |
|
| 376 |
|
| 377 |
raise |
| 378 |
except httpx.TransportError: |
| 379 |
|
| 380 |
|
| 381 |
|
| 382 |
|
| 383 |
|
| 384 |
|
| 385 |
|
| 386 |
he |
| 387 |
|
| 388 |
|
| 389 |
if not self._reconnect_applicable(): |
| 390 |
raise |
| 391 |
break |
| 392 |
yield sse |
| 393 |
if sse.id: |
| 394 |
last_dispatched_id = sse.id |
| 395 |
if sse.retry is not None: |
| 396 |
last_retry = sse.retry |
| 397 |
reconnect_attempts = 0 |
| 398 |
|
| 399 |
if not self._should_reconnect(last_dispatched_id, reconnect_attempts): |
| 400 |
return |
| 401 |
reconnect_attempts += 1 |
| 402 |
|
| 403 |
await self._asleep_before_reconnect(last_retry) |
| 404 |
|
| 405 |
if owned_cm is not None: |
| 406 |
await owned_cm.__aexit__(None, None, None) |
| 407 |
owned_cm = None |
| 408 |
|
| 409 |
assert self._reconnect is not None |
| 410 |
try: |
| 411 |
cm: AsyncContextManager[httpx.Response] = self._reconnect(last_dispatched_id or "") |
| 412 |
new_response = await cm.__aenter__() |
| 413 |
except Exception: |
| 414 |
response = None |
| 415 |
continue |
| 416 |
owned_cm = cm |
| 417 |
if new_response is None or not self._is_reconnect_response_usable(new_response): |
| 418 |
response = None |
| 419 |
continue |
| 420 |
|
| 421 |
response = new_response |
| 422 |
decoder.reset_in_progress_event() |
| 423 |
text_decoder = self._new_text_decoder(new_response) |
| 424 |
finally: |
| 425 |
if owned_cm is not None: |
| 426 |
|
| 427 |
|
| 428 |
|
| 429 |
with anyio.CancelScope(shield=True): |
| 430 |
await owned_cm.__aexit__(None, None, None) |
| 431 |
|
| 432 |
|
| 433 |
@contextmanager |
| 434 |
def connect_sse(client: httpx.Client, method: str, url: str, **kwargs: Any) -> Iterator[EventSource]: |
| 435 |
headers = kwargs.pop("headers", {}) |
| 436 |
headers["Accept"] = "text/event-stream" |
| 437 |
headers["Cache-Control"] = "no-store" |
| 438 |
|
| 439 |
with client.stream(method, url, headers=headers, **kwargs) as response: |
| 440 |
yield EventSource(response) |
| 441 |
|
| 442 |
|
| 443 |
@asynccontextmanager |
| 444 |
async def aconnect_sse( |
| 445 |
client: httpx.AsyncClient, |
| 446 |
method: str, |
| 447 |
url: str, |
| 448 |
**kwargs: Any, |
| 449 |
) -> AsyncIterator[EventSource]: |
| 450 |
headers = kwargs.pop("headers", {}) |
| 451 |
headers["Accept"] = "text/event-stream" |
| 452 |
headers["Cache-Control"] = "no-store" |
| 453 |
|
| 454 |
async with client.stream(method, url, headers=headers, **kwargs) as response: |
| 455 |
yield EventSource(response) |