Skip to content

feat(sse): add server-side event encoding - #243

Merged
Oaklight merged 1 commit into
masterfrom
feat/sse-server-encoding
Oct 23, 2026
Merged

Oaklight merged 1 commit into
masterfrom
feat/sse-server-encoding

Conversation

@Oaklight

@Oaklight Oaklight commented Oct 23, 2026 •

Copy link
Copy Markdown
Owner

Why

httpserver can already stream a response, but nothing in the project turns
application data into a valid text/event-stream body. Every server-side SSE
user therefore hand-rolls the same formatting rules — and gets the edge cases
wrong: a data value containing \n silently truncates on clients that
dispatch per blank line, an id with a newline corrupts the stream, and a
negative retry is accepted by nobody.

This adds the producer half of the protocol next to the existing consumer, in
the same single file, so the two sides are verified against each other.

What

  • encode_event(data="", *, event=None, id=None, retry=None) returns one
    complete block, including the terminating blank line that dispatches it.
    Multi-line payloads produce one data: field per line; CRLF and CR are
    normalized. A line break in event/id, NUL in id, or a retry that is
    not a non-negative integer raises ValueError.
  • encode_comment(text="") returns a comment block for heartbeats.
  • Both are pure functions with no network dependency, so they work with
    httpserver.StreamingResponse, any other transport, or a direct write().

The helpers sit in the same module as EventSource, which makes a round-trip
test possible: whatever encode_event emits, the parser must reconstruct.

Docs

  • docs/modules/sse.md (EN + ZH): title, feature list, a server-side encoding
    example, API reference entries, comparison table.
  • Module index descriptions and changelog entries in both languages.

Tests

12 new cases in TestEncodeEvent cover single-line and multi-line payloads,
CRLF/CR normalization, every optional field, empty data, trailing newlines,
encoder → parser round-trip, and each rejection path. pytest sse/test_sse_correctness.py passes
(71 tests).

Fixes #241

Add encode_event() and encode_comment() so the module can produce
text/event-stream responses as well as consume them. Multi-line data is
split into one data: field per line, line breaks in event/id and NUL in
id are rejected, and retry is validated as a non-negative integer.

The helpers are pure functions with no network dependency, so they work
with httpserver.StreamingResponse or any other streaming transport.

Fixes #241
@Oaklight
Oaklight merged commit 2c3414d into master Oct 23, 2026
6 checks passed
@Oaklight
Oaklight deleted the feat/sse-server-encoding branch October 23, 2026 04:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(sse): server-side event encoding

1 participant