"""SSE framing only; application data stays opaque to the host.""" from collections.abc import AsyncIterable, AsyncIterator from .errors import LimitExceeded, PluginFailure def parse_frame(lines: list[str]) -> dict: event = {"data": "", "comments": []} data = [] for line in lines: if line.startswith(":"): event["comments"].append(line[1:]) continue name, sep, value = line.partition(":") if sep and value.startswith(" "): value = value[1:] if name == "data": data.append(value) elif name in {"event", "id"}: if name != "id" or "\x00" not in value: event[name] = value elif name == "retry" and value.isascii() and value.isdigit(): event["retry"] = int(value) event["data"] = "\n".join(data) event["has_data"] = bool(data) return event async def decode_sse(chunks: AsyncIterable[bytes], max_frame_bytes: int) -> AsyncIterator[dict]: # Byte-level line framing preserves split UTF-8 without unbounded chunk accumulation. line = bytearray() lines = [] frame_size = 0 after_cr = False first_line = True async for chunk in chunks: for byte in chunk: frame_size += 1 if frame_size > max_frame_bytes: raise LimitExceeded() if after_cr: after_cr = False if byte == 10: continue if byte not in (10, 13): line.append(byte) continue text = bytes(line).decode("utf-8", errors="strict") line.clear() if first_line: text = text.removeprefix("\ufeff") first_line = False after_cr = byte == 13 if text: lines.append(text) else: if lines: yield parse_frame(lines) lines = [] frame_size = 0 # SSE dispatches only complete frames; a partial final frame is not trusted/released. if line or lines: raise PluginFailure() def encode_sse(event: dict, max_frame_bytes: int) -> bytes: if not isinstance(event, dict) or set(event) - { "event", "id", "data", "comments", "retry", "has_data", }: raise PluginFailure() lines = [] comments = event.get("comments", []) if not isinstance(comments, list): raise PluginFailure() for comment in comments: if not isinstance(comment, str) or "\r" in comment or "\n" in comment: raise PluginFailure() lines.append(":" + comment) for field in ("event", "id"): if field in event: value = event[field] if not isinstance(value, str) or any(c in value for c in "\r\n\x00"): raise PluginFailure() lines.append(f"{field}: {value}") if "retry" in event: retry = event["retry"] if type(retry) is not int or retry < 0: raise PluginFailure() lines.append(f"retry: {retry}") if event.get("has_data", "data" in event): data = event.get("data", "") if not isinstance(data, str) or "\r" in data: raise PluginFailure() lines.extend("data: " + part for part in data.split("\n")) encoded = ("\n".join(lines) + "\n\n").encode("utf-8") if len(encoded) > max_frame_bytes: raise LimitExceeded() return encoded