From 51de0f831bf4b1bdcb84101f95009fde83d35a27 Mon Sep 17 00:00:00 2001 From: Xargin Date: Wed, 8 Sep 2021 00:22:00 +0800 Subject: [PATCH] crypto/tls: shrink tls Conn's rawInput buffer when Read timeout This will reduce the rawInput buffer memory cost for large number of idle tls connections --- src/crypto/tls/conn.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/crypto/tls/conn.go b/src/crypto/tls/conn.go index 969f357834c..6d37600a38b 100644 --- a/src/crypto/tls/conn.go +++ b/src/crypto/tls/conn.go @@ -797,6 +797,14 @@ func (c *Conn) readFromUntil(r io.Reader, n int) error { // "predict" closeNotify alerts. c.rawInput.Grow(needs + bytes.MinRead) _, err := c.rawInput.ReadFrom(&atLeastReader{r, int64(needs)}) + + // Read timeout, and we do not get any data, connection is idle, + // we should replace rawInput buffer with a small one + if e, ok := err.(net.Error); ok && e.Timeout() && + c.rawInput.Len() == 0 && c.rawInput.Cap() > 4*bytes.MinRead { + c.rawInput = *bytes.NewBuffer(make([]byte, 0, bytes.MinRead)) + } + return err }