Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add custom splitlines to avoid line splitting on text formatter #2

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion filigran_sseclient/sseclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,19 @@
# however, assumes that a system will provide consistent line endings.
end_of_field = re.compile(r"\r\n\r\n|\r\r|\n\n")

# We only supports this newlines char to split message. Formatting could be present in data.
# b"\xc2\x85", # NEL
# b"\xe2\x80\xa8", # LineSeparator
# b"\xe2\x80\xa9", # ParagraphSeparator
# b"\v", # Line Tabulation
# b"\f", # Form Feed
# b"\x1c", File Separator
# b"\x1d", Group Separator
# b"\x1e", Record Separator
# see https://docs.python.org/3.11/library/stdtypes.html#str.splitlines
NEWLINE_MESSAGE_CHARS = b'\r\n', b'\n', b'\r',
DECODED_NEWLINE_MESSAGE_CHARS = [nc.decode('utf-8') for nc in NEWLINE_MESSAGE_CHARS]
SPLIT_PATTERN = re.compile('|'.join(map(re.escape, DECODED_NEWLINE_MESSAGE_CHARS)))

class SSEClient(object):
def __init__(
Expand Down Expand Up @@ -164,14 +177,23 @@ def dump(self):
lines.extend("data: %s" % d for d in self.data.split("\n"))
return "\n".join(lines) + "\n\n"

@staticmethod
def splitlines(raw):
"""
Yield each line from the input string, split by the precompiled newline pattern.
"""
for line in SPLIT_PATTERN.split(raw):
if line: # Skip any empty results
yield line

@classmethod
def parse(cls, raw):
"""
Given a possibly-multiline string representing an SSE message, parse it
and return a Event object.
"""
msg = cls()
for line in raw.splitlines():
for line in cls.splitlines(raw):
m = cls.sse_line_pattern.match(line)
if m is None:
# Malformed line. Discard but warn.
Expand Down