Skip to content

perf: parse WebSocket handshake headers lazily - #610

Open
Emyrk wants to merge 1 commit into
coder:masterfrom
Emyrk:core-824-websocket-header-parsing
Open

Emyrk wants to merge 1 commit into
coder:masterfrom
Emyrk:core-824-websocket-header-parsing

Conversation

@Emyrk

@Emyrk Emyrk commented Dec 2, 2026

Copy link
Copy Markdown
Member

Optimize WebSocket handshake header parsing with strings.SplitSeq iterators instead of constructing slices of tokens and extension parameters.

  • Consume header tokens lazily and stop when matching values are found.
  • Preserve subprotocol, compression, and client-side extension validation behavior.
  • Add delimiter-heavy benchmarks and malformed-extension test cases.

Coder Agents on behalf of @Emyrk.

Use iterators for header tokens and extension parameters instead of collecting split values into slices. Preserve handshake negotiation behavior.
@Emyrk
Emyrk marked this pull request as ready for review December 2, 2026 23:34

@mafredri mafredri left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. Per-offer heap escapes in acceptDeflate / websocketExtension (inline on accept.go:329-353).
  2. Repeated Sec-WebSocket-Protocol scans in selectSubprotocol (inline on accept.go:267-276).
  3. Broader test and benchmark coverage beyond delimiter-only Accept headers (inline on accept_test.go:595-631).

Minor notes (non-blocking):

  • verifyServerExtensions drops the : %+v (exts[1:]) suffix from its error string, and selectSubprotocol now skips empty tokens even if AcceptOptions.Subprotocols contains "". 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 same persistConn leak reproduces locally on master with TestBadDials/badReq/badTLS.

🤖 Created with the help of Coder Agents.

Comment thread accept.go
Comment on lines 329 to 353
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
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread accept.go
Comment on lines 267 to 276
@@ -275,11 +275,11 @@ func selectSubprotocol(r *http.Request, subprotocols []string) string {
return ""
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Suggested change
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.

Comment thread dial.go
Comment on lines +319 to 335
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")
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Suggested change
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.

Comment thread accept_test.go
Comment on lines +595 to +631
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)
}
}
})
}
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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), and Sec-WebSocket-Extensions
  • Repeated rejected permessage-deflate offers (would catch the acceptDeflate escape above) and permessage-deflate with many valid parameters
  • CompressionDisabled with extension headers
  • Client-side verifyServerResponse headers
  • A regression test checking that allocations and allocated bytes stay flat between small and larger token counts (e.g., via testing.Benchmark), so regressions fail go test rather than relying on manual benchmark inspection

🤖 Created with the help of Coder Agents.

This branch has not been deployed

No deployments
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.

2 participants