fix(sse): count retained line cost in the event size cap

An upstream could send millions of empty data lines in one event. The cap counted one byte per line, but each line kept a 16-byte string header in memory. The cap now counts the header too, so retained memory stays within the cap.
This commit is contained in:
2026-11-03 00:04:52 +00:00
parent cbffcb4061
commit c851e237eb
2 changed files with 37 additions and 4 deletions
+10 -4
View File
@@ -39,6 +39,11 @@ const sseScannerMaxLineSize = 4 * 1024 * 1024
// tuning knob.
const sseMaxEventBytes = 8 * 1024 * 1024
// sseDataLineOverhead is the per-"data:" line cost counted against
// sseMaxEventBytes: 1 byte for the joined "\n" plus the 16-byte string
// header the dataLines slice retains for the line.
const sseDataLineOverhead = 1 + 16
// errSSEEventTooLarge is returned by readSSE when one event's accumulated
// "data:" payload exceeds sseMaxEventBytes. It mirrors how the per-line
// cap surfaces (bufio.ErrTooLong is returned as-is): the caller's stream
@@ -195,10 +200,11 @@ func readSSE(r io.Reader, fn func(sseEvent) error) error {
case "event":
event = value
case "data":
// +1 for the "\n" this line will contribute to the joined
// payload. Checked BEFORE appending, so the cap bounds what is
// actually held rather than catching it one line late.
dataBytes += len(value) + 1
// Each line costs its payload plus the "\n" it adds to the
// joined payload plus the string header dataLines retains, so
// many empty lines cannot amplify past the cap. Checked BEFORE
// appending, so the cap bounds what is actually held.
dataBytes += len(value) + sseDataLineOverhead
if dataBytes > sseMaxEventBytes {
return errSSEEventTooLarge
}
+27
View File
@@ -571,3 +571,30 @@ func TestNewFlushWriter_AssertsFlusherOnce(t *testing.T) {
}
})
}
// TestReadSSE_EmptyDataLinesCountTheirRetainedCost pins that an event of
// many empty "data:" lines hits the size cap on retained cost, not just
// payload bytes.
func TestReadSSE_EmptyDataLinesCountTheirRetainedCost(t *testing.T) {
t.Parallel()
maxLines := sseMaxEventBytes / sseDataLineOverhead
tests := []struct {
wantErr error
name string
lines int
}{
{name: "few lines", lines: 10, wantErr: nil},
{name: "just under the cap", lines: maxLines - 10, wantErr: nil},
{name: "past the cap", lines: maxLines + 10, wantErr: errSSEEventTooLarge},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
input := strings.Repeat("data:\n", tt.lines) + "\n"
err := readSSE(strings.NewReader(input), func(sseEvent) error { return nil })
if !errors.Is(err, tt.wantErr) {
t.Errorf("readSSE err = %v, want %v", err, tt.wantErr)
}
})
}
}