sysid / sse-starlette

BSD 3-Clause "New" or "Revised" License
543 stars 36 forks source link

Newline data payloads get converted to empty string #107

Closed bradfox2 closed 1 month ago

bradfox2 commented 1 month ago

I am getting event data that begins as '\n\n\n' and is received as data:'' data:'' data:''

It appears that any data payload in a ServerSentEvent that is only '\n', such as '\n\n\n', will get converted to '', by the code at

`def encode(self) -> bytes: buffer = io.StringIO() if self.comment is not None: for chunk in self.LINE_SEP_EXPR.split(str(self.comment)): buffer.write(f": {chunk}") buffer.write(self._sep)

    if self.id is not None:
        buffer.write(self.LINE_SEP_EXPR.sub("", f"id: {self.id}"))
        buffer.write(self._sep)

    if self.event is not None:
        buffer.write(self.LINE_SEP_EXPR.sub("", f"event: {self.event}"))
        buffer.write(self._sep)

    if self.data is not None:
        for chunk in self.LINE_SEP_EXPR.split(str(self.data)):
            buffer.write(f"data: {chunk}")
            buffer.write(self._sep)

    if self.retry is not None:
        if not isinstance(self.retry, int):
            raise TypeError("retry argument must be int")
        buffer.write(f"retry: {self.retry}")
        buffer.write(self._sep)

    buffer.write(self._sep)
    return buffer.getvalue().encode("utf-8")`

at sse.py:121.

self.LINE_SEP_EXPR.split(str(self.data)) is the suspect.

bradfox2 commented 1 month ago

Nevermind - read the SSE spec and it looks like this is fine. Encoding to JSON gets around this issue.