| 367 | |
| 368 | |
| 369 | class SSEDecoder: |
| 370 | _data: list[str] |
| 371 | _event: str | None |
| 372 | _retry: int | None |
| 373 | _last_event_id: str | None |
| 374 | _raw: list[str] |
| 375 | |
| 376 | def __init__(self) -> None: |
| 377 | self._event = None |
| 378 | self._data = [] |
| 379 | self._last_event_id = None |
| 380 | self._retry = None |
| 381 | self._raw = [] |
| 382 | |
| 383 | def iter_bytes(self, iterator: Iterator[bytes]) -> Iterator[ServerSentEvent]: |
| 384 | """Given an iterator that yields raw binary data, iterate over it & yield every event encountered""" |
| 385 | for chunk in self._iter_chunks(iterator): |
| 386 | # Split before decoding so splitlines() only uses \r and \n |
| 387 | for raw_line in chunk.splitlines(): |
| 388 | line = raw_line.decode("utf-8") |
| 389 | sse = self.decode(line) |
| 390 | if sse: |
| 391 | yield sse |
| 392 | |
| 393 | def _iter_chunks(self, iterator: Iterator[bytes]) -> Iterator[bytes]: |
| 394 | """Given an iterator that yields raw binary data, iterate over it and yield individual SSE chunks""" |
| 395 | data = b"" |
| 396 | for chunk in iterator: |
| 397 | for line in chunk.splitlines(keepends=True): |
| 398 | data += line |
| 399 | if data.endswith((b"\r\r", b"\n\n", b"\r\n\r\n")): |
| 400 | yield data |
| 401 | data = b"" |
| 402 | if data: |
| 403 | yield data |
| 404 | |
| 405 | async def aiter_bytes(self, iterator: AsyncIterator[bytes]) -> AsyncIterator[ServerSentEvent]: |
| 406 | """Given an iterator that yields raw binary data, iterate over it & yield every event encountered""" |
| 407 | async for chunk in self._aiter_chunks(iterator): |
| 408 | # Split before decoding so splitlines() only uses \r and \n |
| 409 | for raw_line in chunk.splitlines(): |
| 410 | line = raw_line.decode("utf-8") |
| 411 | sse = self.decode(line) |
| 412 | if sse: |
| 413 | yield sse |
| 414 | |
| 415 | async def _aiter_chunks(self, iterator: AsyncIterator[bytes]) -> AsyncIterator[bytes]: |
| 416 | """Given an iterator that yields raw binary data, iterate over it and yield individual SSE chunks""" |
| 417 | data = b"" |
| 418 | async for chunk in iterator: |
| 419 | for line in chunk.splitlines(keepends=True): |
| 420 | data += line |
| 421 | if data.endswith((b"\r\r", b"\n\n", b"\r\n\r\n")): |
| 422 | yield data |
| 423 | data = b"" |
| 424 | if data: |
| 425 | yield data |
| 426 |
no outgoing calls
no test coverage detected