Skip to content

Commit

Permalink
reverseproxy: Wait for both ends of websocket to close (#6175)
Browse files Browse the repository at this point in the history
  • Loading branch information
WeidiDeng committed Apr 15, 2024
1 parent 81413ca commit b40cacf
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
4 changes: 3 additions & 1 deletion modules/caddyhttp/reverseproxy/reverseproxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -922,7 +922,9 @@ func (h *Handler) finalizeResponse(
) error {
// deal with 101 Switching Protocols responses: (WebSocket, h2c, etc)
if res.StatusCode == http.StatusSwitchingProtocols {
h.handleUpgradeResponse(logger, rw, req, res)
var wg sync.WaitGroup
h.handleUpgradeResponse(logger, &wg, rw, req, res)
wg.Wait()
return nil
}

Expand Down
8 changes: 6 additions & 2 deletions modules/caddyhttp/reverseproxy/streaming.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import (
"golang.org/x/net/http/httpguts"
)

func (h *Handler) handleUpgradeResponse(logger *zap.Logger, rw http.ResponseWriter, req *http.Request, res *http.Response) {
func (h *Handler) handleUpgradeResponse(logger *zap.Logger, wg *sync.WaitGroup, rw http.ResponseWriter, req *http.Request, res *http.Response) {
reqUpType := upgradeType(req.Header)
resUpType := upgradeType(res.Header)

Expand Down Expand Up @@ -121,7 +121,7 @@ func (h *Handler) handleUpgradeResponse(logger *zap.Logger, rw http.ResponseWrit
defer deleteFrontConn()
defer deleteBackConn()

spc := switchProtocolCopier{user: conn, backend: backConn}
spc := switchProtocolCopier{user: conn, backend: backConn, wg: wg}

// setup the timeout if requested
var timeoutc <-chan time.Time
Expand All @@ -132,6 +132,7 @@ func (h *Handler) handleUpgradeResponse(logger *zap.Logger, rw http.ResponseWrit
}

errc := make(chan error, 1)
wg.Add(2)
go spc.copyToBackend(errc)
go spc.copyFromBackend(errc)
select {
Expand Down Expand Up @@ -529,16 +530,19 @@ func (m *maxLatencyWriter) stop() {
// forth have nice names in stacks.
type switchProtocolCopier struct {
user, backend io.ReadWriteCloser
wg *sync.WaitGroup
}

func (c switchProtocolCopier) copyFromBackend(errc chan<- error) {
_, err := io.Copy(c.user, c.backend)
errc <- err
c.wg.Done()
}

func (c switchProtocolCopier) copyToBackend(errc chan<- error) {
_, err := io.Copy(c.backend, c.user)
errc <- err
c.wg.Done()
}

var streamingBufPool = sync.Pool{
Expand Down

0 comments on commit b40cacf

Please sign in to comment.