| 411 | |
| 412 | |
| 413 | class SSEDecoder: |
| 414 | _data: list[str] |
| 415 | _event: str | None |
| 416 | _retry: int | None |
| 417 | _last_event_id: str | None |
| 418 | _raw: list[str] |
| 419 | |
| 420 | def __init__(self) -> None: |
| 421 | self._event = None |
| 422 | self._data = [] |
| 423 | self._last_event_id = None |
| 424 | self._retry = None |
| 425 | self._raw = [] |
| 426 | |
| 427 | def iter_bytes(self, iterator: Iterator[bytes]) -> Iterator[ServerSentEvent]: |
| 428 | """Given an iterator that yields raw binary data, iterate over it & yield every event encountered""" |
| 429 | for chunk in self._iter_chunks(iterator): |
| 430 | # Split before decoding so splitlines() only uses \r and \n |
| 431 | for raw_line in chunk.splitlines(): |
| 432 | line = raw_line.decode("utf-8") |
| 433 | sse = self.decode(line) |
| 434 | if sse: |
| 435 | yield sse |
| 436 | |
| 437 | def _iter_chunks(self, iterator: Iterator[bytes]) -> Iterator[bytes]: |
| 438 | """Given an iterator that yields raw binary data, iterate over it and yield individual SSE chunks""" |
| 439 | data = b"" |
| 440 | for chunk in iterator: |
| 441 | for line in chunk.splitlines(keepends=True): |
| 442 | data += line |
| 443 | if data.endswith((b"\r\r", b"\n\n", b"\r\n\r\n")): |
| 444 | yield data |
| 445 | data = b"" |
| 446 | if data: |
| 447 | yield data |
| 448 | |
| 449 | async def aiter_bytes(self, iterator: AsyncIterator[bytes]) -> AsyncIterator[ServerSentEvent]: |
| 450 | """Given an iterator that yields raw binary data, iterate over it & yield every event encountered""" |
| 451 | async for chunk in self._aiter_chunks(iterator): |
| 452 | # Split before decoding so splitlines() only uses \r and \n |
| 453 | for raw_line in chunk.splitlines(): |
| 454 | line = raw_line.decode("utf-8") |
| 455 | sse = self.decode(line) |
| 456 | if sse: |
| 457 | yield sse |
| 458 | |
| 459 | async def _aiter_chunks(self, iterator: AsyncIterator[bytes]) -> AsyncIterator[bytes]: |
| 460 | """Given an iterator that yields raw binary data, iterate over it and yield individual SSE chunks""" |
| 461 | data = b"" |
| 462 | async for chunk in iterator: |
| 463 | for line in chunk.splitlines(keepends=True): |
| 464 | data += line |
| 465 | if data.endswith((b"\r\r", b"\n\n", b"\r\n\r\n")): |
| 466 | yield data |
| 467 | data = b"" |
| 468 | if data: |
| 469 | yield data |
| 470 |
no outgoing calls
no test coverage detected