这是indexloc提供的服务,不要输入任何密码
Skip to content

fix(schema): proper array minItems, maxItems and doc reporting in generated schemas #485

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

Merged

Conversation

Grumpfy
Copy link

@Grumpfy Grumpfy commented Jun 20, 2024

Hi!

We have a use case that can be summarised by:

// sRGB color space, normalized : R,G,B,A
type Color4f [4]float64

func (c Color4f) TransformSchema(r huma.Registry, s *huma.Schema) *huma.Schema {
	s.Description = "RGBA floating point color such as semi-transparent white is [1.0,1.0,1.0,0.5]"
	return s
}

type RequestParams struct {
	OptionalColor           *Color4f     `json:"optionalColor,omitempty"`
	RequiredColor          Color4f       `json:"requiredColor"`
}

Expected schema:

    "RequestParams": {
        "additionalProperties": false,
        "properties": {
          "optionalColor": {
            "description": "RGBA floating point color such as semi-transparent white is [1.0,1.0,1.0,0.5]",
            "items": {
              "format": "double",
              "type": "number"
            },
            "maxItems": 4,
            "minItems": 4,
            "type": "array"
          },
          "requiredColor": {
            "description": "RGBA floating point color such as semi-transparent white is [1.0,1.0,1.0,0.5]",
            "items": {
              "format": "double",
              "type": "number"
            },
            "maxItems": 4,
            "minItems": 4,
            "type": "array"
          }
        },
        "required": [
          "requiredColor"
        ],
        "type": "object"
      }

Actual schema:

     "RequestParams": {
        "additionalProperties": false,
        "properties": {
          "optionalColor": {
            "items": {
              "format": "double",
              "type": "number"
            },
            "type": "array"
          },
          "requiredColor": {
            "description": "RGBA floating point color such as semi-transparent white is [1.0,1.0,1.0,0.5]",
            "items": {
              "format": "double",
              "type": "number"
            },
            "type": "array"
          }
        },
        "required": [
          "requiredColor"
        ],
        "type": "object"
      }

We're currently missing the minItems and maxItems for both fields and the custom description is missing if the field is a pointer to the Color4f type.

This PR try to address this issue.

Summary by CodeRabbit

  • New Features

    • Improved schema processing to handle pointers to arrays more efficiently.
    • Enhanced schema generation to support minItems and maxItems tags for better validation.
  • Tests

    • Added tests for custom arrays and pointer arrays with descriptions to ensure robust schema validation.

Copy link

coderabbitai bot commented Jun 20, 2024

Walkthrough

The recent changes introduce enhancements in handling schema generation for collections and pointers to arrays within a Go-based schema registry. The updates include modifications to accurately process arrays and conditionally set schema properties like MinItems and MaxItems, leveraging struct tags. Additionally, new test cases have been added to ensure these functionalities are verified comprehensively, especially focusing on custom descriptions and pointer handling.

Changes

File Change Summary
registry.go Updated Schema function to handle pointers to arrays by mapping them to arrays before further processing.
schema.go Enhanced SchemaFromField function to conditionally set MinItems and MaxItems based on struct tags.
schema_test.go Added various test cases, including a new type with custom descriptions and tests for array-related schema fields.

Sequence Diagram(s)

sequenceDiagram
    participant Developer
    participant Registry
    participant Schema
    Developer->>Registry: Call Schema(t reflect.Type, ...)
    loop Check Type
        Registry->>Registry: t.Kind() == reflect.Ptr
        Registry->>Registry: Check if t.Elem() is Array or Slice
        Registry->>Schema: Decayed Pointer, Process Array
    end
    Developer->>Schema: Call SchemaFromField with struct field
    Schema->>Schema: Check for minItems and maxItems tags
    Schema->>Schema: Set MinItems and MaxItems conditionally
    Developer->>Tests: Run schema tests on new functionality
    Tests->>Results: Validate custom descriptions and array handling
Loading

Poem

In a code enchanted grove, arrays bloom,
Pointers find their rightful room.
Min and Max, tags now decoded,
Schema's charm’s further loaded.
Tested fields, both near and far,
Shine their light, like a coding star.

🌟✨🐇


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

@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 (3)
registry.go (1)

Line range hint 145-145: The //nolint:musttag directive is unused and should be removed to clean up the code.

- return json.Marshal(r.schemas) //nolint:musttag
+ return json.Marshal(r.schemas)
schema_test.go (2)

Line range hint 1025-1025: The //nolint:musttag directive is unused and should be removed to clean up the code.

- //nolint:musttag

Line range hint 1032-1032: Similar to the previous comment, the //nolint:musttag directive here is also unused and should be removed.

- //nolint:musttag
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 4a07c36 and 4f10b32.

Files selected for processing (3)
  • registry.go (1 hunks)
  • schema.go (1 hunks)
  • schema_test.go (3 hunks)
Additional context used
golangci-lint
registry.go

145-145: directive //nolint:musttag is unused for linter "musttag" (nolintlint)

schema_test.go

1025-1025: directive //nolint:musttag is unused for linter "musttag" (nolintlint)


1032-1032: directive //nolint:musttag is unused for linter "musttag" (nolintlint)

Additional comments not posted (5)
registry.go (1)

74-77: The logic to handle pointers to arrays by decaying them to their non-pointer types is correct.

schema.go (1)

562-567: Properly handling the minItems and maxItems tags based on the presence of these fields in the struct tag is a good addition for schema validation.

schema_test.go (3)

69-74: Ensure the custom description is applied correctly in TypedArrayWithCustomDesc.


714-719: The schema definition for RecursiveChildLoop correctly sets minItems and maxItems to 1 for the array field.


850-893: The test case field-custom-array and field-ptr-to-custom-array correctly validate the schema generation for TypedArrayWithCustomDesc and its pointer version. Both cases ensure that the minItems and maxItems are set to 4, which aligns with the PR objectives to fix issues with these properties.

Copy link
Owner

@danielgtaylor danielgtaylor left a comment

Choose a reason for hiding this comment

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

@Grumpfy thank you!

@danielgtaylor danielgtaylor merged commit 6d80377 into danielgtaylor:main Jul 10, 2024
1 check passed
@clems71 clems71 deleted the fix/array_field_schema branch September 3, 2024 07:17
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