Skip to content

refactor(server): rewrite the ws adapter with generators, using and result values (exploratory) - #7895

Draft
KATT wants to merge 10 commits into
mainfrom
cursor/ws-modern-rewrite-62d1
Draft

KATT wants to merge 10 commits into
mainfrom
cursor/ws-modern-rewrite-62d1

Conversation

@KATT

@KATT KATT commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Why

  • An exploratory rewrite of the ws adapter in a modern style, for discussion. Not meant to merge as is.

What

  • One serveConnection per connection. It owns its context signal, subscriptions and message listener with using, and reads frames from events.on in a loop.
  • Async generators build each request's replies. sendReplies sends them, never rejects, and passes send failures back as Result values.
  • A throwing or rejecting onError, a throwing errorFormatter and 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 fallback INTERNAL_SERVER_ERROR, and the failure goes to onError or console.error.
  • A failed started send ends the subscription: an error, then stopped, and its signal aborts. It's reported even when the iterator then can't be opened.
  • A stopped subscription sends no more data, not even a value it yields because of the stop.
  • Public types and wire messages don't change.

Open questions

  • Is a generator plus a few promises per message fine on this hot path?
  • Should attempt and settle move to unstable-core-do-not-import?

Links

Alternatives considered

  • for await over on(client, 'message', { close }): Node 18 ignores close, and the loop keeps the last frame alive.
  • One generator per connection: it serializes requests the protocol runs concurrently.

Testing

AI model

Claude Opus 5.5

Open in WebΒ Open in CursorΒ 

Autofix with [code]smith
Open in [code]smith Β· Need help on this PR? Tag @codesmith-bot with what you need.

@vercel

vercel Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
examples-next-minimal-starter Ready Ready Preview Nov 5, 2026 3:20am UTC
examples-todomvc Ready Ready Preview Nov 5, 2026 3:20am UTC
next-prisma-starter Ready Ready Preview Nov 5, 2026 3:20am UTC
next-prisma-websockets-starter Ready Ready Preview Nov 5, 2026 3:20am UTC
tanstack-start-sse-chat Ready Ready Preview Nov 5, 2026 3:20am UTC
trpc-next-app-dir Ready Ready Preview Nov 5, 2026 3:20am UTC
www Ready Ready Preview Nov 5, 2026 3:20am UTC

Request Review

@coderabbitai

coderabbitai Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix Β· Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

Share

@KATT
KATT added this pull request to stack #7893 November 4, 2026 13:28
Base automatically changed from cursor/wsclient-reconnect-errors-3334 to main November 4, 2026 13:37
@pkg-pr-new

pkg-pr-new Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@trpc/client

npm i https://pkg.pr.new/@trpc/client@7895

@trpc/next

npm i https://pkg.pr.new/@trpc/next@7895

@trpc/openapi

npm i https://pkg.pr.new/@trpc/openapi@7895

@trpc/react-query

npm i https://pkg.pr.new/@trpc/react-query@7895

@trpc/server

npm i https://pkg.pr.new/@trpc/server@7895

@trpc/tanstack-react-query

npm i https://pkg.pr.new/@trpc/tanstack-react-query@7895

@trpc/upgrade

npm i https://pkg.pr.new/@trpc/upgrade@7895

commit: 285e5d2

@cursor
cursor Bot force-pushed the cursor/ws-modern-rewrite-62d1 branch from 79cf86c to b76079e Compare November 4, 2026 13:39
@cursor
cursor Bot force-pushed the cursor/ws-modern-rewrite-62d1 branch from 873eeda to e9a57e3 Compare November 4, 2026 21:41
@cursor
cursor Bot force-pushed the cursor/ws-modern-rewrite-62d1 branch from e9a57e3 to d35c012 Compare November 4, 2026 21:46
cursoragent and others added 8 commits November 4, 2026 23:48
…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]>
…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]>
…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>&nbsp;<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>&nbsp;</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

5 active deployments
Preview – www β€” 285e5d2e Deployed Nov 5, 2026 by vercel[bot]
Preview – examples-todomvc β€” 285e5d2e Deployed Nov 5, 2026 by vercel[bot]
Preview – trpc-next-app-dir β€” 285e5d2e Deployed Nov 5, 2026 by vercel[bot]
Preview – examples-next-minimal-starter β€” 285e5d2e Deployed Nov 5, 2026 by vercel[bot]
Preview – next-prisma-starter β€” 285e5d2e Deployed Nov 5, 2026 by vercel[bot]
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.

2 participants