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(indexer/base): schema and value validation #20665

Merged
merged 52 commits into from
Jun 20, 2024

Conversation

aaronc
Copy link
Member

@aaronc aaronc commented Jun 13, 2024

Description

Ref: #20352

This PR adds schema and value validation logic to Kind, Field, ObjectType, and ModuleSchema types in cosmossdk.io/indexer/base. It also reduces the valid set of go types that conform to Kinds for simplifying future implementation and testing details.


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 validation methods for EnumDefinitions, Fields, Kinds, ModuleSchemas, and ObjectTypes to ensure data integrity.
    • Introduced regex-based name validation and MapValueUpdates for sorted iteration over map keys.
  • Bug Fixes
    • Updated comments for Kinds to clarify value requirements and constraints.
  • Tests
    • Added comprehensive test cases for newly implemented validation methods across various structs and data types in the indexing system.
    • Validated key and value fields in ObjectUpdates through new test functions.

Copy link
Contributor

coderabbitai bot commented Jun 13, 2024

Walkthrough

The updates enhance validation mechanisms throughout the indexerbase package. This includes adding validation methods for enums, fields, kinds, module schemas, and object types, along with their respective tests. The changes ensure that enums, fields, and names adhere to specified formats and rules, while object updates are correctly validated. These improvements are aimed at maintaining the integrity and correctness of data structures within the indexing system.

Changes

File(s) Change Summary
indexer/base/enum.go, indexer/base/enum_test.go Added validation methods (Validate, ValidateValue) to EnumDefinition and introduced corresponding tests.
indexer/base/field.go, indexer/base/field_test.go Integrated validation methods (Validate, ValidateValue) to Field struct and introduced corresponding tests.
indexer/base/kind.go, indexer/base/kind_test.go Enhanced Kind struct comments, added constants for regex patterns, and included validation methods along with tests.
indexer/base/listener.go Updated function signatures and comments to incorporate module name validation based on a regex.
indexer/base/module_schema.go, indexer/base/module_schema_test.go Added validation methods (Validate, ValidateObjectUpdate) to ModuleSchema and introduced corresponding tests.
indexer/base/name.go, indexer/base/name_test.go Introduced regular expression NameFormat for name validation and a test function for validating names.
indexer/base/object_type.go, indexer/base/object_type_test.go Added methods (Validate, ValidateObjectUpdate) to ObjectType and included corresponding tests.
indexer/base/object_update.go, indexer/base/object_update_test.go Introduced MapValueUpdates type with an iteration method and corresponding tests.
indexer/base/fields.go, indexer/base/fields_test.go Added functions for validating key and value fields within ObjectUpdate and corresponding tests.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant IndexerBase
    participant Field
    participant EnumDefinition
    participant ModuleSchema
    
    Client->>IndexerBase: Create/Update EnumDefinition
    IndexerBase->>EnumDefinition: Validate()
    EnumDefinition-->>IndexerBase: Validation Result
    
    Client->>IndexerBase: Create/Update Field
    IndexerBase->>Field: Validate()
    Field-->>IndexerBase: Validation Result
    
    Client->>IndexerBase: Create/Update ModuleSchema
    IndexerBase->>ModuleSchema: Validate()
    ModuleSchema-->>IndexerBase: Validation Result
Loading

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

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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
Contributor

mergify bot commented Jun 13, 2024

⚠️ The sha of the head commit of this PR conflicts with #20629. Mergify cannot evaluate rules on this PR. ⚠️

Copy link
Contributor

mergify bot commented Jun 13, 2024

⚠️ The sha of the head commit of this PR conflicts with #20629. Mergify cannot evaluate rules on this PR. ⚠️

@aaronc aaronc mentioned this pull request Jun 13, 2024
12 tasks
@aaronc aaronc changed the title feat(indexer): base validation code feat(indexer/base): schema and value validation Jun 13, 2024
Copy link
Contributor

mergify bot commented Jun 13, 2024

⚠️ The sha of the head commit of this PR conflicts with #20629. Mergify cannot evaluate rules on this PR. ⚠️

Copy link
Contributor

mergify bot commented Jun 13, 2024

⚠️ The sha of the head commit of this PR conflicts with #20629. Mergify cannot evaluate rules on this PR. ⚠️

Copy link
Contributor

mergify bot commented Jun 13, 2024

⚠️ The sha of the head commit of this PR conflicts with #20629. Mergify cannot evaluate rules on this PR. ⚠️

indexer/base/field.go Fixed Show fixed Hide fixed
indexer/base/kind.go Fixed Show fixed Hide fixed
indexer/base/kind.go Fixed Show fixed Hide fixed
return "float32"
case Float64Kind:
return "float64"
case Bech32AddressKind:

Check warning

Code scanning / CodeQL

Directly using the bech32 constants Warning

Directly using the bech32 constants instead of the configuration values
}

// address prefix only valid with Bech32AddressKind
if c.Kind == Bech32AddressKind && c.AddressPrefix == "" {

Check warning

Code scanning / CodeQL

Directly using the bech32 constants Warning

Directly using the bech32 constants instead of the configuration values
// address prefix only valid with Bech32AddressKind
if c.Kind == Bech32AddressKind && c.AddressPrefix == "" {
return fmt.Errorf("missing address prefix for field %q", c.Name)
} else if c.Kind != Bech32AddressKind && c.AddressPrefix != "" {

Check warning

Code scanning / CodeQL

Directly using the bech32 constants Warning

Directly using the bech32 constants instead of the configuration values
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: 4

Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 1e1ffb7 and ad3f07a.

Files selected for processing (3)
  • indexer/base/fields.go (1 hunks)
  • indexer/base/fields_test.go (1 hunks)
  • indexer/base/object_type.go (2 hunks)
Files skipped from review as they are similar to previous changes (2)
  • indexer/base/fields.go
  • indexer/base/object_type.go
Additional context used
Path-based instructions (1)
indexer/base/fields_test.go (2)

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


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

Comment on lines +8 to +71
func TestValidateForKeyFields(t *testing.T) {
tests := []struct {
name string
keyFields []Field
key interface{}
errContains string
}{
{
name: "no key fields",
keyFields: nil,
key: nil,
},
{
name: "single key field, valid",
keyFields: object1Type.KeyFields,
key: "hello",
errContains: "",
},
{
name: "single key field, invalid",
keyFields: object1Type.KeyFields,
key: []interface{}{"value"},
errContains: "invalid value",
},
{
name: "multiple key fields, valid",
keyFields: object2Type.KeyFields,
key: []interface{}{"hello", int32(42)},
},
{
name: "multiple key fields, not a slice",
keyFields: object2Type.KeyFields,
key: map[string]interface{}{"field1": "hello", "field2": "42"},
errContains: "expected slice of values",
},
{
name: "multiple key fields, wrong number of values",
keyFields: object2Type.KeyFields,
key: []interface{}{"hello"},
errContains: "expected 2 key fields",
},
{
name: "multiple key fields, invalid value",
keyFields: object2Type.KeyFields,
key: []interface{}{"hello", "abc"},
errContains: "invalid value",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := ValidateForKeyFields(tt.keyFields, tt.key)
if tt.errContains == "" {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
} else {
if err == nil || !strings.Contains(err.Error(), tt.errContains) {
t.Fatalf("expected error to contain %q, got: %v", tt.errContains, err)
}
}
})
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider enhancing the error checks in TestValidateForKeyFields to verify the type of errors, not just the error messages.

This ensures that the function not only returns the expected message but also the correct error type, which is crucial for debugging and maintenance.

Comment on lines +57 to +70
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := ValidateForKeyFields(tt.keyFields, tt.key)
if tt.errContains == "" {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
} else {
if err == nil || !strings.Contains(err.Error(), tt.errContains) {
t.Fatalf("expected error to contain %q, got: %v", tt.errContains, err)
}
}
})
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Refactor error handling in TestValidateForKeyFields to use error types or constants instead of string contains checks.

This change would make the tests less fragile to changes in the error message wording and improve the robustness of the test suite.

Comment on lines +73 to +143
func TestValidateForValueFields(t *testing.T) {
tests := []struct {
name string
valueFields []Field
value interface{}
errContains string
}{
{
name: "no value fields",
valueFields: nil,
value: nil,
},
{
name: "single value field, valid",
valueFields: []Field{
{
Name: "field1",
Kind: StringKind,
},
},
value: "hello",
errContains: "",
},
{
name: "value updates, empty",
valueFields: object3Type.ValueFields,
value: MapValueUpdates(map[string]interface{}{}),
},
{
name: "value updates, 1 field valid",
valueFields: object3Type.ValueFields,
value: MapValueUpdates(map[string]interface{}{
"field1": "hello",
}),
},
{
name: "value updates, 2 fields, 1 invalid",
valueFields: object3Type.ValueFields,
value: MapValueUpdates(map[string]interface{}{
"field1": "hello",
"field2": "abc",
}),
errContains: "expected int32",
},
{
name: "value updates, extra value",
valueFields: object3Type.ValueFields,
value: MapValueUpdates(map[string]interface{}{
"field1": "hello",
"field2": int32(42),
"field3": "extra",
}),
errContains: "unexpected values",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := ValidateForValueFields(tt.valueFields, tt.value)
if tt.errContains == "" {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
} else {
if err == nil || !strings.Contains(err.Error(), tt.errContains) {
t.Fatalf("expected error to contain %q, got: %v", tt.errContains, err)
}
}
})
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding checks for specific error types in TestValidateForValueFields to ensure that the correct exceptions are being thrown.

This would enhance the test's ability to verify not only the occurrence of an error but its specific type, aiding in precise troubleshooting and validation.

Comment on lines +129 to +142
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := ValidateForValueFields(tt.valueFields, tt.value)
if tt.errContains == "" {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
} else {
if err == nil || !strings.Contains(err.Error(), tt.errContains) {
t.Fatalf("expected error to contain %q, got: %v", tt.errContains, err)
}
}
})
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Refactor error handling in TestValidateForValueFields to use error types or constants instead of string contains checks.

Using error types or constants would make the tests more reliable and less dependent on specific error message content, which might change over time.

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

Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between ad3f07a and 0b6dfbd.

Files selected for processing (4)
  • indexer/base/module_schema.go (1 hunks)
  • indexer/base/module_schema_test.go (1 hunks)
  • indexer/base/object_type.go (2 hunks)
  • indexer/base/object_type_test.go (1 hunks)
Files skipped from review as they are similar to previous changes (4)
  • indexer/base/module_schema.go
  • indexer/base/module_schema_test.go
  • indexer/base/object_type.go
  • indexer/base/object_type_test.go

// Bech32AddressKind is a bech32 address type and values of this type must be of the go type string or []byte
// or a type which implements fmt.Stringer. Fields of this type are expected to set the AddressPrefix field
// in the field definition to the bech32 address prefix.
// Bech32AddressKind is a bech32 address type and values of this type must be of the go type []byte.
Copy link
Member Author

Choose a reason for hiding this comment

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

I switched the requirement to be just []bytes so the validation logic doesn't need to do any bech32 parsing here (although it is a pretty lightweight dependency). Also wondering if we need a length limit on addresses or not.

Copy link
Member Author

Choose a reason for hiding this comment

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

How about a length limit of 64 or 128 bytes for addresses?

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

Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 0b6dfbd and 85e5114.

Files selected for processing (12)
  • indexer/base/enum.go (1 hunks)
  • indexer/base/enum_test.go (1 hunks)
  • indexer/base/field.go (2 hunks)
  • indexer/base/field_test.go (1 hunks)
  • indexer/base/kind.go (4 hunks)
  • indexer/base/kind_test.go (1 hunks)
  • indexer/base/listener.go (2 hunks)
  • indexer/base/module_schema_test.go (1 hunks)
  • indexer/base/name.go (1 hunks)
  • indexer/base/name_test.go (1 hunks)
  • indexer/base/object_type.go (2 hunks)
  • indexer/base/object_type_test.go (1 hunks)
Files not reviewed due to errors (3)
  • indexer/base/name.go (no review received)
  • indexer/base/name_test.go (no review received)
  • indexer/base/listener.go (no review received)
Files skipped from review as they are similar to previous changes (9)
  • indexer/base/enum.go
  • indexer/base/enum_test.go
  • indexer/base/field.go
  • indexer/base/field_test.go
  • indexer/base/kind.go
  • indexer/base/kind_test.go
  • indexer/base/module_schema_test.go
  • indexer/base/object_type.go
  • indexer/base/object_type_test.go
Additional context used
Path-based instructions (3)
indexer/base/name.go (1)

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

indexer/base/name_test.go (2)

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


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

indexer/base/listener.go (1)

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

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

Copy link
Member

@kocubinski kocubinski left a comment

Choose a reason for hiding this comment

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

LGTM

@aaronc
Copy link
Member Author

aaronc commented Jun 20, 2024

Going to go ahead and merge this and move forward with splitting out to cosmossdk.io/schema

@aaronc aaronc enabled auto-merge June 20, 2024 15:15
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

Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 85e5114 and 9f4c1d0.

Files selected for processing (3)
  • indexer/base/kind.go (4 hunks)
  • indexer/base/kind_test.go (1 hunks)
  • indexer/base/object_type.go (2 hunks)
Files skipped from review as they are similar to previous changes (3)
  • indexer/base/kind.go
  • indexer/base/kind_test.go
  • indexer/base/object_type.go

@aaronc aaronc disabled auto-merge June 20, 2024 15:41
@aaronc aaronc enabled auto-merge June 20, 2024 15:41
@aaronc aaronc added this pull request to the merge queue Jun 20, 2024
Merged via the queue into main with commit a6407f4 Jun 20, 2024
66 checks passed
@aaronc aaronc deleted the aaronc/indexer-base-validation branch June 20, 2024 16:20
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.

4 participants