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: json codec to use custom json marshal unmarshal #118

Merged
merged 1 commit into from
Nov 5, 2024
Merged

Conversation

beer-1
Copy link
Contributor

@beer-1 beer-1 commented Nov 5, 2024

Description

Closes: #XXXX

cosmos jsonpb does not check existing UnmarshalJSON if the type is enum, so we use custom marshal/unmarshal functions which is always execute if exists.


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
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • 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.

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
    • Enhanced serialization capabilities for BatchInfo_ChainType with JSONPB support.
  • Bug Fixes
    • Improved validation checks for unspecified and unknown chain types in the bridge configuration.
  • Tests
    • Added a new test for JSON marshaling and unmarshaling of transactions.
    • Refined existing validation tests for BatchInfo chain types.

@beer-1 beer-1 self-assigned this Nov 5, 2024
@beer-1 beer-1 requested a review from a team as a code owner November 5, 2024 04:50
@beer-1 beer-1 changed the title fix json codec to use custom json marshal unmarshal fix: json codec to use custom json marshal unmarshal Nov 5, 2024
Copy link

coderabbitai bot commented Nov 5, 2024

Walkthrough

The changes involve modifications to the bridge_config.go and bridge_config_test.go files. In bridge_config.go, the BatchInfo_ChainType struct is enhanced with JSONPB marshaling capabilities through the addition of MarshalJSONPB and UnmarshalJSONPB methods. These methods ensure compatibility with both standard JSON and JSONPB formats. In bridge_config_test.go, a new test function is introduced to validate the JSON marshaling and unmarshaling of transactions, along with refinements to existing validation checks for chain types.

Changes

File Path Change Summary
x/ophost/types/bridge_config.go - Added methods: MarshalJSONPB, UnmarshalJSONPB for BatchInfo_ChainType.
- Added variables to assert jsonpb.JSONPBMarshaler and jsonpb.JSONPBUnmarshaler interfaces.
x/ophost/types/bridge_config_test.go - Added test function: TestGoGoProtoJsonPB for JSON marshaling/unmarshaling.
- Modified Test_ValidateBridgeConfig to include validation checks for BatchInfo chain types.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant BridgeConfig
    participant JSONPB

    Client->>BridgeConfig: Request to marshal BatchInfo_ChainType
    BridgeConfig->>JSONPB: Call MarshalJSONPB
    JSONPB-->>BridgeConfig: Return marshaled JSONPB
    BridgeConfig-->>Client: Return marshaled data

    Client->>BridgeConfig: Request to unmarshal JSONPB
    BridgeConfig->>JSONPB: Call UnmarshalJSONPB
    JSONPB-->>BridgeConfig: Return unmarshaled BatchInfo_ChainType
    BridgeConfig-->>Client: Return BatchInfo_ChainType
Loading

🐇 "In the code, we hop and play,
With JSONPB, we find our way.
Marshaling, unmarshaling, all in line,
Testing our bridges, oh so fine!
With every change, we leap with glee,
A better world for you and me!" 🐰


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.

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

codecov bot commented Nov 5, 2024

Codecov Report

Attention: Patch coverage is 50.00000% with 2 lines in your changes missing coverage. Please review.

Project coverage is 49.25%. Comparing base (414508a) to head (082c401).
Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
x/ophost/types/bridge_config.go 50.00% 2 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #118      +/-   ##
==========================================
+ Coverage   48.61%   49.25%   +0.63%     
==========================================
  Files          57       57              
  Lines        4229     4233       +4     
==========================================
+ Hits         2056     2085      +29     
+ Misses       1744     1719      -25     
  Partials      429      429              
Files with missing lines Coverage Δ
x/ophost/types/bridge_config.go 27.94% <50.00%> (+1.37%) ⬆️

... and 1 file with indirect coverage changes

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

🧹 Outside diff range and nitpick comments (3)
x/ophost/types/bridge_config.go (1)

108-116: LGTM! Consider enhancing the documentation.

The implementation correctly delegates to the existing JSON methods, ensuring consistency between JSON and JSONPB serialization. This is a clean and efficient approach.

Consider adding a brief comment explaining why the Marshaler/Unmarshaler parameters are ignored:

 // MarshalJSONPB marshals the BatchInfo_ChainType to JSON
-func (cy BatchInfo_ChainType) MarshalJSONPB(_ *jsonpb.Marshaler) ([]byte, error) {
+// The jsonpb.Marshaler parameter is ignored as we delegate to the standard JSON marshaling
+func (cy BatchInfo_ChainType) MarshalJSONPB(_ *jsonpb.Marshaler) ([]byte, error) {

 // UnmarshalJSONPB unmarshals the BatchInfo_ChainType from JSON
-func (cy *BatchInfo_ChainType) UnmarshalJSONPB(_ *jsonpb.Unmarshaler, inputBz []byte) error {
+// The jsonpb.Unmarshaler parameter is ignored as we delegate to the standard JSON unmarshaling
+func (cy *BatchInfo_ChainType) UnmarshalJSONPB(_ *jsonpb.Unmarshaler, inputBz []byte) error {
x/ophost/types/bridge_config_test.go (2)

73-74: Consider extracting the test JSON into a separate test data file.

The hardcoded JSON string makes the test difficult to maintain and read. Consider:

  1. Moving it to a separate test data file
  2. Using a more maintainable way to construct the test JSON, such as marshaling a struct

59-85: Enhance test documentation and structure.

The test would benefit from:

  1. Adding comments explaining the test's purpose and what it's validating
  2. Converting to a table-driven test to cover multiple chain types and error cases
  3. Breaking down the large JSON string into smaller, more manageable test cases

Example structure:

func TestGoGoProtoJsonPB(t *testing.T) {
    // Test cases for different chain types and scenarios
    testCases := []struct {
        name      string
        chainType BatchInfo_ChainType
        wantErr   bool
    }{
        {
            name:      "valid celestia chain type",
            chainType: BatchInfo_CHAIN_TYPE_CELESTIA,
            wantErr:   false,
        },
        // Add more test cases
    }

    for _, tc := range testCases {
        t.Run(tc.name, func(t *testing.T) {
            // Test implementation
        })
    }
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 851f016 and 082c401.

📒 Files selected for processing (2)
  • x/ophost/types/bridge_config.go (2 hunks)
  • x/ophost/types/bridge_config_test.go (2 hunks)
🔇 Additional comments (5)
x/ophost/types/bridge_config.go (2)

11-11: LGTM! Good use of interface assertions.

The interface assertions ensure compile-time verification that BatchInfo_ChainType correctly implements both jsonpb.JSONPBMarshaler and jsonpb.JSONPBUnmarshaler interfaces.

Also applies to: 14-15


14-15: Verify JSONPB implementation completeness.

Let's verify if there are other enum types that might need similar JSONPB support.

Also applies to: 108-116

✅ Verification successful

Let me gather more information about the enum definitions in the proto files to ensure we have a complete picture.


Based on the comprehensive analysis of the proto files and codebase usage, I can now provide the final response:

JSONPB implementation is complete and correctly implemented

The verification shows that:

  1. BatchInfo_ChainType is the only enum type that requires JSONPB support as it's the only enum used in JSON serialization contexts (via BatchSubmissionTarget field in configs)
  2. The implementation is complete with both MarshalJSONPB and UnmarshalJSONPB methods properly delegating to the existing JSON methods
  3. The enum is properly used across the codebase in a consistent manner
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other enum types defined in .proto files that might need JSONPB support
echo "Searching for enum definitions in .proto files..."
fd -e proto -x grep -l "enum" {} \;

# Search for existing MarshalJSON/UnmarshalJSON implementations that might need JSONPB counterparts
echo "Searching for existing JSON marshal/unmarshal implementations..."
rg "func.*Marshal(JSON|JSON)" -A 5
rg "func.*Unmarshal(JSON|JSON)" -A 5

Length of output: 3539


Script:

#!/bin/bash
# Check the content of proto files for enum definitions
echo "Content of ./proto/opinit/opchild/v1/types.proto:"
cat ./proto/opinit/opchild/v1/types.proto

echo -e "\nContent of ./proto/opinit/ophost/v1/types.proto:"
cat ./proto/opinit/ophost/v1/types.proto

# Search for any usage of these enums in the codebase
echo -e "\nSearching for enum usages:"
rg "BatchInfo_ChainType" -A 2

Length of output: 19560

x/ophost/types/bridge_config_test.go (3)

5-5: LGTM! Import changes are well-structured.

The new imports appropriately support the added test functionality for JSON/JSONPB marshaling and codec operations.

Also applies to: 10-17


58-58: LGTM! Validation test cases are comprehensive.

The additional validation cases for UNSPECIFIED and unknown chain types strengthen the test coverage and align with the PR's objective of proper enum handling.


74-74: Verify the contents of the encoded metadata.

The test contains base64 encoded metadata in the JSON string. Please verify its contents and consider adding explicit validation of the decoded metadata.

✅ Verification successful

Metadata validation is properly implemented

The codebase has appropriate validation for the metadata:

  • There is a defined maximum length limit (MaxMetadataLength = 1024 * 5)
  • The MsgCreateBridge.Validate() method enforces this limit with a clear error message
  • The same validation is also applied in MsgUpdateMetadata.Validate()
  • The test data contains valid JSON metadata for IBC channels configuration

The base64 encoded metadata in the test is used as a valid test fixture and doesn't require additional validation since the length check provides sufficient protection against malicious input.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Decode and verify the metadata content
echo "eyJwZXJtX2NoYW5uZWxzIjpbeyJwb3J0X2lkIjoibmZ0LXRyYW5zZmVyIiwiY2hhbm5lbF9pZCI6ImNoYW5uZWwtMzUzIn0seyJwb3J0X2lkIjoidHJhbnNmZXIiLCJjaGFubmVsX2lkIjoiY2hhbm5lbC0zNTIifV19" | base64 -d

Length of output: 257


Script:

#!/bin/bash
# Search for metadata validation in the test file and related files
rg -A 5 "metadata.*base64" x/ophost/types/

# Look for any metadata validation patterns in the codebase
ast-grep --pattern 'func $_ ($_, $_) {
  $$$
  base64.Decode$$$($$$)
  $$$
}'

# Check if there are any validation functions for bridge config
ast-grep --pattern 'func (m *MsgCreateBridge) Validate() error {
  $$$
}'

Length of output: 200


Script:

#!/bin/bash
# Look for metadata validation in bridge config files
rg -l "metadata" x/ophost/types/

# Check the test file content for context
cat x/ophost/types/bridge_config_test.go

# Look for any validation related to bridge config
rg "Validate.*Bridge" x/ophost/types/

Length of output: 4388


Script:

#!/bin/bash
# Check the validation implementation in tx.go
cat x/ophost/types/tx.go

# Look for any metadata-specific validation
rg -A 5 "Config.*Validate" x/ophost/types/

Length of output: 12006

Comment on lines +67 to +69
if err != nil {
panic(err)
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Replace panic with proper test error handling.

Using panic in tests is not recommended. Instead, use require.NoError for consistency with the rest of the test file.

-	if err != nil {
-		panic(err)
-	}
+	require.NoError(t, err)

Committable suggestion skipped: line range outside the PR's diff.

Copy link
Contributor

@sh-cha sh-cha left a comment

Choose a reason for hiding this comment

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

lgtm

@beer-1 beer-1 merged commit 0ef48cf into main Nov 5, 2024
8 checks passed
@beer-1 beer-1 deleted the fix/json-codec branch November 5, 2024 06:13
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