net/memnet: implement CloseRead and CloseWrite

tcpproxy propagates a backend's close to the client by calling CloseWrite
on the source connection. connHalf did not implement it, so the call was a
no-op and the client never saw EOF. TestTCPRoundRobinHandler only unblocked
the proxy's remaining copy goroutine by writing more data after the first
echo. When the backend closed with that data still buffered in the pipe,
the write was discarded and the test hung until the 10 minute timeout.

Implement both halves of the half-close contract on connHalf. A new test
covers buffered data surviving CloseWrite, EOF on the read after it, and
writes failing after CloseRead.

Fixes #17533

Signed-off-by: Yunus Emre Karaman <emre884k@gmail.com>
This commit is contained in:
Yunus Emre Karaman authored and Brad Fitzpatrick committed 2026-11-15 10:35:58 -08:00
1 parent daf82a50f0
commit a6baab333a
2 files changed
+50

No files matched your search

+13
View File
@@ -85,6 +85,19 @@ func (c *connHalf) Close() error {
return c.r.Close()
}
// CloseWrite closes the write side of the connection. The peer can read
// buffered data, then gets io.EOF. It matches net.TCPConn.CloseWrite, which
// proxies such as tcpproxy rely on to propagate a backend's close.
func (c *connHalf) CloseWrite() error {
return c.w.Close()
}
// CloseRead closes the read side of the connection. Subsequent reads return
// io.EOF and the peer's writes fail.
func (c *connHalf) CloseRead() error {
return c.r.Close()
}
func (c *connHalf) SetDeadline(t time.Time) error {
err1 := c.SetReadDeadline(t)
err2 := c.SetWriteDeadline(t)
+37
View File
@@ -4,6 +4,8 @@
package memnet
import (
"errors"
"io"
"net"
"testing"
@@ -19,3 +21,38 @@ func TestConn(t *testing.T) {
}, nil
})
}
func TestConnCloseWriteAndCloseRead(t *testing.T) {
a, b := NewConn("test", bufferSize)
// Half-close is not part of the Conn interface, matching net.Conn.
ac := a.(interface{ CloseWrite() error })
bc := b.(interface{ CloseRead() error })
if _, err := a.Write([]byte("hello")); err != nil {
t.Fatal(err)
}
if err := ac.CloseWrite(); err != nil {
t.Fatal(err)
}
// Buffered data survives the half-close; the next read is EOF.
buf := make([]byte, 8)
if n, err := b.Read(buf); n != 5 || err != nil {
t.Fatalf("Read = %d, %v; want 5, nil", n, err)
}
if _, err := b.Read(buf); !errors.Is(err, io.EOF) {
t.Fatalf("Read after CloseWrite = %v; want io.EOF", err)
}
if _, err := a.Write([]byte("x")); err == nil {
t.Fatal("Write after CloseWrite succeeded")
}
if err := bc.CloseRead(); err != nil {
t.Fatal(err)
}
if _, err := b.Read(buf); !errors.Is(err, io.EOF) {
t.Fatalf("Read after CloseRead = %v; want io.EOF", err)
}
if _, err := a.Write([]byte("x")); err == nil {
t.Fatal("Write after peer CloseRead succeeded")
}
}