edge: SSE block reader for held streams (#432)
Human
Prompt
Task 4 of #432, the SSE block reader the held-stream relay uses.
From this commit's own message. The prompt ledger has no entries for it — which is what a squashed, rebased or amended commit looks like, and what every commit looks like in a repo without a ledger.
Summary
sseReader returns whole event blocks (Raw normalized to LF, one closing blank line), tracks the last valid id field (NUL ignored, bare id resets), flags comment-only blocks, strips a leading BOM, and accepts CRLF, CR and LF. A block is capped at 64 KiB, enforced while reading a line. Empty blocks are skipped. A partial block at EOF is dropped as io.ErrUnexpectedEOF.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2 files changed,
+202
−0
internal/edge/sse.go+134 −0internal/edge/sse_test.go+68 −0
diff --git a/internal/edge/sse.go b/internal/edge/sse.go| new file mode 100644 |
| index 000000000..648bfa9b8 |
| --- /dev/null |
| +++ b/internal/edge/sse.go |
| @@ -0,0 +1,134 @@ |
| +package edge |
| + |
| +import ( |
| + "bufio" |
| + "bytes" |
| + "errors" |
| + "io" |
| +) |
| + |
| +// sseMaxEvent caps the bytes held for one event in progress. |
| +const sseMaxEvent = 64 << 10 |
| + |
| +var errSSEEventTooLarge = errors.New("edge: SSE event exceeds size cap") |
| + |
| +// sseBlock is one event block read from a held leg's body. |
| +type sseBlock struct { |
| + Raw []byte // the block's lines normalized to "\n", ending in "\n\n" |
| + CommentOnly bool // every line is a comment (starts with ':') |
| + HasID bool |
| + ID string // valid only when HasID; "" means the spec's reset |
| +} |
| + |
| +// sseReader splits an event stream into blocks. It never buffers more than |
| +// sseMaxEvent bytes for a block, including a single over-long line. |
| +type sseReader struct { |
| + br *bufio.Reader |
| + first bool // no byte read yet (BOM check pending) |
| + skipLF bool // previous line ended in \r; drop a directly following \n |
| +} |
| + |
| +func newSSEReader(r io.Reader) *sseReader { |
| + return &sseReader{br: bufio.NewReaderSize(r, 4096), first: true} |
| +} |
| + |
| +// readLine appends one line (without its terminator) to dst. Lines end in |
| +// \r\n, \r or \n. It returns io.EOF only when no byte of a line was read, and |
| +// io.ErrUnexpectedEOF when the stream ends mid-line. limit is the most bytes |
| +// dst may hold after the call (the caller adds the "\n" itself). |
| +func (s *sseReader) readLine(dst []byte, limit int) ([]byte, error) { |
| + got := false |
| + for { |
| + c, err := s.br.ReadByte() |
| + if err != nil { |
| + if err == io.EOF && got { |
| + return dst, io.ErrUnexpectedEOF |
| + } |
| + return dst, err |
| + } |
| + if s.skipLF { |
| + s.skipLF = false |
| + if c == '\n' { |
| + continue |
| + } |
| + } |
| + if s.first { |
| + s.first = false |
| + if c == 0xEF { |
| + if b, _ := s.br.Peek(2); len(b) == 2 && b[0] == 0xBB && b[1] == 0xBF { |
| + _, _ = s.br.Discard(2) |
| + got = true |
| + continue |
| + } |
| + } |
| + } |
| + got = true |
| + switch c { |
| + case '\n': |
| + return dst, nil |
| + case '\r': |
| + s.skipLF = true |
| + return dst, nil |
| + } |
| + if len(dst) >= limit { |
| + return dst, errSSEEventTooLarge |
| + } |
| + dst = append(dst, c) |
| + } |
| +} |
| + |
| +// Next returns the next non-empty block. A block of nothing but a blank line |
| +// (the spec's empty event) is skipped. A partial block at EOF is dropped and |
| +// reported as io.ErrUnexpectedEOF. |
| +func (s *sseReader) Next() (sseBlock, error) { |
| + var ( |
| + raw []byte |
| + line []byte |
| + blk sseBlock |
| + comment = true |
| + lines int |
| + ) |
| + for { |
| + // Leave room for the line's "\n" and the block's closing "\n". |
| + limit := sseMaxEvent - len(raw) - 2 |
| + if limit < 0 { |
| + // Only the closing blank line still fits. |
| + limit = 0 |
| + } |
| + var err error |
| + line, err = s.readLine(line[:0], limit) |
| + if err != nil { |
| + if err == io.EOF && lines > 0 { |
| + err = io.ErrUnexpectedEOF |
| + } |
| + return sseBlock{}, err |
| + } |
| + if len(line) == 0 { |
| + if lines == 0 { |
| + continue |
| + } |
| + raw = append(raw, '\n') |
| + blk.Raw = raw |
| + blk.CommentOnly = comment |
| + return blk, nil |
| + } |
| + lines++ |
| + raw = append(raw, line...) |
| + raw = append(raw, '\n') |
| + if line[0] == ':' { |
| + continue |
| + } |
| + comment = false |
| + name, value := line, []byte(nil) |
| + if i := bytes.IndexByte(line, ':'); i >= 0 { |
| + name, value = line[:i], line[i+1:] |
| + if len(value) > 0 && value[0] == ' ' { |
| + value = value[1:] |
| + } |
| + } |
| + if string(name) == "id" && bytes.IndexByte(value, 0) < 0 { |
| + blk.HasID = true |
| + blk.ID = string(value) |
| + } |
| + } |
| +} |
diff --git a/internal/edge/sse_test.go b/internal/edge/sse_test.go| new file mode 100644 |
| index 000000000..9dbe375aa |
| --- /dev/null |
| +++ b/internal/edge/sse_test.go |
| @@ -0,0 +1,68 @@ |
| +package edge |
| + |
| +import ( |
| + "errors" |
| + "io" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestSSEReader(t *testing.T) { |
| + type want struct { |
| + raw string |
| + comment bool |
| + hasID bool |
| + id string |
| + } |
| + cases := []struct { |
| + name string |
| + in string |
| + blocks []want |
| + err error |
| + }{ |
| + {"id and data", "id: 7\ndata: x\n\n", []want{{"id: 7\ndata: x\n\n", false, true, "7"}}, io.EOF}, |
| + {"bare id resets", "id\n\n", []want{{"id\n\n", false, true, ""}}, io.EOF}, |
| + {"id with NUL ignored", "id: a\x00b\ndata: x\n\n", []want{{"id: a\x00b\ndata: x\n\n", false, false, ""}}, io.EOF}, |
| + {"comment only", ": ping\n\n", []want{{": ping\n\n", true, false, ""}}, io.EOF}, |
| + {"BOM and CRLF", "\xEF\xBB\xBFdata: x\r\n\r\n", []want{{"data: x\n\n", false, false, ""}}, io.EOF}, |
| + {"partial at EOF", "data: x\n", nil, io.ErrUnexpectedEOF}, |
| + {"partial line at EOF", "data: x", nil, io.ErrUnexpectedEOF}, |
| + {"too large line", "data: " + strings.Repeat("a", 70<<10) + "\n\n", nil, errSSEEventTooLarge}, |
| + {"retry is not a comment", "retry: 5\n\n", []want{{"retry: 5\n\n", false, false, ""}}, io.EOF}, |
| + {"last id wins", "id: 1\nid: 2\n\n", []want{{"id: 1\nid: 2\n\n", false, true, "2"}}, io.EOF}, |
| + {"NUL id after good id keeps good", "id: 1\nid: a\x00\n\n", []want{{"id: 1\nid: a\x00\n\n", false, true, "1"}}, io.EOF}, |
| + {"id no space", "id:9\n\n", []want{{"id:9\n\n", false, true, "9"}}, io.EOF}, |
| + {"comment then data", ": c\ndata: x\n\n", []want{{": c\ndata: x\n\n", false, false, ""}}, io.EOF}, |
| + {"two blocks", "id: 1\ndata: a\n\n: ping\n\nid: 2\ndata: b\n\n", []want{ |
| + {"id: 1\ndata: a\n\n", false, true, "1"}, |
| + {": ping\n\n", true, false, ""}, |
| + {"id: 2\ndata: b\n\n", false, true, "2"}, |
| + }, io.EOF}, |
| + {"empty blocks skipped", "\n\n\r\ndata: x\n\n\n", []want{{"data: x\n\n", false, false, ""}}, io.EOF}, |
| + {"lone CR terminators", "data: x\r\rdata: y\r\r", []want{{"data: x\n\n", false, false, ""}, {"data: y\n\n", false, false, ""}}, io.EOF}, |
| + {"CR then LF across blank", "data: x\r\n\r\ndata: y\n\n", []want{{"data: x\n\n", false, false, ""}, {"data: y\n\n", false, false, ""}}, io.EOF}, |
| + {"just under cap", "data: " + strings.Repeat("a", sseMaxEvent-6-2) + "\n\n", []want{{"data: " + strings.Repeat("a", sseMaxEvent-6-2) + "\n\n", false, false, ""}}, io.EOF}, |
| + {"many lines over cap", strings.Repeat("data: "+strings.Repeat("a", 1000)+"\n", 70) + "\n", nil, errSSEEventTooLarge}, |
| + } |
| + for _, tc := range cases { |
| + t.Run(tc.name, func(t *testing.T) { |
| + r := newSSEReader(strings.NewReader(tc.in)) |
| + for i, w := range tc.blocks { |
| + b, err := r.Next() |
| + if err != nil { |
| + t.Fatalf("block %d: %v", i, err) |
| + } |
| + if string(b.Raw) != w.raw || b.CommentOnly != w.comment || b.HasID != w.hasID || (w.hasID && b.ID != w.id) { |
| + t.Fatalf("block %d = %q comment=%v hasID=%v id=%q; want %+v", i, b.Raw, b.CommentOnly, b.HasID, b.ID, w) |
| + } |
| + } |
| + b, err := r.Next() |
| + if !errors.Is(err, tc.err) { |
| + t.Fatalf("final err = %v, want %v", err, tc.err) |
| + } |
| + if len(b.Raw) != 0 { |
| + t.Fatalf("block returned with error: %q", b.Raw) |
| + } |
| + }) |
| + } |
| +} |