Repository navigation
fix(client): handle AbortSignal events and pre-aborted signals in wsLink - #7442
aryamirani wants to merge 1 commit into
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
π WalkthroughWalkthrough
ChangesWebSocket AbortSignal handling
Estimated code review effort: 3 (Moderate) | ~20 minutes Possibly related issues
Possibly related PRs
Sequence Diagram(s)sequenceDiagram
participant AbortController
participant WsClient
participant WebSocket
participant Observer
AbortController->>WsClient: abort signal
WsClient->>WsClient: abort batchSend
WsClient->>WebSocket: send subscription.stop when applicable
WsClient->>Observer: report TRPCClientError
Suggested reviewers: π₯ Pre-merge checks | β 5β Passed checks (5 passed)
β¨ Finishing Touchesπ§ͺ Generate unit tests (beta)
Comment |
@trpc/client
@trpc/next
@trpc/openapi
@trpc/react-query
@trpc/server
@trpc/tanstack-react-query
@trpc/upgrade
commit: |
There was a problem hiding this comment.
Actionable comments posted: 5
π€ Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/client/src/links/wsLink/wsClient/wsClient.ts`:
- Line 198: Move the pre-aborted signal check ahead of the this.batchSend(...)
call in the surrounding request flow. Ensure an already-aborted operation
returns through the existing abort path before serializing input, registering
the request, resetting timeouts, or scheduling open/flush work; preserve normal
batching for non-aborted signals.
- Around line 225-259: Make cancellation idempotent in the abort/unsubscribe
flow by adding a one-shot guard shared by abort(), the signal-abort handler, and
the returned teardown. Ensure subscription.stop is sent at most once while
preserving existing error reporting and cleanup behavior.
- Around line 238-251: Normalize signal.reason in both abort error paths before
passing it to TRPCClientError.from: preserve it when it is an Error, and convert
non-Error values into a valid Error using the existing cancellation
fallback/message strategy. Update the surrounding abort handling, including
onAbort, without relying on `as Error` casts.
In `@packages/tests/server/websockets.test.ts`:
- Line 2230: Replace the `factory()` resource setup in both affected tests with
`await using ctx = testServerAndClientResource(...)`. Configure each testβs
fresh mocks through the resourceβs `client` callback while preserving the
existing combined server/client test behavior.
- Around line 2229-2253: Update the websocket cancellation tests around the
existing query cases so the in-flight test waits for the server to receive and
start the request before invoking AbortController.abort(), ensuring cancellation
is dispatched rather than pre-dispatch. Add equivalent cancellation coverage for
a mutation and a subscription, including assertions for subscription.stop and
the required cleanup behavior, while retaining the already-aborted signal test.
πͺ Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
βΉοΈ Review info
βοΈ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 1f50c447-17fe-4908-8da1-dea53ef7ea68
π Files selected for processing (2)
packages/client/src/links/wsLink/wsClient/wsClient.tspackages/tests/server/websockets.test.ts
| test('aborts in-flight query when AbortSignal is triggered', async () => { | ||
| await using ctx = factory(); | ||
|
|
||
| const ac = new AbortController(); | ||
| const queryPromise = ctx.client.greeting.query('world', { | ||
| signal: ac.signal, | ||
| }); | ||
|
|
||
| ac.abort(); | ||
|
|
||
| await expect(queryPromise).rejects.toThrow('This operation was aborted'); | ||
| }); | ||
|
|
||
| test('rejects immediately if signal is already aborted', async () => { | ||
| await using ctx = factory(); | ||
|
|
||
| const ac = new AbortController(); | ||
| ac.abort(); | ||
|
|
||
| const queryPromise = ctx.client.greeting.query('world', { | ||
| signal: ac.signal, | ||
| }); | ||
|
|
||
| await expect(queryPromise).rejects.toThrow('This operation was aborted'); | ||
| }); |
There was a problem hiding this comment.
π― Functional Correctness | π Major | ποΈ Heavy lift
Make the tests exercise dispatched cancellation and all required operation types.
The first test aborts immediately after query(). WsClient.batchSend waits at Line 452 before sending, so this normally tests pre-dispatch cancellation rather than an in-flight query. Gate on the server receiving/starting the request before calling abort(). Also add mutation and subscription cases to cover the subscription.stop branch and cleanup contract required by issue #7439.
π€ Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/tests/server/websockets.test.ts` around lines 2229 - 2253, Update
the websocket cancellation tests around the existing query cases so the
in-flight test waits for the server to receive and start the request before
invoking AbortController.abort(), ensuring cancellation is dispatched rather
than pre-dispatch. Add equivalent cancellation coverage for a mutation and a
subscription, including assertions for subscription.stop and the required
cleanup behavior, while retaining the already-aborted signal test.
|
|
||
| describe('wsLink AbortSignal support', () => { | ||
| test('aborts in-flight query when AbortSignal is triggered', async () => { | ||
| await using ctx = factory(); |
There was a problem hiding this comment.
π Maintainability & Code Quality | π Major | β‘ Quick win
Use the required test resource directly.
Both tests create ctx with factory(), but this path requires await using ctx = testServerAndClientResource(...) for tests that set up both server and client. Replace the wrapper at both sites and configure fresh mocks through the resourceβs client callback.
As per coding guidelines: **/*.test.ts must always use await using ctx = testServerAndClientResource(...) for combined server/client setup.
Also applies to: 2243-2243
π€ Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/tests/server/websockets.test.ts` at line 2230, Replace the
`factory()` resource setup in both affected tests with `await using ctx =
testServerAndClientResource(...)`. Configure each testβs fresh mocks through the
resourceβs `client` callback while preserving the existing combined
server/client test behavior.
Source: Coding guidelines
There was a problem hiding this comment.
Pull request overview
This PR fixes wsLink so operations respect an AbortSignal, including already-aborted signals, and adds integration tests to cover the behavior (issue #7439).
Changes:
- Registers an
AbortSignallistener for WebSocket operations and performs cleanup when it fires. - Adds handling for pre-aborted signals to reject without proceeding.
- Adds WebSocket integration tests for in-flight abort and pre-aborted signals.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 4 comments.
| File | Description |
|---|---|
| packages/client/src/links/wsLink/wsClient/wsClient.ts | Adds abort listener + pre-abort handling and teardown logic for wsLink operations. |
| packages/tests/server/websockets.test.ts | Adds integration tests asserting abort behavior for wsLink queries. |
Comments suppressed due to low confidence (3)
packages/client/src/links/wsLink/wsClient/wsClient.ts:202
signal?.abortedis checked afterbatchSend()has already been scheduled/registered. For already-aborted signals this can still trigger side effects (e.g. opening the WS connection / scheduling a flush) even though the operation should reject immediately without dispatching.
const batchSendAbort = this.batchSend(
{
id,
method: type,
params: {
packages/client/src/links/wsLink/wsClient/wsClient.ts:252
- Same as above: the fallback abort error message should match the standard AbortError message used across the repo/test suite.
TRPCClientError.from(
(signal?.reason as Error) ?? new Error('Operation aborted'),
),
);
packages/tests/server/websockets.test.ts:2253
- Same brittleness as above: prefer asserting
cause.name === 'AbortError'over matching the exact message string, which can differ between environments ("This" vs "The" operation was aborted).
const queryPromise = ctx.client.greeting.query('world', {
signal: ac.signal,
});
await expect(queryPromise).rejects.toThrow('This operation was aborted');
});
π‘ Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.
Comments suppressed due to low confidence (2)
packages/client/src/links/wsLink/wsClient/wsClient.ts:240
- In the pre-aborted path, calling
abort()invokes theRequestManager.registercleanup (viabatchSendAbort()), which callsobserver.complete()beforeobserver.error(...). That can suppress the error and break promise rejection semantics. Prefer removing the request fromRequestManagerwithout completing, then error the observer.
if (signal?.aborted) {
abort();
observer.error(
TRPCClientError.from(
(signal.reason as Error) ?? new Error('Operation aborted'),
packages/client/src/links/wsLink/wsClient/wsClient.ts:250
- Similarly to the pre-aborted path, the abort event handler calls
abort()(which completes the observer viaRequestManager.registercleanup) and then callsobserver.error(...). This can lead to the abort error being dropped. Delete the request without completing, stop the subscription (if applicable), then error the observer.
const onAbort = () => {
abort();
observer.error(
TRPCClientError.from(
(signal?.reason as Error) ?? new Error('Operation aborted'),
| describe('wsLink AbortSignal support', () => { | ||
| test('aborts in-flight query when AbortSignal is triggered', async () => { | ||
| await using ctx = factory(); | ||
|
|
||
| const ac = new AbortController(); | ||
| const queryPromise = ctx.client.greeting.query('world', { | ||
| signal: ac.signal, | ||
| }); | ||
|
|
||
| ac.abort(); | ||
|
|
||
| await expect(queryPromise).rejects.toThrow('This operation was aborted'); |
b513c20 to
68aced5
Compare
There was a problem hiding this comment.
β»οΈ Duplicate comments (2)
packages/client/src/links/wsLink/wsClient/wsClient.ts (2)
198-257: π Performance & Scalability | π‘ Minor | β‘ Quick winPre-abort check still runs after
batchSendβ resurfaces prior unresolved comment.The
signal?.abortedcheck at line 249 runs afterthis.batchSend(...)(line 200) has already reset the inactivity timeout, registered the request, and scheduledthis.open()/flush viarun(async () => {...}). For a pre-aborted operation this still opens a WebSocket connection in lazy mode before being torn down bystop(). This was flagged in a prior review and hasn't been addressed.π Proposed fix: check abort before scheduling the batch
>((observer) => { let isDone = false; + if (signal?.aborted) { + observer.error( + TRPCClientError.from( + (signal.reason as Error) ?? new Error('Operation aborted'), + ), + ); + return; + } + const batchSendAbort = this.batchSend( { id, method: type, params: { input: transformer.input.serialize(input), path, lastEventId, }, }, { ...observer, next(event) { const transformed = transformResult(event, transformer.output); if (!transformed.ok) { observer.error(TRPCClientError.from(transformed.error)); return; } observer.next({ result: transformed.result, }); }, error(err) { isDone = true; observer.error(err); }, complete() { isDone = true; observer.complete(); }, }, ); const stop = () => { if (isDone) return; isDone = true; batchSendAbort(); if (type === 'subscription' && this.activeConnection.isOpen()) { this.send({ id, method: 'subscription.stop', }); } }; - if (signal?.aborted) { - stop(); - observer.error( - TRPCClientError.from( - (signal.reason as Error) ?? new Error('Operation aborted'), - ), - ); - return; - } - const onAbort = () => {π€ Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/client/src/links/wsLink/wsClient/wsClient.ts` around lines 198 - 257, Move the signal?.aborted check before the batchSend call so pre-aborted operations return an abort error without registering the request, resetting timeouts, or scheduling connection opening. Preserve the existing stop behavior for aborts occurring after batchSend has been scheduled, using the surrounding stop function and observer error handling appropriately.
249-267: π― Functional Correctness | π‘ Minor | β‘ Quick win
signal.reason as Errorcast doesn't normalize non-Error abort reasons β still unresolved.
AbortController.abort(reason)accepts any value;as Erroris a compile-time-only assertion that doesn't convert a string/object reason into anErrorat runtime, soTRPCClientError.fromcan receive a non-Error and produce a degraded message. This was already raised in a prior review and remains unfixed, and the same unsafe cast is duplicated at lines 253 and 264.β»οΈ Proposed fix: shared normalization helper
+function toAbortError(signal?: AbortSignal): Error { + const reason = signal?.reason; + if (reason instanceof Error) return reason; + return new Error( + typeof reason === 'string' ? reason : 'Operation aborted', + ); +} +if (signal?.aborted) { stop(); observer.error( - TRPCClientError.from( - (signal.reason as Error) ?? new Error('Operation aborted'), - ), + TRPCClientError.from(toAbortError(signal)), ); return; } const onAbort = () => { if (isDone) return; stop(); observer.error( - TRPCClientError.from( - (signal?.reason as Error) ?? new Error('Operation aborted'), - ), + TRPCClientError.from(toAbortError(signal)), ); };As per coding guidelines,
**/*.{ts,tsx}files should "Use type assertions sparingly" and "Use proper type guards and optional chaining instead of non-null assertions" β the unguardedas Errorcast on an arbitrarysignal.reasonvalue violates this.π€ Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/client/src/links/wsLink/wsClient/wsClient.ts` around lines 249 - 267, Normalize abort reasons before passing them to TRPCClientError.from: add or reuse a shared helper near the websocket client abort handling that returns the existing Error when the reason is an Error and otherwise creates an Error from the reason. Replace both signal.reason as Error expressions in the initial aborted check and onAbort with this helper, preserving the existing fallback message when no reason is provided.Source: Coding guidelines
π€ Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Duplicate comments:
In `@packages/client/src/links/wsLink/wsClient/wsClient.ts`:
- Around line 198-257: Move the signal?.aborted check before the batchSend call
so pre-aborted operations return an abort error without registering the request,
resetting timeouts, or scheduling connection opening. Preserve the existing stop
behavior for aborts occurring after batchSend has been scheduled, using the
surrounding stop function and observer error handling appropriately.
- Around line 249-267: Normalize abort reasons before passing them to
TRPCClientError.from: add or reuse a shared helper near the websocket client
abort handling that returns the existing Error when the reason is an Error and
otherwise creates an Error from the reason. Replace both signal.reason as Error
expressions in the initial aborted check and onAbort with this helper,
preserving the existing fallback message when no reason is provided.
βΉοΈ Review info
βοΈ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 5c40d4c9-2a87-4ba9-a98a-d3dfabef87c9
π Files selected for processing (2)
packages/client/src/links/wsLink/wsClient/wsClient.tspackages/tests/server/websockets.test.ts
π§ Files skipped from review as they are similar to previous changes (1)
- packages/tests/server/websockets.test.ts
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.
Comments suppressed due to low confidence (3)
packages/client/src/links/wsLink/wsClient/wsClient.ts:267
onAbortcallsstop()beforeobserver.error(...). Sincestop()triggersbatchSendAbort()which completes the observable, the subsequentobserver.error(...)is ignored by the observableβs internalisDoneguard. This makes the abort error path ineffective (especially for subscriptions) and the codeβs intent unclear.
const onAbort = () => {
if (isDone) return;
stop();
observer.error(
TRPCClientError.from(
(signal?.reason as Error) ?? new Error('Operation aborted'),
),
);
};
packages/tests/server/websockets.test.ts:2239
- This assertion hard-codes the abort message string. Abort messages can vary across runtimes (Node versions / browser DOMException implementations), and other tests in this repo typically match
/aborted/instead of an exact message.
await expect(queryPromise).rejects.toThrow('This operation was aborted');
packages/tests/server/websockets.test.ts:2252
- This assertion hard-codes the abort message string. Abort messages can vary across runtimes (Node versions / browser DOMException implementations), and other tests in this repo typically match
/aborted/instead of an exact message.
await expect(queryPromise).rejects.toThrow('This operation was aborted');
68aced5 to
962b73d
Compare
In wsLink (wsClient.ts), operation AbortSignal listener was never registered (signal?.removeEventListener was called in teardown, but addEventListener was missing). As a result, calling controller.abort() on an in-flight query, mutation, or subscription did not cancel the request or unsubscribe from the WebSocket. This change: - Registers an 'abort' event listener on signal when an operation starts - Immediately aborts and cleans up pending requests when signal is aborted - Rejects immediately if signal is already aborted prior to dispatch - Adds unit tests in packages/tests/server/websockets.test.ts Fixes trpc#7439
962b73d to
fa6a1fe
Compare
|
Duplicate of this #7434 |
There was a problem hiding this comment.
π‘ Changes recommended
Unresolved critical cleanup and type-safety issues, plus abort-reason handling concerns, block approval.
Get a fresh assessment by requesting another Copilot review.
Review details
Suppressed comments (1)
packages/client/src/links/wsLink/wsClient/wsClient.ts:256
- The new tests do not cover the subscription-only cleanup introduced here. Add an integration test that starts a WebSocket subscription, aborts its signal after it is started, and verifies the server-side subscription ends (or observes the
subscription.stopmessage); the query tests would still pass if this branch were broken.
if (type === 'subscription' && this.activeConnection.isOpen()) {
this.send({
id,
method: 'subscription.stop',
});
- Files reviewed: 2/2 changed files
- Comments generated: 4
- Review effort level: Lite
| import { ResettableTimeout, TRPCWebSocketClosedError } from './utils'; | ||
| import { backwardCompatibility, WsConnection } from './wsConnection'; | ||
|
|
||
| function toAbortError(signal?: AbortSignal): Error { |
| error(err) { | ||
| isDone = true; | ||
| observer.error(err); | ||
| }, | ||
| complete() { | ||
| isDone = true; | ||
| observer.complete(); | ||
| }, |
| function toAbortError(signal?: AbortSignal): Error { | ||
| const reason = signal?.reason; | ||
| if (reason instanceof Error) return reason; | ||
| return new Error(typeof reason === 'string' ? reason : 'Operation aborted'); |
| test('aborts in-flight query when AbortSignal is triggered', async () => { | ||
| await using ctx = factory(); | ||
|
|
||
| const ac = new AbortController(); | ||
| const queryPromise = ctx.client.greeting.query('world', { | ||
| signal: ac.signal, | ||
| }); | ||
|
|
||
| ac.abort(); | ||
|
|
||
| await expect(queryPromise).rejects.toThrow(/aborted/i); |
|
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. |
Summary
Fixes #7439 where
wsLinkignored theAbortSignalpassed with an operation. Callingcontroller.abort()on anAbortControllerhad no effect on in-flight queries, mutations, or subscriptions over WebSocket because the abort event listener was never registered onsignal.Problem Statement & Root Cause
In
packages/client/src/links/wsLink/wsClient/wsClient.ts,signal?.removeEventListener('abort', abort)was called in the cleanup function returned byrequest(), butsignal?.addEventListener('abort', ...)was never called during operation setup. Additionally, pre-abortedAbortSignalinstances were not checked before sending batch messages.Solution
{ once: true }listener for'abort'onop.signalwhen an operation is dispatched. When triggered, it cleans up the pending request fromRequestManager, sendssubscription.stopif an active subscription, and notifies observers with aTRPCClientError.signal?.abortedbefore dispatching, rejecting immediately if already aborted.Test Coverage
Added integration tests in
packages/tests/server/websockets.test.ts:AbortSignaltrigger over WebSocket.AbortSignal.Tested via
npx vitest run packages/tests/server/websockets.test.ts(45/45 tests passing).Summary by CodeRabbit
Bug Fixes
AbortSignal, including immediate rejection when the signal is already aborted.Tests