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

fix(server/v2/grpc): fix reflection #23333

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open

Conversation

julienrbrt
Copy link
Member

@julienrbrt julienrbrt commented Jan 11, 2025

Description

Closes: #XXXX


Author Checklist

All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.

I have...

  • included the correct type prefix in the PR title, you can find examples of the prefixes below:
  • confirmed ! in the type prefix if API or client breaking change
  • targeted the correct branch (see PR Targeting)
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • added a changelog entry to CHANGELOG.md
  • updated the relevant documentation or specification, including comments for documenting Go code
  • confirmed all CI checks have passed

Reviewers Checklist

All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.

Please see Pull Request Reviewer section in the contributing guide for more information on how to review a pull request.

I have...

  • confirmed the correct type prefix in the PR title
  • confirmed all author checklist items have been addressed
  • reviewed state machine logic, API design and naming, documentation is accurate, tests and test coverage

Summary by CodeRabbit

  • New Features
    • Added integration with app v2.
    • Introduced simulation of nested messages.
    • Supported importing hex keys via standard input.
    • Allowed custom verification for public keys during transaction validation.
  • Improvements
    • Enhanced edge case handling for recursion limits.
  • Bug Fixes
    • Resolved pagination issues in collections.
    • Fixed handling of optional fields in transaction decoding.
    • Prevented panic in specific functions related to optional fields.
  • Refactor
    • Updated gRPC server reflection to focus on message-based reflection instead of method-based.
    • Renamed internal fields and method signatures to align with new message-centric approach.
    • Introduced a new helper function to find services associated with message descriptors.
  • Tests
    • Added new test for validating gRPC reflection functionality.

@julienrbrt julienrbrt requested a review from a team as a code owner January 11, 2025 20:36
Copy link
Contributor

coderabbitai bot commented Jan 11, 2025

📝 Walkthrough

Walkthrough

The pull request introduces significant modifications to the gRPC server reflection implementation in the gogoreflection package. The primary change involves a conceptual shift from method-based to message-based reflection. The serverReflectionServer struct and associated methods have been refactored to focus on messages instead of methods. This includes renaming the methods field to messages, updating method signatures, and introducing a new helper function findServiceForMessage to determine service associations based on message descriptors.

Changes

File Change Summary
server/v2/api/grpc/gogoreflection/serverreflection.go - Renamed methods field to messages in serverReflectionServer struct
- Updated Register function signature to use messages instead of methods
- Modified getServices method to work with message descriptors
- Added new findServiceForMessage helper function
CHANGELOG.md - Added new features including integration with app v2 and support for importing hex keys
- Documented improvements and bug fixes
- Updated breaking changes and removal of components
tests/integration/runtime/query_test.go - File deleted, which contained integration tests for runtime query functionality
tests/systemtests/go.mod - Added new dependencies for various packages
- Changed google.golang.org/grpc from comment to active requirement
tests/systemtests/grpc_test.go - Added new test function TestGRPCReflection to validate gRPC reflection functionality

Sequence Diagram

sequenceDiagram
    participant Client
    participant ServerReflection
    participant ServiceRegistry
    
    Client->>ServerReflection: Request service reflection
    ServerReflection->>ServiceRegistry: Find services for messages
    ServiceRegistry-->>ServerReflection: Return service descriptors
    ServerReflection-->>Client: Provide reflection information
Loading

Possibly related PRs

Suggested labels

C:server/v2 cometbft, Type: CI

Suggested reviewers

  • sontrinh16
  • kocubinski
  • testinginprod
  • julienrbrt

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.

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
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 (2)
server/v2/api/grpc/gogoreflection/serverreflection.go (2)

461-491: Add documentation and improve error handling.

While the implementation is correct, consider these improvements:

  1. Add documentation explaining the message-based service lookup strategy.
  2. Enhance error messages with more context about why the descriptor or service lookup failed.
+// getServices returns a unique list of services and their file descriptors based on the provided messages.
+// It looks up each message in the registry and finds associated services by scanning method input/output types.
 func (s *serverReflectionServer) getServices(messages []string) (svcs []string, fds []*dpb.FileDescriptorProto) {
     registry, err := gogoproto.MergedRegistry()
     if err != nil {
-        s.log.Error("unable to load merged registry", "err", err)
+        s.log.Error("failed to load protobuf registry for reflection", "err", err)
         return nil, nil
     }
     seenSvc := map[protoreflect.FullName]struct{}{}
     for _, messageName := range messages {
         md, err := registry.FindDescriptorByName(protoreflect.FullName(messageName))
         if err != nil {
-            s.log.Error("unable to load message descriptor", "message", messageName, "err", err)
+            s.log.Error("failed to find message descriptor in registry", 
+                "message", messageName,
+                "err", err,
+                "hint", "ensure the message is properly registered")
             continue
         }

493-517: Add documentation and improve return values.

The implementation is efficient, but consider these improvements:

  1. Add documentation explaining the function's purpose and return values.
  2. Consider returning (protoreflect.ServiceDescriptor, error) instead of a boolean for more idiomatic Go.
+// findServiceForMessage searches the registry for a service that uses the given message
+// as either an input or output type in any of its methods. It returns the first matching
+// service descriptor and true if found, or a nil descriptor and false if not found.
 func findServiceForMessage(registry *protoregistry.Files, messageDesc protoreflect.MessageDescriptor) (protoreflect.ServiceDescriptor, bool) {
     var (
         service protoreflect.ServiceDescriptor
         found   bool
     )

Alternative implementation with error return:

-func findServiceForMessage(registry *protoregistry.Files, messageDesc protoreflect.MessageDescriptor) (protoreflect.ServiceDescriptor, bool) {
+func findServiceForMessage(registry *protoregistry.Files, messageDesc protoreflect.MessageDescriptor) (protoreflect.ServiceDescriptor, error) {
     var service protoreflect.ServiceDescriptor
     
     registry.RangeFiles(func(fileDescriptor protoreflect.FileDescriptor) bool {
         // ... existing implementation ...
     })
     
-    return service, found
+    if service == nil {
+        return nil, fmt.Errorf("no service found for message %s", messageDesc.FullName())
+    }
+    return service, nil
 }
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a1a4c9a and ff01297.

📒 Files selected for processing (1)
  • server/v2/api/grpc/gogoreflection/serverreflection.go (5 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
server/v2/api/grpc/gogoreflection/serverreflection.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Summary
🔇 Additional comments (3)
server/v2/api/grpc/gogoreflection/serverreflection.go (3)

57-57: LGTM!

The addition of the protoregistry import is necessary for the new message-based reflection implementation.


66-66: LGTM!

The field rename from methods to messages accurately reflects the shift to message-based reflection.


75-80: LGTM!

The Register function changes are consistent with the shift to message-based reflection, and the logger is properly initialized.

@julienrbrt
Copy link
Member Author

I will migrate this test:

func TestReflectionService(t *testing.T) {
as a system test, as it was testing reflection but only for v0 apps.

@julienrbrt
Copy link
Member Author

I will migrate this test:

func TestReflectionService(t *testing.T) {

as a system test, as it was testing reflection but only for v0 apps.

Adding the backport label only backporting the test changes

@julienrbrt julienrbrt added the backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release label Jan 11, 2025
Copy link
Member

@tac0turtle tac0turtle left a comment

Choose a reason for hiding this comment

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

nice find!

@github-actions github-actions bot added C:server/v2 Issues related to server/v2 C:server/v2 api labels Jan 11, 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 (8)
tests/systemtests/grpc_test.go (2)

22-24: Consider making the gRPC endpoint configurable.

The gRPC endpoint (localhost:9090) is hardcoded. Consider making it configurable through environment variables or test configuration.

+const (
+    defaultGRPCHost = "localhost"
+    defaultGRPCPort = "9090"
+)
+
 ctx := context.Background()
-grpcClient, err := grpc.NewClient("localhost:9090", grpc.WithTransportCredentials(insecure.NewCredentials()))
+host := getEnvOrDefault("GRPC_HOST", defaultGRPCHost)
+port := getEnvOrDefault("GRPC_PORT", defaultGRPCPort)
+grpcClient, err := grpc.NewClient(fmt.Sprintf("%s:%s", host, port), grpc.WithTransportCredentials(insecure.NewCredentials()))

26-30: Consider adding more comprehensive service checks.

The test only verifies one service. Consider adding checks for other critical services that should be available through reflection.

server/v2/api/grpc/gogoreflection/serverreflection.go (3)

461-489: Consider adding metrics for reflection service health.

The error handling is good, but consider adding metrics to track:

  • Number of failed message descriptor lookups
  • Number of services not found for messages
  • Total number of successful reflections

493-517: Consider optimizing service lookup performance.

The findServiceForMessage function iterates through all files and services. For large service registries, this could be inefficient. Consider:

  1. Caching service-to-message mappings
  2. Using a more efficient lookup structure
+type serviceCache struct {
+    sync.RWMutex
+    messageToService map[protoreflect.FullName]protoreflect.ServiceDescriptor
+}
+
+func (s *serverReflectionServer) buildServiceCache(registry *protoregistry.Files) {
+    s.cache.Lock()
+    defer s.cache.Unlock()
+    
+    registry.RangeFiles(func(fd protoreflect.FileDescriptor) bool {
+        // Build cache
+        return true
+    })
+}

506-510: Consider adding debug logging for service matching.

Adding debug logs here would help troubleshoot when messages don't match with any service.

 if methodDesc.Input() == messageDesc || methodDesc.Output() == messageDesc {
+    s.log.Debug("found service for message",
+        "message", messageDesc.FullName(),
+        "service", serviceDesc.FullName(),
+        "method", methodDesc.FullName())
     service = serviceDesc
     found = true
     return false
 }
CHANGELOG.md (3)

Line range hint 1-1: Add title to the CHANGELOG file

The CHANGELOG file should start with a clear title like "# Changelog" to follow standard changelog conventions.

+ # Changelog

Line range hint 44-48: Consider adding migration guide links

For major breaking changes sections, consider adding links to migration guides to help users upgrade smoothly.


Line range hint 2960-2965: Add link to current changelog

The reference to previous changelog versions should include a link to the current changelog location for better navigation.

📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ff01297 and ca2e802.

⛔ Files ignored due to path filters (1)
  • tests/systemtests/go.sum is excluded by !**/*.sum
📒 Files selected for processing (5)
  • CHANGELOG.md (2 hunks)
  • server/v2/api/grpc/gogoreflection/serverreflection.go (5 hunks)
  • tests/integration/runtime/query_test.go (0 hunks)
  • tests/systemtests/go.mod (6 hunks)
  • tests/systemtests/grpc_test.go (1 hunks)
💤 Files with no reviewable changes (1)
  • tests/integration/runtime/query_test.go
🧰 Additional context used
📓 Path-based instructions (4)
tests/systemtests/grpc_test.go (3)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern tests/**/*: "Assess the integration and e2e test code assessing sufficient code coverage for the changes associated in the pull request"


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

tests/systemtests/go.mod (1)

Pattern tests/**/*: "Assess the integration and e2e test code assessing sufficient code coverage for the changes associated in the pull request"

server/v2/api/grpc/gogoreflection/serverreflection.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

CHANGELOG.md (1)

Pattern **/*.md: "Assess the documentation for misspellings, grammatical errors, missing documentation and correctness"

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Summary
🔇 Additional comments (4)
tests/systemtests/grpc_test.go (1)

23-23: Review security implications of using insecure credentials.

The test uses insecure.NewCredentials(). While this might be acceptable for testing, ensure this aligns with your security requirements.

tests/systemtests/go.mod (1)

9-9: LGTM! Dependencies look appropriate.

The added dependencies align well with the gRPC reflection testing requirements.

Also applies to: 30-30, 37-37, 67-68, 106-106, 126-126, 171-171

server/v2/api/grpc/gogoreflection/serverreflection.go (1)

66-66: LGTM! Field rename reflects the new message-based approach.

The rename from methods to messages better represents the new message-based reflection approach.

CHANGELOG.md (1)

Line range hint 1-3000: LGTM on overall changelog structure and content

The changelog follows good practices by:

  • Organizing changes by type (Features, Bug Fixes, etc.)
  • Including version numbers and dates
  • Documenting breaking changes clearly
  • Providing detailed descriptions of changes

require.NoError(t, err)
require.Greater(t, len(services), 0)
require.Contains(t, services, "cosmos.staking.v1beta1.Query")
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

Shall add a query invocation in this test?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release C:server/v2 api C:server/v2 Issues related to server/v2
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants