Repository navigation
feat(client): make subscribe() without callbacks return an async iterable - #7865
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
Walkthrough
Merge Risk:
|
@trpc/client
@trpc/next
@trpc/openapi
@trpc/react-query
@trpc/server
@trpc/tanstack-react-query
@trpc/upgrade
commit: |
b779fc7 to
1576f64
Compare
1576f64 to
f0d2dcf
Compare
…me id (trpc#7889) <!-- CURSOR_AGENT_PR_BODY_BEGIN --> Closes trpc#7886 ## Why - With `retryLink` in front of `wsLink` and the default `retryDelayMs` (0), a retry is never sent: - a retried query never settles; - a retried subscription never resumes, and `onError` and `onComplete` are never called. - `retryLink` retries synchronously, with the same `op.id`. The retry's request is registered while the failed request with that id is still being cleaned up. - `RequestManager` deletes requests by id, so that cleanup removed the retry too, before it was sent: - the failed request's teardown: `requestManager.ts:79`, called from `wsClient.ts:234`; - `handleResponseMessage`: `wsClient.ts:419`. - With a positive `retryDelayMs`, the retry runs after the cleanup, so it worked. ## What - `RequestManager.delete()` takes the outgoing message instead of its id, and deletes only that request. A newer request with the same id stays. - Its four callers pass the message: the cleanup returned by `register()`, and `wsClient.ts`'s close/error handling, `handleResponseMessage` and the `batchSend` failure path. - No public API change. Wire messages and ids are unchanged. ## Links None. There are no docs or example changes. ## Alternatives considered - **Defer the retry in `retryLink`, e.g. with `setTimeout(0)`.** It hides the bug for `retryLink` only. Any link that resubscribes synchronously with the same op would still lose its request. - **Give each request its own wire id in `wsClient`, apart from `op.id`.** It would also tell a late message for the failed request apart from one for the retry. But it changes the ids the server sees, and the hang doesn't need it. ## Testing - New `packages/tests/server/websockets.retryLink.test.ts`, which uses `retryLink` + `wsLink` against a real WebSocket server: - a query that fails once resolves `'ok'` on the retry, and the server is called twice; - a tracked subscription that errors after its first event is resubscribed with `lastEventId: 1`, gets `[1, 2]`, and has no `onError` or `onComplete`. - Regression check: both tests fail on `main` (8ff8793) with `AssertionError: expected 'timed out' to be 'ok'` and `AssertionError: expected [ [ undefined ] ] to deeply equal [ [ undefined ], [ 1 ] ]` (the server is never called again). Both pass with the fix. - `pnpm exec vitest run packages/tests/server packages/client packages/server/src/observable`: 102 files, 811 tests pass. - `tsc --noEmit` for `packages/client` and `packages/tests`, `oxlint` and `oxfmt --check` are clean. - With a subscription whose `return()` takes 50 ms, a retry still gets `[1, 2]` and doesn't complete early, on `main` and on trpc#7704 merged with `main`. **Merge order:** independent of trpc#7704 and trpc#7865. - trpc#7704 changes no client files. - trpc#7865 changes `TRPCUntypedClient` and `createTRPCClient`, but not `wsClient` or `RequestManager`. - `git merge-tree --write-tree` is clean against trpc#7704 (10c47ed) and trpc#7865 (38d9df4). - The new tests pass on both heads merged with this branch. ## AI model Claude Opus 5.5 <!-- CURSOR_AGENT_PR_BODY_END --> <div><a href="https://cursor.com/agents/bc-9cf4eb23-1980-4dc1-bd36-ff50b58f3334?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-9cf4eb23-1980-4dc1-bd36-ff50b58f3334&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=1796385672&installation_model_id=443568&pr_number=7889&ref=codesmith_pr_footer&repository=trpc%2Ftrpc&return_to=https%3A%2F%2Fgithub.com%2Ftrpc%2Ftrpc%2Fpull%2F7889&signature=4966dc49b18ed713e3508e3735c18cecc27cb6b159c8a0d1794e12289bb93a78"><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/7889?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** * Improved WebSocket request handling so an older request no longer interferes with a newer request that reuses its identifier. * Improved WebSocket retry behavior: queries can recover after an initial failure, and subscriptions can resume from the latest delivered event without ending prematurely. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Cursor Agent <[email protected]>
…t stops it (trpc#7888) <!-- CURSOR_AGENT_PR_BODY_BEGIN --> Closes trpc#7887 ## Why - When a client stops a WebSocket subscription (`subscription.stop`, or disconnecting), its cleanup can throw. That error never reached the server's `onError`, and nothing was logged. This happens with: - an observable teardown; - an `async function*` whose `finally` throws once the stop wakes it. - `ws.ts:363-371` races the pending `iterator.next()` against the stop. On `'abort'` it breaks and stops waiting for that `next()`. - The cleanup error rejects that `next()` after the race is decided, and the rejection was dropped: - With an observable, `observableToAsyncIterable` unsubscribes on abort and rejects the pending `next()` with the teardown error (trpc#7884). - With a generator, the `finally` runs inside the pending `next()`. - trpc#7884 stopped this from crashing the server, and its test checks only that. A cleanup error when the subscription completes on its own already goes to `onError`. ## What - New `nextUnlessStopped()` in `ws.ts`. The subscription loop uses it in place of `iterator.next().catch(getTRPCErrorFromUnknown)`. - Before the stop: unchanged. A rejection becomes a `TRPCError`, and the loop sends it to the client and `onError`. - After the stop: the rejection goes to `onError`, and the call resolves `'abort'`. Whichever way the race goes, it's reported once, and the client still gets `stopped`. - An `AbortError` isn't reported. It's how a stopped subscription normally ends, e.g. `on(ee, 'x', { signal })`. - No public API change. The messages the client gets are unchanged. ## Links None. There are no docs or example changes. ## Alternatives considered - **Make `observableToAsyncIterable`'s `return()` throw the stored teardown error.** It covers observables only, not generators. It would also change the helper's contract from trpc#7867 and trpc#7884, which trpc#7865 builds on. - **Await the pending `next()` after the stop.** A hand-written iterator whose `next()` never settles would hang the loop, and `stopped` would never be sent. (An `async function*` that ignores the signal already hangs at `iterator.return()` on `main`; this PR doesn't change that.) - **Send the cleanup error to the client.** The client already stopped. trpc#7704 also reports cleanup failures after a stop to the server only, and sends `stopped`. ## Testing - New `packages/tests/server/websockets.stopTeardown.test.ts`, using `wsLink` against a real server with `onError` spied: - an observable teardown that throws on `unsubscribe()` is reported to `onError` once, the client gets no error, and the connection still works; - a generator `finally` that throws after the stop is reported; - a teardown that throws when the client disconnects (`wsClient.close()`) is reported; - an `AbortError` from a stopped `on(ee, …, { signal })` loop is not reported. - Regression check: the first three fail on `main` (8ff8793) with `AssertionError: expected [] to deeply equal [ [ 'onObservable', …(1) ] ]` (and `'onGenerator'`): `onError` is never called. All four pass with the fix. - `pnpm exec vitest run packages/tests/server packages/client packages/server`: 119 files, 954 tests pass. - `tsc --noEmit` for `packages/server`, `packages/client` and `packages/tests`, `oxlint` and `oxfmt --check` are clean. - An independent review confirmed that each error is reported once and never sent to the client, that `onError` fires before `stopped`, and that no unhandled rejections remain. The new file passed 10 of 10 repeat runs. **Merge order:** this touches `ws.ts`, which trpc#7704 rewrites. trpc#7704 alone doesn't fix this: it keeps the same race, and its new test covers only an iterator whose `return()` rejects. - The change is one line in the loop, which trpc#7704 leaves unchanged, plus a helper in a region trpc#7704 doesn't touch, plus `isAbortError` in the import that trpc#7704 also adds it to. - `git merge-tree --write-tree` is clean against trpc#7704 (10c47ed), trpc#7865 (38d9df4) and trpc#7889. - On trpc#7704 merged with `main` and this branch, the full suite passes: 121 files, 981 tests, including trpc#7704's `websocketsLifecycle.test.ts`. `tsc` passes too. - Either order works. If trpc#7704 lands first, its `reportError` helper could replace the inline `opts.onError?.(…)` callback. ## AI model Claude Opus 5.5 <!-- CURSOR_AGENT_PR_BODY_END --> <div><a href="https://cursor.com/agents/bc-9cf4eb23-1980-4dc1-bd36-ff50b58f3334?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-9cf4eb23-1980-4dc1-bd36-ff50b58f3334&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=1796385670&installation_model_id=443568&pr_number=7888&ref=codesmith_pr_footer&repository=trpc%2Ftrpc&return_to=https%3A%2F%2Fgithub.com%2Ftrpc%2Ftrpc%2Fpull%2F7888&signature=936559c21acb17177f424e0414e8c8d52ae932907d6bf498047b7aeb60d9c166"><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/7888?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 subscription errors that occur during teardown are now reported through server error handling, including failures after a client unsubscribes or disconnects. * Expected aborts after a subscription stops are not reported as errors. Active subscription errors continue through the existing error-response flow. * Subscription cleanup errors are now covered by tests, including cases where subscriptions complete and subsequent queries succeed. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Cursor Agent <[email protected]>
trpc-bot
left a comment
There was a problem hiding this comment.
🤖 Re-approving at 01fa0b9: covers #7850's remaining cases (already-aborted signal, teardown emissions on abort and return(), iterating once) and credits @tarikermis.
…able Without callbacks, subscribe() returns an AsyncIterableIterator over observableToAsyncIterable, with no unsubscribe(): a signal, break or return() stops it, like Node's events.on(). With callbacks, at least one must be defined, and it returns Unsubscribable as before; options with callback keys that are all undefined are a type error and throw. observableToAsyncIterable now returns its iterator. Ports #7850's tests and docs, and adds a migration note for unsubscribe(). Co-authored-by: alexander <[email protected]>
A second `for await` over a subscription started without callbacks now throws instead of sharing the iterator, which would split the data between two loops or end the second one silently. Covers the rest of #7850's cases with real-client tests: an already aborted signal tears down a link that ignores it, aborting or calling return() during a running loop drops what the link emits while it tears down, and each of the six observer callbacks on its own counts as a callback. The reconnect test releases suppressed logs in a `finally`. Co-authored-by: Tarik Ermis <[email protected]> Co-authored-by: alexander <[email protected]>
Co-authored-by: alexander <[email protected]>
01fa0b9 to
00b5030
Compare
|
This pull request has been locked because we are very unlikely to see comments on closed issues. If you think, this PR is still necessary, create a new one with the same branch. Thank you. |
Why
People want to read a vanilla-client subscription with
for await.iterate()method to subscriptions #7461subscribe()async-iterable #7850What
subscribe()returns an async iterator, like Node'sevents.on(). Stop it withsignal,breakorreturn(). With callbacks, it works as before.observableToAsyncIterable.unsubscribe()on a subscription without callbacks, pass asignalandabort()it instead.for awaitover the same subscription throws, so two loops can't silently split or miss data.Links
for awaitusage and rules.Alternatives considered
subscribe()async-iterable #7850:subscribe()returns an iterableUnsubscribable, through a separate client wrapper. Lost to reusing the server helper.iterate()method to subscriptions #7461: a separateiterate()method. Lost to keeping onesubscribe().Testing
subscriptionAsyncIterable.test.tsfails if teardown emissions reach the loop, if an already-aborted signal leaves the link open, or if a second loop doesn't throw.AI model
Claude Opus 5.5
Open in [code]smith · Need help on this PR? Tag
@codesmith-botwith what you need.Summary by CodeRabbit
for await...ofinstead of callbacks. Use anAbortSignalor exit the loop to stop; queued results are delivered before aborts or errors.