Skip to content

fix: stop CloseRead from waiting on itself - #607

Draft
mafredri wants to merge 1 commit into
masterfrom
mafredri/closeread-self-wait
Draft

mafredri wants to merge 1 commit into
masterfrom
mafredri/closeread-self-wait

Conversation

@mafredri

Copy link
Copy Markdown
Member

When the CloseRead goroutine reads a data message, it calls Close, and Close waits for that same goroutine to exit. That wait ends only at its 15 second timeout, so the context CloseRead returns is cancelled 15 seconds late. A Close that the application calls in that window also waits about 15 seconds. If it starts before the goroutine's own wait, it then returns failed to close WebSocket: failed to wait for close read goroutine to exit.

The goroutine now runs the close handshake itself instead of calling Close, and its deferred close closes the connection. If another Close is already closing the connection, the goroutine waits until that Close has closed it.

TestCloseReadDataMessage/closesConn and TestCloseReadDataMessage/duringClose fail on master and pass here. They run in a testing/synctest bubble, so a close that waits on the 15 second timer fails the test without waiting for it. Lint, go test -race ./... on Go 1.26 and 1.27, and the Wasm tests pass.

This conflicts with #564 in the CloseRead goroutine in read.go, where #564 replaces the same Close call with an internal close. Whichever merges second needs a rebase that keeps this change's handshake.

Decision log
  • The goroutine cannot call Close, because Close waits for the CloseRead goroutine to exit.
  • When a concurrent Close is closing the connection, the goroutine waits for c.closed instead of returning. Returning runs the deferred close, which would close the connection before that Close has finished its handshake.
  • The close code and reason are unchanged: StatusPolicyViolation and "unexpected data message".
  • The handshake's error is dropped, as the result of master's Close call was.
  • Wasm is unchanged. Its Close waits for the browser's close event, not for the CloseRead goroutine.

🤖 Created with the help of Coder Agents.

When the CloseRead goroutine reads a data message it calls Close, and
Close waits for that same goroutine to exit. The wait ended only on
its 15 second timeout, so the CloseRead context was cancelled 15
seconds late and a concurrent Close stalled for as long.

The goroutine now runs the close handshake itself. When another Close
is already running, it waits for that Close to close the connection,
because exiting earlier closes the connection before that Close has
finished its handshake.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant