Skip to content

fix(server): apply error validation to event iterator - #893

Merged
dinwwwh merged 2 commits into
mainfrom
fix/server/validate-event-iterator-error
Aug 19, 2025
Merged

fix(server): apply error validation to event iterator#893
dinwwwh merged 2 commits into
mainfrom
fix/server/validate-event-iterator-error

Conversation

@dinwwwh

@dinwwwh dinwwwh commented Aug 18, 2025

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • New Features
    • Improved support for streaming responses: consistent error mapping for event iterators and preserved signal propagation during streaming.
  • Bug Fixes
    • Ensures errors thrown inside streaming handlers are correctly transformed and surfaced, including both mapped and generic errors.
    • Preserves iterator instances returned by handlers without unintended modification.
  • Tests
    • Added coverage for event iterator behavior, error flows, and signal handling to prevent regressions.

@dinwwwh
dinwwwh requested a review from Copilot August 18, 2025 12:49
@vercel

vercel Bot commented Aug 18, 2025

Copy link
Copy Markdown

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

Project Deployment Preview Comments Updated (UTC)
orpc Ready Ready Preview Comment Aug 19, 2025 1:31am

@coderabbitai

coderabbitai Bot commented Aug 18, 2025

Copy link
Copy Markdown

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Adds event-iterator tests to the procedure client and updates the client to map async-iterator events through a validateError function (using the procedure's error map) via mapEventIterator; preserves HibernationEventIterator passthrough and ensures iterator signal propagation.

Changes

Cohort / File(s) Summary
Procedure client implementation
packages/server/src/procedure-client.ts
Import mapEventIterator; add validateError (wraps validateORPCError); wrap non-Hibernation async iterator outputs with mapEventIterator using identity for values and validateError for errors; route caught errors through validateError; keep HibernationEventIterator unchanged.
Tests: event iterator and error handling
packages/server/src/procedure-client.test.ts
Add event-iterator coverage: tests for async generator yielding and throwing (ORPCError and non-ORPCError flows), signal propagation for iterator path, and assertion that a HibernationEventIterator from the handler is returned unmodified; add HibernationEventIterator import.

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant ProcedureClient
  participant Handler
  participant AsyncIterator
  participant ErrorValidator as validateError
  participant Mapper as mapEventIterator

  Caller->>ProcedureClient: call()
  ProcedureClient->>Handler: invoke with ctx & signal
  alt Handler returns HibernationEventIterator
    Handler-->>ProcedureClient: HibernationEventIterator
    ProcedureClient-->>Caller: same iterator instance
  else Handler returns AsyncIterator
    Handler-->>ProcedureClient: AsyncIterator
    ProcedureClient->>Mapper: mapEventIterator(AsyncIterator, onValue=id, onError=validateError)
    Mapper-->>ProcedureClient: Mapped AsyncIterator
    ProcedureClient-->>Caller: Mapped AsyncIterator
    AsyncIterator--xMapper: throw error
    Mapper->>ErrorValidator: validateError(e)
    ErrorValidator-->>Mapper: mapped/unchanged error
    Mapper-->>Caller: propagate error
  end
  Note over ProcedureClient: In catch paths, errors pass through validateError and are rethrown
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • unnoq/orpc#854 — Touches procedure-client.ts import/handling around HibernationEventIterator; overlaps iterator/import changes.
  • unnoq/orpc#210 — Modifies procedure-client.test.ts around error handling and event-iterator behavior; overlaps testing surface for non-Error expectations.

Suggested labels

size:L

Poem

In the burrow of bytes I hop and peer,
Streams now map their errors clear.
Iterator keeps its gentle pace,
Signals pass through—no scrambled trace.
I nibble tests and nod, "Bravo!" 🥕🐇

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between dc03144 and a30e88c.

📒 Files selected for processing (1)
  • packages/server/src/procedure-client.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/server/src/procedure-client.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: test
  • GitHub Check: lint
  • GitHub Check: publish-commit
  • GitHub Check: Analyze (javascript-typescript)
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/server/validate-event-iterator-error

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
🪧 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

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

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Aug 18, 2025

@gemini-code-assist gemini-code-assist 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.

Summary of Changes

Hello @unnoq, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request focuses on enhancing the error handling within the server's procedure client, specifically for errors originating from event iterators. It centralizes the error validation logic into a dedicated helper function, ensuring that all errors, particularly ORPCError instances, are consistently validated and processed. This change improves the robustness and predictability of error handling across the server's client-side interactions.

Highlights

  • Centralized Error Validation: Introduced a new 'validateError' helper function within 'createProcedureClient' to consolidate the logic for validating ORPCError instances and handling other error types, improving code maintainability.
  • Event Iterator Error Handling: Implemented robust error validation for errors thrown by event iterators, ensuring that ORPCError instances are properly processed and validated before being re-thrown to the caller.
  • Enhanced Test Coverage: Added new test cases specifically targeting error handling within event iterators, covering scenarios where both ORPCError and generic errors are thrown, enhancing the reliability of the error handling mechanism.
  • HibernationEventIterator Integrity: Included a test to confirm that HibernationEventIterator instances are returned directly without modification by the client, preserving their intended behavior and ensuring compatibility.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request addresses an issue where errors from event iterators were not being validated. The fix involves wrapping event iterators with mapEventIterator to apply error validation. A new validateError helper function has been created to centralize the error validation logic, which is now used for both regular procedure calls and event iterators. The changes are well-supported by new tests. I have one suggestion to refactor the validateError function for improved readability.

Comment thread packages/server/src/procedure-client.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

This PR applies error validation to event iterators in the procedure client, ensuring that ORPC errors thrown from async iterators are properly validated against the procedure's error map.

  • Extracts error validation logic into a reusable validateError function
  • Applies error validation to event iterators using mapEventIterator
  • Adds comprehensive test coverage for error handling in event iterators

Reviewed Changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
packages/server/src/procedure-client.ts Extracts error validation logic and applies it to event iterators using mapEventIterator
packages/server/src/procedure-client.test.ts Adds test cases for error validation in event iterators and HibernationEventIterator handling

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

@codecov

codecov Bot commented Aug 18, 2025

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@pkg-pr-new

pkg-pr-new Bot commented Aug 18, 2025

Copy link
Copy Markdown
More templates

@orpc/arktype

npm i https://pkg.pr.new/@orpc/arktype@893

@orpc/client

npm i https://pkg.pr.new/@orpc/client@893

@orpc/contract

npm i https://pkg.pr.new/@orpc/contract@893

@orpc/experimental-durable-event-iterator

npm i https://pkg.pr.new/@orpc/experimental-durable-event-iterator@893

@orpc/hey-api

npm i https://pkg.pr.new/@orpc/hey-api@893

@orpc/interop

npm i https://pkg.pr.new/@orpc/interop@893

@orpc/json-schema

npm i https://pkg.pr.new/@orpc/json-schema@893

@orpc/nest

npm i https://pkg.pr.new/@orpc/nest@893

@orpc/openapi

npm i https://pkg.pr.new/@orpc/openapi@893

@orpc/openapi-client

npm i https://pkg.pr.new/@orpc/openapi-client@893

@orpc/otel

npm i https://pkg.pr.new/@orpc/otel@893

@orpc/react

npm i https://pkg.pr.new/@orpc/react@893

@orpc/react-query

npm i https://pkg.pr.new/@orpc/react-query@893

@orpc/server

npm i https://pkg.pr.new/@orpc/server@893

@orpc/shared

npm i https://pkg.pr.new/@orpc/shared@893

@orpc/solid-query

npm i https://pkg.pr.new/@orpc/solid-query@893

@orpc/standard-server

npm i https://pkg.pr.new/@orpc/standard-server@893

@orpc/standard-server-aws-lambda

npm i https://pkg.pr.new/@orpc/standard-server-aws-lambda@893

@orpc/standard-server-fetch

npm i https://pkg.pr.new/@orpc/standard-server-fetch@893

@orpc/standard-server-node

npm i https://pkg.pr.new/@orpc/standard-server-node@893

@orpc/standard-server-peer

npm i https://pkg.pr.new/@orpc/standard-server-peer@893

@orpc/svelte-query

npm i https://pkg.pr.new/@orpc/svelte-query@893

@orpc/tanstack-query

npm i https://pkg.pr.new/@orpc/tanstack-query@893

@orpc/trpc

npm i https://pkg.pr.new/@orpc/trpc@893

@orpc/valibot

npm i https://pkg.pr.new/@orpc/valibot@893

@orpc/vue-colada

npm i https://pkg.pr.new/@orpc/vue-colada@893

@orpc/vue-query

npm i https://pkg.pr.new/@orpc/vue-query@893

@orpc/zod

npm i https://pkg.pr.new/@orpc/zod@893

commit: a30e88c

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
packages/server/src/procedure-client.ts (2)

101-109: Minor simplification: make validateError a concise expression and keep a consistent Promise type.

Functionally correct as-is. You can simplify while keeping the promise shape for both branches.

Apply this diff:

-    const validateError = async (e: unknown) => {
-      if (!(e instanceof ORPCError)) {
-        return e
-      }
-
-      const validated = await validateORPCError(procedure['~orpc'].errorMap, e)
-
-      return validated
-    }
+    const validateError = (e: unknown) =>
+      e instanceof ORPCError
+        ? validateORPCError(procedure['~orpc'].errorMap, e)
+        : Promise.resolve(e)

149-158: Iterator error validation path looks solid; small ergonomic tweak available.

Wrapping with asyncIteratorWithSpan + mapEventIterator is the right approach and preserves event metadata. You can pass validateError directly.

Apply this diff:

         return mapEventIterator(
           asyncIteratorWithSpan(
             { name: 'consume_event_iterator_output', signal: callerOptions?.signal },
             output,
           ),
           {
             value: v => v,
-            error: e => validateError(e),
+            error: validateError,
           },
         ) as typeof output
📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 3b7800f and dc03144.

📒 Files selected for processing (2)
  • packages/server/src/procedure-client.test.ts (4 hunks)
  • packages/server/src/procedure-client.ts (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
packages/server/src/procedure-client.ts (8)
packages/server/src/index.ts (1)
  • ORPCError (24-24)
packages/client/src/error.ts (1)
  • ORPCError (101-133)
packages/contract/src/index.ts (1)
  • ORPCError (20-20)
packages/server/src/error.ts (1)
  • validateORPCError (50-75)
packages/client/src/event-iterator.ts (1)
  • mapEventIterator (4-52)
packages/shared/src/iterator.ts (1)
  • asyncIteratorWithSpan (171-206)
packages/server/src/builder.ts (1)
  • output (258-266)
packages/contract/src/builder.ts (1)
  • output (142-149)
packages/server/src/procedure-client.test.ts (3)
packages/server/src/procedure.ts (1)
  • Procedure (55-71)
packages/server/src/procedure-client.ts (1)
  • createProcedureClient (72-167)
packages/server/src/error.ts (1)
  • validateORPCError (50-75)
🪛 Biome (2.1.2)
packages/server/src/procedure-client.test.ts

[error] 482-484: This generator function doesn't contain yield.

(lint/correctness/useYield)


[error] 495-497: This generator function doesn't contain yield.

(lint/correctness/useYield)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: lint
  • GitHub Check: publish-commit
  • GitHub Check: test
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (6)
packages/server/src/procedure-client.ts (2)

8-8: Good call importing mapEventIterator and applying it to iterator outputs.

This aligns the server client’s iterator pathway with the client’s event iterator semantics and enables centralized error mapping.


164-164: Consistent catch-path error normalization.

Rethrowing with validateError unifies iterator-originating and top-level errors under the procedure’s error map. Nice.

packages/server/src/procedure-client.test.ts (4)

2-2: LGTM: Importing HibernationEventIterator for pass-through test.

This enables verifying the no-transform contract for hibernation iterators.


43-51: Unvalidated procedure fixture is appropriate for iterator-focused tests.

Keeping schemas undefined here isolates iterator error-mapping behavior from schema validation.


477-507: Great coverage for event iterator error mapping and signal propagation.

  • Validates ORPCError mapping on next() throws.
  • Confirms non-ORPC errors are passed through.
  • Exercises signal propagation via asyncIteratorWithSpan.

Nicely aligned with the implementation changes.


558-563: Nice safeguard: ensure HibernationEventIterator is returned unchanged.

Confirms the “no transform/track” contract is preserved.

Comment thread packages/server/src/procedure-client.test.ts
Comment thread packages/server/src/procedure-client.test.ts
@dinwwwh
dinwwwh merged commit 03fed0c into main Aug 19, 2025
11 checks passed
@dinwwwh
dinwwwh deleted the fix/server/validate-event-iterator-error branch June 22, 2026 01:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants