Skip to content

Commit

Permalink
Use built in Go APIs to buffer the read
Browse files Browse the repository at this point in the history
  • Loading branch information
ankur22 committed Oct 14, 2024
1 parent 14fbdd8 commit 184556f
Showing 1 changed file with 8 additions and 27 deletions.
35 changes: 8 additions & 27 deletions common/connection.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
package common

import (
"bufio"
"bytes"
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"net/http"
"sync"
"sync/atomic"
Expand Down Expand Up @@ -321,13 +319,7 @@ func (c *Connection) findTargetIDForLog(id target.SessionID) target.ID {
}

func (c *Connection) recvLoop() {
// Setting the wsBuffer as the same size as bufio.NewReader. We should look at
// optimizing it depending on the average website, or allow it to be
// configurable, but it depends on how much this affects the user.
wsBuffer := make([]byte, 4096)
// This buffer grows as the test progresses.
var recvBuffer []byte
var bufReader bufio.Reader
var buffer bytes.Buffer

c.logger.Debugf("Connection:recvLoop", "wsURL:%q", c.wsURL)
for {
Expand All @@ -337,28 +329,17 @@ func (c *Connection) recvLoop() {
return
}

// Buffered reads from the websocket connection.
bufReader.Reset(reader)
for {
n, err := bufReader.Read(wsBuffer)
if err == io.EOF {
break
}
if err != nil {
c.handleIOError(err)
return
}
recvBuffer = append(recvBuffer, bytes.Clone(wsBuffer[:n])...)
if _, err := buffer.ReadFrom(reader); err != nil {
c.handleIOError(err)
return
}

// Clone the bytes from the recvBuffer to buf before unmarshaling
// the message. Without this test the unmarshaling will fail as
// it reuses the buf as the underlying bytes buffer.
buf := make([]byte, len(recvBuffer))
copy(buf, recvBuffer)
// the message. Without this, the unmarshaling will fail as it
// reuses the buf as the underlying bytes buffer.
buf := bytes.Clone(buffer.Bytes())

// Reset recvBuffer so it can be reused.
recvBuffer = recvBuffer[:0]
buffer.Reset()

c.logger.Tracef("cdp:recv", "<- %s", buf)

Expand Down

0 comments on commit 184556f

Please sign in to comment.