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

feat(collections): add Address and Integer codecs #22517

Merged
merged 11 commits into from
Jan 6, 2025
Merged

Conversation

cool-develope
Copy link
Contributor

@cool-develope cool-develope commented Nov 12, 2024

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

    • Enhanced schema encoding and decoding mechanisms for keys
    • Improved indexing functionality with address codec support
  • Deprecation Notices

    • Marked several existing key codecs as deprecated
    • Recommended alternative storage key approaches
  • Improvements

    • Refined error handling in codec conversions
    • Added more robust type conversion methods for schema types

Copy link
Contributor

coderabbitai bot commented Nov 12, 2024

Warning

Rate limit exceeded

@julienrbrt has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 29 minutes and 15 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 9506c52 and 0a1e0ae.

📒 Files selected for processing (1)
  • types/collections.go (3 hunks)
📝 Walkthrough

Walkthrough

This pull request introduces enhancements to key and codec handling across multiple files in the Cosmos SDK. The changes focus on improving schema type conversions, error handling, and codec functionality. In collections/pair.go, new functions are added to facilitate key schema type conversions. types/collections.go introduces SchemaCodec methods for address and integer keys, and includes deprecation notices for certain key codecs. The baseapp/streaming.go modification adds an AddressCodec to the indexing options, potentially improving address handling during indexing.

Changes

File Change Summary
collections/pair.go Added toKeySchemaType and fromKeySchemaType functions to improve key schema type conversions
types/collections.go Added SchemaCodec methods to genericAddressKey and intValueCodec; marked several key codecs as deprecated
baseapp/streaming.go Updated EnableIndexer method to include AddressCodec in indexing options

Possibly related PRs

Suggested labels

C:x/bank

Suggested reviewers

  • facundomedica
  • testinginprod
  • aaronc
  • 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 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: 1

🧹 Outside diff range and nitpick comments (6)
collections/indexing.go (1)

153-155: Consider refactoring decoder handling to reduce duplication

The key and value decoder logic follows similar patterns. Consider extracting the common decoder handling logic into a helper function to improve maintainability and reduce code duplication.

Example refactor:

func decodeWithSchemaType(decoder codec.SchemaCodec, data []byte, decode func([]byte) (any, error)) (any, error) {
    x, err := decode(data)
    if err != nil {
        return nil, err
    }
    if decoder.ToSchemaType == nil {
        return x, nil
    }
    return decoder.ToSchemaType(x)
}

This helper could then be used for both key and value decoding:

res.keyDecoder = func(i []byte) (any, error) {
    return decodeWithSchemaType(keyDecoder, i, func(data []byte) (any, error) {
        _, x, err := c.m.kc.Decode(data)
        return x, err
    })
}

res.valueDecoder = func(i []byte) (any, error) {
    return decodeWithSchemaType(valueDecoder, i, c.m.vc.Decode)
}
types/collections.go (2)

124-139: LGTM with a minor suggestion for error messages

The implementation correctly handles schema encoding/decoding for address types with proper error handling and type assertions.

Consider enhancing the error message to include the actual value:

-				return t, fmt.Errorf("expected string, got %T", s)
+				return t, fmt.Errorf("expected string, got %T: %v", s, s)

235-253: LGTM with suggestions for error handling and performance

The implementation correctly handles schema encoding/decoding for math.Int with proper validation.

Consider these improvements:

  1. Enhance error messages to include the actual value:
-				return math.Int{}, fmt.Errorf("expected string, got %T", s)
+				return math.Int{}, fmt.Errorf("expected string, got %T: %v", s, s)
  1. Optimize the error path by combining the parsing check and conversion:
-			t, ok := math.NewIntFromString(sz)
-			if !ok {
-				return math.Int{}, fmt.Errorf("failed to parse Int from string: %s", sz)
-			}
-			return t, nil
+			if t, ok := math.NewIntFromString(sz); ok {
+				return t, nil
+			}
+			return math.Int{}, fmt.Errorf("failed to parse Int from string: %s", sz)
collections/pair.go (3)

248-257: Refactor duplicated code for obtaining schema codecs

The code blocks for obtaining codec1 and codec2 from codec.KeySchemaCodec and handling errors are nearly identical. Refactoring this duplication into a helper function can improve maintainability and reduce redundancy.

Here's how you might refactor:

 func (p pairKeyCodec[K1, K2]) SchemaCodec() (codec.SchemaCodec[Pair[K1, K2]], error) {
     field1, err := getNamedKeyField(p.keyCodec1, p.key1Name)
     if err != nil {
         return codec.SchemaCodec[Pair[K1, K2]]{}, fmt.Errorf("error getting key1 field: %w", err)
     }

     field2, err := getNamedKeyField(p.keyCodec2, p.key2Name)
     if err != nil {
         return codec.SchemaCodec[Pair[K1, K2]]{}, fmt.Errorf("error getting key2 field: %w", err)
     }

-    codec1, err := codec.KeySchemaCodec(p.keyCodec1)
-    if err != nil {
-        return codec.SchemaCodec[Pair[K1, K2]]{}, fmt.Errorf("error getting key1 schema codec: %w", err)
-    }
-
-    codec2, err := codec.KeySchemaCodec(p.keyCodec2)
-    if err != nil {
-        return codec.SchemaCodec[Pair[K1, K2]]{}, fmt.Errorf("error getting key2 schema codec: %w", err)
-    }
+    codec1, err := getKeySchemaCodec(p.keyCodec1, "key1")
+    if err != nil {
+        return codec.SchemaCodec[Pair[K1, K2]]{}, err
+    }
+
+    codec2, err := getKeySchemaCodec(p.keyCodec2, "key2")
+    if err != nil {
+        return codec.SchemaCodec[Pair[K1, K2]]{}, err
+    }

And define the helper function getKeySchemaCodec to encapsulate the error handling.


261-269: Refactor duplicated code when converting to schema types

The conversion of k1 and k2 using toKeySchemaType is duplicated. Refactoring this into a loop or helper function can reduce redundancy and enhance code readability.

Here's an example of how you might refactor:

-            k1, err := toKeySchemaType(codec1, pair.K1())
-            if err != nil {
-                return nil, err
-            }
-            k2, err := toKeySchemaType(codec2, pair.K2())
-            if err != nil {
-                return nil, err
-            }
-            return []interface{}{k1, k2}, nil
+            keys := make([]interface{}, 2)
+            codecs := []codec.SchemaCodec{codec1, codec2}
+            pairValues := []any{pair.K1(), pair.K2()}
+            for i, cdc := range codecs {
+                k, err := toKeySchemaType(cdc, pairValues[i])
+                if err != nil {
+                    return nil, err
+                }
+                keys[i] = k
+            }
+            return keys, nil

276-284: Refactor duplicated code when converting from schema types

Similarly, the code for converting k1 and k2 from schema types is duplicated. Consider refactoring to reduce repetition and improve maintainability.

Here's how you might adjust the code:

-            k1, err := fromKeySchemaType(codec1, aSlice[0])
-            if err != nil {
-                return Pair[K1, K2]{}, err
-            }
-            k2, err := fromKeySchemaType(codec2, aSlice[1])
-            if err != nil {
-                return Pair[K1, K2]{}, err
-            }
-            return Join(k1, k2), nil
+            keys := make([]interface{}, 2)
+            codecs := []codec.SchemaCodec{codec1, codec2}
+            for i, cdc := range codecs {
+                k, err := fromKeySchemaType(cdc, aSlice[i])
+                if err != nil {
+                    return Pair[K1, K2]{}, err
+                }
+                keys[i] = k
+            }
+            return Join(keys[0].(K1), keys[1].(K2)), nil
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f1bd0d8 and 1853871.

📒 Files selected for processing (5)
  • collections/indexing.go (1 hunks)
  • collections/pair.go (2 hunks)
  • indexer/postgres/params.go (1 hunks)
  • schema/kind.go (0 hunks)
  • types/collections.go (3 hunks)
💤 Files with no reviewable changes (1)
  • schema/kind.go
🧰 Additional context used
📓 Path-based instructions (4)
collections/indexing.go (1)

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

collections/pair.go (1)

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

indexer/postgres/params.go (1)

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

types/collections.go (1)

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

🔇 Additional comments (2)
indexer/postgres/params.go (1)

111-115: LGTM! The changes look good but require verification.

The modification to handle address values as strings instead of byte slices is well-implemented with proper error handling and clear error messages.

Let's verify that all callers have been updated to pass string values:

✅ Verification successful

Verified: All callers have been updated to pass string values.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all potential callers of bindParam that might be affected by the AddressKind change
# Look for any code that might still be passing []byte for AddressKind fields

# Search for struct field declarations of AddressKind type
rg -l "schema\.AddressKind" | xargs -I {} rg -A 5 "type.*struct" {}

# Search for direct usage of bindParam with byte slices
ast-grep --pattern 'bindParam($_, []byte{$$$})'

Length of output: 1406

collections/indexing.go (1)

153-155: LGTM: Consistent nil check for schema type conversion

The added nil check for valueDecoder.ToSchemaType is a good defensive programming practice that:

  1. Maintains consistency with the key decoder's behavior
  2. Prevents potential nil pointer dereferences
  3. Provides a clean fallback to return the original decoded value

collections/pair.go Outdated Show resolved Hide resolved
Copy link
Contributor

@cool-develope your pull request is missing a changelog!

param, err = tm.options.addressCodec.BytesToString(value.([]byte))
if err != nil {
return nil, fmt.Errorf("address encoding failed for field %q: %w", field.Name, err)
t, ok := value.(string)
Copy link
Member

Choose a reason for hiding this comment

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

Where are passed the address codec then now? cc @facundomedica

Copy link
Member

Choose a reason for hiding this comment

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

We now have a difference between how are read the values (readCol uses the address codec) and how they are rendered (expecting the field being a string). I think we should use the address codec for both. They are in the indexing options and now properly wired: 0cda5c3

@github-actions github-actions bot removed the C:schema label Jan 6, 2025
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@julienrbrt julienrbrt added the backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release label Jan 6, 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: 1

🧹 Nitpick comments (1)
types/collections.go (1)

236-254: LGTM with a minor improvement suggestion.

The implementation is thorough and handles all edge cases correctly. Consider extracting error messages into constants for better maintainability.

+const (
+    errExpectedString = "expected string, got %T"
+    errFailedIntParse = "failed to parse Int from string: %s"
+)

 func (i intValueCodec) SchemaCodec() (collcodec.SchemaCodec[math.Int], error) {
 	return collcodec.SchemaCodec[math.Int]{
 		Fields: []schema.Field{{Kind: schema.IntegerKind}},
 		ToSchemaType: func(t math.Int) (any, error) {
 			return t.String(), nil
 		},
 		FromSchemaType: func(s any) (math.Int, error) {
 			sz, ok := s.(string)
 			if !ok {
-				return math.Int{}, fmt.Errorf("expected string, got %T", s)
+				return math.Int{}, fmt.Errorf(errExpectedString, s)
 			}
 			t, ok := math.NewIntFromString(sz)
 			if !ok {
-				return math.Int{}, fmt.Errorf("failed to parse Int from string: %s", sz)
+				return math.Int{}, fmt.Errorf(errFailedIntParse, sz)
 			}
 			return t, nil
 		},
 	}, 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 77c2d50 and 9506c52.

📒 Files selected for processing (1)
  • types/collections.go (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
types/collections.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 (7)
  • GitHub Check: tests (00)
  • GitHub Check: test-simapp-v2
  • GitHub Check: test-system-v2
  • GitHub Check: test-integration
  • GitHub Check: Analyze
  • GitHub Check: build (amd64)
  • GitHub Check: Summary
🔇 Additional comments (1)
types/collections.go (1)

12-12: LGTM!

The schema import is correctly added and necessary for the new SchemaCodec implementations.

types/collections.go Outdated Show resolved Hide resolved
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@julienrbrt julienrbrt enabled auto-merge January 6, 2025 14:01
@julienrbrt julienrbrt added this pull request to the merge queue Jan 6, 2025
Merged via the queue into main with commit 261f0b9 Jan 6, 2025
71 of 72 checks passed
@julienrbrt julienrbrt deleted the schema/codec_missing branch January 6, 2025 14:17
mergify bot pushed a commit that referenced this pull request Jan 6, 2025
Co-authored-by: Julien Robert <[email protected]>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
(cherry picked from commit 261f0b9)

# Conflicts:
#	collections/pair.go
julienrbrt added a commit that referenced this pull request Jan 6, 2025
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:collections 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.

8 participants