Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 19 additions & 3 deletions dial.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -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)
}
32 changes: 32 additions & 0 deletions dial_write_buffer_internal_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
191 changes: 191 additions & 0 deletions dial_write_buffer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
//go:build !js

package websocket_test

import (
"bytes"
"context"
"net"
"net/http"
"net/http/httptest"
"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 {
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, 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
}
defer c.CloseNow()
c.SetReadLimit(-1)
for {
typ, p, err := c.Read(context.Background())
if err != nil {
return
}
if err := c.Write(context.Background(), typ, p); err != nil {
return
}
}
}))
t.Cleanup(s.Close)

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) {
var d net.Dialer
conn, err := d.DialContext(ctx, network, addr)
if err != nil {
return nil, err
}
return countingConn{Conn: conn, writes: &writes}, nil
}
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()
<-serverDone // httptest.Server.Close does not wait for hijacked connections.
})
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 _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()

ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
defer cancel()
c, writes := dialCounting(t, tt.writeBufferSize)
msg := xrand.Bytes(tt.messageSize)

before := writes.Load()
assert.Success(t, c.Write(ctx, websocket.MessageBinary, msg))
got := writes.Load() - before
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 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)
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")
}

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))

assert.Success(t, c.Close(websocket.StatusNormalClosure, ""))
})
}
}

func BenchmarkDialWriteBufferSize(b *testing.B) {
const messageSize = 64 << 10
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()
before := writes.Load()
for b.Loop() {
if err := c.Write(b.Context(), websocket.MessageBinary, msg); err != nil {
b.Fatal(err)
}
if _, _, err := c.Read(b.Context()); err != nil {
b.Fatal(err)
}
}
b.ReportMetric(float64(writes.Load()-before)/float64(b.N), "writes/op")
})
}
}
2 changes: 2 additions & 0 deletions write.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
3 changes: 3 additions & 0 deletions ws_js.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading