Skip to content

LineFramer

🛈 DocStrings

Reassembles complete lines from a stream that yields arbitrary chunks.

anyio's TextReceiveStream yields CHUNKS (one per receive() call, up to 64KiB on the asyncio backend), not lines, so a large line spans several chunks and a chunk boundary can fall anywhere, including inside a JSON string value. Splitting on newlines and never stripping a chunk is what keeps whitespace at the seam intact. (Backported from upstream #1083.)

Source code in src/clawd_code_sdk/_internal/transport/subprocess_utils.py
class LineFramer:
    """Reassembles complete lines from a stream that yields arbitrary chunks.

    anyio's TextReceiveStream yields CHUNKS (one per receive() call, up to 64KiB
    on the asyncio backend), not lines, so a large line spans several chunks and
    a chunk boundary can fall anywhere, including inside a JSON string value.
    Splitting on newlines and never stripping a chunk is what keeps whitespace
    at the seam intact. (Backported from upstream #1083.)
    """

    def __init__(self) -> None:
        # Only ever holds fragments of the line currently being received, none
        # of which contain a newline. Joining once a newline arrives keeps
        # reassembly linear in the line's size.
        self._pending: list[str] = []
        self.pending_len = 0

    def push(self, chunk: str) -> list[str]:
        """Add a chunk, returning any lines it completed."""
        self._pending.append(chunk)
        self.pending_len += len(chunk)
        if "\n" not in chunk:
            return []
        *lines, tail = "".join(self._pending).split("\n")
        self._pending, self.pending_len = [tail], len(tail)
        return lines

    def flush(self) -> str:
        """Take the trailing partial line, if any."""
        line = "".join(self._pending)
        self._pending, self.pending_len = [], 0
        return line

flush

flush() -> str

Take the trailing partial line, if any.

Source code in src/clawd_code_sdk/_internal/transport/subprocess_utils.py
def flush(self) -> str:
    """Take the trailing partial line, if any."""
    line = "".join(self._pending)
    self._pending, self.pending_len = [], 0
    return line

push

push(chunk: str) -> list[str]

Add a chunk, returning any lines it completed.

Source code in src/clawd_code_sdk/_internal/transport/subprocess_utils.py
def push(self, chunk: str) -> list[str]:
    """Add a chunk, returning any lines it completed."""
    self._pending.append(chunk)
    self.pending_len += len(chunk)
    if "\n" not in chunk:
        return []
    *lines, tail = "".join(self._pending).split("\n")
    self._pending, self.pending_len = [tail], len(tail)
    return lines

:fa-brands-github: Show source on GitHub