websocket icon indicating copy to clipboard operation
websocket copied to clipboard

Graceful shutdown of the websocket connection.

Open markusthoemmes opened this issue 7 years ago • 9 comments

It seems like to achieve a "normal" shutdown of a websocket connection, one needs to do a dance like:

  1. Send Close message
  2. Wait for receiving a Close message
  3. Actually close the connection

The Close method of today closes the connection immediately, without warning or graceful shutdown. Would it be desirable to have a Shutdown method like golang's http servers, which does the dance explained above for the user?

markusthoemmes avatar Nov 05 '18 14:11 markusthoemmes

I think this is desirable to have, as well as in-built support for checking liveness using ping/pong and deadlines. Most applications need these features.

The current API mostly handles the wire format. The only thing the package does above the wire format is respond to ping and respond to close. This low-level API provides flexibility for the applications that need it (like the one I work on), but most don't need this flexibility.

This package can benefit from a high-level API that wraps up all these things that applications need: shutdown, checking liveness, concurrent sends, ...

ghost avatar Nov 14 '18 14:11 ghost

@garyburd Can you please assign this issue to me. I would like to work on it.

ankur0493 avatar Dec 06 '18 07:12 ankur0493

@ankur0493 Please post a proposed API and overview of the implementation for discussion.

I tried to assign you to this issue, but Github will not let me do it. Please let me know what I need to do.

garyburd avatar Dec 10 '18 03:12 garyburd

(Can’t assign to non-maintainers of a repo. I think it’s fair just note that @ankur0493 has it & follow up!) On Sun, Dec 9, 2018 at 7:44 PM Gary Burd [email protected] wrote:

@ankur0493 https://github.com/ankur0493 Please post a proposed API and overview of the implementation for discussion.

I tried to assign you to this issue, but Github will not let me do it. Please let me know what I need to do.

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/gorilla/websocket/issues/448#issuecomment-445659075, or mute the thread https://github.com/notifications/unsubscribe-auth/AABIcJ-3eUsrZCkdzplRzK_dqmoxrQhwks5u3dh-gaJpZM4YOjKk .

elithrar avatar Dec 10 '18 04:12 elithrar

Thanks @garyburd. Will soon share the API details.

ankur0493 avatar Dec 11 '18 07:12 ankur0493

This feature is a helper method. It's possible for applications to implement the RFC today. If an application does not initiate the closing handshake, then the application probably implements the RFC without doing anything special.

Based on discussion in #487, here's my summary of the design:

To avoid concurrent reads on the connection, the following two cases must be handled differently:

  • Shutdown is executed from the reading goroutine
  • Shutdown in executed from some other goroutine.

The common code for both cases starts with:

err := c.WriteControlMessage(CloseMessage,FormatCloseMessage(code, msg))
if err != nil && err != ErrCloseSent {
      // If close message could not be sent, then close without the handshake.
      return c.Close()
}

The remaining code for the reading goroutine case is:

 // To prevent ping, pong and close handlers from setting the read deadline, set these handlers to the default.
c.SetPingHandler(nil)
c.SetPongHandler(nil)
c.SetCloseHandler(nil)
c.SetReadDeadline(timeout)
for {
    if _, _, err := c.NextReader(); err != nil {
        break
    }
}
return c.Close()

The remaining code for shutdown from another goroutine is:

    select {
    case <- c.readDone:
    case <- time.After(timeout):
    }
    return c.Close()

where c.readDone is a channel that's closed when c.readErr is changed from nil to a non-nil value.

garyburd avatar Mar 05 '19 23:03 garyburd

For someone who wants this now, I've implemented it in nhooyr.io/[email protected]

See discussion in https://github.com/nhooyr/websocket/pull/160

nhooyr avatar Oct 09 '19 01:10 nhooyr

How to implement:

Add field to Upgrader and Dialer:

 CloseTimeout time.Duration 

Add field to Conn:

  maxReadDeadline time.Time

When a close message is sent, CloseTimeout is not zero, and maxReadDeadline is zero, then set maxReadDeadline to time.Now().Add(CloseTimeout). Set read deadline on underlying connection to the same value.

Modify SetReadDeadline to honor maxReadDeadline.

Use a mutex to protect against data races in the code above.

Applications that set the upgrader/dialer field get graceful shutdown by sending a close message. The application’s read loop will either exit with the echoed close message or a timeout.

This proposal allows any goroutine to initiate the graceful shutdown by using WriteControl to send a close message.

greenmarmot avatar Apr 01 '24 00:04 greenmarmot