Skip to content

Conversation

@unnoq
Copy link
Member

@unnoq unnoq commented Feb 28, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Corrected event payload formatting by ensuring each event message ends with a proper double newline, enhancing downstream processing reliability.
  • Tests

    • Restructured the test suite to clearly separate scenarios for successful event processing and error handling for incomplete messages.
    • Removed outdated test cases related to ErrorEvent handling and added new tests for deserialization of invalid ORPCError.
  • Refactor

    • Updated event stream decoding logic to consistently handle incomplete input and raise errors as needed.
    • Simplified error handling in the OpenAPISerializer and RPCSerializer classes for a more uniform approach.
    • Enhanced the EventMessage structure to include optional data and a new comments array for better information handling.

@vercel
Copy link

vercel bot commented Feb 28, 2025

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

Name Status Preview Comments Updated (UTC)
orpc ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 28, 2025 0:25am

@coderabbitai
Copy link

coderabbitai bot commented Feb 28, 2025

Walkthrough

This update modifies event payload formatting in test files by appending a double newline to the event strings for "done" and "error" events. The tests for the event source in both the fetch and node packages have been updated accordingly. Additionally, the test cases for the EventDecoder and EventDecoderStream have been restructured to include more scenarios, particularly for incomplete messages. The error handling in the OpenAPISerializer and RPCSerializer classes has been simplified by removing specific checks for ErrorEvent, and the UnknownEvent class has been removed from the codebase.

Changes

File(s) Change Summary
packages/standard-server-{fetch,node}/src/event-source.test.ts Updated event strings in tests to append a double newline (\n\n) for "done" and "error" events; removed test case for "unknown" events.
packages/standard-server/src/event-source/decoder.test.ts Restructured tests for decodeEventMessage, EventDecoder, and EventDecoderStream by adding scenarios for incomplete messages and modifying expected outputs.
packages/standard-server/src/event-source/decoder.ts Modified decoder logic: adjusted handling of incomplete messages and changed how data is processed and validated.
packages/client/src/openapi/serializer.test.ts Removed test case for error handling with ErrorEvent in openAPISerializer.
packages/client/src/openapi/serializer.ts Simplified error handling in OpenAPISerializer by removing specific checks for ErrorEvent.
packages/client/src/rpc/serializer.test.ts Removed test case for error handling with ErrorEvent and added a new test for deserializing invalid ORPCError.
packages/client/src/rpc/serializer.ts Simplified error handling in RPCSerializer by removing specific checks for ErrorEvent.
packages/client/src/index.ts Added export for ErrorEvent from @orpc/standard-server.
packages/standard-server/src/event-source/errors.ts Removed UnknownEvent class.
packages/standard-server/src/event-source/types.ts Updated EventMessage interface: made data optional and added comments property.
packages/standard-server/src/event-source.ts Removed UnknownEvent class and its error handling logic from toEventIterator.

Sequence Diagram(s)

sequenceDiagram
    participant F as Event Feed
    participant D as EventDecoder
    participant C as Callback

    F->>D: feed("event data\n\n")
    D->>C: onEvent(complete event)
    F->>D: feed("incomplete event data")
    D-->>D: Accumulate incomplete segment
    D->>D: end() called
    D-->>F: throw EventDecoderError (if incomplete message remains)
Loading

Possibly related PRs

  • unnoq/orpc#176: Related changes to the event handling logic in the toEventIterator function, specifically regarding the removal of the UnknownEvent class.
  • unnoq/orpc#179: Modifications to the event handling logic in the toEventIterator tests, focusing on newline character additions for event strings.

Poem

I'm a rabbit hopping through the code maze,
Newlines added to light up dark days.
Events now finish with a double clear sign,
Tests and decoders in a perfect line.
With every hop and every tiny step I cheer,
Celebrating improvements so bright and dear! 🐇


📜 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 319c3ae and a2aa94c.

📒 Files selected for processing (10)
  • packages/standard-server-fetch/src/event-source.test.ts (6 hunks)
  • packages/standard-server-fetch/src/event-source.ts (0 hunks)
  • packages/standard-server-node/src/event-source.test.ts (6 hunks)
  • packages/standard-server-node/src/event-source.ts (0 hunks)
  • packages/standard-server/src/event-source/decoder.test.ts (1 hunks)
  • packages/standard-server/src/event-source/decoder.ts (3 hunks)
  • packages/standard-server/src/event-source/encoder.test.ts (1 hunks)
  • packages/standard-server/src/event-source/encoder.ts (1 hunks)
  • packages/standard-server/src/event-source/errors.ts (0 hunks)
  • packages/standard-server/src/event-source/types.ts (1 hunks)
💤 Files with no reviewable changes (3)
  • packages/standard-server/src/event-source/errors.ts
  • packages/standard-server-node/src/event-source.ts
  • packages/standard-server-fetch/src/event-source.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/standard-server-fetch/src/event-source.test.ts
  • packages/standard-server/src/event-source/decoder.ts
🔇 Additional comments (19)
packages/standard-server/src/event-source/encoder.ts (1)

23-23: Improved handling of undefined data values

The change to use optional chaining and nullish coalescing provides a cleaner approach to handling undefined data. This change aligns with making the data property optional in the EventMessage interface.

packages/standard-server/src/event-source/types.ts (2)

4-4: Well-structured type change for optional data property

Making the data property optional aligns with the encoder implementation changes and provides better flexibility for event messages.


10-11: Good addition of comments field to EventMessage

Adding the comments field allows the decoder to handle non-standard or informational lines in event source messages, improving error resilience and debugging capabilities.

packages/standard-server/src/event-source/encoder.test.ts (3)

4-4: Aligned test expectation with implementation change

This test update correctly reflects the new behavior where undefined data results in an empty string rather than 'data: \n'.


11-11: Updated test for empty message encoding

The test now correctly reflects that encodeEventMessage({}) returns only a newline character, consistent with the updated implementation handling of undefined data.


13-14: Correct test expectation update for messages without data

The test properly reflects that messages without a data property will no longer include a 'data: ' line in the encoded output.

packages/standard-server/src/event-source/decoder.test.ts (6)

6-13: Complete test coverage for simple event messages

These tests now properly validate the expected behavior with the new comments array in the EventMessage interface. Good coverage of simple cases.


21-25: Comprehensive test for comment handling

Excellent addition of a test case that verifies the proper handling of comment lines (lines starting with colon). This validates that the decoder correctly populates the new comments array.


36-47: Good test coverage for space handling in message fields

These tests ensure that leading spaces in field values are preserved correctly, which is important for compatibility with the SSE specification.


50-83: Improved error resilience in decoder implementation

The tests for unknown keys, duplicate keys, and invalid retry values now correctly expect structured outputs rather than errors. This shows a more resilient approach to handling malformed input.


132-150: Important test for incomplete message handling

Great addition of a test case for incomplete messages, ensuring that the decoder correctly throws an error when the stream ends prematurely. This is essential for proper error handling in event streams.


211-243: Comprehensive test for incomplete message handling in stream

This test effectively validates the stream decoder's behavior when receiving an incomplete message, ensuring it both throws the correct error and delivers any complete messages received before the incomplete one.

packages/standard-server-node/src/event-source.test.ts (7)

3-3: Import statement updated to remove UnknownEvent

The import statement has been updated to remove UnknownEvent from the imported entities, which aligns with the broader changes in the codebase to simplify error handling by removing the UnknownEvent class.


12-12: Proper event termination for "done" event

The "done" event now correctly ends with a double newline (\n\n), which adheres to the EventSource specification for proper event termination. This makes the event format consistent and ensures correct parsing by event source clients.


89-89: Proper event termination for "error" event

The "error" event now correctly ends with a double newline (\n\n), ensuring proper event termination according to the EventSource specification. This change ensures consistent formatting across different event types.


166-166: Updated test expectation for message event

The test expectation has been updated to match the new format for empty message events. The data field has been removed from the expectation, correctly reflecting how empty data should be formatted in SSE events.


185-186: Updated test expectations for message and error events

These test expectations have been updated to reflect the new event formatting:

  1. Line 185: Empty message event now uses simpler format without data field
  2. Line 186: Error event no longer includes data in the test case, matching the changes in error event handling

These changes align with the PR objective to update event-source errors behavior.


204-204: Updated test expectation for message event in ErrorEvent test

The test expectation has been updated to use the simpler format for empty message events, consistent with the other similar changes in this file.


129-129: Verify that unknown event handling is intended to remain unchanged

Unlike the "done" and "error" events which now have double newlines added, the "unknown" event on this line is still missing the terminating newlines. This seems intentional based on other code changes in this PR, but it would be good to confirm that unknown events are meant to be handled differently.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
  • @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.

@pkg-pr-new
Copy link

pkg-pr-new bot commented Feb 28, 2025

Open in Stackblitz

More templates

@orpc/client

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

@orpc/contract

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

@orpc/openapi

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

@orpc/react-query

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

@orpc/server

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

@orpc/shared

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

@orpc/standard-server

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

@orpc/standard-server-node

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

@orpc/standard-server-fetch

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

@orpc/vue-colada

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

@orpc/vue-query

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

@orpc/zod

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

commit: a2aa94c

Copy link

@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: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ca29a36 and 9c91e74.

📒 Files selected for processing (4)
  • packages/standard-server-fetch/src/event-source.test.ts (3 hunks)
  • packages/standard-server-node/src/event-source.test.ts (3 hunks)
  • packages/standard-server/src/event-source/decoder.test.ts (1 hunks)
  • packages/standard-server/src/event-source/decoder.ts (2 hunks)
✅ Files skipped from review due to trivial changes (2)
  • packages/standard-server-fetch/src/event-source.test.ts
  • packages/standard-server-node/src/event-source.test.ts
🔇 Additional comments (5)
packages/standard-server/src/event-source/decoder.ts (1)

89-92: Added error handling for incomplete event streams

This change addresses the core issue in the PR. Previously, the code attempted to force-complete the message by adding newlines. Now it correctly throws an error when an event source ends prematurely with incomplete data, making the behavior more predictable and explicit.

packages/standard-server/src/event-source/decoder.test.ts (4)

68-108: Improved test structure for successful event decoding

The test case has been restructured to provide better clarity by separating success scenarios. The test now explicitly verifies that the decoder properly handles multiple complete messages including when parts of a message arrive in separate chunks.


110-127: Added test coverage for incomplete message handling

This new test case is crucial for validating the core fix introduced in this PR. It properly verifies that the decoder throws an error when an incomplete message is encountered at the end of the stream while still correctly processing any complete messages that came before.


130-182: Restructured stream decoder tests for successful processing

The test implementation now more thoroughly validates the stream decoder's handling of complete messages, ensuring that multiple messages are correctly decoded even when split across different stream chunks.


184-215: Added test coverage for stream decoder with incomplete messages

This test case is essential for verifying that the stream decoder properly propagates errors from the underlying decoder when encountering incomplete messages, while still correctly handling any complete messages that came before the error.

}

const completes = this.incomplete.slice(0, lastCompleteIndex + 2).split(/\n{2,}/)
const completes = this.incomplete.slice(0, lastCompleteIndex).split(/\n\n/)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactored incomplete message handling

The modification to use slice(0, lastCompleteIndex) before splitting ensures that only fully complete portions of the message string are processed, improving message boundary detection reliability.

@codecov
Copy link

codecov bot commented Feb 28, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

📢 Thoughts on this report? Let us know!

Copy link

@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/client/src/rpc/serializer.test.ts (1)

180-193: Consider using a regular async function instead of a generator.

The test correctly validates that an ErrorEvent is properly deserialized with its data. However, the static analysis tool flagged that the generator function doesn't contain any yield statements. Since this function only throws an error without yielding any values, consider using a regular async function instead:

  it('deserialize an invalid-ORPCError', async () => {
-   const iterator = serializer.deserialize((async function* () {
+   const iterator = serializer.deserialize((async function () {
      throw new ErrorEvent({
        data: { json: { value: 1234 } },
      })
    })()) as any

    await expect(iterator.next()).rejects.toSatisfy((e: any) => {
      expect(e).toBeInstanceOf(ErrorEvent)
      expect(e.data).toEqual({ value: 1234 })

      return true
    })
  })

This change would eliminate the static analysis warning while maintaining the same test behavior.

🧰 Tools
🪛 Biome (1.9.4)

[error] 181-185: This generator function doesn't contain yield.

(lint/correctness/useYield)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b702eb4 and 319c3ae.

📒 Files selected for processing (5)
  • packages/client/src/index.ts (1 hunks)
  • packages/client/src/openapi/serializer.test.ts (0 hunks)
  • packages/client/src/openapi/serializer.ts (0 hunks)
  • packages/client/src/rpc/serializer.test.ts (1 hunks)
  • packages/client/src/rpc/serializer.ts (0 hunks)
💤 Files with no reviewable changes (3)
  • packages/client/src/rpc/serializer.ts
  • packages/client/src/openapi/serializer.test.ts
  • packages/client/src/openapi/serializer.ts
🧰 Additional context used
🪛 Biome (1.9.4)
packages/client/src/rpc/serializer.test.ts

[error] 181-185: This generator function doesn't contain yield.

(lint/correctness/useYield)

🔇 Additional comments (1)
packages/client/src/index.ts (1)

10-11: Looks good - exposing ErrorEvent to clients.

Adding this export makes ErrorEvent directly accessible to consumers of the client package, which aligns with the simplified error handling approach mentioned in the PR.

@unnoq unnoq changed the title fix(client, server)!: throw an error if event source ends incompletely feat(client, server)!: update event-source errors behavior Feb 28, 2025
@unnoq unnoq changed the title feat(client, server)!: update event-source errors behavior feat(client, server)!: update event-source errors and decode behavior Feb 28, 2025
@unnoq unnoq merged commit 92faaf9 into main Feb 28, 2025
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants