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/cometbft): proper query error #22746

Merged
merged 6 commits into from
Dec 4, 2024
Merged

Conversation

julienrbrt
Copy link
Member

@julienrbrt julienrbrt commented Dec 4, 2024

Description

Closes: #22742

Replicates baseapp module query error handling:

cosmos-sdk/baseapp/abci.go

Lines 1200 to 1232 in 99dd55b

resp, err := handler(ctx, req)
if err != nil {
resp = queryResult(gRPCErrorToSDKError(err), app.trace)
resp.Height = req.Height
return resp
}
return resp
}
func gRPCErrorToSDKError(err error) error {
status, ok := grpcstatus.FromError(err)
if !ok {
return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, err.Error())
}
switch status.Code() {
case codes.NotFound:
return errorsmod.Wrap(sdkerrors.ErrKeyNotFound, err.Error())
case codes.InvalidArgument:
return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, err.Error())
case codes.FailedPrecondition:
return errorsmod.Wrap(sdkerrors.ErrInvalidRequest, err.Error())
case codes.Unauthenticated:
return errorsmod.Wrap(sdkerrors.ErrUnauthorized, err.Error())
default:
return errorsmod.Wrap(sdkerrors.ErrUnknownRequest, err.Error())
}
}


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
    • Introduced a new function to convert gRPC errors into SDK-specific errors for improved error handling.
  • Bug Fixes
    • Enhanced error reporting mechanisms for query responses, ensuring more accurate categorization of errors.
  • Refactor
    • Updated naming conventions for consistency and clarity in function names.
    • Streamlined dependency management by adding a direct requirement for the errors package.

@julienrbrt julienrbrt added the backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release label Dec 4, 2024
Copy link
Contributor

coderabbitai bot commented Dec 4, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces changes to the server/v2/cometbft module, focusing on the error handling and query response mechanisms within the ABCI interface. Key modifications include updates to the Query method, adjustments in error handling in the maybeRunGRPCQuery method, and the addition of a new function for converting gRPC errors to SDK errors. The go.mod file has been updated to reflect a direct dependency on the cosmossdk.io/errors package. Overall, these changes aim to enhance the clarity and robustness of error management and query handling.

Changes

File Change Summary
server/v2/cometbft/abci.go Updated Query method to use queryResult, modified error handling in maybeRunGRPCQuery.
server/v2/cometbft/go.mod Added direct dependency on cosmossdk.io/errors v1.0.1, removed it from indirect dependencies.
server/v2/cometbft/utils.go Added gRPCErrorToSDKError function, renamed QueryResult to queryResult, updated import for errors.

Assessment against linked issues

Objective Addressed Explanation
Fix error status code on RPC query (#22742)

Possibly related PRs

Suggested reviewers

  • facundomedica
  • testinginprod
  • kocubinski
  • akhilkumarpilli
  • sontrinh16

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 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.

@github-actions github-actions bot added C:server/v2 Issues related to server/v2 C:server/v2 cometbft labels Dec 4, 2024
@julienrbrt julienrbrt marked this pull request as ready for review December 4, 2024 10:05
Copy link
Contributor

github-actions bot commented Dec 4, 2024

@julienrbrt your pull request is missing a changelog!

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

🧹 Outside diff range and nitpick comments (1)
server/v2/cometbft/utils.go (1)

273-291: Consider enhancing error mapping

The gRPC to SDK error mapping could be improved in the following ways:

  1. Add mapping for additional gRPC codes (e.g., Unavailable, DeadlineExceeded)
  2. Consider adding error context preservation
 func gRPCErrorToSDKError(err error) error {
     status, ok := grpcstatus.FromError(err)
     if !ok {
         return sdkerrors.ErrInvalidRequest.Wrap(err.Error())
     }
 
     switch status.Code() {
     case codes.NotFound:
         return sdkerrors.ErrKeyNotFound.Wrap(err.Error())
     case codes.InvalidArgument:
         return sdkerrors.ErrInvalidRequest.Wrap(err.Error())
     case codes.FailedPrecondition:
         return sdkerrors.ErrInvalidRequest.Wrap(err.Error())
     case codes.Unauthenticated:
         return sdkerrors.ErrUnauthorized.Wrap(err.Error())
+    case codes.Unavailable:
+        return sdkerrors.ErrInvalidRequest.Wrap("service temporarily unavailable: " + err.Error())
+    case codes.DeadlineExceeded:
+        return sdkerrors.ErrInvalidRequest.Wrap("request timeout: " + err.Error())
     default:
         return sdkerrors.ErrUnknownRequest.Wrap(err.Error())
     }
 }
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 99dd55b and 9d7c395.

📒 Files selected for processing (3)
  • server/v2/cometbft/abci.go (3 hunks)
  • server/v2/cometbft/go.mod (1 hunks)
  • server/v2/cometbft/utils.go (3 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
server/v2/cometbft/utils.go (1)

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

server/v2/cometbft/abci.go (1)

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

🔇 Additional comments (5)
server/v2/cometbft/go.mod (1)

24-24: LGTM: Direct dependency on errors package

Making cosmossdk.io/errors a direct dependency is appropriate given the enhanced error handling being implemented.

server/v2/cometbft/utils.go (2)

23-23: LGTM: Clear documentation of error package usage

The comment explains why v2 of errors package isn't used, providing good context for future maintainers.


Line range hint 263-270: LGTM: Function renamed to follow Go conventions

Renaming QueryResult to queryResult correctly reflects its package-private scope.

server/v2/cometbft/abci.go (2)

183-183: LGTM: Consistent error handling in Query method

The error handling is now consistent throughout the Query method, properly using queryResult for all error cases.

Also applies to: 197-197, 201-201


286-291: LGTM: Improved gRPC error handling

The error handling now properly converts gRPC errors to SDK errors, maintaining the query height in the response.

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

🧹 Outside diff range and nitpick comments (2)
server/v2/cometbft/utils.go (2)

273-300: Consider handling additional gRPC status codes

The error mapping is good but could be enhanced by handling additional common gRPC codes:

  • codes.Unavailable for service unavailability
  • codes.DeadlineExceeded for timeout scenarios
  • codes.Internal for internal errors (instead of using ErrUnknownRequest in default case)
 func gRPCErrorToSDKError(err error) *abci.QueryResponse {
     // ... existing code ...
     switch status.Code() {
     // ... existing cases ...
+    case codes.Unavailable:
+        return toQueryResp(sdkerrors.ErrServiceUnavailable, err)
+    case codes.DeadlineExceeded:
+        return toQueryResp(sdkerrors.ErrTimeout, err)
+    case codes.Internal:
+        return toQueryResp(sdkerrors.ErrInternalError, err)
     default:
         return toQueryResp(sdkerrors.ErrUnknownRequest, err)
     }
 }
🧰 Tools
🪛 golangci-lint (1.62.2)

280-280: File is not gofumpt-ed with -extra

(gofumpt)


274-281: Consider extracting the helper function

The toQueryResp helper function could be extracted to package level for better testability and reuse. This would also improve readability by separating concerns.

+func toQueryResp(sdkErr *errorsmod.Error, err error) *abci.QueryResponse {
+    return &abci.QueryResponse{
+        Code:      sdkErr.ABCICode(),
+        Codespace: sdkErr.Codespace(),
+        Log:       err.Error(),
+    }
+}
+
 func gRPCErrorToSDKError(err error) *abci.QueryResponse {
-    toQueryResp := func(sdkErr *errorsmod.Error, err error) *abci.QueryResponse {
-        return &abci.QueryResponse{
-            Code:      sdkErr.ABCICode(),
-            Codespace: sdkErr.Codespace(),
-            Log:       err.Error(),
-        }
-    }
     // ... rest of the function
 }
🧰 Tools
🪛 golangci-lint (1.62.2)

280-280: File is not gofumpt-ed with -extra

(gofumpt)

📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9d7c395 and acb08a7.

📒 Files selected for processing (2)
  • server/v2/cometbft/abci.go (3 hunks)
  • server/v2/cometbft/utils.go (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • server/v2/cometbft/abci.go
🧰 Additional context used
📓 Path-based instructions (1)
server/v2/cometbft/utils.go (1)

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

🪛 golangci-lint (1.62.2)
server/v2/cometbft/utils.go

280-280: File is not gofumpt-ed with -extra

(gofumpt)

🔇 Additional comments (2)
server/v2/cometbft/utils.go (2)

15-16: LGTM: Well-structured import changes

The new imports are appropriately organized and the comment explains the rationale for using errorsmod instead of errors/v2.

Also applies to: 23-23, 27-27


Line range hint 263-271: LGTM: Appropriate function visibility change

Good change to make the function unexported as it's an internal utility. The function maintains its core functionality while following Go naming conventions.

server/v2/cometbft/utils.go Outdated Show resolved Hide resolved
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

🧹 Outside diff range and nitpick comments (2)
server/v2/cometbft/utils.go (2)

273-306: Add documentation for error mapping logic

The function implements comprehensive gRPC to SDK error mapping, but would benefit from documentation explaining the mapping rationale and when it's used.

Add a doc comment like:

+// gRPCErrorToSDKError converts gRPC errors to appropriate SDK errors while preserving
+// the original error message. It maps common gRPC status codes to their SDK counterparts
+// to ensure consistent error handling across the application.
 func gRPCErrorToSDKError(err error) *abci.QueryResponse {
🧰 Tools
🪛 golangci-lint (1.62.2)

286-286: File is not gofumpt-ed with -extra

(gofumpt)


274-286: Consider simplifying the nested function

The nested toQueryResp function could be simplified and potentially moved out for better readability.

Consider this refactoring:

-func gRPCErrorToSDKError(err error) *abci.QueryResponse {
-	toQueryResp := func(sdkErr *errorsmod.Error, err error) *abci.QueryResponse {
-		res := &abci.QueryResponse{
-			Code:      sdkErr.ABCICode(),
-			Codespace: sdkErr.Codespace(),
-		}
-		type grpcStatus interface{ GRPCStatus() *grpcstatus.Status }
-		if grpcErr, ok := err.(grpcStatus); ok {
-			res.Log = grpcErr.GRPCStatus().Message()
-		} else {
-			res.Log = err.Error()
-		}
-		return res
-	}
+// toQueryResp creates an ABCI QueryResponse from an SDK error and the original error
+func toQueryResp(sdkErr *errorsmod.Error, err error) *abci.QueryResponse {
+	res := &abci.QueryResponse{
+		Code:      sdkErr.ABCICode(),
+		Codespace: sdkErr.Codespace(),
+	}
+	
+	if grpcErr, ok := err.(interface{ GRPCStatus() *grpcstatus.Status }); ok {
+		res.Log = grpcErr.GRPCStatus().Message()
+	} else {
+		res.Log = err.Error()
+	}
+	return res
+}
+
+func gRPCErrorToSDKError(err error) *abci.QueryResponse {
🧰 Tools
🪛 golangci-lint (1.62.2)

286-286: File is not gofumpt-ed with -extra

(gofumpt)

📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between acb08a7 and 58e7759.

📒 Files selected for processing (1)
  • server/v2/cometbft/utils.go (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
server/v2/cometbft/utils.go (1)

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

🪛 golangci-lint (1.62.2)
server/v2/cometbft/utils.go

286-286: File is not gofumpt-ed with -extra

(gofumpt)

🔇 Additional comments (2)
server/v2/cometbft/utils.go (2)

15-16: LGTM: Import changes align with error handling improvements

The new imports appropriately support gRPC error handling integration, and the comment explains the rationale for using errorsmod instead of errors/v2.

Also applies to: 23-23, 27-27


Line range hint 263-271: LGTM: Appropriate function visibility change

The renaming of QueryResult to queryResult correctly reflects its internal usage scope while maintaining the existing error handling functionality.

Copy link
Contributor

@testinginprod testinginprod left a comment

Choose a reason for hiding this comment

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

lgtm

@tac0turtle tac0turtle added this pull request to the merge queue Dec 4, 2024
Merged via the queue into main with commit 556102c Dec 4, 2024
72 of 73 checks passed
@tac0turtle tac0turtle deleted the julien/query-err branch December 4, 2024 16:12
mergify bot pushed a commit that referenced this pull request Dec 4, 2024
Co-authored-by: mmsqe <[email protected]>
(cherry picked from commit 556102c)
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 cometbft C:server/v2 Issues related to server/v2
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Bug]: wrong error status code on rpc query
6 participants