Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Propagate response headers with grpc error metadata #32

Open
wants to merge 4 commits into
base: 3.x
Choose a base branch
from

Conversation

rauanmayemir
Copy link

@rauanmayemir rauanmayemir commented Sep 9, 2024

Q A
Bugfix?
Breaks BC?
New feature? ✔️

This change propagates response headers as part of grpc error response. This is helpful when your server needs to send certain headers (like X-Correlation-Id, etc) even in case of Exception.

Update: this change also introduces ResponseTrailers which could be used alongside ResponseHeaders. It is expected to send data like this:

{
  "error": "base64_encoded_proto",
  "headers": "{\"header_key_1\": \"header_value_1\", \"header_key_2\": \"header_value_2\"}",
  "trailers": "{\"trailer_key_1\": \"trailer_value_1\", \"trailer_key_2\": \"trailer_value_2\"}"
}

And if it's a successful response, then binary payload headers part will also accordingly change from this:

{"header_key_1": "header_value_1", "header_key_2": "header_value_2"}

to this:

{
  "headers": "{\"header_key_1\": \"header_value_1\", \"header_key_2\": \"header_value_2\"}",
  "trailers": "{\"trailer_key_1\": \"trailer_value_1\", \"trailer_key_2\": \"trailer_value_2\"}"
}

ref: roadrunner-server/roadrunner#2006

@rustatian:
Note, this PR should be synced with RR 2024.3 release.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced a CallContext class for structured representation of gRPC call contexts, enhancing organization and handling of service calls.
    • Added a getHeaders() method to the ResponseHeaders class for improved access to internal headers.
    • Introduced a ResponseTrailers class for managing and manipulating trailer headers in gRPC responses.
  • Improvements

    • Streamlined gRPC request handling by removing the tick method and utilizing the new CallContext for better efficiency.
    • Enhanced error handling in the workerError method by allowing a nullable context parameter.
  • Configuration Updates

    • Updated composer.json to include a branch-alias for flexible dependency management.

Copy link

coderabbitai bot commented Sep 9, 2024

Walkthrough

The pull request introduces several changes across multiple files. It adds a new CallContext class for managing gRPC call contexts, modifies the Server class to streamline request handling by removing the tick method, and enhances the ResponseHeaders class with a new method for retrieving headers. Additionally, the composer.json file is updated to include a branch alias for improved versioning strategy. A new ResponseTrailers class is also introduced to manage trailers in gRPC responses.

Changes

File Change Summary
composer.json Added "extra": { "branch-alias": { "3.x": "3.4.x-dev" } } for flexible dependency management.
src/Internal/CallContext.php Added CallContext class with a constructor and a static decode method for gRPC call context.
src/ResponseHeaders.php Added public function getHeaders(): array to retrieve internal headers.
src/ResponseTrailers.php Introduced ResponseTrailers class for managing trailers with methods for setting, getting, iterating, counting, and serializing.
src/Server.php Removed tick method; updated serve method for direct service invocation; modified error handling in workerError.

Poem

🐇 In the meadow where code does play,
New classes hop and dance today.
With headers bright and contexts clear,
The gRPC calls bring us cheer!
So let us code and not delay,
For every change, a brighter way! 🌼

Tip

Announcements
  • The review status is no longer posted as a separate comment when there are no actionable or nitpick comments. In such cases, the review status is included in the walkthrough comment.
  • We have updated our review workflow to use the Anthropic's Claude family of models. Please share any feedback in the discussion post on our Discord.
  • Possibly related PRs: Walkthrough comment now includes a list of potentially related PRs to help you recall past context. Please share any feedback in the discussion post on our Discord.
  • Suggested labels: CodeRabbit can now suggest labels by learning from your past PRs in the walkthrough comment. You can also provide custom labeling instructions in the UI or configuration file.
  • Possibly related PRs, automatic label suggestions based on past PRs, learnings, and possibly related issues require data opt-in (enabled by default).

Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 3467c13 and 492e85f.

Files selected for processing (1)
  • src/Internal/CallContext.php (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • src/Internal/CallContext.php

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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 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.

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: 2

Outside diff range, codebase verification and nitpick comments (2)
src/Internal/CallContext.php (1)

30-38: Add error handling in Json::decode method to manage JSON parsing errors.

The Json::decode method in src/Internal/Json.php uses json_decode but lacks error handling for potential parsing errors. Consider implementing checks using json_last_error() to ensure robust handling of malformed JSON inputs.

  • File: src/Internal/Json.php
  • Method: Json::decode
Analysis chain

Method decode is effectively implemented but ensure robust error handling.

The method effectively decodes the JSON payload and initializes a CallContext instance. Ensure that Json::decode properly handles JSON parsing errors. If Json::decode does not handle exceptions, consider adding error handling in this method to manage malformed JSON inputs gracefully.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify error handling in Json::decode method.

# Test: Search for the Json::decode implementation. Expect: Exception handling for JSON errors.
ast-grep --lang php --pattern $'class Json {
  $$$
  decode($_, $_) {
    $$$
  }
  $$$  
}'

Length of output: 93


Script:

#!/bin/bash
# Description: Search for the decode method in any Json class to verify its existence and error handling.

# Test: Use ripgrep to find the decode method in any Json class.
rg 'class Json' -A 10 | rg 'function decode'

Length of output: 46


Script:

#!/bin/bash
# Description: Search for any decode method in the codebase that might handle JSON parsing.

# Test: Use ripgrep to find any decode method that might be responsible for JSON parsing.
rg 'function decode' -A 5

Length of output: 658

src/Server.php (1)

Line range hint 123-161: Enhancements and potential issues in error response handling.

The workerGrpcError method has been significantly modified to include a nullable ContextInterface and to utilize the ResponseHeaders within the error handling process. This is a crucial part of the PR's objective to propagate response headers with gRPC error metadata.

Key observations:

  • Nullable Context: The method now accepts a nullable ContextInterface, which allows for more flexible error handling. However, this also introduces the risk of null dereferencing when accessing methods on context. It's important to ensure that all calls to context methods are safe and handle the possibility of a null context.
  • Response Header Propagation: The method attempts to merge response headers with error details, which aligns with the PR's goals. However, the implementation assumes that responseHeaders is always initialized when context is not null. This might not always be the case, and could lead to issues if responseHeaders is null.

Consider adding null checks and more defensive programming to ensure that the headers and error details are always correctly handled.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between ddb3e21 and 4af6c83.

Files selected for processing (4)
  • composer.json (1 hunks)
  • src/Internal/CallContext.php (1 hunks)
  • src/ResponseHeaders.php (1 hunks)
  • src/Server.php (6 hunks)
Additional comments not posted (2)
src/Internal/CallContext.php (1)

20-24: Constructor implementation is clean and modern.

The use of PHP 8 promoted properties in the constructor enhances readability and maintainability. The type declarations for parameters ensure that the method can only be called with the correct types.

composer.json (1)

75-79: branch-alias addition is correctly implemented.

The addition of the branch-alias section is correctly formatted and follows best practices for Composer configuration. This change will facilitate easier dependency management and versioning during development.

src/ResponseHeaders.php Outdated Show resolved Hide resolved
src/Server.php Outdated Show resolved Hide resolved
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 4af6c83 and a1d1265.

Files selected for processing (1)
  • src/Server.php (6 hunks)
Files skipped from review as they are similar to previous changes (1)
  • src/Server.php

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a1d1265 and 143cb1c.

Files selected for processing (1)
  • src/Server.php (6 hunks)
Additional comments not posted (4)
src/Server.php (4)

136-139: Proper handling of response headers in gRPC responses.

The modifications to the workerSend method ensure that response headers are correctly packaged and sent with gRPC responses. This change is essential for maintaining the integrity of the communication protocol and ensuring that all necessary headers are included in responses.

Verify that headers are correctly handled in all response scenarios to ensure that no headers are missed or incorrectly formatted.

Run the following script to verify the correct handling of headers in responses:

Verification successful

Proper handling of response headers in gRPC responses confirmed.

The workerSend method is used appropriately to ensure that headers are included in both successful and error responses. The headers are encoded as JSON, indicating they are structured correctly. No issues were found with the handling of headers.

  • Usage of workerSend in src/Server.php confirms proper handling of headers.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correct handling of headers in gRPC responses.

# Test: Search for the usage of `workerSend` method. Expect: Proper handling and inclusion of headers in responses.
rg --type php -A 5 $'workerSend'

Length of output: 1051


70-101: Streamlined gRPC request and response handling.

The modifications to the serve method enhance clarity and efficiency by using CallContext for managing request headers and context. The direct invocation of service methods and the inclusion of response headers in error responses align well with the PR objectives.

Ensure that the integration of CallContext with other components is thoroughly tested, especially in error scenarios, to confirm that all necessary headers are correctly propagated.

Run the following script to verify the integration of CallContext:


128-131: Enhanced flexibility in error handling.

The addition of a nullable ContextInterface parameter to the workerError method allows for more nuanced error handling, supporting the propagation of error context. This change is a positive step towards improving error diagnostics and response management.

Verify that the new parameter is used effectively across all error handling scenarios to ensure that error contexts are properly utilized.

Run the following script to verify the usage of the new ContextInterface parameter:


Line range hint 141-157: Correct encoding of gRPC error statuses.

The modifications to the createGrpcError method ensure that gRPC error statuses are correctly formatted and encoded. This change is essential for maintaining the integrity of error communication and ensuring that all necessary details are included in error responses.

Verify that error statuses are correctly encoded in all error scenarios to ensure that no details are missed or incorrectly formatted.

Run the following script to verify the correct encoding of gRPC error statuses:

@rustatian rustatian added the enhancement New feature or request label Sep 10, 2024
@rustatian rustatian added this to the v3.5.x milestone Sep 10, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants