Skip to content

feat: introduce custom validator for addon - #2633

Merged
chrisgacsal merged 5 commits into
mainfrom
refactor/productcatalog
Apr 9, 2025
Merged

chrisgacsal merged 5 commits into
mainfrom
refactor/productcatalog

Conversation

@chrisgacsal

@chrisgacsal chrisgacsal commented Apr 9, 2025 •

Copy link
Copy Markdown
Collaborator

Overview

Add custom validator support for Addon type.

Summary by CodeRabbit

  • New Features

    • Enhanced add-on validations now ensure that all add-ons meet publishing requirements.
    • Introduced a smoother conversion process to align add-ons with our product catalog.
    • Added robust version management, including sorting and draft detection, to improve add-on lifecycle handling.
  • Refactor

    • Simplified validation workflows across add-on services.
    • Adjusted plan processing by removing fixed pagination, enabling more flexible plan management.
  • Bug Fixes

    • Improved error handling in add-on status checks and version calculations.

@chrisgacsal chrisgacsal self-assigned this Apr 9, 2025
@chrisgacsal
chrisgacsal requested a review from a team as a code owner April 9, 2025 07:39
@chrisgacsal chrisgacsal added the release-note/misc Miscellaneous changes label Apr 9, 2025
@coderabbitai

coderabbitai Bot commented Apr 9, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This pull request updates several areas of the product catalog and validation logic. In the add-on modules, it renames method receivers and adds new methods for validation and data transformation. The service layer now features a dedicated type for managing add-on versions along with associated methods, and the plan service updates its pagination approach. Additionally, the models package has been extended with generic validator types and functions to support flexible multi-validator use.

Changes

File(s) Change Summary
openmeter/productcatalog/addon.go
openmeter/productcatalog/addon/addon.go
Renamed method receivers in Status and StatusAt; added ValidateWith and Publishable methods along with interface assertion variables; and introduced AsProductCatalogAddon for converting an add-on instance.
openmeter/productcatalog/addon/service/addon.go Introduced new type addonVersions with methods (Len, Less, Swap, Sort, Latest, HasDraft) to encapsulate add-on version management, and refactored service methods to use this type.
openmeter/productcatalog/plan/service/plan.go Removed fixed pagination parameters from the CreatePlan method, altering how plans are retrieved.
pkg/models/validator.go Added ValidatorFunc[T any] type, CustomValidator[T any] interface, and a generic Validate function to support multi-validator aggregation.

Possibly related PRs

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (1.64.8)

Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2
Failed executing command with error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ab82fac and 030c747.

📒 Files selected for processing (2)
  • openmeter/productcatalog/addon.go (4 hunks)
  • openmeter/productcatalog/addon/service/addon.go (18 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • openmeter/productcatalog/addon/service/addon.go
  • openmeter/productcatalog/addon.go
⏰ Context from checks skipped due to timeout of 90000ms (13)
  • GitHub Check: Artifacts / Container image
  • GitHub Check: Artifacts / Benthos Collector Container image
  • GitHub Check: Test
  • GitHub Check: Quickstart
  • GitHub Check: Migration Checks
  • GitHub Check: Lint
  • GitHub Check: E2E
  • GitHub Check: Developer environment
  • GitHub Check: CI
  • GitHub Check: Commit hooks
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Build
  • GitHub Check: Analyze (go)

🪧 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

@chrisgacsal chrisgacsal added the release-note/ignore Ignore this change when generating release notes label Apr 9, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
openmeter/productcatalog/addon/service/addon.go (1)

80-118: Good implementation of addonVersions with sort interface

The new addonVersions type with its related methods provides a clean abstraction for managing collections of addon versions. The implementation of the sort.Interface (Len, Less, Swap) is correct and the additional utility methods improve code readability.

However, there's a potential issue with the Latest() method:

  1. It assumes the collection is already sorted, but this is not enforced or documented
  2. It returns a pointer to an element in the slice, which could be problematic if the slice is modified later

Consider adding documentation to indicate that Latest() should only be called after Sort(), or have Latest() call Sort() internally:

// Latest returns add-on with the latest version regardless of its deleted status.
+// The collection should be sorted before calling this method, or you can call Sort() 
+// first to ensure correct ordering.
func (a addonVersions) Latest() *addon.Addon {
    if len(a) == 0 {
        return nil
    }
+   
+   // Ensure the collection is sorted
+   a.Sort()
    
    return &a[len(a)-1]
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between db92aff and 9bf6a8f.

📒 Files selected for processing (5)
  • openmeter/productcatalog/addon.go (4 hunks)
  • openmeter/productcatalog/addon/addon.go (1 hunks)
  • openmeter/productcatalog/addon/service/addon.go (18 hunks)
  • openmeter/productcatalog/plan/service/plan.go (0 hunks)
  • pkg/models/validator.go (1 hunks)
💤 Files with no reviewable changes (1)
  • openmeter/productcatalog/plan/service/plan.go
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: Artifacts / Container image
  • GitHub Check: Test
  • GitHub Check: Quickstart
  • GitHub Check: Migration Checks
  • GitHub Check: Lint
  • GitHub Check: E2E
  • GitHub Check: Developer environment
  • GitHub Check: CI
  • GitHub Check: Commit hooks
  • GitHub Check: Build
🔇 Additional comments (16)
openmeter/productcatalog/addon/addon.go (1)

46-51: Great implementation of the AsProductCatalogAddon conversion method

The method provides a clean transformation from the addon package's Addon type to the productcatalog package's Addon, with proper field mapping and reuse of the RateCards conversion method.

pkg/models/validator.go (3)

3-4: Good addition of the errors import

Properly importing the standard errors package to use errors.Join which provides cleaner error aggregation.


10-14: Well-designed generic validation interfaces

The generic ValidatorFunc and CustomValidator definitions provide a flexible, type-safe way to implement custom validation logic. This pattern will make validation more composable and reusable across different entity types.


16-26: Solid implementation of the generic Validate function

This function elegantly applies multiple validators and aggregates errors, making validation more modular. The implementation correctly handles the case when no errors are found by using NewNillableGenericValidationError.

openmeter/productcatalog/addon/service/addon.go (5)

120-133: Well-implemented getAddonVersions helper method

This method cleanly encapsulates the logic for retrieving addon versions, improving code reusability. The error handling is good with proper context in the error message.


148-162: Improved code with refactored version handling

The refactoring to use the new addonVersions type and its methods (HasDraft, Latest) has simplified the code and improved readability. The error handling is also more specific and informative.


217-221: Good use of the new validation framework

The code now uses the ValidateWith method with the WithAllowedAddonStatus validator, which makes the validation logic more explicit and maintainable. This approach will make it easier to add or modify validation rules in the future.


378-380: Improved validation with the Publishable method

Using the Publishable method for validation before publishing is a good approach that ensures all required validations are performed consistently. This encapsulates the validation logic in the model instead of the service.


476-480: Good use of ValidateWith with appropriate validators

The code correctly uses the ValidateWith method to validate that an addon can only be archived if it has the Active status. This makes the validation requirements explicit and maintainable.

openmeter/productcatalog/addon.go (7)

132-134: Improved receiver naming for better readability

Changing the receiver name from a to m in AddonMeta methods makes the code more descriptive and easier to understand, as it clearly refers to the AddonMeta type.


160-164: Good compile-time interface assertions

These assertions ensure that Addon implements the specified interfaces (Validator, CustomValidator, Equaler), which helps catch errors at compile time rather than runtime.


173-175: Well-implemented ValidateWith method

This method integrates nicely with the new validation framework, allowing for flexible validation of Addon instances using multiple validators.


204-213: Excellent Publishable validation method

The Publishable method provides a higher-level validation specifically for publishing scenarios. It applies multiple validators to ensure all requirements are met, which is a good example of composing validators for a specific use case.


246-255: Well-designed validator function for addon status

The WithAllowedAddonStatus validator function follows good functional programming patterns and provides clear error messages. It correctly uses the lo.Contains function for checking allowed statuses.


257-265: Good validator for billing cadence alignment

This validator ensures that all rate cards in an addon have aligned billing cadences, which is an important business rule. The error message is clear and informative.


267-284: Comprehensive validator for instance type constraints

This validator enforces complex business rules that prevent usage-based rate cards in multiple-instance addons. The switch statement handles all cases, including an explicit check for invalid instance types.

turip
turip previously approved these changes Apr 9, 2025
Comment thread openmeter/productcatalog/addon.go Resolved
@chrisgacsal
chrisgacsal force-pushed the refactor/productcatalog branch from ab82fac to 030c747 Compare April 9, 2025 09:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/ignore Ignore this change when generating release notes release-note/misc Miscellaneous changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants