Visitar URL original
Support sending comments with SSE (#1054) · danielgtaylor/huma@6cc787b · GitHub
Skip to content

Commit 6cc787b

Browse files
seanwu1105robtme
andauthored
Support sending comments with SSE (#1054)
* Support sending comment with SSE * fix(sse): harden comment serialization against field injection SSE treats CR, LF, and CRLF all as line terminators, but comments were only split on LF. A comment containing a lone CR (or CRLF) followed by "field: value" would be re-emitted so a spec-compliant client parses a separate, injected field line. Comment is the only free-form string written to the wire un-escaped, so normalize CR/CRLF to LF before splitting into ": " comment lines. Also correct the Message.Comment doc: comments may accompany an event, not only comment-only messages. --------- Co-authored-by: Robert Thomas <31854736+wolveix@users.noreply.github.com>
1 parent da460b9 commit 6cc787b

2 files changed

Lines changed: 96 additions & 7 deletions

File tree

‎sse/sse.go‎

Lines changed: 38 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,11 @@ type Message struct {
4141
ID int
4242
Data any
4343
Retry int
44+
// Comment, if set, is written as one or more SSE comment lines (each line
45+
// prefixed with a colon and ignored by clients). It may accompany an event
46+
// or, when `Data` is nil, form a comment-only message such as a heartbeat
47+
// used to keep the connection alive.
48+
Comment string
4449
}
4550

4651
// Sender is a send function for sending SSE messages to the client. It is
@@ -54,6 +59,13 @@ func (s Sender) Data(data any) error {
5459
return s(Message{Data: data})
5560
}
5661

62+
// Comment sends an SSE comment to the client. Comments are ignored by clients
63+
// and are commonly used as heartbeats to keep the connection alive. This is
64+
// equivalent to calling `sender(Message{Comment: comment})`.
65+
func (s Sender) Comment(comment string) error {
66+
return s(Message{Comment: comment})
67+
}
68+
5769
// Register a new SSE operation. The `eventTypeMap` maps from event name to
5870
// the type of the data that will be sent. The `f` function is called with
5971
// the context, input, and a `send` function that can be used to send messages
@@ -170,6 +182,15 @@ func Register[I any](api huma.API, op huma.Operation, eventTypeMap map[string]an
170182
}
171183
}
172184

185+
flush := func() error {
186+
if flusher == nil {
187+
fmt.Fprintln(os.Stderr, "error: unable to flush")
188+
return fmt.Errorf("unable to flush: %w", http.ErrNotSupported)
189+
}
190+
flusher.Flush()
191+
return nil
192+
}
193+
173194
send := func(msg Message) error {
174195
if deadliner != nil {
175196
if err := deadliner.SetWriteDeadline(time.Now().Add(WriteTimeout)); err != nil {
@@ -187,6 +208,22 @@ func Register[I any](api huma.API, op huma.Operation, eventTypeMap map[string]an
187208
bw.Write(fmt.Appendf(nil, "retry: %d\n", msg.Retry))
188209
}
189210

211+
if msg.Comment != "" {
212+
// CR, LF, and CRLF are all SSE line terminators. Normalize
213+
// them to LF so every line of the comment is re-emitted as
214+
// its own ": " comment line and can't inject other fields.
215+
comment := strings.ReplaceAll(msg.Comment, "\r\n", "\n")
216+
comment = strings.ReplaceAll(comment, "\r", "\n")
217+
for line := range strings.SplitSeq(comment, "\n") {
218+
bw.Write(fmt.Appendf(nil, ": %s\n", line))
219+
}
220+
}
221+
222+
if msg.Data == nil {
223+
bw.Write([]byte("\n"))
224+
return flush()
225+
}
226+
190227
event, ok := typeToEvent[deref(reflect.TypeOf(msg.Data))]
191228
if !ok {
192229
fmt.Fprintf(os.Stderr, "error: unknown event type %v\n", reflect.TypeOf(msg.Data))
@@ -208,13 +245,7 @@ func Register[I any](api huma.API, op huma.Operation, eventTypeMap map[string]an
208245
return err
209246
}
210247
bw.Write([]byte("\n"))
211-
if flusher != nil {
212-
flusher.Flush()
213-
} else {
214-
fmt.Fprintln(os.Stderr, "error: unable to flush")
215-
return fmt.Errorf("unable to flush: %w", http.ErrNotSupported)
216-
}
217-
return nil
248+
return flush()
218249
}
219250

220251
// Call the user-provided SSE handler.

‎sse/sse_test.go‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,64 @@ data: {"error": "encode error: json: unsupported type: chan int"}
161161
api.Adapter().ServeHTTP(w, req)
162162
},
163163
},
164+
{
165+
Title: "sse comment heartbeat",
166+
TestFunc: func(t *testing.T) {
167+
_, api := humatest.New(t)
168+
sse.Register(api, huma.Operation{
169+
OperationID: "sse",
170+
Method: http.MethodGet,
171+
Path: "/sse",
172+
}, map[string]any{
173+
"message": &DefaultMessage{},
174+
}, func(ctx context.Context, input *struct{}, send sse.Sender) {
175+
send.Comment("heartbeat")
176+
send(sse.Message{ID: 5, Comment: "keep\nalive"})
177+
send.Data(DefaultMessage{Message: "Hello, world!"})
178+
})
179+
180+
resp := api.Get("/sse")
181+
182+
assert.Equal(t, http.StatusOK, resp.Code)
183+
assert.Equal(t, `: heartbeat
184+
185+
id: 5
186+
: keep
187+
: alive
188+
189+
data: {"message":"Hello, world!"}
190+
191+
`, resp.Body.String())
192+
},
193+
},
194+
{
195+
Title: "sse comment normalizes line breaks",
196+
TestFunc: func(t *testing.T) {
197+
_, api := humatest.New(t)
198+
sse.Register(api, huma.Operation{
199+
OperationID: "sse",
200+
Method: http.MethodGet,
201+
Path: "/sse",
202+
}, map[string]any{
203+
"message": &DefaultMessage{},
204+
}, func(ctx context.Context, input *struct{}, send sse.Sender) {
205+
// CR, CRLF, and LF are all SSE line terminators. Each line must
206+
// be re-prefixed with a colon so an embedded line break can't
207+
// inject another SSE field (here a stray "data:" line).
208+
send.Comment("a\rb\r\nc\ndata: not-injected")
209+
})
210+
211+
resp := api.Get("/sse")
212+
213+
assert.Equal(t, http.StatusOK, resp.Code)
214+
assert.Equal(t, `: a
215+
: b
216+
: c
217+
: data: not-injected
218+
219+
`, resp.Body.String())
220+
},
221+
},
164222
{
165223
Title: "sse flushes headers before first event",
166224
TestFunc: func(t *testing.T) {

0 commit comments

Comments
 (0)