Repository navigation
ws: implement client 'upgrade' and 'unexpected-response' events - #36272
Conversation
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
|
Warning Review limit reached
Next review available in: 50 seconds Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (9)
Comment |
Jarred-Sumner
left a comment
There was a problem hiding this comment.
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.
|
Found 3 issues this PR may fix:
🤖 Generated with Claude Code |
|
This PR may be a duplicate of:
🤖 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.
|
Refactored in 4429857. The handshake handling now breaks down as:
Net vs the first commit: 29 fewer |
Jarred-Sumner
left a comment
There was a problem hiding this comment.
There should be 0 unsafe and 0 unsafe-laundered-as-safe
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.
|
Stripped further in 4d4ab33. The deferred-body state machine is gone entirely; the handshake forward is now two functions:
No new fields on
Also trimmed the comments flagged by comment-cop, dropped the dead |
|
Parallel attempt on branch |
- 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.
…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.
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.
|
CI status (builds #84572, #84764): the only consistently red lane is The other failures across both builds are marked This PR's own tests ( |
There was a problem hiding this comment.
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_responsere-parses into an owned buffer + local scratch so nothing borrowsselfacrossdispatch_handshake, and re-checksoutgoing_websocket.is_none()after the JS calldidReceiveHandshakeResponseearly-returns when no listener is registered, brackets dispatch with inc/decPendingActivity, and copies all slices before control returns to RustmakeHandshakeResponsenow uses a realhttp.IncomingMessage+_addHeaderLines, soinstanceofand header coalescing match Node- The
#unexpectedResponseEmittedvs#unexpectedResponseHandledsplit 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.
What does this PR do?
Implements the
wspackage client's'upgrade'and'unexpected-response'events, which Bun previously stubbed with:This is the load-bearing fix for miniflare / wrangler /
@cloudflare/vite-pluginhanging under Bun (theirdispatchFetchresolves 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
Before: prints the "not implemented" warning;
unexpected-responsenever fires. After:503 not-ready.Fix
WebSocketUpgradeClient.rsdrops 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 callsdid_receive_handshake_responseon the C++WebSocket.process_websocket_upgrade_response(this, full: &[u8]): re-parses the owned buffer into local scratch so nothing borrowsselfacross the JS dispatch, surfaces'handshake'(under one event-loop scope on 101 so microtasks drain after'open', matching npmws), then hands off to the existingprocess_response.No new state on
HTTPClient;handle_close/handle_end/terminateare 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). Netunsafein this file vs main: -1.WebSocket.cppgainsdidReceiveHandshakeResponse, which packages{statusCode, statusMessage, rawHeaders, body}into aMessageEventand dispatches'handshake'. It early-returns when no listener is registered, so the browser-stylenew WebSocket()path pays nothing.src/js/thirdparty/ws.jslazily registers the nativehandshakelistener on first'upgrade'/'unexpected-response'subscription and folds the payload into anIncomingMessage-shapedReadable(duplicate-header coalescing matches Node'shttp.IncomingMessage). A minimalClientRequeststub is passed as the firstunexpected-responseargument so code that inspectsreq.method/req.path/req.getHeader()does not crash.addListener/prependListener/prependOnceListener/addEventListenerall arm the bridge. Onceunexpected-responsehas fired, the native "Expected 101" error is suppressed across every registration style (on('error'),addEventListener('error'),onerror) so listeners fire exactly once, matching realws.How did you verify your code works?
test/js/first_party/ws/ws-upgrade-events.test.ts(12 tests):unexpected-responsefires with status / headers / body on non-101;reqstub hasmethod/path/getHeader()errorstill fires on non-101 with nounexpected-responselistenerupgradefires beforeopenon 101 with the handshake headersupgradehandler seesreadyState OPENIncomingMessageaddListener/prependListener/prependOnceListener/addEventListenerall arm the bridgeunexpected-responseacrosson/addEventListener/onerrorunexpected-responselisteneron('error')fires once (not twice) for non-101 with nounexpected-responselisteneron('error')+addEventListener('error')each fire onceaddEventListenerdedup for'upgrade'and'error',removeEventListenerdetaches the suppression wrappertest/js/web/websocket/websocket-handshake-event.test.tsexercises the native'handshake'event directly.8 of 12 tests fail (mostly time out) under
USE_SYSTEM_BUN=1and all pass underbun bd test. Existingtest/js/first_party/ws/ws.test.ts(45 tests) andtest/js/web/websocket/websocket-client*.test.tspass unchanged.[review] gate passed · iteration 1 · 9 files touched
fails on main (without fix)
passes on PR (with fix)
diff hotspot
gate history · 4 passed · 0 rejected · iteration 1
evidence per changed file