Skip to content

fix(websocket): queue Close frame behind pending sends - #6237

Open
A2wkiller wants to merge 1 commit into
nodejs:mainfrom
A2wkiller:fix-websocket-close-frame-ordering
Open

A2wkiller wants to merge 1 commit into
nodejs:mainfrom
A2wkiller:fix-websocket-close-frame-ordering

Conversation

@A2wkiller

Copy link
Copy Markdown

Fixes #6236.

Problem

ws.send(blob) followed by ws.close() writes the Close frame before the Blob (and before anything queued after it). The close path in connection.js wrote the Close frame straight to the socket, bypassing the SendQueue that data frames go through, so it overtook any queued sends (a Blob send waits on blob.arrayBuffer()). A server that follows RFC 6455 stops reading once it has the Close frame, so those messages are silently lost while the client's close event reports code 1000, wasClean: true.

Fix

Queue the Close frame behind pending sends instead of writing it directly:

  • SendQueue.addFrame(frame, cb) enqueues an already serialized frame behind any pending sends.
  • The handler keeps a reference to the SendQueue created in #onConnectionEstablished.
  • closeWebSocketConnection uses the queue when one exists, falling back to the direct socket write otherwise.

Only the client-initiated close path changes; the receiver's Close-frame reply is untouched.

Tests

Added Close frame is queued behind pending blob sends (#6236) to test/websocket/close.js: send(new Blob(...)), send('after'), close(1000) from an open connection, asserting the server receives both messages before the close handshake completes. The test fails without the fix (Close overtakes the queue, both messages are lost) and passes with it.

  • node --test test/websocket/close.js: 8 passed.
  • Full websocket suite (borp -p "test/websocket/**/*.js"): 179 passed, 0 failed.
  • ESLint on the changed files: clean.
  • The WPT suite was not run locally; relying on CI for it.

AI assistance disclosure: this PR was prepared with the help of an AI coding assistant; the change was reviewed and tested locally before submission.

Copilot AI balanced review requested due to automatic review settings November 21, 2026 05:22

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Pending Blob conversions can prevent Close frames from being written while falsely recording them as sent, causing incorrect clean-close reporting and dropping protocol-error status before socket destruction.

2 open issues
What changed in this PR

This PR addresses #6236 by routing WebSocket Close frames through the send queue so they do not overtake pending Blob messages.

Changes:

  • Adds support for queuing already serialized frames.
  • Exposes the send queue to the connection close helper, retaining a direct-write fallback.
  • Adds a regression test for Blob and text messages sent immediately before closing.
File Description
test/​websocket/​close.js Tests message delivery before the close handshake.
lib/​web/​websocket/​websocket.js Shares the send queue with the connection handler.
lib/​web/​websocket/​sender.js Adds addFrame() for serialized frames.
lib/​web/​websocket/​connection.js Queues Close frames behind pending sends when a queue exists.

Review effort: Balanced

Comment thread lib/web/websocket/connection.js Outdated
Comment on lines +296 to +299
if (object.sendQueue) {
// Queue the Close frame behind any pending sends so queued
// messages are not overtaken (and lost) by the Close frame.
object.sendQueue.addFrame(frame.createFrame(opcodes.CLOSE))
Comment thread lib/web/websocket/connection.js Outdated
if (object.sendQueue) {
// Queue the Close frame behind any pending sends so queued
// messages are not overtaken (and lost) by the Close frame.
object.sendQueue.addFrame(frame.createFrame(opcodes.CLOSE))

@mcollina mcollina left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we do this without adding a queue?

@codecov-commenter

codecov-commenter commented Nov 21, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.72%. Comparing base (2d30c32) to head (dad31f8).
⚠️ Report is 3 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6237      +/-   ##
==========================================
+ Coverage   91.71%   91.72%   +0.01%     
==========================================
  Files         113      113              
  Lines       44835    44872      +37     
==========================================
+ Hits        41121    41160      +39     
+ Misses       3714     3712       -2     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

ws.close() wrote the Close frame directly to the socket, so it could
overtake a pending Blob send still being read in the send queue; the
server then closed the connection without ever receiving that message.

Graceful closes now go through the existing SendQueue with a new
sendHints.close hint, so the Close frame is written after already
queued messages. Failure-triggered closes keep writing directly, as
the socket is destroyed immediately afterwards.

Fixes nodejs#6236.
@A2wkiller
A2wkiller force-pushed the fix-websocket-close-frame-ordering branch from dad31f8 to 9aad130 Compare November 22, 2026 04:09
@A2wkiller

Copy link
Copy Markdown
Author

Yes, good call. Reworked in 9aad130: the graceful close now goes through the existing SendQueue with a new sendHints.close hint (a Close frame arrives already serialized, so createFrame passes it through), instead of the extra addFrame/closeFrameQueued machinery I had before. No new queue structures - the Close frame is just another entry in the same queue pending Blob sends already use. Failure-triggered closes still write directly since the socket is destroyed right after. The SENT state is marked at enqueue time, matching the existing direct-write path where socket.write likewise only buffers. All 179 websocket tests pass, including the new ordering test.

(Disclosure: this change was drafted with AI assistance and reviewed/tested by me.)

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.

WebSocket: send(blob) followed by close() sends the Close frame before the queued messages, so they are lost

4 participants