Repository navigation
refactor(server): rewrite the ws adapter with generators, using and result values (exploratory) - #7895
Draft
KATT wants to merge 10 commits into
Draft
refactor(server): rewrite the ws adapter with generators, using and result values (exploratory)#7895KATT wants to merge 10 commits into
using and result values (exploratory)#7895KATT wants to merge 10 commits into
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
Contributor
|
Important Draft PR not reviewedDraft PRs are not automatically reviewed by default.
To automatically review draft PRs, update your CodeRabbit configuration: reviews:
auto_review:
drafts: true
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. |
Base automatically changed from
cursor/wsclient-reconnect-errors-3334
to
main
November 4, 2026 13:37
@trpc/client
@trpc/next
@trpc/openapi
@trpc/react-query
@trpc/server
@trpc/tanstack-react-query
@trpc/upgrade
commit: |
cursor
Bot
force-pushed
the
cursor/ws-modern-rewrite-62d1
branch
from
November 4, 2026 13:39
79cf86c to
b76079e
Compare
cursor
Bot
force-pushed
the
cursor/ws-modern-rewrite-62d1
branch
from
November 4, 2026 21:41
873eeda to
e9a57e3
Compare
cursor
Bot
force-pushed
the
cursor/ws-modern-rewrite-62d1
branch
from
November 4, 2026 21:46
e9a57e3 to
d35c012
Compare
β¦source management and result values Serves each connection from one async function whose subscriptions, abort controller, keepAlive timers and listeners are 'using' resources, receives frames through a generator, and sends each request's responses from an async generator that's told whether each send succeeded. Errors are passed around as Result values instead of try/catch. Adds integration tests for the adapter's error paths, connection params, batches, keepAlive and prefix filtering. Co-authored-by: alexander <[email protected]>
β¦d refuse a taken subscription id in the registry Nothing awaits the promises the ws adapter starts per request, and the frame generator ends on its first throw, so a throwing onError, errorFormatter or encoder became an unhandled rejection, or left the connection ignoring every later frame. onError's throws are now ignored, sendAll reports a reply generator that throws, connection-level replies go through sendOrReport, and each frame is handled under attempt(). The subscription registry now refuses an id that's already claimed instead of replacing the running subscription, so the duplicate check can't drift from the registration. Also renames the Responses type to Replies, and uses property access where destructuring was used once or twice. Co-authored-by: alexander <[email protected]>
β¦a listener serveConnection now pulls messages from events.on(), ended by a signal when the socket closes, since Node 18 ignores on()'s close option. The loop reads the connection params frame first and then requests, which replaces the push-style receiveFrames coroutine. The error listener stays a callback: ws needs one attached for the socket's whole life. Co-authored-by: alexander <[email protected]>
β¦ sent, and restructure the adapter after review A stop or disconnect that landed while `started` was being sent was lost: the abort listener was added after the signal had already aborted, so the subscription streamed forever. abortPromiseResource now resolves for an already-aborted signal, and nextUnlessStopped doesn't ask a stopped subscription's iterator for more. The new test sweeps how many frames sit between the subscribe and the stop, since the window is a few microtasks. From an independent maintainability review: - serveConnection starts with its read loop, and its helpers are grouped by what they do; frame decoding, message classification, connection params and lastEventId handling are pure module-level functions - one comment states which functions catch what user code throws - subscription setup (including an iterable that arrives after a stop) is one function returning started, stopped or failed; the streaming loop aborts explicitly instead of through a resource that read mutable state - the Replies protocol is documented on its type; clearer names (sendReplies, finalReply, reportedErrorReply, nextMessage, noRequest) - the garbage collection constraint is explained once at the top - createDeferred instead of non-null-asserted resolvers - tests: a permanent error listener on raw sockets, no polling for frames, names that say when a request gets no reply, two new tests Co-authored-by: alexander <[email protected]>
β¦s are unchanged Co-authored-by: alexander <[email protected]>
β¦wingCallbacks.test.ts already covers Co-authored-by: alexander <[email protected]>
β¦ the fallback error, catch an async onError's rejection, and log what onError can't take Co-authored-by: alexander <[email protected]>
β¦#7915 does Co-authored-by: alexander <[email protected]>
cursor
Bot
force-pushed
the
cursor/ws-modern-rewrite-62d1
branch
from
November 4, 2026 23:48
d35c012 to
0c4cd39
Compare
β¦the iterator then can't be opened Co-authored-by: alexander <[email protected]>
meefs
pushed a commit
to meefs/trpc
that referenced
this pull request
Nov 5, 2026
β¦crashing the ws server (trpc#7915) <!-- CURSOR_AGENT_PR_BODY_BEGIN --> ## Why - In the ws adapter, a throwing `onError`, `errorFormatter` or encoder escapes as an unhandled rejection or uncaught exception, which ends the Node process by default. A realistic trigger: an `errorFormatter` that puts a BigInt or a circular `cause` in `data`. ## What - Every `onError` call is guarded: one that throws or rejects is ignored. - When `errorFormatter` throws, or an error reply can't be encoded, the request still gets a minimal `INTERNAL_SERVER_ERROR`. The failure goes to `onError`, or to `console.error` when `onError` is missing or fails. - Error responses not tied to a request (context failure, parse error, non-Buffer frame, oversized batch) report to `onError` when they can't be built or sent, and one that can't be sent is replaced by the same fallback error. - A `handleRequest` rejection goes to `onError` instead of being unhandled. ## Links - None ## Alternatives considered - The full rewrite in trpc#7895: much larger, and still a draft. ## Testing - `websocketsThrowingCallbacks.test.ts`: one minimal test per failure mode, each against a real server. - Regression check: on `main` (ce8f309, same `ws.ts` as 1cee3df), all 11 tests fail. Four time out waiting for a reply or a close. The rest fail their assertions: a reply missing, or an unhandled rejection or uncaught exception collected. With the fix, all 11 pass, 5 of 5 runs. ## AI model Claude Opus 5.5 <!-- CURSOR_AGENT_PR_BODY_END --> <div><a href="https://cursor.com/agents/bc-bedd951f-04ac-519f-93ed-860f81cd62d1?cursor_ref=pr_footer&cursor_cta=open_in_web"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/open-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/open-in-web-light.png"><img alt="Open in Web" width="114" height="28" src="https://cursor.com/assets/images/open-in-web-dark.png"></picture></a> <a href="https://cursor.com/background-agent?bcId=bc-bedd951f-04ac-519f-93ed-860f81cd62d1&cursor_ref=pr_footer&cursor_cta=open_in_cursor"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/open-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/open-in-cursor-light.png"><img alt="Open in Cursor" width="131" height="28" src="https://cursor.com/assets/images/open-in-cursor-dark.png"></picture></a> </div> <!-- codesmith:footer --> --- <a href="https://backend.blacksmith.sh/track/enable-autofix?expires=1796414572&installation_model_id=443568&pr_number=7915&ref=codesmith_pr_footer&repository=trpc%2Ftrpc&return_to=https%3A%2F%2Fgithub.com%2Ftrpc%2Ftrpc%2Fpull%2F7915&signature=0bae41aa06eb5132848363bcb65e9e62436747a14fbe5b1b6ac62ad294bf9fc0"><picture><source media="(prefers-color-scheme: dark)" srcset="https://pr-comments-assets.blacksmith.sh/codesmith/autofix-with-codesmith-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://pr-comments-assets.blacksmith.sh/codesmith/autofix-with-codesmith-light.svg"><img alt="Autofix with [code]smith" src="https://pr-comments-assets.blacksmith.sh/codesmith/autofix-with-codesmith-dark-3x.png" width="190" height="28"></picture></a> <sup><a href="https://app.blacksmith.sh/trpc/codesmith/trpc/pr/7915?autoLogin=true&ref=codesmith_pr_footer">Open in [code]smith</a> Β· Need help on this PR? Tag <code>@codesmith-bot</code> with what you need.</sup> <!-- codesmith:autofix:disabled --> <!-- /codesmith:footer --> <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * WebSocket connection errors are reported through the error callback, including failures while handling requests or preparing responses. * Errors from malformed messages, parsing failures, oversized batches, response encoding, and asynchronous request handling are routed through the connection error path. * If an error callback throws or rejects, subsequent requests and messages can still be handled, and the failure is logged. * If formatting or sending an error response fails, a fallback response is attempted where possible. * Failed context creation continues to close the connection. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Cursor Agent <[email protected]>
nextUnlessStopped checked the signal only before iterator.next(), and the stop's promise resolves a microtask after the abort, so a value yielded because of the stop won the race and was sent after it, and after the PONG of a PING sent in the same chunk. Co-authored-by: alexander <[email protected]>
This branch was successfully deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Why
What
serveConnectionper connection. It owns its context signal, subscriptions and message listener withusing, and reads frames fromevents.onin a loop.sendRepliessends them, never rejects, and passes send failures back asResultvalues.onError, a throwingerrorFormatterand a failing encoder are handled as in fix(server): keep a throwing onError, errorFormatter or encoder from crashing the ws serverΒ #7915: the request gets the fallbackINTERNAL_SERVER_ERROR, and the failure goes toonErrororconsole.error.startedsend ends the subscription: an error, thenstopped, and its signal aborts. It's reported even when the iterator then can't be opened.Open questions
attemptandsettlemove tounstable-core-do-not-import?Links
main.Alternatives considered
for awaitoveron(client, 'message', { close }): Node 18 ignoresclose, and the loop keeps the last frame alive.Testing
websocketsThrowingCallbacks.test.tspasses unchanged.ws.ts, two rewrite-only tests inwebsockets.adapter.test.tsfail: "a subscription whose started message cannot be encoded disposes its iterator" and "a frame that throws while it is handled is reported, and later frames are served".main, which stops after the failed send.main.mainat 33ee2ba: allpackages/tests/server/websockets*files pass.AI model
Claude Opus 5.5
Open in [code]smith Β· Need help on this PR? Tag
@codesmith-botwith what you need.