websocket icon indicating copy to clipboard operation
websocket copied to clipboard

fix: len(buf) => cap(buf)

Open BaiZe1998 opened this issue 1 year ago • 1 comments

What type of PR is this? (check all applicable)

  • [ ] Refactor
  • [ ] Feature
  • [x] Bug Fix
  • [ ] Optimization
  • [ ] Documentation Update
  • [ ] Go Version Update
  • [ ] Dependency Update

Description

len(buf) must equal to 0 for AvailableBuffer()

// AvailableBuffer returns an empty buffer with b.Available() capacity.
// This buffer is intended to be appended to and
// passed to an immediately succeeding [Writer.Write] call.
// The buffer is only valid until the next write operation on b.
func (b *Writer) AvailableBuffer() []byte {
	return b.buf[b.n:][:0]
}

i think the len(buf) may switch to cap(buf) ?

https://github.com/gorilla/websocket/blob/main/server.go#L208

buf := brw.Writer.AvailableBuffer()

var writeBuf []byte
if u.WriteBufferPool == nil && u.WriteBufferSize == 0 && len(buf) >= maxFrameHeaderSize+256 {
    // Reuse hijacked write buffer as connection buffer.
    writeBuf = buf
}

Related Tickets & Documents

  • Related Issue #
  • Closes #

Added/updated tests?

  • [ ] Yes
  • [ ] No, and this is why: please replace this line with details on why tests have not been included
  • [ ] I need help with writing tests

Run verifications and test

  • [ ] make verify is passing
  • [x] make test is passing

BaiZe1998 avatar Jan 17 '25 16:01 BaiZe1998

Please note, it seems not enough because the code here will panic due to slice bounds out of range (try using conn.WriteMessage).

It seems that https://github.com/gorilla/websocket/commit/8915bad18b7592fd4503ff0b5accff8a91e75b47 introduced performance regression here because buffer is not really re-used now.

Also, the mentioned commit disabled test - https://github.com/gorilla/websocket/commit/8915bad18b7592fd4503ff0b5accff8a91e75b47#diff-53170cac6baf0bf02f3aaa3994259ea4cffaaf2498e768fb7e03cf9f752af96cR124

FZambia avatar May 12 '25 08:05 FZambia