Skip to content

fix(client): handle AbortSignal events and pre-aborted signals in wsLink - #7442

Closed
aryamirani wants to merge 1 commit into
trpc:mainfrom
aryamirani:fix/wslink-abort-signal
Closed

aryamirani wants to merge 1 commit into
trpc:mainfrom
aryamirani:fix/wslink-abort-signal

Conversation

@aryamirani

@aryamirani aryamirani commented Jul 23, 2026 •

Copy link
Copy Markdown

Summary

Fixes #7439 where wsLink ignored the AbortSignal passed with an operation. Calling controller.abort() on an AbortController had no effect on in-flight queries, mutations, or subscriptions over WebSocket because the abort event listener was never registered on signal.

Problem Statement & Root Cause

In packages/client/src/links/wsLink/wsClient/wsClient.ts, signal?.removeEventListener('abort', abort) was called in the cleanup function returned by request(), but signal?.addEventListener('abort', ...) was never called during operation setup. Additionally, pre-aborted AbortSignal instances were not checked before sending batch messages.

Solution

  1. Abort Listener Registration: Register a { once: true } listener for 'abort' on op.signal when an operation is dispatched. When triggered, it cleans up the pending request from RequestManager, sends subscription.stop if an active subscription, and notifies observers with a TRPCClientError.
  2. Pre-aborted Check: Check signal?.aborted before dispatching, rejecting immediately if already aborted.
  3. Clean Teardown: Remove event listener on normal completion or unsubscription.

Test Coverage

Added integration tests in packages/tests/server/websockets.test.ts:

  • Verifies in-flight query cancellation upon AbortSignal trigger over WebSocket.
  • Verifies immediate rejection when passing an already-aborted AbortSignal.

Tested via npx vitest run packages/tests/server/websockets.test.ts (45/45 tests passing).

Summary by CodeRabbit

  • Bug Fixes

    • Improved cancellation behavior for WebSocket-backed queries using AbortSignal, including immediate rejection when the signal is already aborted.
    • Ensures in-flight requests and active subscriptions are stopped cleanly, and sends stop messages when the WebSocket connection is open.
  • Tests

    • Added coverage for aborting in-flight WebSocket queries and for handling already-aborted signals.

@aryamirani
aryamirani requested a review from a team as a code owner July 23, 2026 04:43
Copilot AI lite review requested due to automatic review settings July 23, 2026 04:43
@vercel

vercel Bot commented Jul 23, 2026 •

Copy link
Copy Markdown

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

Project Deployment Actions Updated
next-prisma-starter Ready Ready Preview Sep 12, 2026 11:49am UTC
og-image Ready Ready Preview Sep 12, 2026 11:49am UTC

Request Review

@coderabbitai

coderabbitai Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

πŸ“ Walkthrough

Walkthrough

WsClient.request now handles pre-aborted and in-flight AbortSignal cancellation, aborts batched requests, stops active subscriptions when applicable, and reports normalized cancellation errors. WebSocket tests cover both timing cases.

Changes

WebSocket AbortSignal handling

Layer / File(s) Summary
Abort flow and validation
packages/client/src/links/wsLink/wsClient/wsClient.ts, packages/tests/server/websockets.test.ts
WsClient.request normalizes abort reasons, handles immediate and asynchronous cancellation, prevents duplicate cleanup, stops open subscriptions, and tests both cancellation paths.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related issues

  • Issue 7431: Covers the missing WebSocket AbortSignal handling addressed by this change.

Possibly related PRs

  • trpc/trpc#6223: Introduced the WsClient implementation that this abort lifecycle extends.
  • trpc/trpc#7434: Modifies the same WebSocket abort lifecycle and related tests.
  • trpc/trpc#7440: Adds comparable immediate and event-driven abort handling in WsClient.request.

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
Loading

Suggested reviewers: copilot

πŸš₯ Pre-merge checks | βœ… 5
βœ… Passed checks (5 passed)
Check name Status Explanation
Title check βœ… Passed The title clearly summarizes the main wsLink AbortSignal fix.
Description check βœ… Passed The description covers the issue, root cause, solution, and tests, though it doesn't mirror the template exactly.
Linked Issues check βœ… Passed The changes implement one-time abort listeners, pre-aborted checks, and teardown behavior required by #7439.
Out of Scope Changes check βœ… Passed The diff stays focused on wsLink abort handling and matching tests, with no obvious unrelated changes.
Docstring Coverage βœ… Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
πŸ§ͺ Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands.

@pkg-pr-new

pkg-pr-new Bot commented Jul 23, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@trpc/client

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

@trpc/next

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

@trpc/openapi

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

@trpc/react-query

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

@trpc/server

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

@trpc/tanstack-react-query

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

@trpc/upgrade

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

commit: 962b73d

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 340811b and 117eaa9.

πŸ“’ Files selected for processing (2)
  • packages/client/src/links/wsLink/wsClient/wsClient.ts
  • packages/tests/server/websockets.test.ts

Comment on lines +2229 to +2253
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');
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

πŸ“ 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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 AbortSignal listener 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?.aborted is checked after batchSend() 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.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 the RequestManager.register cleanup (via batchSendAbort()), which calls observer.complete() before observer.error(...). That can suppress the error and break promise rejection semantics. Prefer removing the request from RequestManager without 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 via RequestManager.register cleanup) and then calls observer.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'),

Comment on lines +2228 to +2239
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');

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ Duplicate comments (2)
packages/client/src/links/wsLink/wsClient/wsClient.ts (2)

198-257: πŸš€ Performance & Scalability | 🟑 Minor | ⚑ Quick win

Pre-abort check still runs after batchSend β€” resurfaces prior unresolved comment.

The signal?.aborted check at line 249 runs after this.batchSend(...) (line 200) has already reset the inactivity timeout, registered the request, and scheduled this.open()/flush via run(async () => {...}). For a pre-aborted operation this still opens a WebSocket connection in lazy mode before being torn down by stop(). 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 Error cast doesn't normalize non-Error abort reasons β€” still unresolved.

AbortController.abort(reason) accepts any value; as Error is a compile-time-only assertion that doesn't convert a string/object reason into an Error at runtime, so TRPCClientError.from can 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 unguarded as Error cast on an arbitrary signal.reason value 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

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between b513c20 and 68aced5.

πŸ“’ Files selected for processing (2)
  • packages/client/src/links/wsLink/wsClient/wsClient.ts
  • packages/tests/server/websockets.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/tests/server/websockets.test.ts

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  • onAbort calls stop() before observer.error(...). Since stop() triggers batchSendAbort() which completes the observable, the subsequent observer.error(...) is ignored by the observable’s internal isDone guard. 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');

Copilot AI review requested due to automatic review settings July 23, 2026 05:54
@aryamirani
aryamirani force-pushed the fix/wslink-abort-signal branch from 68aced5 to 962b73d Compare July 23, 2026 05:54

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

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
@Nick-Lucas

Copy link
Copy Markdown
Contributor

Duplicate of this #7434

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟑 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.stop message); 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 {
Comment on lines +235 to +242
error(err) {
isDone = true;
observer.error(err);
},
complete() {
isDone = true;
observer.complete();
},
Comment on lines +28 to +31
function toAbortError(signal?: AbortSignal): Error {
const reason = signal?.reason;
if (reason instanceof Error) return reason;
return new Error(typeof reason === 'string' ? reason : 'Operation aborted');
Comment on lines +2229 to +2239
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);
@github-actions

Copy link
Copy Markdown
Contributor

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.

@github-actions github-actions Bot locked as resolved and limited conversation to collaborators Sep 13, 2026

This branch had an error being deployed

1 failed and 4 active deployments
Preview – www β€” fa6a1fe6 Deployed Sep 12, 2026 by vercel[bot]
Preview – examples-todomvc β€” fa6a1fe6 Deployed Sep 12, 2026 by vercel[bot]
Preview – trpc-next-app-dir β€” fa6a1fe6 Deployed Sep 12, 2026 by vercel[bot]
Preview – next-prisma-starter β€” fa6a1fe6 Deployed Sep 12, 2026 by vercel[bot]
Preview – og-image β€” fa6a1fe6 Deployed Sep 12, 2026 by vercel[bot]
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

wsLink: AbortSignal on operations is ignored β€” abort does not cancel in-flight requests or subscriptions

3 participants