Skip to content

Commit

Permalink
Close conn when HTTP/1.1 clients call bidi methods (#408)
Browse files Browse the repository at this point in the history
If an HTTP/1.1 client calls a bidi RPC method, the caller has likely
written application-level code that expects a full-duplex stream. Unless
the server closes the TCP connection, the client code will often end up
blocked because it's trying to read the response before it closes the
request body.
  • Loading branch information
akshayjshah authored Nov 30, 2022
1 parent 9a4d409 commit 7a79704
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
23 changes: 23 additions & 0 deletions connect_ext_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1824,6 +1824,29 @@ func TestUnflushableResponseWriter(t *testing.T) {
}
}

func TestBidiOverHTTP1(t *testing.T) {
t.Parallel()
mux := http.NewServeMux()
mux.Handle(pingv1connect.NewPingServiceHandler(pingServer{}))
server := httptest.NewServer(mux)
t.Cleanup(server.Close)

// Clients expecting a full-duplex connection that end up with a simplex
// HTTP/1.1 connection shouldn't hang. Instead, the server should close the
// TCP connection.
client := pingv1connect.NewPingServiceClient(server.Client(), server.URL)
stream := client.CumSum(context.Background())
if err := stream.Send(&pingv1.CumSumRequest{Number: 2}); err != nil {
assert.ErrorIs(t, err, io.EOF)
}
_, err := stream.Receive()
assert.NotNil(t, err)
assert.Equal(t, connect.CodeOf(err), connect.CodeUnknown)
assert.Equal(t, err.Error(), "unknown: HTTP status 505 HTTP Version Not Supported")
assert.Nil(t, stream.CloseRequest())
assert.Nil(t, stream.CloseResponse())
}

type unflushableWriter struct {
w http.ResponseWriter
}
Expand Down
4 changes: 4 additions & 0 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,10 @@ func (h *Handler) ServeHTTP(responseWriter http.ResponseWriter, request *http.Re
// okay if we can't re-use the connection.
isBidi := (h.spec.StreamType & StreamTypeBidi) == StreamTypeBidi
if isBidi && request.ProtoMajor < 2 {
// Clients coded to expect full-duplex connections may hang if they've
// mistakenly negotiated HTTP/1.1. To unblock them, we must close the
// underlying TCP connection.
responseWriter.Header().Set("Connection", "close")
responseWriter.WriteHeader(http.StatusHTTPVersionNotSupported)
return
}
Expand Down

0 comments on commit 7a79704

Please sign in to comment.