Repository navigation
Conversation
Use iterators for header tokens and extension parameters instead of collecting split values into slices. Preserve handshake negotiation behavior.
mafredri
left a comment
There was a problem hiding this comment.
Nice cleanup. Switching handshake header parsing to iterators avoids intermediate slice allocations and skips extension parsing when CompressionDisabled is set.
A few things to address before merging:
- Per-offer heap escapes in
acceptDeflate/websocketExtension(inline onaccept.go:329-353). - Repeated
Sec-WebSocket-Protocolscans inselectSubprotocol(inline onaccept.go:267-276). - Broader test and benchmark coverage beyond delimiter-only
Acceptheaders (inline onaccept_test.go:595-631).
Minor notes (non-blocking):
verifyServerExtensionsdrops the: %+v(exts[1:]) suffix from its error string, andselectSubprotocolnow skips empty tokens even ifAcceptOptions.Subprotocolscontains"". Both are reasonable changes; worth noting briefly in the PR description / commit message instead of saying all behavior is unchanged.- The
test (1.26)goroutine-leak failure is not caused by this PR. The samepersistConnleak reproduces locally onmasterwithTestBadDials/badReq/badTLS.
🤖 Created with the help of Coder Agents.
| type websocketExtension struct { | ||
| name string | ||
| params []string | ||
| params iter.Seq[string] | ||
| } | ||
|
|
||
| func websocketExtensions(h http.Header) []websocketExtension { | ||
| var exts []websocketExtension | ||
| extStrs := headerTokens(h, "Sec-WebSocket-Extensions") | ||
| for _, extStr := range extStrs { | ||
| if extStr == "" { | ||
| continue | ||
| } | ||
|
|
||
| vals := strings.Split(extStr, ";") | ||
| for i := range vals { | ||
| vals[i] = strings.TrimSpace(vals[i]) | ||
| } | ||
|
|
||
| e := websocketExtension{ | ||
| name: vals[0], | ||
| params: vals[1:], | ||
| func websocketExtensions(h http.Header) iter.Seq[websocketExtension] { | ||
| return func(yield func(websocketExtension) bool) { | ||
| for token := range headerTokens(h, "Sec-WebSocket-Extensions") { | ||
| name, rawParams, hasParams := strings.Cut(token, ";") | ||
| params := func(yieldParam func(string) bool) { | ||
| if !hasParams { | ||
| return | ||
| } | ||
| for param := range strings.SplitSeq(rawParams, ";") { | ||
| if !yieldParam(strings.TrimSpace(param)) { | ||
| return | ||
| } | ||
| } | ||
| } | ||
| if !yield(websocketExtension{name: strings.TrimSpace(name), params: params}) { | ||
| return | ||
| } | ||
| } | ||
|
|
||
| exts = append(exts, e) | ||
| } | ||
| return exts | ||
| } |
There was a problem hiding this comment.
Storing params as an iter.Seq[string] closure field causes the closure and range state to escape to the heap when acceptDeflate or verifyServerExtensions iterates over it, and mode.opts() allocates *compressionOptions before parameters are validated. This adds allocations even on a normal permessage-deflate; client_max_window_bits handshake compared to master, and allocates on every rejected permessage-deflate offer.
Storing rawParams string and hasParams bool on websocketExtension (iterating via strings.SplitSeq directly or an inlinable params() method) and having acceptDeflate return compressionOptions by value, allocating the pointer only in the ok branch, avoids those per-offer escapes and drops allocations below master for the common handshake too.
A brief comment on hasParams explaining why it is needed (so permessage-deflate; yields an empty parameter and fails validation, while bare permessage-deflate yields none) would also help preserve that edge case.
🤖 Created with the help of Coder Agents.
| @@ -275,11 +275,11 @@ func selectSubprotocol(r *http.Request, subprotocols []string) string { | |||
| return "" | |||
| } | |||
There was a problem hiding this comment.
Calling headerTokens inside the subprotocols loop re-canonicalizes the header key and re-scans Sec-WebSocket-Protocol once per configured subprotocol, which can be slower than master when several subprotocols are configured and miss.
A single pass over headerTokens tracking the best-ranked match preserves server preference order and client casing while scanning the header once:
| func selectSubprotocol(r *http.Request, subprotocols []string) string { | |
| if len(subprotocols) == 0 { | |
| return "" | |
| } | |
| selected, rank := "", len(subprotocols) | |
| for cp := range headerTokens(r.Header, "Sec-WebSocket-Protocol") { | |
| for i, sp := range subprotocols[:rank] { | |
| if strings.EqualFold(sp, cp) { | |
| selected, rank = cp, i | |
| if rank == 0 { | |
| return selected | |
| } | |
| break | |
| } | |
| } | |
| } | |
| return selected | |
| } |
🤖 Created with the help of Coder Agents.
| var ext websocketExtension | ||
| count := 0 | ||
| for e := range websocketExtensions(h) { | ||
| if count == 0 { | ||
| ext = e | ||
| } | ||
| count++ | ||
| if count == 2 { | ||
| break | ||
| } | ||
| } | ||
| if count == 0 { | ||
| return nil, nil | ||
| } | ||
|
|
||
| ext := exts[0] | ||
| if ext.name != "permessage-deflate" || len(exts) > 1 || copts == nil { | ||
| return nil, fmt.Errorf("WebSocket protcol violation: unsupported extensions from server: %+v", exts[1:]) | ||
| if ext.name != "permessage-deflate" || count > 1 || copts == nil { | ||
| return nil, errors.New("WebSocket protcol violation: unsupported extensions from server") | ||
| } |
There was a problem hiding this comment.
Nit: a found flag is a bit clearer than counting to 2 and lets the loop return immediately when copts == nil or the first extension is not permessage-deflate, while keeping parameter validation after the loop preserves error precedence:
| var ext websocketExtension | |
| count := 0 | |
| for e := range websocketExtensions(h) { | |
| if count == 0 { | |
| ext = e | |
| } | |
| count++ | |
| if count == 2 { | |
| break | |
| } | |
| } | |
| if count == 0 { | |
| return nil, nil | |
| } | |
| ext := exts[0] | |
| if ext.name != "permessage-deflate" || len(exts) > 1 || copts == nil { | |
| return nil, fmt.Errorf("WebSocket protcol violation: unsupported extensions from server: %+v", exts[1:]) | |
| if ext.name != "permessage-deflate" || count > 1 || copts == nil { | |
| return nil, errors.New("WebSocket protcol violation: unsupported extensions from server") | |
| } | |
| var ext websocketExtension | |
| found := false | |
| for e := range websocketExtensions(h) { | |
| if found || copts == nil || e.name != "permessage-deflate" { | |
| return nil, errors.New("WebSocket protcol violation: unsupported extensions from server") | |
| } | |
| ext = e | |
| found = true | |
| } | |
| if !found { | |
| return nil, nil | |
| } |
🤖 Created with the help of Coder Agents.
| func BenchmarkAcceptDelimiterHeaders(b *testing.B) { | ||
| cases := []struct { | ||
| name string | ||
| header string | ||
| value string | ||
| }{ | ||
| {"connection-commas", "Connection", strings.Repeat(",", http.DefaultMaxHeaderBytes) + "Upgrade"}, | ||
| {"extension-commas", "Sec-WebSocket-Extensions", strings.Repeat(",", http.DefaultMaxHeaderBytes)}, | ||
| {"extension-semicolons", "Sec-WebSocket-Extensions", strings.Repeat(";", http.DefaultMaxHeaderBytes)}, | ||
| } | ||
|
|
||
| for _, tc := range cases { | ||
| b.Run(tc.name, func(b *testing.B) { | ||
| r := httptest.NewRequest("GET", "/", nil) | ||
| r.Header.Set("Connection", "Upgrade") | ||
| r.Header.Set("Upgrade", "websocket") | ||
| r.Header.Set("Sec-WebSocket-Version", "13") | ||
| r.Header.Set("Sec-WebSocket-Key", xrand.Base64(16)) | ||
| r.Header.Set(tc.header, tc.value) | ||
|
|
||
| errHijack := errors.New("hijack error") | ||
| b.ReportAllocs() | ||
| for b.Loop() { | ||
| w := mockHijacker{ | ||
| ResponseWriter: httptest.NewRecorder(), | ||
| hijack: func() (net.Conn, *bufio.ReadWriter, error) { | ||
| return nil, nil, errHijack | ||
| }, | ||
| } | ||
| _, err := Accept(w, r, &AcceptOptions{CompressionMode: CompressionNoContextTakeover}) | ||
| if !errors.Is(err, errHijack) { | ||
| b.Fatalf("expected hijack error, got %v", err) | ||
| } | ||
| } | ||
| }) | ||
| } | ||
| } |
There was a problem hiding this comment.
Both new unit tests already pass on master, and this benchmark only covers delimiter-only inputs on Accept. A slice-collecting implementation that skips empty tokens and empty parameters would still pass all current tests and match these benchmark numbers.
Could we expand coverage to include:
- Non-empty repeated tokens across
Connection,Upgrade,Sec-WebSocket-Protocol(with multiple server preferences), andSec-WebSocket-Extensions - Repeated rejected
permessage-deflateoffers (would catch theacceptDeflateescape above) andpermessage-deflatewith many valid parameters CompressionDisabledwith extension headers- Client-side
verifyServerResponseheaders - A regression test checking that allocations and allocated bytes stay flat between small and larger token counts (e.g., via
testing.Benchmark), so regressions failgo testrather than relying on manual benchmark inspection
🤖 Created with the help of Coder Agents.
Optimize WebSocket handshake header parsing with
strings.SplitSeqiterators instead of constructing slices of tokens and extension parameters.Coder Agents on behalf of @Emyrk.