Skip to content

Conversation

@KATT
Copy link
Member

@KATT KATT commented Feb 7, 2025

Closes #6461

🎯 Changes

  • Add failing test
  • Fix failing test

✅ Checklist

  • I have followed the steps listed in the Contributing guide.
  • If necessary, I have added documentation related to the changes made.
  • I have added or updated the tests related to the changes made.

Summary by CodeRabbit

  • Bug Fixes
    • Updated error messages to clarify unsupported subscription operations and improve specificity for aborted operations.
  • Refactor
    • Simplified error handling in JSON streaming by removing custom error types and standardizing responses.
  • Tests
    • Introduced new tests for streaming queries and refined existing tests to ensure accurate error reporting during cancellations.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 7, 2025

Walkthrough

This pull request refines error management across client and server packages. The error message in httpBatchStreamLink now explicitly mentions its own name when subscription operations are attempted. On the server side, custom error types have been removed and error handling improved in the JSON streaming logic. Additionally, tests have been updated to reflect these error message changes and to validate streaming query interruptions using an AbortController.

Changes

File(s) Change Summary
packages/client/.../httpBatchStreamLink.ts Updated error message to specify that subscriptions are unsupported by httpBatchStreamLink.
packages/server/.../stream/jsonl.ts, packages/server/.../stream/jsonl.test.ts Removed the custom StreamInterruptedError; updated error handling and expected error messages in JSON streaming tests to use generic error types.
packages/tests/server/regression/issue-6461-stream-error.test.ts, packages/tests/server/streaming.test.ts Added a new test for streaming query interruption using AbortController and updated error messages to indicate AbortError on stream abort.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant AC as AbortController
    participant S as Streaming Server
    participant E as Error Handler

    C->>S: Initiate streaming query
    C->>AC: Signal abort
    AC->>S: Propagate abort signal
    S->>E: Detect streaming interruption
    E-->>C: Return AbortError / TRPCClientError
Loading

Assessment against linked issues

Objective Addressed Explanation
Error thrown for streaming query termination should be a TRPCClientError (#6461)

Possibly related PRs

Poem

I'm just a rabbit, coding with delight,
Hopping through errors, setting things right.
Subscriptions clarified and streams now sing,
Abort signals handled like the breeze in spring.
With tests in place, my ears perk with cheer—
A code garden blooming, far and near!
🐇🌼


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ac93208 and ef97964.

📒 Files selected for processing (2)
  • packages/server/src/unstable-core-do-not-import/stream/jsonl.ts (5 hunks)
  • packages/tests/server/streaming.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/tests/server/streaming.test.ts
🔇 Additional comments (5)
packages/server/src/unstable-core-do-not-import/stream/jsonl.ts (5)

420-421: LGTM! Type refinement improves type safety.

The change from ControllerChunk to ChunkData simplifies the type system by removing the custom error type, making the code more maintainable.


452-466: LGTM! Clean resource management.

The new clear function properly cleans up resources by replacing methods with no-ops after the stream is closed or errored. This prevents memory leaks and improves resource management.


486-489: LGTM! Simplified error propagation.

The cancelAll function now directly propagates the error reason without wrapping it in a custom error type. This aligns with the PR's objective of fixing stream termination errors.


591-594: Verify error message consistency.

The error message "Stream closed" should be consistent with other error messages in the codebase. Let's verify this.

Also applies to: 617-617

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Search for similar error messages in the codebase
rg -A 2 'new Error\(' packages/server/src

Length of output: 10173


Action: Error message consistency verified.
After reviewing the error messages across the codebase, the error message "Stream closed" in packages/server/src/unstable-core-do-not-import/stream/jsonl.ts is formatted and phrased in a manner consistent with other similar error messages (e.g., starting with a capital letter and using plain descriptive text). No discrepancy was found between this message and similar ones used elsewhere.


427-451: Verify error propagation in stream controller.

The error handling has been simplified by directly propagating the error reason. However, we should verify that errors are properly handled by downstream consumers.

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Search for error handling in downstream consumers
ast-grep --pattern 'catch (error) {
  $$$
}'

# Search for error handling in tests
rg -A 5 'controller.error' packages/server/src/unstable-core-do-not-import/stream/jsonl.test.ts

Length of output: 142


I'll run a new shell script to get more insights into the error propagation tests in the file. This will help verify if any tests assert that errors produced via streamController.error (and ultimately through originalController.error) are handled downstream.


🏁 Script executed:

#!/bin/bash
echo "=== Content of jsonl.test.ts ==="
cat packages/server/src/unstable-core-do-not-import/stream/jsonl.test.ts

echo "=== Searching for error handling patterns ==="
rg -A 10 "error(" packages/server/src/unstable-core-do-not-import/stream/jsonl.test.ts

echo "=== Searching for abort controller usage ==="
rg -n "abortController.abort" packages/server/src/unstable-core-do-not-import/stream/jsonl.test.ts

Length of output: 16678


Verification of Error Propagation in Stream Controller

The tests in jsonl.test.ts demonstrate that errors are properly propagated downstream. In the "encode/decode - error" test, errors thrown in both promise resolution (for deferred values) and during async iteration are caught and validated against a snapshot ([Error: Received error from server]). Additionally, producer error callbacks are invoked as expected (with snapshots verifying the error details). This confirms that the simplified error handling in the stream controller reliably passes error information to downstream consumers.

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@railway-app
Copy link

railway-app bot commented Feb 7, 2025

🚅 Previously deployed to Railway in the trpc-sse-and-websockets project. Environment has been deleted.

@vercel
Copy link

vercel bot commented Feb 7, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
next-prisma-starter ✅ Ready (Inspect) Visit Preview Feb 7, 2025 5:39pm
og-image ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 7, 2025 5:39pm
www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 7, 2025 5:39pm

@pkg-pr-new
Copy link

pkg-pr-new bot commented Feb 7, 2025

Open in Stackblitz

npm i https://pkg.pr.new/trpc/trpc/@trpc/client@6462
npm i https://pkg.pr.new/trpc/trpc/@trpc/next@6462
npm i https://pkg.pr.new/trpc/trpc/@trpc/react-query@6462
npm i https://pkg.pr.new/trpc/trpc/@trpc/server@6462

commit: ef97964

@KATT KATT added the 🙋‍♂️ help wanted Extra attention is needed label Feb 7, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
packages/tests/server/regression/issue-6461-stream-error.test.ts (1)

11-18: Consider adding a timeout or max iterations to prevent resource exhaustion.

The infinite loop with a 1ms delay might be too aggressive for testing. Consider:

  1. Adding a maximum number of iterations
  2. Increasing the delay between yields
  3. Adding a timeout mechanism
 const appRouter = t.router({
   stream: t.procedure.query(async function* () {
+    const MAX_ITERATIONS = 1000;
+    const YIELD_DELAY_MS = 10;
+    let iterations = 0;
     while (true) {
+      if (iterations++ >= MAX_ITERATIONS) {
+        break;
+      }
       yield 'tick';
-      await new Promise((resolve) => setTimeout(resolve, 1));
+      await new Promise((resolve) => setTimeout(resolve, YIELD_DELAY_MS));
     }
   }),
 });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6c15b05 and ac93208.

📒 Files selected for processing (5)
  • packages/client/src/links/httpBatchStreamLink.ts (1 hunks)
  • packages/server/src/unstable-core-do-not-import/stream/jsonl.test.ts (3 hunks)
  • packages/server/src/unstable-core-do-not-import/stream/jsonl.ts (6 hunks)
  • packages/tests/server/regression/issue-6461-stream-error.test.ts (1 hunks)
  • packages/tests/server/streaming.test.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/client/src/links/httpBatchStreamLink.ts
⏰ Context from checks skipped due to timeout of 90000ms (20)
  • GitHub Check: E2E-tests (fastify-server)
  • GitHub Check: E2E-tests (express-server)
  • GitHub Check: E2E-tests (express-minimal)
  • GitHub Check: e2e-legacy-node (next-prisma-todomvc, 20.x)
  • GitHub Check: E2E-tests (cloudflare-workers)
  • GitHub Check: e2e-legacy-node (next-prisma-todomvc, 18.x)
  • GitHub Check: E2E-tests (.test/ssg)
  • GitHub Check: e2e-legacy-node (next-prisma-websockets-starter, 20.x)
  • GitHub Check: E2E-tests (.test/internal-types-export)
  • GitHub Check: Release using pkg.pr.new
  • GitHub Check: e2e-legacy-node (next-prisma-websockets-starter, 18.x)
  • GitHub Check: E2E-tests (.test/diagnostics-big-router)
  • GitHub Check: Test a monorepo using built declaration files
  • GitHub Check: e2e-legacy-node (next-prisma-starter, 20.x)
  • GitHub Check: E2E-tests (.experimental/next-app-dir)
  • GitHub Check: e2e-legacy-node (next-prisma-starter, 18.x)
  • GitHub Check: E2E-tests (Bun) (bun, ubuntu-latest)
  • GitHub Check: E2E-tests (Deno) (deno-deploy)
  • GitHub Check: Lint and auto-fix
  • GitHub Check: test
🔇 Additional comments (7)
packages/tests/server/regression/issue-6461-stream-error.test.ts (2)

1-18: LGTM! Well-structured test setup.

The imports and router setup are clean and follow best practices.


20-46: LGTM! Well-structured test for stream interruption.

The test effectively verifies that:

  1. Stream interruption is handled correctly
  2. AbortController works as expected
  3. Error is propagated properly
packages/server/src/unstable-core-do-not-import/stream/jsonl.ts (2)

402-402: LGTM! Simplified error handling.

Removing the custom StreamInterruptedError type in favor of standard error handling improves code maintainability.


451-471: LGTM! Improved error handling and cleanup.

The changes enhance the stream controller by:

  1. Adding proper error propagation
  2. Implementing thorough cleanup
  3. Following best practices for resource management
packages/server/src/unstable-core-do-not-import/stream/jsonl.test.ts (2)

212-213: LGTM! Consistent error message formatting.

The error message format follows the standard pattern.


557-557: LGTM! Proper error type expectation.

Using DOMException for abort errors aligns with web standards.

packages/tests/server/streaming.test.ts (1)

356-360: LGTM! Standardized abort error messages.

The error messages now correctly reflect the abort operation using standard web platform error messages.

Copy link
Contributor

@lucacasonato lucacasonato left a comment

Choose a reason for hiding this comment

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

This works. Using AbortError here makes sense to me.

@KATT KATT enabled auto-merge (squash) February 7, 2025 21:11
@KATT KATT disabled auto-merge February 7, 2025 21:49
@KATT KATT merged commit 6471468 into next Feb 7, 2025
45 checks passed
@KATT KATT deleted the issues/6461 branch February 7, 2025 21:49
@github-actions
Copy link
Contributor

github-actions bot commented Feb 9, 2025

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 Feb 9, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug: ending a streaming query with a signal rejects the async iterable with a non TRPCClientError

3 participants