Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion lib/web/websocket/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,9 @@ function failWebsocketConnection (handler, code, reason, cause) {

if (isConnecting(handler.readyState)) {
// If the connection was not established, we must still emit an 'error' and 'close' events
handler.onSocketClose()
// Use queueMicrotask to ensure the close event fires after readyState is set to CLOSING
// See: https://websockets.spec.whatwg.org/#closeWebSocket
queueMicrotask(() => handler.onSocketClose())
} else if (handler.socket?.destroyed === false) {
handler.socket.destroy()
}
Expand Down
9 changes: 8 additions & 1 deletion lib/web/websocket/websocket.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,9 @@ class WebSocket extends EventTarget {

this.#handler.socket.destroy()
},
onSocketClose: () => this.#onSocketClose(),
// Queue a task for the close event
// See: https://websockets.spec.whatwg.org/#closeWebSocket
onSocketClose: () => setImmediate(() => this.#onSocketClose()),
onPing: (body) => {
if (channels.ping.hasSubscribers) {
channels.ping.publish({
Expand Down Expand Up @@ -554,6 +556,11 @@ class WebSocket extends EventTarget {
* @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4
*/
#onSocketClose () {
// Guard against the close event firing twice
if (isClosed(this.#handler.readyState)) {
return
}

// If the TCP connection was closed after the
// WebSocket closing handshake was completed, the WebSocket connection
// is said to have been closed _cleanly_.
Expand Down
Loading
Loading