Event Streams for API Clients
Sections Structure Splitting lines across reads Assembling events Putting it together Habits worth keeping

A parser that survives real networks

An HTTP library hands a streamed body over in reads of whatever size the network produced. A read can end in the middle of a line, in the middle of a multi-byte character, or between the carriage return and the line feed of a single CRLF. A correct parser keeps state between reads and applies the rules of the format to complete lines only.

Structure

Split the work into three stages, each with its own buffer:

  1. Decode bytes to text with an incremental UTF-8 decoder. The next chapter explains why a plain bytes.decode() per read is wrong.
  2. Split text into lines, holding back an unfinished last line until more text arrives.
  3. Assemble lines into events and yield each event when its empty line arrives.

Splitting lines across reads

The awkward case is a carriage return at the very end of a read. It might be a complete CR line ending, or the first half of a CRLF whose line feed arrives in the next read. Treating it as a line ending immediately and then skipping one following line feed handles both cases.

import codecs

class LineSplitter:
    def __init__(self):
        self.buffer = ""
        self.skip_lf = False          # the last chunk ended with CR; a leading LF belongs to it

    def feed(self, text):
        if not text:                  # the decoder may return nothing for a partial character
            return []
        if self.skip_lf and text.startswith("\n"):
            text = text[1:]
        self.skip_lf = False
        self.buffer += text
        lines = []
        start = 0
        i = 0
        while i < len(self.buffer):
            ch = self.buffer[i]
            if ch == "\r" or ch == "\n":
                lines.append(self.buffer[start:i])
                if ch == "\r":
                    if i + 1 < len(self.buffer):
                        if self.buffer[i + 1] == "\n":
                            i += 1
                    else:
                        self.skip_lf = True
                start = i + 1
            i += 1
        self.buffer = self.buffer[start:]
        return lines

Assembling events

class EventAssembler:
    def __init__(self):
        self.data = []
        self.event = ""
        self.last_id = ""

    def line(self, line):
        """Returns (event_type, data, last_id) when an event completes, otherwise None."""
        if line == "":
            if not self.data:
                self.event = ""
                return None
            done = (self.event or "message", "\n".join(self.data), self.last_id)
            self.data, self.event = [], ""
            return done
        if line.startswith(":"):
            return None
        name, colon, value = line.partition(":")
        if colon and value.startswith(" "):
            value = value[1:]
        if name == "data":
            self.data.append(value)
        elif name == "event":
            self.event = value
        elif name == "id" and "\0" not in value:
            self.last_id = value
        return None

Joining the collected data values with line feeds gives the same result as the specification's "append the value and a line feed, then remove the final line feed".

Putting it together

def events(byte_chunks):
    decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
    splitter, assembler = LineSplitter(), EventAssembler()
    first = True
    for chunk in byte_chunks:
        text = decoder.decode(chunk)
        if first and text:
            text = text.removeprefix("\ufeff")   # byte order mark, only at the very start
            first = False
        for line in splitter.feed(text):
            event = assembler.line(line)
            if event:
                yield event
    # end of body: an unfinished event is dropped, as the specification requires

Habits worth keeping