Skip to content

ws: implement client 'upgrade' and 'unexpected-response' events - #36272

Merged
Jarred-Sumner merged 9 commits into
mainfrom
farm/8ad45c5e/ws-upgrade-unexpected-response
Jul 29, 2026
Merged

Jarred-Sumner merged 9 commits into
mainfrom
farm/8ad45c5e/ws-upgrade-unexpected-response

Conversation

@robobun

@robobun robobun commented Jul 28, 2026 •

Copy link
Copy Markdown
Collaborator

What does this PR do?

Implements the ws package client's 'upgrade' and 'unexpected-response' events, which Bun previously stubbed with:

[bun] Warning: ws.WebSocket 'upgrade' event is not implemented in bun
[bun] Warning: ws.WebSocket 'unexpected-response' event is not implemented in bun

This is the load-bearing fix for miniflare / wrangler / @cloudflare/vite-plugin hanging under Bun (their dispatchFetch resolves exclusively off these two events) and for several playwright / puppeteer CDP connection paths.

Fixes #5951
Fixes #24229
Fixes #31406
Fixes #31792

Closes #28114
Closes #31408
Closes #25777

Reproduction

const { createServer } = require("net");
const { once } = require("events");
const { WebSocket } = require("ws");

const server = createServer(s =>
  s.once("data", () => s.end("HTTP/1.1 503 Service Unavailable\r\nX-Reason: not-ready\r\n\r\nworkerd starting")),
).listen(0, "127.0.0.1");
await once(server, "listening");

const ws = new WebSocket("ws://127.0.0.1:" + server.address().port);
ws.on("error", () => {});
ws.once("unexpected-response", (req, res) => {
  console.log(res.statusCode, res.headers["x-reason"]);  // 503 not-ready
});

Before: prints the "not implemented" warning; unexpected-response never fires. After: 503 not-ready.

Fix

WebSocketUpgradeClient.rs drops the early "fail on non-101 status line" check so the response is parsed, and adds two functions:

  • dispatch_handshake(ws, &response, body): stateless; builds the raw-header FFI array and calls did_receive_handshake_response on the C++ WebSocket.
  • process_websocket_upgrade_response(this, full: &[u8]): re-parses the owned buffer into local scratch so nothing borrows self across the JS dispatch, surfaces 'handshake' (under one event-loop scope on 101 so microtasks drain after 'open', matching npm ws), then hands off to the existing process_response.

No new state on HTTPClient; handle_close / handle_end / terminate are unchanged from main. The non-101 body is whatever arrived in the first read with the headers, which covers the real-world error-page case (workerd restart text, JSON API errors). Net unsafe in this file vs main: -1.

WebSocket.cpp gains didReceiveHandshakeResponse, which packages {statusCode, statusMessage, rawHeaders, body} into a MessageEvent and dispatches 'handshake'. It early-returns when no listener is registered, so the browser-style new WebSocket() path pays nothing.

src/js/thirdparty/ws.js lazily registers the native handshake listener on first 'upgrade' / 'unexpected-response' subscription and folds the payload into an IncomingMessage-shaped Readable (duplicate-header coalescing matches Node's http.IncomingMessage). A minimal ClientRequest stub is passed as the first unexpected-response argument so code that inspects req.method/req.path/req.getHeader() does not crash. addListener / prependListener / prependOnceListener / addEventListener all arm the bridge. Once unexpected-response has fired, the native "Expected 101" error is suppressed across every registration style (on('error'), addEventListener('error'), onerror) so listeners fire exactly once, matching real ws.

How did you verify your code works?

test/js/first_party/ws/ws-upgrade-events.test.ts (12 tests):

  • unexpected-response fires with status / headers / body on non-101; req stub has method/path/getHeader()
  • native error still fires on non-101 with no unexpected-response listener
  • upgrade fires before open on 101 with the handshake headers
  • microtask queued in an upgrade handler sees readyState OPEN
  • duplicate headers coalesce like Node IncomingMessage
  • addListener / prependListener / prependOnceListener / addEventListener all arm the bridge
  • native error suppression after unexpected-response across on / addEventListener / onerror
  • native error still delivered to DOM-style handlers when there is no unexpected-response listener
  • on('error') fires once (not twice) for non-101 with no unexpected-response listener
  • mixed on('error') + addEventListener('error') each fire once
  • addEventListener dedup for 'upgrade' and 'error', removeEventListener detaches the suppression wrapper

test/js/web/websocket/websocket-handshake-event.test.ts exercises the native 'handshake' event directly.

8 of 12 tests fail (mostly time out) under USE_SYSTEM_BUN=1 and all pass under bun bd test. Existing test/js/first_party/ws/ws.test.ts (45 tests) and test/js/web/websocket/websocket-client*.test.ts pass unchanged.


[review] gate passed · iteration 1 · 9 files touched

fails on main (without fix)
ASAN without fix: 10 FAILED
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/first_party/ws/ws-upgrade-events.test.ts test/js/web/websocket/websocket-handshake-event.test.ts
bun test v1.4.0 (4234810c4)

test/js/first_party/ws/ws-upgrade-events.test.ts:
31 |     }
32 |     ws.on("error", () => {});
33 |     ws.terminate();
34 |     console.log("ok");
35 |   `);
36 |     expect(stderr).toBe("");
                        ^
error: expect(received).toBe(expected)

- ""
+ "[bun] Warning: ws.WebSocket 'upgrade' event is not implemented in bun
+ [bun] Warning: ws.WebSocket 'unexpected-response' event is not implemented in bun"

- Expected  - 1
+ Received  + 2

      at <anonymous> (/workspace/bun/test/js/first_party/ws/ws-upgrade-events.test.ts:36:20)
(fail) ws on/addListener/prepend*/addEventListener for upgrade/unexpected-response emit no warning [2913.96ms]
(pass) ws emits native 'error' on non-101 when no 'unexpected-response' listener [3738.15ms]
141 |       server.close();
142 |     });
143 |     await once(ws, "close");
144 |     console.log(order.join(","));
145 |   `);
146 |   expect(stdout).toMatchInli
... (truncated)

release without fix: all passed
bun test v1.4.0-canary.1 (48a8c517e)

test/js/first_party/ws/ws-upgrade-events.test.ts:
(pass) ws on/addListener/prepend*/addEventListener for upgrade/unexpected-response emit no warning [90.89ms]
(pass) ws emits native 'error' on non-101 when no 'unexpected-response' listener [73.27ms]
(pass) ws 'unexpected-response' coalesces duplicate headers like Node IncomingMessage [70.91ms]
(pass) ws still delivers the native error to addEventListener/onerror when there is no 'unexpected-response' listener [63.84ms]
(pass) ws error handlers each fire once when on('error') and addEventListener/onerror are mixed [60.57ms]
(pass) ws emits 'unexpected-response' with status, headers and body on non-101 [79.53ms]
(pass) ws 'unexpected-response' fires for addListener / prependListener / addEventListener [86.73ms]
(pass) ws addEventListener('upgrade', h) dedupes the same handler [79.29ms]
(pass) ws microtask queued in 'upgrade' handler observes readyState OPEN [91.76ms]
(pass) ws on('error') fires once (not twice) for a non-101 with no 'unexpected-response' listener [105.02ms]
(pass) ws suppresses the native error after 'unexpected-response' across on/addEventListener/onerror [120.66
... (truncated)
passes on PR (with fix)
ASAN with fix: all passed
$ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/mechgate.xml" test/js/first_party/ws/ws-upgrade-events.test.ts test/js/web/websocket/websocket-handshake-event.test.ts
bun test v1.4.0 (4234810c4)

test/js/first_party/ws/ws-upgrade-events.test.ts:
(pass) ws on/addListener/prepend*/addEventListener for upgrade/unexpected-response emit no warning [1911.22ms]
(pass) ws emits native 'error' on non-101 when no 'unexpected-response' listener [2273.72ms]
(pass) ws microtask queued in 'upgrade' handler observes readyState OPEN [2642.07ms]
(pass) ws emits 'unexpected-response' with status, headers and body on non-101 [2755.86ms]
(pass) ws emits 'upgrade' with headers before 'open' on 101 [2770.82ms]
(pass) ws 'unexpected-response' coalesces duplicate headers like Node IncomingMessage [3693.18ms]
(pass) ws 'unexpected-response' fires for addListener / prependListener / addEventListener [3541.24ms]
(pass) ws suppresses the native error after 'unexpected-response' across on/addEventListener/onerror [3486.96ms]
(pass) ws still delivers the native error to addEventListener/onerror when there is no 'unexpected-re
... (truncated)

release with fix: all passed
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped) in 971ms (unchanged)
ninja: Entering directory `/workspace/bun/build/release'
[1/123] gen bake.{client,server,error}.js
-> bake.client.js, bake.server.js, bake.error.js
[2/123] gen cpp.rs (cppbind)
[3/123] gen generated_host_exports.rs
generated_host_exports.rs: 94 exports (host=3, lazy=10, generic=81, rust=0); 240 extern-C blocks audited
[4/123] gen JS modules (bundle-modules)
Preprocess modules (16150ms)
Bundle modules (69ms)
Postprocesss modules (177ms)
Bundle Functions (985ms)
Generate Code (43ms)

[17.44s] Bundled "src/js" for production
  2575 kb
  193 internal modules
  13 native modules
  90 internal functions across 19 files
[4/123] cargo bun_bin → libbun_rust.a (--target x86_64-unknown-linux-gnu)

  nightly-2026-07-20-x86_64-unknown-linux-gnu unchanged - rustc 1.99.0-nightly (9f36de775 2026-07-19)

�[1m�[92m   Compiling�[0m bun_core v0.0.0 (/workspace/bun/src/bun_core)
�[1m�[92m   Compiling�[0m bun_errno v0.0.0 (/workspace/bun/src/errno)
�[1m�[92m   Compiling�[0m bun_ptr v0.0.0 (/workspace/bun/src/ptr)
�[1m�[92m   Compiling�[0m bun_boringssl_sys v0.0.0 (/workspace/bun/sr
... (truncated)
diff hotspot
src/http_jsc/websocket_client/CppWebSocket.rs      |  47 ++
 .../websocket_client/WebSocketUpgradeClient.rs     | 100 ++--
 src/js/builtins/BunBuiltinNames.h                  |   3 +
 src/js/thirdparty/ws.js                            | 176 ++++++-
 src/jsc/bindings/webcore/EventNames.h              |  21 +-
 src/jsc/bindings/webcore/WebSocket.cpp             |  56 +++
 src/jsc/bindings/webcore/WebSocket.h               |   7 +
 test/js/first_party/ws/ws-upgrade-events.test.ts   | 560 +++++++++++++++++++++
 .../websocket/websocket-handshake-event.test.ts    |  59 +++
 9 files changed, 975 insertions(+), 54 deletions(-)

gate history · 4 passed · 0 rejected · iteration 1

evidence per changed file
file                                                     reads  edits  tests
src/http_jsc/websocket_client/CppWebSocket.rs                2      4      0
src/http_jsc/websocket_client/WebSocketUpgradeClient.rs     12     33      0
src/js/builtins/BunBuiltinNames.h                            1      1      0
src/js/thirdparty/ws.js                                      8     16      0
src/jsc/bindings/webcore/EventNames.h                        0      0      0
src/jsc/bindings/webcore/WebSocket.cpp                       1      2      0
src/jsc/bindings/webcore/WebSocket.h                         0      0      0
test/js/first_party/ws/ws-upgrade-events.test.ts             1      1      0
test/js/web/websocket/websocket-handshake-event.test.ts      1      1      0

The ws shim previously stubbed both events with a 'not implemented in bun'
warning. The native WebSocket upgrade client now forwards the parsed
handshake response (status, reason, headers, body) to the C++ WebSocket as
a 'handshake' event, and the shim folds that into the IncomingMessage-shaped
object that ws listeners expect.

For non-101 responses the client no longer fails early: it buffers the
response body (honoring Content-Length, RFC 7230 3.3.3 bodiless statuses,
and Transfer-Encoding) up to a 64 MB cap, then dispatches
'unexpected-response' (or the 'Unexpected server response: N' error when
no listener is registered) before terminating. On 101, 'upgrade' and 'open'
are dispatched under one event-loop scope so a microtask queued in an
'upgrade' handler observes readyState OPEN, matching Node + npm ws.

The handshake listener is registered lazily on first 'upgrade' /
'unexpected-response' subscription so callers that only use open/message/
close never touch the new path. addListener / prependListener /
prependOnceListener / addEventListener all arm the bridge, and the native
'Expected 101' error is suppressed across every registration style once
'unexpected-response' has handled the response.

Squashed and rebased from #28114.

Fixes #5951
Fixes #24229
@coderabbitai

coderabbitai Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@robobun, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 50 seconds

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 92c000d8-1b70-40d6-8a71-6a3ad3811051

📥 Commits

Reviewing files that changed from the base of the PR and between e532ad9 and 4234810.

📒 Files selected for processing (9)
  • src/http_jsc/websocket_client/CppWebSocket.rs
  • src/http_jsc/websocket_client/WebSocketUpgradeClient.rs
  • src/js/builtins/BunBuiltinNames.h
  • src/js/thirdparty/ws.js
  • src/jsc/bindings/webcore/EventNames.h
  • src/jsc/bindings/webcore/WebSocket.cpp
  • src/jsc/bindings/webcore/WebSocket.h
  • test/js/first_party/ws/ws-upgrade-events.test.ts
  • test/js/web/websocket/websocket-handshake-event.test.ts

Comment @coderabbitai help to get the list of available commands.

@robobun

robobun commented Jul 28, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 1:06 AM PT - Jul 29th, 2026

@robobun, your commit 4234810 is building: #84764

@Jarred-Sumner Jarred-Sumner left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The need for ref_guard is a code smell. The long comments are a code smell. The usage of unsafe and multiple mutable this is a code smell. Refactor this.

@github-actions

Copy link
Copy Markdown
Contributor

Found 3 issues this PR may fix:

  1. ws.WebSocket 'unexpected-response' event is not implemented, breaks chrome-devtools-mcp and puppeteer #31792 - Directly implements the missing unexpected-response event that breaks chrome-devtools-mcp and puppeteer
  2. ws client does not emit upgrade event in Bun 1.3.8 #31406 - Directly implements the missing upgrade event on the ws client
  3. Playwright connectOverCDP() not working #9911 - Playwright connectOverCDP() fails due to missing ws upgrade/unexpected-response events needed for CDP handshake

If this is helpful, copy the block below into the PR description to auto-close these issues on merge.

Fixes #31792
Fixes #31406
Fixes #9911

🤖 Generated with Claude Code

@github-actions

Copy link
Copy Markdown
Contributor

This PR may be a duplicate of:

  1. ws: Implement upgrade and unexpected-response events #25777 - ws: Implement upgrade and unexpected-response events
  2. ws: support upgrade and unexpected-response events #28114 - ws: support upgrade and unexpected-response events

🤖 Generated with Claude Code

Split the non-101 body handling into a pure route_handshake_body() that
returns a HandshakeBody decision, a stateless dispatch_handshake() that
just forwards the parsed response to C++, and one ThisPtr<Self>
orchestrator that owns the response buffer locally so nothing borrows
self across the JS dispatch. Callers (handle_data / handle_decrypted_data
/ handle_end / handle_close / terminate) hold a ref_guard themselves;
the orchestrator does not.

handle_close's deferred branch collapses into the normal path: the ext
slot is taken and tcp detached before any dispatch so a reentrant
cancel() finds nothing to release, and the flush is a single call
instead of inline bookkeeping.

Drops 29 unsafe blocks and ~250 lines from the previous commit.
@robobun

robobun commented Jul 29, 2026

Copy link
Copy Markdown
Collaborator Author

Refactored in 4429857. The handshake handling now breaks down as:

  • route_handshake_body(&response, head_len, available) -> HandshakeBody: pure function encoding the RFC 7230 body-length rules. No self, no unsafe.
  • dispatch_handshake(ws, &response, body): stateless forward to C++. No self.
  • process_websocket_upgrade_response(this: ThisPtr<Self>, full: Vec<u8>, is_final): parses full into a local scratch buffer so the response borrows nothing from self, then routes and dispatches. The caller holds a ref_guard; this function does not.
  • take_deferred_body / append_deferred_handshake_body: ThisPtr<Self> field accessors.

handle_close collapses to one path: take the ext slot and detach tcp before any dispatch (so a reentrant cancel() finds nothing to release), flush if a body was buffered, then the existing clear_data / dispatch_abrupt_close / deref. The 40-line deferred block with its reentrancy essay is gone.

Net vs the first commit: 29 fewer unsafe blocks in added code (44 → 15), ~250 fewer lines added to this file vs main. All 16 regression tests and the existing 87 ws / websocket-client tests pass.

Comment thread src/js/thirdparty/ws.js Resolved
Comment thread src/js/thirdparty/ws.js Resolved
Comment thread src/js/thirdparty/ws.js Resolved
Comment thread src/js/thirdparty/ws.js Resolved

@Jarred-Sumner Jarred-Sumner left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

There should be 0 unsafe and 0 unsafe-laundered-as-safe

Comment thread src/js/thirdparty/ws.js Resolved
Comment thread test/regression/issue/05951.test.ts Resolved
The handshake forward is now two functions: a stateless dispatch_handshake
that builds the raw-header array and calls C++, and
process_websocket_upgrade_response which re-parses the owned response
buffer into local scratch (so nothing borrows self across the JS
dispatch), surfaces the handshake, and hands off to the existing
process_response.

No new state on HTTPClient; handle_close / handle_end / terminate are
untouched. The non-101 body is whatever arrived in the first read with
the headers, which covers the real-world error-page case; the earlier
Content-Length / read-until-EOF accumulation (and its DeferredHandshake
state machine, 64 MB cap, flush-on-RST reentrancy guard, and 12 unsafe
blocks) is gone.

Net unsafe in WebSocketUpgradeClient.rs vs main: -1 (two early-101-fail
terminates removed; two calls to the existing unsafe terminate /
process_response added from the orchestrator; one ThisPtr::new wrap in
handle_decrypted_data matching the file's existing idiom).

Also: trimmed comments across CppWebSocket.rs and ws.js, dropped the
dead eventIds entries, and moved tests to first_party/ws and
web/websocket per the file-placement convention.
@robobun

robobun commented Jul 29, 2026

Copy link
Copy Markdown
Collaborator Author

Stripped further in 4d4ab33. The deferred-body state machine is gone entirely; the handshake forward is now two functions:

  • dispatch_handshake(ws, &response, body): stateless, no self, no unsafe.
  • process_websocket_upgrade_response(this: ThisPtr<Self>, full: &[u8]): re-parses full into local scratch so nothing borrows self across the JS dispatch, surfaces 'handshake', hands off to process_response.

No new fields on HTTPClient; handle_close / handle_end / terminate are untouched from main. The non-101 body is whatever arrived in the first read with the headers, which covers the real-world error-page case (workerd restart text, JSON errors, etc).

unsafe vs main in WebSocketUpgradeClient.rs: net -1. The two early-101-fail terminate calls in handle_data/handle_decrypted_data are removed; the orchestrator makes two calls to the existing unsafe fn terminate / unsafe fn process_response (same call sites that were there before, just routed through the orchestrator), plus one ThisPtr::new wrap in handle_decrypted_data matching the idiom every other handler uses. Getting those to literal zero would mean changing the terminate/process_response signatures, which are called from ~15 other places in this file.

Also trimmed the comments flagged by comment-cop, dropped the dead eventIds entries, and moved the tests to test/js/first_party/ws/ and test/js/web/websocket/ per the file-placement convention.

Comment thread src/js/thirdparty/ws.js Resolved
Comment thread src/js/thirdparty/ws.js Resolved
Comment thread src/jsc/bindings/webcore/WebSocket.cpp Resolved
Comment thread src/jsc/bindings/webcore/WebSocket.cpp Resolved
Comment thread src/js/thirdparty/ws.js Resolved
@robobun

robobun commented Jul 29, 2026

Copy link
Copy Markdown
Collaborator Author

Parallel attempt on branch farm/fa575560/ws-client-upgrade-event landed on a near-identical shape; one difference worth carrying over here: its makeHandshakeResponse constructs a real http.IncomingMessage and calls _addHeaderLines(rawHeaders, n) rather than hand-rolling the header fold. That keeps res instanceof http.IncomingMessage true and gives Node's per-field duplicate rules (first-wins for content-type/server/location/etc., array for set-cookie, "; " for cookie) for free, with one source of truth in _http_incoming. Happy to fold that into this branch if useful.

Comment thread src/js/thirdparty/ws.js Resolved
- Drop dead #[allow(clippy::not_unsafe_ptr_arg_deref)] on
  did_receive_handshake_response (no raw-pointer params).
- Restore the pre-existing ShortRead why-comment in handle_decrypted_data
  to stay symmetric with handle_data / handle_proxy_response.
- addEventListener('error', h, { signal }): also delete the WeakMap entry
  on signal abort so a subsequent add of the same listener isn't deduped
  away.
- websocket-handshake-event.test.ts: wire 'close' to reject so a
  regression fails fast instead of timing out.
Comment thread src/js/thirdparty/ws.js Resolved
robobun and others added 2 commits July 29, 2026 02:40
…no-warning

- addEventListener('error', h, { signal }): return early when the signal
  is already aborted, matching the native EventTarget's own check, so the
  WeakMap never holds a stale entry.
- Add a test that subscribes to 'upgrade'/'unexpected-response' via every
  registration API and asserts stderr is empty (no 'not implemented'
  warning). run() now returns stderr.
Comment thread src/js/thirdparty/ws.js Resolved
Comment thread src/js/thirdparty/ws.js Resolved
Comment thread src/js/thirdparty/ws.js Resolved
Replaces the hand-rolled header-coalescing loop and kSingletonHeaders table
with a real http.IncomingMessage and its _addHeaderLines, which already
implements Node's duplicate-header rules. Deletes ~40 lines of duplicated
logic and makes res instanceof http.IncomingMessage true (matching real ws).

Also: initialize the synthetic ClientRequest stub via EventEmitter.$call
to match the existing finishRequest stub in this file.
@robobun

robobun commented Jul 29, 2026

Copy link
Copy Markdown
Collaborator Author

CI status (builds #84572, #84764): the only consistently red lane is test/js/node/worker_threads/worker-transfer-terminate-stress.test.ts SIGABRTing on debian-13 x64-asan. That test's own header comment documents it as an intermittent ASAN-lane-only race in MessagePort transfer + terminate() that "does not reproduce locally (0/115 loaded runs)"; my diff doesn't touch workers, MessagePort, or structured clone, and the test passes 3/3 locally with this PR's exact sha under the ASAN debug build. Reported to main-break triage.

The other failures across both builds are marked [flaky] (timing-dependent tests that passed when run alone: setInterval.test.js, fetch-tls-abortsignal-timeout.test.ts, bun-install-registry.test.ts on windows-aarch64, fetch-leak.test.ts, test-quic-session-initial-rtt.mjs, 14029.test.ts, 25432.test.ts).

This PR's own tests (ws-upgrade-events.test.ts, websocket-handshake-event.test.ts) and the existing ws.test.ts / websocket-client*.test.ts suites are green on every lane that ran them. Ready for review.

@claude claude Bot 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.

No issues found in this pass — the earlier nits (IncomingMessage reuse, EventEmitter.$call, aborted-signal guard, stderr assertions) are addressed, and the intentionally-left {handleEvent} gap is a reasonable call. That said, this is ~1000 lines across Rust unsafe (upgrade-client re-entrancy, ref_guard, event-loop scoping), a new C++ dispatch path, a two-flag error-suppression state machine in ws.js, and a Bun-only 'handshake' event on the native WebSocket — worth a human pass on the design and the re-entrancy story.

Checked this round:

  • process_websocket_upgrade_response re-parses into an owned buffer + local scratch so nothing borrows self across dispatch_handshake, and re-checks outgoing_websocket.is_none() after the JS call
  • didReceiveHandshakeResponse early-returns when no listener is registered, brackets dispatch with inc/decPendingActivity, and copies all slices before control returns to Rust
  • makeHandshakeResponse now uses a real http.IncomingMessage + _addHeaderLines, so instanceof and header coalescing match Node
  • The #unexpectedResponseEmitted vs #unexpectedResponseHandled split cleanly separates EE-bridge suppression from DOM-listener suppression (covered by the mixed-registration test)
Extended reasoning...

Overview

Implements the ws package client's 'upgrade' and 'unexpected-response' events end-to-end. Rust side (WebSocketUpgradeClient.rs) drops the early non-101 fail-fast, copies the full response into an owned buffer, re-parses into stack scratch, dispatches a new native 'handshake' event via a new FFI call (CppWebSocket.rs → WebSocket__didReceiveHandshakeResponse), then falls through to the existing process_response. C++ side (WebSocket.cpp/.h, EventNames.h, BunBuiltinNames.h) adds the 'handshake' event and packages status/headers/body into a MessageEvent. JS side (ws.js) lazily arms a native listener on first 'upgrade'/'unexpected-response' subscription, builds a real http.IncomingMessage from the raw headers, and layers a two-flag suppression scheme so the follow-up native "Expected 101" error doesn't double-fire across on/addEventListener/onerror. Two new test files, 13 tests total.

Security risks

Low. The response bytes come from the network but are already parsed by picohttp under the existing max_http_header_size cap; the new code only re-parses an owned copy and forwards slices to C++, which copies them into WTF::String/JSUint8Array before user JS runs. No new auth/crypto/permission surface. The new 'handshake' event exposes handshake headers/body to JS, but only to code that already owns the WebSocket object.

Level of scrutiny

High. This is a client-path behavioral change in native code with several non-obvious pieces: (1) removing the early non-101 bail means every non-101 response is now fully parsed and dispatched to JS before the terminate path — user JS can now synchronously close()/terminate() from a 'handshake' handler, which the Rust side guards by re-reading this.outgoing_websocket after dispatch and by holding a ref_guard across the whole sequence; (2) the 101 path wraps both 'handshake' and 'open' in a single enter_event_loop_scope so microtasks queued in 'upgrade' observe readyState OPEN — a subtle ordering contract that a maintainer should sign off on; (3) the ws.js suppression machinery adds prependListener/prependOnceListener/addListener overrides and wraps every DOM-style 'error' listener, which is a fair amount of new stateful surface on a compat shim; (4) adding 'handshake' as a public event on the browser-style WebSocket is a Bun-specific API extension.

Other factors

Test coverage is thorough (12 concurrent subprocess tests over the registration matrix + suppression semantics + microtask ordering + header coalescing, plus a direct native-event test), CI is green on every lane that ran the new tests, and the PR has been through five bot-review rounds with every nit either fixed or explicitly declined with a stated reason. All prior inline threads are resolved. Nothing blocking from my side — deferring purely on scope and the API/design decisions a human should confirm.

@Jarred-Sumner
Jarred-Sumner merged commit 9d7f85b into main Jul 29, 2026
53 of 54 checks passed
@Jarred-Sumner
Jarred-Sumner deleted the farm/8ad45c5e/ws-upgrade-unexpected-response branch July 29, 2026 11:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

2 participants