From 09cab45f2c50cc3a99c3a032d656b0c493557cf9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tam=C3=A1s=20Mojzes?= Date: Fri, 27 Nov 2026 14:49:04 +0100 Subject: [PATCH 1/2] feat: add DialOptions.WriteBufferSize Client frames are masked by copying the payload through the connection's bufio.Writer, which Dial always creates with the bufio default of 4096 bytes and flushes every time it fills. A 64 KiB message therefore costs 17 writes (16 over TLS records), while server frames, which are not masked, go out in one. WriteBufferSize lets the dialer size that buffer. Zero or negative keeps the pooled 4096-byte writer, so existing users are unaffected; other sizes get a dedicated writer that is not returned to the pool and is released when the connection closes. On WASM the field has no effect, since the browser frames writes, and exists so code compiles on both platforms. BenchmarkDialWriteBufferSize (64 KiB echo, loopback): default 17 writes/op 213 MB/s 128KiB 1 write/op 527 MB/s --- dial.go | 22 +++- dial_write_buffer_internal_test.go | 32 +++++ dial_write_buffer_test.go | 191 +++++++++++++++++++++++++++++ write.go | 2 + ws_js.go | 3 + 5 files changed, 247 insertions(+), 3 deletions(-) create mode 100644 dial_write_buffer_internal_test.go create mode 100644 dial_write_buffer_test.go diff --git a/dial.go b/dial.go index 92820ed6..3a18f982 100644 --- a/dial.go +++ b/dial.go @@ -63,6 +63,12 @@ type DialOptions struct { // Unlike OnPingReceived, this callback does not return a value because a pong frame // is a response to a ping and does not trigger any further frame transmission. OnPongReceived func(ctx context.Context, payload []byte) + + // WriteBufferSize controls the size of the buffer used to mask and write frames. + // A frame larger than the buffer is sent in multiple writes. + // + // Defaults to 4096 bytes when zero or negative. + WriteBufferSize int } func (opts *DialOptions) cloneWithDefaults(ctx context.Context) (context.Context, context.CancelFunc, *DialOptions) { @@ -198,7 +204,7 @@ func dial(ctx context.Context, urls string, opts *DialOptions, rand io.Reader) ( onPingReceived: opts.OnPingReceived, onPongReceived: opts.OnPongReceived, br: getBufioReader(rwc), - bw: getBufioWriter(rwc), + bw: getBufioWriter(rwc, opts.WriteBufferSize), }), resp, nil } @@ -363,17 +369,27 @@ func putBufioReader(br *bufio.Reader) { bufioReaderPool.Put(br) } +// defaultWriteBufferSize matches the bufio package default. +const defaultWriteBufferSize = 4096 + var bufioWriterPool sync.Pool -func getBufioWriter(w io.Writer) *bufio.Writer { +func getBufioWriter(w io.Writer, size int) *bufio.Writer { + if size > 0 && size != defaultWriteBufferSize { + return bufio.NewWriterSize(w, size) + } bw, ok := bufioWriterPool.Get().(*bufio.Writer) if !ok { - return bufio.NewWriter(w) + return bufio.NewWriterSize(w, defaultWriteBufferSize) } bw.Reset(w) return bw } func putBufioWriter(bw *bufio.Writer) { + // Only pool default-size writers; getBufioWriter relies on it. + if bw.Size() != defaultWriteBufferSize { + return + } bufioWriterPool.Put(bw) } diff --git a/dial_write_buffer_internal_test.go b/dial_write_buffer_internal_test.go new file mode 100644 index 00000000..53391e2d --- /dev/null +++ b/dial_write_buffer_internal_test.go @@ -0,0 +1,32 @@ +//go:build !js + +package websocket + +import ( + "io" + "testing" + + "github.com/coder/websocket/internal/test/assert" +) + +func TestBufioWriterPool(t *testing.T) { + t.Parallel() + + for _, size := range []int{-1, 0, defaultWriteBufferSize, 5, 1024, 128 << 10} { + bw := getBufioWriter(io.Discard, size) + want := size + if size <= 0 { + want = defaultWriteBufferSize + } + assert.Equal(t, "size", want, bw.Size()) + putBufioWriter(bw) + } + + // sync.Pool may drop a Put, so repeat to reliably catch a leaked writer. + for range 100 { + putBufioWriter(getBufioWriter(io.Discard, 128<<10)) + bw := getBufioWriter(io.Discard, 0) + assert.Equal(t, "pooled size", defaultWriteBufferSize, bw.Size()) + putBufioWriter(bw) + } +} diff --git a/dial_write_buffer_test.go b/dial_write_buffer_test.go new file mode 100644 index 00000000..fc514815 --- /dev/null +++ b/dial_write_buffer_test.go @@ -0,0 +1,191 @@ +//go:build !js + +package websocket_test + +import ( + "bytes" + "context" + "crypto/rand" + "net" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/coder/websocket" + "github.com/coder/websocket/internal/test/assert" +) + +type countingConn struct { + net.Conn + writes *atomic.Int64 +} + +func (c countingConn) Write(p []byte) (int, error) { + c.writes.Add(1) + return c.Conn.Write(p) +} + +func dialCounting(t testing.TB, ctx context.Context, writeBufferSize int) (*websocket.Conn, *atomic.Int64) { + t.Helper() + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + c, err := websocket.Accept(w, r, nil) + if err != nil { + return + } + defer c.CloseNow() + c.SetReadLimit(-1) + for { + typ, p, err := c.Read(ctx) + if err != nil { + return + } + if err := c.Write(ctx, typ, p); err != nil { + return + } + } + })) + t.Cleanup(s.Close) + + writes := &atomic.Int64{} + transport := http.DefaultTransport.(*http.Transport).Clone() + t.Cleanup(transport.CloseIdleConnections) + transport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { + conn, err := (&net.Dialer{}).DialContext(ctx, network, addr) + if err != nil { + return nil, err + } + return countingConn{Conn: conn, writes: writes}, nil + } + c, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(s.URL, "http"), &websocket.DialOptions{ + HTTPClient: &http.Client{Transport: transport}, + WriteBufferSize: writeBufferSize, + }) + assert.Success(t, err) + c.SetReadLimit(-1) + t.Cleanup(func() { c.CloseNow() }) + return c, writes +} + +func TestDialWriteBufferSize(t *testing.T) { + t.Parallel() + + const defaultMsgSize = 64 << 10 + tests := []struct { + name string + writeBufferSize int + messageSize int + maxWrites int64 + minWrites int64 + }{ + { + name: "default", + writeBufferSize: 0, + messageSize: defaultMsgSize, + minWrites: defaultMsgSize / 4096, + }, + { + name: "negative", + writeBufferSize: -1, + messageSize: defaultMsgSize, + minWrites: defaultMsgSize / 4096, + }, + { + name: "explicitDefault", + writeBufferSize: 4096, + messageSize: defaultMsgSize, + minWrites: defaultMsgSize / 4096, + }, + { + name: "large", + writeBufferSize: 128 << 10, + messageSize: defaultMsgSize, + maxWrites: 1, + }, + { + name: "small", + writeBufferSize: 1024, + messageSize: defaultMsgSize, + minWrites: defaultMsgSize / 1024, + }, + // Smaller than a frame header and not a multiple of the 4-byte mask key. + { + name: "tiny", + writeBufferSize: 5, + messageSize: 1024, + minWrites: 1024 / 5, + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + c, writes := dialCounting(t, ctx, tc.writeBufferSize) + + msg := make([]byte, tc.messageSize) + _, err := rand.Read(msg) + assert.Success(t, err) + + before := writes.Load() + err = c.Write(ctx, websocket.MessageBinary, msg) + assert.Success(t, err) + got := writes.Load() - before + + if tc.maxWrites > 0 && got > tc.maxWrites { + t.Fatalf("%d writes for a %d byte message, want at most %d", got, tc.messageSize, tc.maxWrites) + } + if tc.minWrites > 0 && got < tc.minWrites { + t.Fatalf("%d writes for a %d byte message, want at least %d", got, tc.messageSize, tc.minWrites) + } + + typ, echoed, err := c.Read(ctx) + assert.Success(t, err) + assert.Equal(t, "message type", websocket.MessageBinary, typ) + if !bytes.Equal(msg, echoed) { + t.Fatal("echoed message differs from the one sent") + } + + err = c.Write(ctx, websocket.MessageText, []byte("small")) + assert.Success(t, err) + _, echoed, err = c.Read(ctx) + assert.Success(t, err) + assert.Equal(t, "small message", "small", string(echoed)) + + assert.Success(t, c.Close(websocket.StatusNormalClosure, "")) + }) + } +} + +func BenchmarkDialWriteBufferSize(b *testing.B) { + const messageSize = 64 << 10 + for _, size := range []int{0, 128 << 10} { + name := "default" + if size > 0 { + name = "128KiB" + } + b.Run(name, func(b *testing.B) { + ctx := b.Context() + c, writes := dialCounting(b, ctx, size) + msg := make([]byte, messageSize) + + b.SetBytes(messageSize) + b.ReportAllocs() + b.ResetTimer() + before := writes.Load() + for range b.N { + if err := c.Write(ctx, websocket.MessageBinary, msg); err != nil { + b.Fatal(err) + } + if _, _, err := c.Read(ctx); err != nil { + b.Fatal(err) + } + } + b.StopTimer() + b.ReportMetric(float64(writes.Load()-before)/float64(b.N), "writes/op") + }) + } +} diff --git a/write.go b/write.go index 1d4305c5..d7148928 100644 --- a/write.go +++ b/write.go @@ -267,6 +267,8 @@ func (mw *msgWriter) close() { if mw.c.client { mw.c.writeFrameMu.forceLock() putBufioWriter(mw.c.bw) + mw.c.bw = nil + mw.c.writeBuf = nil } mw.writeMu.forceLock() diff --git a/ws_js.go b/ws_js.go index 95f13e1a..a18adad0 100644 --- a/ws_js.go +++ b/ws_js.go @@ -287,6 +287,9 @@ func (c *Conn) Subprotocol() string { type DialOptions struct { // Subprotocols lists the subprotocols to negotiate with the server. Subprotocols []string + + // WriteBufferSize is unused. It's only here to match the core API. + WriteBufferSize int } // Dial creates a new WebSocket connection to the given url with the given options. From 79a199201a206ff98bb26b30f71b34a9bb8b7c9c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tam=C3=A1s=20Mojzes?= Date: Fri, 27 Nov 2026 15:47:13 +0100 Subject: [PATCH 2/2] test: wait for the echo server to exit in dialCounting httptest.Server.Close does not wait for hijacked connections, so the goroutine leak check in the bench job could catch the handler exiting. --- dial_write_buffer_test.go | 82 +++++++++++++++++++-------------------- 1 file changed, 41 insertions(+), 41 deletions(-) diff --git a/dial_write_buffer_test.go b/dial_write_buffer_test.go index fc514815..03d53785 100644 --- a/dial_write_buffer_test.go +++ b/dial_write_buffer_test.go @@ -5,17 +5,16 @@ package websocket_test import ( "bytes" "context" - "crypto/rand" "net" "net/http" "net/http/httptest" - "strings" "sync/atomic" "testing" "time" "github.com/coder/websocket" "github.com/coder/websocket/internal/test/assert" + "github.com/coder/websocket/internal/test/xrand" ) type countingConn struct { @@ -28,9 +27,12 @@ func (c countingConn) Write(p []byte) (int, error) { return c.Conn.Write(p) } -func dialCounting(t testing.TB, ctx context.Context, writeBufferSize int) (*websocket.Conn, *atomic.Int64) { +func dialCounting(t testing.TB, writeBufferSize int) (*websocket.Conn, *atomic.Int64) { t.Helper() + + serverDone := make(chan struct{}) s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + defer close(serverDone) c, err := websocket.Accept(w, r, nil) if err != nil { return @@ -38,35 +40,39 @@ func dialCounting(t testing.TB, ctx context.Context, writeBufferSize int) (*webs defer c.CloseNow() c.SetReadLimit(-1) for { - typ, p, err := c.Read(ctx) + typ, p, err := c.Read(context.Background()) if err != nil { return } - if err := c.Write(ctx, typ, p); err != nil { + if err := c.Write(context.Background(), typ, p); err != nil { return } } })) t.Cleanup(s.Close) - writes := &atomic.Int64{} + var writes atomic.Int64 transport := http.DefaultTransport.(*http.Transport).Clone() t.Cleanup(transport.CloseIdleConnections) transport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { - conn, err := (&net.Dialer{}).DialContext(ctx, network, addr) + var d net.Dialer + conn, err := d.DialContext(ctx, network, addr) if err != nil { return nil, err } - return countingConn{Conn: conn, writes: writes}, nil + return countingConn{Conn: conn, writes: &writes}, nil } - c, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(s.URL, "http"), &websocket.DialOptions{ + c, _, err := websocket.Dial(t.Context(), s.URL, &websocket.DialOptions{ HTTPClient: &http.Client{Transport: transport}, WriteBufferSize: writeBufferSize, }) assert.Success(t, err) c.SetReadLimit(-1) - t.Cleanup(func() { c.CloseNow() }) - return c, writes + t.Cleanup(func() { + c.CloseNow() + <-serverDone // httptest.Server.Close does not wait for hijacked connections. + }) + return c, &writes } func TestDialWriteBufferSize(t *testing.T) { @@ -118,28 +124,23 @@ func TestDialWriteBufferSize(t *testing.T) { minWrites: 1024 / 5, }, } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { t.Parallel() - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) defer cancel() - c, writes := dialCounting(t, ctx, tc.writeBufferSize) - - msg := make([]byte, tc.messageSize) - _, err := rand.Read(msg) - assert.Success(t, err) + c, writes := dialCounting(t, tt.writeBufferSize) + msg := xrand.Bytes(tt.messageSize) before := writes.Load() - err = c.Write(ctx, websocket.MessageBinary, msg) - assert.Success(t, err) + assert.Success(t, c.Write(ctx, websocket.MessageBinary, msg)) got := writes.Load() - before - - if tc.maxWrites > 0 && got > tc.maxWrites { - t.Fatalf("%d writes for a %d byte message, want at most %d", got, tc.messageSize, tc.maxWrites) + if tt.maxWrites > 0 && got > tt.maxWrites { + t.Errorf("got %d writes for a %d byte message, want at most %d", got, tt.messageSize, tt.maxWrites) } - if tc.minWrites > 0 && got < tc.minWrites { - t.Fatalf("%d writes for a %d byte message, want at least %d", got, tc.messageSize, tc.minWrites) + if tt.minWrites > 0 && got < tt.minWrites { + t.Errorf("got %d writes for a %d byte message, want at least %d", got, tt.messageSize, tt.minWrites) } typ, echoed, err := c.Read(ctx) @@ -149,8 +150,7 @@ func TestDialWriteBufferSize(t *testing.T) { t.Fatal("echoed message differs from the one sent") } - err = c.Write(ctx, websocket.MessageText, []byte("small")) - assert.Success(t, err) + assert.Success(t, c.Write(ctx, websocket.MessageText, []byte("small"))) _, echoed, err = c.Read(ctx) assert.Success(t, err) assert.Equal(t, "small message", "small", string(echoed)) @@ -162,29 +162,29 @@ func TestDialWriteBufferSize(t *testing.T) { func BenchmarkDialWriteBufferSize(b *testing.B) { const messageSize = 64 << 10 - for _, size := range []int{0, 128 << 10} { - name := "default" - if size > 0 { - name = "128KiB" - } - b.Run(name, func(b *testing.B) { - ctx := b.Context() - c, writes := dialCounting(b, ctx, size) + benchmarks := []struct { + name string + size int + }{ + {name: "default", size: 0}, + {name: "128KiB", size: 128 << 10}, + } + for _, bm := range benchmarks { + b.Run(bm.name, func(b *testing.B) { + c, writes := dialCounting(b, bm.size) msg := make([]byte, messageSize) b.SetBytes(messageSize) b.ReportAllocs() - b.ResetTimer() before := writes.Load() - for range b.N { - if err := c.Write(ctx, websocket.MessageBinary, msg); err != nil { + for b.Loop() { + if err := c.Write(b.Context(), websocket.MessageBinary, msg); err != nil { b.Fatal(err) } - if _, _, err := c.Read(ctx); err != nil { + if _, _, err := c.Read(b.Context()); err != nil { b.Fatal(err) } } - b.StopTimer() b.ReportMetric(float64(writes.Load()-before)/float64(b.N), "writes/op") }) }