diff --git a/internal/gateway/upstream_closed_unsent_test.go b/internal/gateway/upstream_closed_unsent_test.go index 45321acfa..9743fd970 100644 --- a/internal/gateway/upstream_closed_unsent_test.go +++ b/internal/gateway/upstream_closed_unsent_test.go @@ -9,25 +9,35 @@ import ( "net" "net/http" "net/http/httptest" + "net/http/httptrace" "strconv" "strings" "sync/atomic" + "syscall" "testing" "time" ) // closingUpstream is a TLS vendor whose first closeFirst new connections are // ended by the far side as soon as the handshake is done, before the -// request is read (a TUN proxy's fake IP doing so, dealyang_ on X), or, -// with afterSent, once the whole request was read. The rest are -// answered 200 with the body's length. +// request is read (a TUN proxy's fake IP doing so, dealyang_ on X), or +// once the whole request was read: reset (afterSentReset) or ended +// (afterSentEnd). The rest are answered 200 with the body's length. type closingUpstream struct { addr string accepts atomic.Int32 answered atomic.Int32 } -func newClosingUpstream(t *testing.T, closeFirst int32, afterSent bool) *closingUpstream { +type closeWhen int + +const ( + atHandshake closeWhen = iota + afterSentReset + afterSentEnd +) + +func newClosingUpstream(t *testing.T, closeFirst int32, when closeWhen) *closingUpstream { t.Helper() srv := httptest.NewUnstartedServer(nil) srv.StartTLS() @@ -55,11 +65,15 @@ func newClosingUpstream(t *testing.T, closeFirst int32, afterSent bool) *closing return } if n <= closeFirst { - if afterSent { - // the whole request, then reset + if when != atHandshake { + // the whole request, then reset or ended if r, err := http.ReadRequest(bufio.NewReader(tc)); err == nil { io.Copy(io.Discard, r.Body) } + if when == afterSentEnd { + tc.Close() + return + } c.(*net.TCPConn).SetLinger(0) c.Close() return @@ -142,7 +156,7 @@ func closedUnsentPost(t *testing.T, cl *http.Client, addr string) (*http.Respons // before a byte of the request went out, is not the vendor's answer: the // request goes again on another new connection and is answered, whole. func TestClosedBeforeSentIsSentAgain(t *testing.T) { - u := newClosingUpstream(t, 2, false) + u := newClosingUpstream(t, 2, atHandshake) res, err := closedUnsentPost(t, closedUnsentClient(t), u.addr) if err != nil { t.Fatalf("a request whose first two new connections were closed before it was sent failed: %v", err) @@ -157,10 +171,74 @@ func TestClosedBeforeSentIsSentAgain(t *testing.T) { } } +// goEnded is Go's HTTP/1.1 transport as replayable sees it when a new +// connection ends under a request: GotConn for a new connection, then, +// if wrote, WroteRequest without an error, then err. The first ends +// calls end so, the rest are answered 200. +type goEnded struct { + ends int32 + wrote bool + err error + tries atomic.Int32 +} + +func (g *goEnded) RoundTrip(r *http.Request) (*http.Response, error) { + trace := httptrace.ContextClientTrace(r.Context()) + if trace.GotConn != nil { + trace.GotConn(httptrace.GotConnInfo{}) + } + if g.tries.Add(1) > g.ends { + return &http.Response{StatusCode: 200, Body: http.NoBody, Request: r}, nil + } + if g.wrote && trace.WroteRequest != nil { + trace.WroteRequest(httptrace.WroteRequestInfo{}) + } + return nil, g.err +} + +// On a busy machine the reader can see a proxy's close right after the +// handshake before Go's write goroutine has run: Go then drops the +// request unwritten (no WroteRequest) and says only "EOF", not a write +// error (#5519, red on CI's race run). Nothing went out, so the request +// goes again; so too for a reset seen first. +func TestEndedBeforeWriteBeganIsSentAgain(t *testing.T) { + closedUnsentClient(t) // the short pauses + reset := &net.OpError{Op: "read", Net: "tcp", Err: syscall.ECONNRESET} + for _, end := range []error{io.EOF, reset} { + g := &goEnded{ends: 2, err: end} + res, err := closedUnsentPost(t, &http.Client{Transport: replayable{g}}, "127.0.0.1:1") + if err != nil { + t.Fatalf("a request whose first two new connections ended (%v) before its write began failed: %v", end, err) + } + res.Body.Close() + if n := g.tries.Load(); n != 3 { + t.Errorf("%v: %d tries, want 3: two ended, one answered", end, n) + } + } +} + +// Once Go has written the whole request, the same end may follow a +// vendor that read it and acted on it: not sent again. +func TestEndedAfterWriteIsNotSentAgain(t *testing.T) { + closedUnsentClient(t) + g := &goEnded{ends: 2, wrote: true, err: io.EOF} + _, err := closedUnsentPost(t, &http.Client{Transport: replayable{g}}, "127.0.0.1:1") + if !errors.Is(err, io.EOF) { + t.Fatalf("err = %v, want the EOF as it was", err) + } + var cu errClosedUnsent + if errors.As(err, &cu) { + t.Errorf("err = %v: a request written whole was called unsent", err) + } + if n := g.tries.Load(); n != 1 { + t.Errorf("%d tries, want 1", n) + } +} + // Closed on every try, the request fails with why, in the words the // routing reads to rest nobody for it. func TestClosedBeforeSentEveryTimeSaysWhy(t *testing.T) { - u := newClosingUpstream(t, 100, false) + u := newClosingUpstream(t, 100, atHandshake) _, err := closedUnsentPost(t, closedUnsentClient(t), u.addr) var cu errClosedUnsent if !errors.As(err, &cu) { @@ -179,18 +257,21 @@ func TestClosedBeforeSentEveryTimeSaysWhy(t *testing.T) { // A connection closed after the vendor read the whole request may have // had it acted on: that is not sent again here. +// Reset or ended ("EOF"), the same. func TestClosedAfterSentIsNotSentAgain(t *testing.T) { - u := newClosingUpstream(t, 100, true) - _, err := closedUnsentPost(t, closedUnsentClient(t), u.addr) - if err == nil { - t.Fatal("no error from a connection closed under the request") - } - var cu errClosedUnsent - if errors.As(err, &cu) { - t.Errorf("err = %v: a request whose bytes went out was called unsent", err) - } - if n := u.accepts.Load(); n != 1 { - t.Errorf("%d connections for a request the vendor had read whole, want 1 (%v)", n, err) + for _, when := range []closeWhen{afterSentReset, afterSentEnd} { + u := newClosingUpstream(t, 100, when) + _, err := closedUnsentPost(t, closedUnsentClient(t), u.addr) + if err == nil { + t.Fatalf("close %d: no error from a connection closed under the request", when) + } + var cu errClosedUnsent + if errors.As(err, &cu) { + t.Errorf("close %d: err = %v: a request whose bytes went out was called unsent", when, err) + } + if n := u.accepts.Load(); n != 1 { + t.Errorf("close %d: %d connections for a request the vendor had read whole, want 1 (%v)", when, n, err) + } } } diff --git a/internal/gateway/upstream_transport.go b/internal/gateway/upstream_transport.go index 9c9d14c19..40dbcd6e9 100644 --- a/internal/gateway/upstream_transport.go +++ b/internal/gateway/upstream_transport.go @@ -173,7 +173,10 @@ type replayable struct{ http.RoundTripper } // one: "write tcp …: use of closed network connection". The vendor never // had the whole request, so it is sent again on another new connection, // after a moment, up to unsentAgain times (dealyang_ on X: a Codex turn through a TUN proxy's -// fake IP, 198.18.0.17, failed with it on every reconnect). Still closed, +// fake IP, 198.18.0.17, failed with it on every reconnect). When the +// reader saw the close before the write began, as on a busy machine, Go +// says only "EOF"; that too goes again, as long as the request's write +// had not finished (#5519). Still closed, // the error says why (errClosedUnsent), and the routing rests nobody for // it (failProxy). func (t replayable) RoundTrip(req *http.Request) (*http.Response, error) { @@ -189,16 +192,19 @@ func (t replayable) RoundTrip(req *http.Request) (*http.Response, error) { r.Header["X-Idempotency-Key"] = nil } for n := 0; ; n++ { - var fresh, h2 atomic.Bool + var fresh, h2, wrote atomic.Bool trace := &httptrace.ClientTrace{GotConn: func(i httptrace.GotConnInfo) { fresh.Store(!i.Reused) if tc, ok := i.Conn.(interface{ ConnectionState() tls.ConnectionState }); ok { h2.Store(tc.ConnectionState().NegotiatedProtocol == "h2") } + }, WroteRequest: func(i httptrace.WroteRequestInfo) { + wrote.Store(i.Err == nil) }} try := r.WithContext(httptrace.WithClientTrace(r.Context(), trace)) res, err := t.RoundTripper.RoundTrip(try) - if err == nil || !fresh.Load() || h2.Load() || !closedBeforeSent(err) || req.Context().Err() != nil { + if err == nil || !fresh.Load() || h2.Load() || req.Context().Err() != nil || + !closedBeforeSent(err) && (wrote.Load() || !endedUnwritten(err)) { return res, err } if n >= len(unsentAgain) || (r.Body != nil && r.Body != http.NoBody && r.GetBody == nil) { @@ -235,14 +241,29 @@ var unsentAgain = []time.Duration{250 * time.Millisecond, time.Second} // "nothing written" doesn't hold over TLS: a server had read 1186 bytes // of a request Go called unwritten.) A TLS connection the reader closed // first fails the write with a bare net.ErrClosed; the reader's own end is -// "EOF" or a read error. A close the reader saw before the write began is -// Go's errServerClosedIdle (seen on Windows). +// "EOF" or a read error, read by endedUnwritten. A close the reader saw +// before the request was handed to the connection is Go's +// errServerClosedIdle (seen on Windows). func closedBeforeSent(err error) bool { var op *net.OpError return errors.As(err, &op) && op.Op == "write" || errors.Is(err, net.ErrClosed) || strings.Contains(err.Error(), "http: server closed idle connection") } +// endedUnwritten says err is the reader's end of a connection the far +// side closed — "EOF", or a read error such as a reset — which counts as +// closed before sent only while the request's write had not finished +// (no WroteRequest without an error): on a busy machine Go's write +// goroutine may not have run yet when a proxy's close right after the +// handshake arrives, so the reader sees the end first and Go returns a +// bare "EOF", not a write error (#5519). Once the whole request was +// written, the same end may follow a vendor that read and acted on it, +// and it is never sent again here. +func endedUnwritten(err error) bool { + var op *net.OpError + return errors.Is(err, io.EOF) || errors.As(err, &op) && op.Op == "read" && !op.Timeout() +} + // errClosedUnsent is a request's error once every new connection it was // tried on was closed before the whole of it was sent: what went wrong and // where to look, read by failure as nobody's fault (closedUnsentWords).