[IMPROVED] Memory growth on compressed websocket connections. (#4620)

Holding onto the compressor and not recycling the internal byte slice
could cause havoc with GC.

This needs to be improved but this at least should allow the GC to
cleanup more effectively.

Signed-off-by: Derek Collison <derek@nats.io>
This commit is contained in:
Derek Collison
2023-10-03 15:37:01 -07:00
committed by GitHub

View File

@@ -115,7 +115,6 @@ type websocket struct {
nocompfrag bool // No fragment for compressed frames nocompfrag bool // No fragment for compressed frames
maskread bool maskread bool
maskwrite bool maskwrite bool
compressor *flate.Writer
cookieJwt string cookieJwt string
clientIP string clientIP string
} }
@@ -1295,15 +1294,8 @@ func (c *client) wsCollapsePtoNB() (net.Buffers, int64) {
if mfs > 0 && c.ws.nocompfrag { if mfs > 0 && c.ws.nocompfrag {
mfs = 0 mfs = 0
} }
buf := &bytes.Buffer{} buf := bytes.NewBuffer(nbPoolGet(usz))
cp, _ := flate.NewWriter(buf, flate.BestSpeed)
cp := c.ws.compressor
if cp == nil {
c.ws.compressor, _ = flate.NewWriter(buf, flate.BestSpeed)
cp = c.ws.compressor
} else {
cp.Reset(buf)
}
var csz int var csz int
for _, b := range nb { for _, b := range nb {
cp.Write(b) cp.Write(b)
@@ -1352,6 +1344,7 @@ func (c *client) wsCollapsePtoNB() (net.Buffers, int64) {
} }
csz = len(h) + ol csz = len(h) + ol
} }
nbPoolPut(b) // No longer needed as we copied from above.
// Add to pb the compressed data size (including headers), but // Add to pb the compressed data size (including headers), but
// remove the original uncompressed data size that was added // remove the original uncompressed data size that was added
// during the queueing. // during the queueing.