Skip to content

refactor(productcatalog): validation errors - #2895

Merged
chrisgacsal merged 4 commits into
mainfrom
refactor/productcatalog
May 28, 2025
Merged

chrisgacsal merged 4 commits into
mainfrom
refactor/productcatalog

Conversation

@chrisgacsal

@chrisgacsal chrisgacsal commented May 26, 2025 •

Copy link
Copy Markdown
Collaborator

Overview

Rework validation of CRUD inputs and resources in productcatalog:

  • adopt common ValidationIssue for validation errors
  • extend plan, addon with validationErrors field to provide more detailed errors and their locality
{
  "validationErrors": [
    {
      "code": "plan_has_last_phase_with_duration",
      "field": "$.phases[?(@.key=='pro')].duration",
      "message": "duration must not be set for the last plan phase"
    }
  ]
}

Summary by CodeRabbit

  • New Features
    • Validation errors are now included in API responses for Addon, Plan, PlanAddon, and related resources, enhancing feedback on configuration issues.
  • Bug Fixes
    • Added nil checks and refined error messages to prevent runtime panics and improve clarity.
    • Improved error handling in validation, including severity filtering and standardized error wrapping.
  • Refactor
    • Modularized and standardized validation logic across product catalog entities with reusable validator functions.
    • Centralized error encoding for HTTP handlers using a validation error encoder specific to resource kinds.
    • Enhanced error severity representation and field path handling with structured field selectors and JSONPath support.
    • Consolidated conversion functions for metadata, annotations, and validation errors for consistent API responses.
  • Documentation
    • Minor comment corrections for clarity.
  • Tests
    • Enhanced tests to verify detailed validation error content and improved error formatting.

@chrisgacsal chrisgacsal self-assigned this May 26, 2025
@chrisgacsal
chrisgacsal requested a review from a team as a code owner May 26, 2025 12:05
@chrisgacsal
chrisgacsal marked this pull request as draft May 26, 2025 12:05
@coderabbitai

coderabbitai Bot commented May 26, 2025 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

📝 Walkthrough

Walkthrough

This change systematically adds a validationErrors field to numerous resource schemas and models in the product catalog, updates validation logic to use structured error codes and severity levels, and refactors error handling for improved diagnostics. The update affects OpenAPI schemas, Go models, validation methods, and related HTTP mapping functions, ensuring consistent validation error reporting across the API.

Changes

Files/Paths Change Summary
api/client/javascript/src/client/schemas.ts
api/openapi.cloud.yaml
api/openapi.yaml
Added validationErrors (nullable, readonly array of ValidationError) to multiple resource schemas including Addon, Plan, and PlanAddon.
api/spec/src/productcatalog/addon.tsp
api/spec/src/productcatalog/plan.tsp
Added validationErrors property to Addon and Plan models, marked as read-only.
openmeter/productcatalog/addon.go Refactored validation logic, modularized validators, standardized error handling, added ValidationErrors() method.
openmeter/productcatalog/addon/httpdriver/addon.go
openmeter/productcatalog/plan/httpdriver/plan.go
Set IgnoreNonCriticalIssues = true in create/update request handlers for add-ons and plans; replaced generic error encoders with validation error encoders.
openmeter/productcatalog/addon/httpdriver/mapping.go
openmeter/productcatalog/plan/httpdriver/mapping.go
Populated ValidationErrors in API responses using new validation logic and centralized mapping helpers.
openmeter/productcatalog/addon/service.go
openmeter/productcatalog/plan/service.go
Embedded inputOptions with IgnoreNonCriticalIssues flag; updated validation to convert errors into ValidationIssues and filter by severity.
openmeter/productcatalog/addon/service/addon.go Updated to use new validation function for allowed status checks.
openmeter/productcatalog/discount.go Refactored discount validation, added composable validator functions, improved error context.
openmeter/productcatalog/effectiveperiod.go
openmeter/productcatalog/phase.go
openmeter/productcatalog/plan/phase.go
Added ValidateWith methods for composable validation; refactored validation logic to accumulate errors.
openmeter/productcatalog/effectiveperiod_test.go
openmeter/productcatalog/plan_test.go
Updated tests to use new validation methods and check for structured validation issues.
openmeter/productcatalog/entitlement.go Refactored validation logic for entitlements to aggregate and standardize error reporting.
openmeter/productcatalog/errors.go Replaced string-based errors with structured error codes/constants and ValidationIssue objects with severity and field metadata.
openmeter/productcatalog/http/mapping.go
openmeter/productcatalog/planaddon/httpdriver/mapping.go
Centralized model-to-API conversion functions for metadata, annotations, and validation errors.
openmeter/productcatalog/plan.go
openmeter/productcatalog/plan/plan.go
Added ValidationErrors() method to Plan; refactored validation into modular functions; removed deprecated methods.
openmeter/productcatalog/plan/adapter/phase.go
openmeter/productcatalog/plan/addon.go
Standardized validation error handling and messaging using predefined errors.
openmeter/productcatalog/plan/ratecard.go Standardized error reporting in rate card validation; removed redundant checks.
openmeter/productcatalog/plan/service/plan.go Updated plan publishing validation to use new validation method and improved error messages.
openmeter/productcatalog/plan/validators.go Updated validator naming/comments and improved deletion check logic.
openmeter/productcatalog/planaddon.go Refactored field prefix handling in validation errors to use new field selector constructs.
openmeter/productcatalog/planaddon_test.go Updated tests to use builder pattern for validation issues with field selectors and severity.
openmeter/productcatalog/price.go Added nil check to Price.Validate() to prevent panics; refined error messages.
openmeter/productcatalog/ratecard.go Added ValidateWith methods, improved error contextualization, and enhanced rate card validation.
openmeter/productcatalog/subscription/service/plan.go Switched plan validation to use new Validate() method.
openmeter/productcatalog/tax.go Updated struct comment for grammatical correctness.
pkg/models/error_test.go Deleted obsolete test for field path normalization.
pkg/models/errors.go
pkg/models/errors_test.go
Refactored error severity to int-based enum, added ErrorContext, updated error wrappers and tests.
pkg/models/fieldselector.go
pkg/models/fieldselector_test.go
Introduced FieldExpression interface, refactored field selector logic, expanded tests.
pkg/models/validationissue.go
pkg/models/validationissue_test.go
Made ValidationIssue fields private, added accessors, improved JSON serialization, updated tests.
openmeter/productcatalog/addon/httpdriver/errors.go
openmeter/productcatalog/plan/httpdriver/errors.go
openmeter/productcatalog/planaddon/httpdriver/errors.go
Removed obsolete error encoder functions; replaced with centralized validation error encoder.
openmeter/productcatalog/http/errors.go Added centralized ValidationErrorEncoder for HTTP handlers to encode validation issues with resource kind.
openmeter/productcatalog/http/resource.go Added ResourceKind type and constants for "plan" and "add-on" resource kinds.
openmeter/productcatalog/planaddon/httpdriver/planaddon.go Replaced generic error encoder with validation error encoder for plan add-ons.

Possibly related PRs

  • openmeterio/openmeter#2859: Related enhancements to the ValidationIssue type with cloning and chainable modifiers, complementing this PR's changes to validation issue structure and serialization.
  • openmeterio/openmeter#2842: Related work on validation error handling for plan add-ons, sharing schema and error representation improvements.
  • openmeterio/openmeter#2838: Introduces the structured validation error model and error wrapping framework used extensively in this PR for improved validation diagnostics.

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 408442b and 6922060.

📒 Files selected for processing (49)
  • api/client/javascript/src/client/schemas.ts (2 hunks)
  • api/openapi.cloud.yaml (4 hunks)
  • api/openapi.yaml (4 hunks)
  • api/spec/src/productcatalog/addon.tsp (1 hunks)
  • api/spec/src/productcatalog/plan.tsp (1 hunks)
  • openmeter/productcatalog/addon.go (4 hunks)
  • openmeter/productcatalog/addon/httpdriver/addon.go (10 hunks)
  • openmeter/productcatalog/addon/httpdriver/errors.go (0 hunks)
  • openmeter/productcatalog/addon/httpdriver/mapping.go (1 hunks)
  • openmeter/productcatalog/addon/service.go (8 hunks)
  • openmeter/productcatalog/addon/service/addon.go (3 hunks)
  • openmeter/productcatalog/discount.go (6 hunks)
  • openmeter/productcatalog/effectiveperiod.go (4 hunks)
  • openmeter/productcatalog/effectiveperiod_test.go (4 hunks)
  • openmeter/productcatalog/entitlement.go (3 hunks)
  • openmeter/productcatalog/errors.go (1 hunks)
  • openmeter/productcatalog/http/errors.go (1 hunks)
  • openmeter/productcatalog/http/mapping.go (2 hunks)
  • openmeter/productcatalog/http/resource.go (1 hunks)
  • openmeter/productcatalog/phase.go (3 hunks)
  • openmeter/productcatalog/plan.go (2 hunks)
  • openmeter/productcatalog/plan/adapter/phase.go (1 hunks)
  • openmeter/productcatalog/plan/addon.go (1 hunks)
  • openmeter/productcatalog/plan/httpdriver/errors.go (0 hunks)
  • openmeter/productcatalog/plan/httpdriver/mapping.go (3 hunks)
  • openmeter/productcatalog/plan/httpdriver/plan.go (12 hunks)
  • openmeter/productcatalog/plan/phase.go (3 hunks)
  • openmeter/productcatalog/plan/plan.go (2 hunks)
  • openmeter/productcatalog/plan/ratecard.go (1 hunks)
  • openmeter/productcatalog/plan/service.go (9 hunks)
  • openmeter/productcatalog/plan/service/plan.go (1 hunks)
  • openmeter/productcatalog/plan/validators.go (1 hunks)
  • openmeter/productcatalog/plan_test.go (3 hunks)
  • openmeter/productcatalog/planaddon.go (3 hunks)
  • openmeter/productcatalog/planaddon/httpdriver/errors.go (0 hunks)
  • openmeter/productcatalog/planaddon/httpdriver/mapping.go (2 hunks)
  • openmeter/productcatalog/planaddon/httpdriver/planaddon.go (6 hunks)
  • openmeter/productcatalog/planaddon_test.go (2 hunks)
  • openmeter/productcatalog/price.go (2 hunks)
  • openmeter/productcatalog/ratecard.go (20 hunks)
  • openmeter/productcatalog/subscription/service/plan.go (1 hunks)
  • openmeter/productcatalog/tax.go (1 hunks)
  • pkg/models/error_test.go (0 hunks)
  • pkg/models/errors.go (3 hunks)
  • pkg/models/errors_test.go (1 hunks)
  • pkg/models/fieldselector.go (3 hunks)
  • pkg/models/fieldselector_test.go (3 hunks)
  • pkg/models/validationissue.go (8 hunks)
  • pkg/models/validationissue_test.go (9 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in this 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.

@chrisgacsal chrisgacsal added area/api release-note/misc Miscellaneous changes labels May 26, 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: 11

🔭 Outside diff range comments (5)
openmeter/productcatalog/http/mapping.go (4)

103-103: ⚠️ Potential issue

Use FromMetadata for consistency.

This line should use the new FromMetadata function instead of direct conversion for consistency with the rest of the codebase.

Apply this diff:

-			Metadata:            lo.EmptyableToPtr(api.Metadata(meta.Metadata)),
+			Metadata:            FromMetadata(meta.Metadata),

278-278: 🛠️ Refactor suggestion

Use FromAnnotations for metadata fields in entitlement templates.

The metadata fields in entitlement templates should use FromAnnotations instead of direct conversion.

Apply this diff:

-			Metadata:                lo.EmptyableToPtr(api.Metadata(metered.Metadata)),
+			Metadata:                FromAnnotations(metered.Metadata),
-			Metadata: lo.EmptyableToPtr(api.Metadata(static.Metadata)),
+			Metadata: FromAnnotations(static.Metadata),
-			Metadata: lo.EmptyableToPtr(api.Metadata(boolean.Metadata)),
+			Metadata: FromAnnotations(boolean.Metadata),

Also applies to: 293-293, 307-307


103-103: 🛠️ Refactor suggestion

Use FromMetadata for consistency.

For consistency with line 70, use the FromMetadata function instead of direct conversion.

-			Metadata:            lo.EmptyableToPtr(api.Metadata(meta.Metadata)),
+			Metadata:            FromMetadata(meta.Metadata),

278-278: 💡 Verification agent

🧩 Analysis chain

Consider using FromAnnotations for consistency.

The entitlement template metadata fields are using direct conversion instead of the new FromAnnotations function. However, verify if these should use FromMetadata or FromAnnotations based on the actual types.

Also applies to: 293-293, 307-307


🏁 Script executed:

#!/bin/bash
# Check the actual types of metadata fields in entitlement templates
ast-grep --pattern 'type MeteredEntitlementTemplate struct {
  $$$
  Metadata $_
  $$$
}'

ast-grep --pattern 'type StaticEntitlementTemplate struct {
  $$$
  Metadata $_
  $$$
}'

ast-grep --pattern 'type BooleanEntitlementTemplate struct {
  $$$
  Metadata $_
  $$$
}'

Length of output: 3460


#!/bin/bash

Display relevant mapping code around the metadata conversion

echo "----- mapping.go (lines 250–330) -----"
sed -n '250,330p' openmeter/productcatalog/http/mapping.go

echo
echo "----- Conversion helpers in mapping.go -----"
grep -R "func FromAnnotations" -n openmeter/productcatalog/http/mapping.go || echo "no FromAnnotations found in mapping.go"
grep -R "func FromMetadata" -n openmeter/productcatalog/http/mapping.go || echo "no FromMetadata found in mapping.go"

echo
echo "----- Conversion helpers across the repo -----"
rg "func FromAnnotations" -n .
rg "func FromMetadata" -n . || echo "no FromMetadata helper found elsewhere"


🏁 Script executed:

#!/bin/bash
echo "----- mapping.go (lines 250–330) -----"
sed -n '250,330p' openmeter/productcatalog/http/mapping.go

echo
echo "----- Conversion helpers in mapping.go -----"
grep -R "FromAnnotations" -n openmeter/productcatalog/http/mapping.go || echo "no FromAnnotations found in mapping.go"
grep -R "FromMetadata" -n openmeter/productcatalog/http/mapping.go || echo "no FromMetadata found in mapping.go"

echo
echo "----- Conversion helpers across the repo -----"
rg "func FromAnnotations" -n .
rg "func FromMetadata" -n .

Length of output: 3691


Use FromMetadata helper for entitlement template metadata

The metadata fields in the Metered, Static, and Boolean entitlement mappings should call the existing FromMetadata helper instead of performing a direct api.Metadata cast. This ensures empty metadata is serialized as nil and keeps conversions consistent.

Locations to update:

  • openmeter/productcatalog/http/mapping.go: around line 278 (Metered)
  • openmeter/productcatalog/http/mapping.go: around line 293 (Static)
  • openmeter/productcatalog/http/mapping.go: around line 307 (Boolean)

Suggested changes:

 func FromEntitlementTemplate(t productcatalog.EntitlementTemplate) (api.RateCardEntitlement, error) {
     …
     case entitlement.EntitlementTypeMetered:
         err = result.FromRateCardMeteredEntitlement(api.RateCardMeteredEntitlement{
-            Metadata: lo.EmptyableToPtr(api.Metadata(metered.Metadata)),
+            Metadata: FromMetadata(metered.Metadata),
         })
     …

     case entitlement.EntitlementTypeStatic:
         err = result.FromRateCardStaticEntitlement(api.RateCardStaticEntitlement{
-            Metadata: lo.EmptyableToPtr(api.Metadata(static.Metadata)),
+            Metadata: FromMetadata(static.Metadata),
         })
     …

     case entitlement.EntitlementTypeBoolean:
         err = result.FromRateCardBooleanEntitlement(api.RateCardBooleanEntitlement{
-            Metadata: lo.EmptyableToPtr(api.Metadata(boolean.Metadata)),
+            Metadata: FromMetadata(boolean.Metadata),
         })
     …
pkg/models/validationissue_test.go (1)

209-231: ⚠️ Potential issue

Remove duplicate test case.

There are two test cases with the same name "mixed" which could cause confusion. The second one appears to be a duplicate and should be removed or renamed if it's testing a different scenario.

-		{
-			name: "mixed",
-			err: fmt.Errorf("test: %w",
-				errors.Join(
-					errors.New("error 1"),
-					NewValidationError("errcode1", "error message 1"),
-					NewValidationWarning("errcode2", "error message 2"),
-				),
-			),
-			expectError:    true,
-			expectedIssues: nil,
-		},
♻️ Duplicate comments (2)
api/openapi.cloud.yaml (1)

19108-19112: Duplicate: confirm inclusion of validationErrors in required for Plan schema
The same consideration from the Addon schema applies here—adding validationErrors to required mandates its presence on all Plan responses. Please verify this is intended.

api/client/javascript/src/client/schemas.ts (1)

7966-7972: Consistent implementation across schemas.

Good job maintaining consistency with the Addon schema implementation. The same documentation enhancement suggested above would apply here as well.

🧹 Nitpick comments (11)
openmeter/productcatalog/plan/validators.go (1)

13-13: Track the TODO items for consistent validator naming.

The TODO comments indicate planned renames to align with the productcatalog package conventions. This will improve consistency across the codebase.

Would you like me to create an issue to track these TODO items for future implementation?

Also applies to: 24-24

openmeter/productcatalog/http/mapping.go (2)

890-906: Simplify redundant length check in FromMetadata.

The function already checks for empty metadata on line 891, making the check on line 897 redundant.

Apply this diff to simplify the function:

 func FromMetadata(metadata models.Metadata) *api.Metadata {
 	if len(metadata) == 0 {
 		return nil
 	}
 
-	var result api.Metadata
-
-	if len(metadata) > 0 {
-		result = make(api.Metadata)
-
-		for k, v := range metadata {
-			result[k] = v
-		}
+	result := make(api.Metadata)
+	for k, v := range metadata {
+		result[k] = v
 	}
 
 	return &result
 }

908-924: Simplify redundant length check in FromAnnotations.

Similar to FromMetadata, this function has a redundant length check.

Apply this diff to simplify the function:

 func FromAnnotations(annotations models.Annotations) *api.Annotations {
 	if len(annotations) == 0 {
 		return nil
 	}
 
-	var result api.Annotations
-
-	if len(annotations) > 0 {
-		result = make(api.Annotations)
-
-		for k, v := range annotations {
-			result[k] = v
-		}
+	result := make(api.Annotations)
+	for k, v := range annotations {
+		result[k] = v
 	}
 
 	return &result
 }
openmeter/productcatalog/discount.go (1)

95-114: Consider validating the discount even when price is nil.

While the current implementation correctly identifies when a price is missing, consider continuing to validate the discount itself to catch all validation issues in a single pass:

 func UsageDiscountWithPrice(price *Price) models.ValidatorFunc[UsageDiscount] {
 	return func(d UsageDiscount) error {
 		var errs []error
 
+		if err := d.Validate(); err != nil {
+			errs = append(errs, err)
+		}
+
 		if price == nil {
 			// We cannot validate usage discount without a price.
-			return errors.New("price is required for usage discount")
+			errs = append(errs, errors.New("price is required for usage discount"))
+			return errors.Join(errs...)
 		}
 
-		if err := d.Validate(); err != nil {
-			errs = append(errs, err)
-		}
-
 		if price.Type() == FlatPriceType {
 			errs = append(errs, ErrUsageDiscountWithFlatPrice)
 		}
 
 		return errors.Join(errs...)
 	}
 }

This ensures all validation issues are reported together, improving the developer experience.

openmeter/productcatalog/addon/httpdriver/mapping.go (1)

17-18: Consider handling the error from ValidationErrors().

The code ignores the error returned by ValidationErrors(). While this might be intentional, it's worth checking if this error should be handled or logged:

-	validationIssues, _ := a.AsProductCatalogAddon().ValidationErrors()
+	validationIssues, err := a.AsProductCatalogAddon().ValidationErrors()
+	if err != nil {
+		// Log the error or handle it appropriately
+		// For now, we can continue with empty validation issues
+		validationIssues = nil
+	}
api/openapi.cloud.yaml (1)

11332-11339: Consider defaulting validationErrors to an empty array
Currently, validationErrors is marked as nullable so clients must handle null. To simplify client logic and avoid null checks, you may add default: [] so the field is always an array (possibly empty).

api/client/javascript/src/client/schemas.ts (1)

2227-2233: Consider enhancing the JSDoc documentation for better clarity.

The implementation is correct, but the JSDoc comment could be more descriptive to help API consumers understand when and how these validation errors are populated.

      /**
-      * Validation errors
-      * @description List of validation errors.
+      * Validation errors
+      * @description List of validation errors associated with this resource. Populated when the resource has validation issues that need attention. Each error includes details about the validation failure and its location within the resource.
       */
pkg/models/fieldselector.go (1)

27-42: Consider better handling of unsupported value types.

The valueString() method returns "!UNSUPPORTED" for unknown types, which could lead to invalid JSONPath expressions. Consider either panicking or returning an error instead.

Consider this alternative approach:

 func (f FieldAttrValue) valueString() string {
 	b := strings.Builder{}
 
 	switch v := f.value.(type) {
 	case int, int32, int64, float32, float64:
 		b.WriteString(fmt.Sprintf("%v", v))
 	case string:
 		b.WriteString(v)
 	case fmt.Stringer:
 		b.WriteString(v.String())
 	default:
-		b.WriteString("!UNSUPPORTED")
+		// Consider using reflection for other basic types
+		b.WriteString(fmt.Sprintf("%v", v))
 	}
 
 	return b.String()
 }
openmeter/productcatalog/plan/adapter/phase.go (2)

37-37: Consider using a predefined error constant for consistency.

While the error message is clear, consider defining a constant like productcatalog.ErrPhaseKeyOrPlanIDEmpty to maintain consistency with the other validation errors in this method.


45-45: Clear error message, but consider a predefined constant.

The error message "phase index must be greater than or equal to 0" is clear and specific. However, for consistency with the validation error pattern established in this PR, consider using a predefined error constant like productcatalog.ErrPhaseIndexInvalid.

pkg/models/validationissue_test.go (1)

121-147: Consider using the original field value for comparison.

Instead of hardcoding the expected field string, consider using the original field value for better maintainability.

-			assert.Equalf(t, "field", errTestValidationIssue.Field().String(), "path not must be overwritten in the source error")
+			assert.Equalf(t, NewFieldSelectors(NewFieldSelector("field")).String(), errTestValidationIssue.Field().String(), "path not must be overwritten in the source error")
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ff857f1 and 408442b.

📒 Files selected for processing (43)
  • api/client/javascript/src/client/schemas.ts (2 hunks)
  • api/openapi.cloud.yaml (4 hunks)
  • api/openapi.yaml (4 hunks)
  • api/spec/src/productcatalog/addon.tsp (1 hunks)
  • api/spec/src/productcatalog/plan.tsp (1 hunks)
  • openmeter/productcatalog/addon.go (4 hunks)
  • openmeter/productcatalog/addon/httpdriver/addon.go (2 hunks)
  • openmeter/productcatalog/addon/httpdriver/mapping.go (1 hunks)
  • openmeter/productcatalog/addon/service.go (8 hunks)
  • openmeter/productcatalog/addon/service/addon.go (3 hunks)
  • openmeter/productcatalog/discount.go (6 hunks)
  • openmeter/productcatalog/effectiveperiod.go (4 hunks)
  • openmeter/productcatalog/effectiveperiod_test.go (4 hunks)
  • openmeter/productcatalog/entitlement.go (3 hunks)
  • openmeter/productcatalog/errors.go (1 hunks)
  • openmeter/productcatalog/http/mapping.go (2 hunks)
  • openmeter/productcatalog/phase.go (3 hunks)
  • openmeter/productcatalog/plan.go (2 hunks)
  • openmeter/productcatalog/plan/adapter/phase.go (1 hunks)
  • openmeter/productcatalog/plan/addon.go (1 hunks)
  • openmeter/productcatalog/plan/httpdriver/mapping.go (3 hunks)
  • openmeter/productcatalog/plan/httpdriver/plan.go (2 hunks)
  • openmeter/productcatalog/plan/phase.go (3 hunks)
  • openmeter/productcatalog/plan/plan.go (2 hunks)
  • openmeter/productcatalog/plan/ratecard.go (1 hunks)
  • openmeter/productcatalog/plan/service.go (9 hunks)
  • openmeter/productcatalog/plan/service/plan.go (1 hunks)
  • openmeter/productcatalog/plan/validators.go (1 hunks)
  • openmeter/productcatalog/plan_test.go (3 hunks)
  • openmeter/productcatalog/planaddon.go (3 hunks)
  • openmeter/productcatalog/planaddon/httpdriver/mapping.go (2 hunks)
  • openmeter/productcatalog/planaddon_test.go (2 hunks)
  • openmeter/productcatalog/price.go (2 hunks)
  • openmeter/productcatalog/ratecard.go (20 hunks)
  • openmeter/productcatalog/subscription/service/plan.go (1 hunks)
  • openmeter/productcatalog/tax.go (1 hunks)
  • pkg/models/error_test.go (0 hunks)
  • pkg/models/errors.go (3 hunks)
  • pkg/models/errors_test.go (1 hunks)
  • pkg/models/fieldselector.go (3 hunks)
  • pkg/models/fieldselector_test.go (3 hunks)
  • pkg/models/validationissue.go (9 hunks)
  • pkg/models/validationissue_test.go (9 hunks)
💤 Files with no reviewable changes (1)
  • pkg/models/error_test.go
🧰 Additional context used
🧬 Code Graph Analysis (1)
openmeter/productcatalog/planaddon/httpdriver/mapping.go (1)
openmeter/productcatalog/http/mapping.go (3)
  • FromAnnotations (908-924)
  • FromMetadata (890-906)
  • FromValidationErrors (926-943)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: E2E
  • GitHub Check: CI
  • GitHub Check: Analyze (go)
🔇 Additional comments (90)
openmeter/productcatalog/tax.go (1)

35-35: Good documentation improvement!

The hyphenation of "provider-specific" correctly formats the compound adjective, improving grammatical accuracy.

openmeter/productcatalog/subscription/service/plan.go (1)

62-62:

Details

✅ Verification successful

Verify that the general validation is sufficient for subscription creation context.

The change from ValidForCreatingSubscriptions() to Validate() appears to be part of the validation standardization effort. However, the original method name suggests it may have contained specific validations for the subscription creation context.

Run the following script to check if there are any differences between the two validation methods:


🏁 Script executed:

#!/bin/bash
# Description: Compare the validation methods to ensure no critical checks are lost

# Search for the ValidForCreatingSubscriptions method definition
echo "Searching for ValidForCreatingSubscriptions method..."
ast-grep --pattern 'func $_ ValidForCreatingSubscriptions() $_'

# Search for any references to ValidForCreatingSubscriptions
echo -e "\nSearching for any remaining references to ValidForCreatingSubscriptions..."
rg "ValidForCreatingSubscriptions" -A 5

# Look for the Validate method on plan types
echo -e "\nSearching for Plan.Validate() method..."
ast-grep --pattern 'func ($_ Plan) Validate() error {
  $$$
}'

Length of output: 2058


Validation standardized and sufficient for subscription context

The ValidForCreatingSubscriptions() method no longer exists, and the generic Validate() implementation invokes both ValidatePlanMeta() and ValidatePlanPhases(), preserving all prior subscription‐creation checks. No additional, context-specific validations are lost.

  • Confirmed absence of ValidForCreatingSubscriptions()
  • func (p Plan) Validate() error { … } defined in:
    • openmeter/productcatalog/plan.go (lines 105–110)
    • openmeter/productcatalog/plan/plan.go (lines 36–41)
api/spec/src/productcatalog/addon.tsp (1)

98-103: LGTM! Validation errors field properly added.

The validationErrors field is correctly implemented with:

  • Read-only visibility (Lifecycle.Read)
  • Proper nullable array type
  • Clear documentation

This addition aligns well with the PR's objective of enhancing validation error reporting.

api/spec/src/productcatalog/plan.tsp (1)

120-125: Consistent implementation of validation errors field.

The validationErrors field follows the same pattern as in the Addon model, ensuring consistency across the API. The implementation is correct with proper visibility and type annotations.

openmeter/productcatalog/plan/service/plan.go (1)

516-521:

Details

❓ Verification inconclusive

Verify that Validate() covers all subscription-related validations.

The change from ValidForCreatingSubscriptions() to Validate() improves the error message with better context. However, please ensure that the new Validate() method includes all the validation checks that were previously performed by ValidForCreatingSubscriptions(), particularly those specific to subscription creation scenarios.


🏁 Script executed:

#!/bin/bash
# Description: Search for the old ValidForCreatingSubscriptions method to understand what validations it performed

# Look for the ValidForCreatingSubscriptions method definition
ast-grep --pattern 'func $_ ValidForCreatingSubscriptions() $_'

# Also search with ripgrep for any references or implementations
rg -A 10 "ValidForCreatingSubscriptions" --type go

Length of output: 116


🏁 Script executed:

#!/bin/bash
# Locate the Validate method implementation in the codebase

# Using ast-grep to find all Validate() function definitions
ast-grep --pattern 'func $_ Validate() $$$'

# Using ripgrep to show context around Validate() calls
rg -A 10 "Validate()" --type go

Length of output: 77134


🏁 Script executed:

#!/bin/bash
set -e

# Locate the plan.go file under productcatalog/plan/service
plan_file=$(fd --full-path 'openmeter/productcatalog/plan/service/plan.go$' || echo "")
if [ -z "$plan_file" ]; then
  plan_file=$(fd 'plan.go$' | grep 'plan/service/plan.go' | head -n1)
fi
echo "Plan file: $plan_file"

# Show the PublishPlan method signature and its first lines
echo "--- PublishPlan signature and context ---"
rg -n 'func .*PublishPlan' "$plan_file" -A5 -B3

# Show lines 510–530 around the Validate call
echo "--- Lines 510–530 ---"
sed -n '510,530p' "$plan_file"

# Find where pp is initialized in PublishPlan
echo "--- pp initialization ---"
rg -n 'pp\s*:=' "$plan_file" -A3 -B3

# Derive the type name of pp
pp_type=$(grep -E 'pp\s*:=\s*' -m1 "$plan_file" | sed -E 's/.*pp\s*:=\s*([^ ]+).*/\1/')
echo "pp type: $pp_type"

# Locate the Validate() implementation on pp's type
if [ -n "$pp_type" ]; then
  echo "--- Validate() implementation for $pp_type ---"
  rg -R "func \([^)]+ $pp_type\) Validate" -A20 --type go
else
  echo "Could not determine pp type; manual inspection required."
fi

Length of output: 2983


🏁 Script executed:

#!/bin/bash
set -e

# Directory containing plan domain definitions
dir="openmeter/productcatalog/plan"

echo "🔍 Searching in $dir..."

# 1. Locate AsProductCatalogPlan method definition
echo "--- AsProductCatalogPlan definition ---"
rg -n "func .*AsProductCatalogPlan" -A3 -B1 "$dir"

# 2. Locate the ProductCatalogPlan type declaration
echo "--- ProductCatalogPlan type declaration ---"
rg -n "type .*ProductCatalogPlan" -A3 -B1 "$dir"

# 3. Locate Validate() implementation on ProductCatalogPlan
echo "--- Validate() on ProductCatalogPlan ---"
rg -n "func \(.*ProductCatalogPlan\) Validate" -A20 "$dir"

# 4. Search for any remnant of the old ValidForCreatingSubscriptions
echo "--- References to ValidForCreatingSubscriptions ---"
rg -n "ValidForCreatingSubscriptions" -A3 -B1 "$dir"

Length of output: 923


Verify productcatalog.Plan.Validate() for subscription‐specific checks

I wasn’t able to locate the Validate() implementation on the productcatalog.Plan type. Please confirm that it fully replaces the old ValidForCreatingSubscriptions() logic, in particular that it enforces:

  • Phase definitions (dates, ordering, no overlaps)
  • Billing intervals, currency and price requirements
  • Any limits or flags that must be set for a subscriptionable plan
  • Other domain‐specific invariants previously covered

Once you’ve ensured those checks are present in Validate(), this update can safely replace the old method.

pkg/models/errors_test.go (1)

1-67: Well-structured test coverage for error wrappers!

The test file properly validates the new error wrapper functionality with:

  • Complex nested field selectors with expressions
  • Component wrapping scenarios
  • Clear expected outputs
  • Good use of table-driven tests
openmeter/productcatalog/planaddon_test.go (2)

353-407: Good refactoring to use the new validation issue builder pattern!

The changes improve test clarity by:

  • Using structured field selectors with expressions for precise field identification
  • Making validation issues more expressive with the builder pattern
  • Properly setting severity levels to ErrorSeverityWarning

565-635: Consistent application of the validation issue builder pattern!

The refactoring maintains consistency with the previous test case, using the same structured approach for building validation issues with field selectors and expressions.

openmeter/productcatalog/addon/httpdriver/addon.go (1)

127-127: Verify the intention to ignore non-critical validation issues by default.

Both CreateAddon and UpdateAddon handlers now ignore non-critical validation issues. While this aligns with the PR's validation improvements, it changes the default validation behavior to be less strict.

Consider:

  1. Is this the intended default behavior for all addon operations?
  2. Should this be configurable via API parameters instead of hardcoded?
  3. Document this behavior in the API documentation so clients understand that warnings won't block operations.

Also applies to: 177-177

pkg/models/fieldselector_test.go (4)

14-17: LGTM! Clear and descriptive test struct fields.

The field names expectedString and expectedJSONPath are more explicit about what they represent compared to generic names, improving test readability.


27-29: Well-structured test cases for the new FieldSelector API.

The test cases properly exercise the new constructor pattern and expression-based filtering with both single and multiple field attributes.

Also applies to: 33-48


63-132: Excellent test coverage for the new FieldSelectors functionality.

The tests comprehensively cover:

  • Various selector combinations including wildcards and complex expressions
  • Prefix functionality for building nested paths
  • Both string representation and JSONPath generation

The use of dots (.) as separators aligns well with JSONPath syntax standards.


172-221: Great integration test validating JSONPath query execution.

This test provides valuable validation that the generated JSONPath expressions actually work against real JSON data. Using the RFC 9535 example data is a nice touch that follows standards.

The test cases effectively demonstrate both single and multi-attribute filtering capabilities.

openmeter/productcatalog/plan_test.go (1)

188-189: Good API simplification with the unified Validate() method.

The change from ValidForCreatingSubscriptions() to Validate() simplifies the API surface while maintaining the same validation logic. The updated error message assertion correctly validates the specific validation rule.

Also applies to: 238-239, 288-290

openmeter/productcatalog/plan/ratecard.go (1)

40-50:

Details

✅ Verification successful

Good standardization with predefined error constants.

Using productcatalog.ErrNamespaceEmpty and productcatalog.ErrIDEmpty improves error consistency across the codebase. The more descriptive error message for PhaseID provides better context.

Let me verify that these error constants are properly defined:


🏁 Script executed:

#!/bin/bash
# Description: Verify the error constants are defined in the productcatalog package
# Expected: Find definitions for ErrNamespaceEmpty and ErrIDEmpty

# Search for error constant definitions
rg -A 2 "ErrNamespaceEmpty|ErrIDEmpty" --type go

Length of output: 5645


Approved: Error constants are properly defined

Verified that productcatalog.ErrNamespaceEmpty and productcatalog.ErrIDEmpty are defined in openmeter/productcatalog/errors.go via models.NewValidationIssue with the correct error codes and messages. No further changes required.

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

341-341: Good naming improvement for validation functions.

The rename from AddonWithAllowedStatus to ValidateAddonWithStatus makes the function's purpose clearer and aligns with the validation naming conventions used throughout the codebase.

Also applies to: 440-440, 600-600

openmeter/productcatalog/plan/validators.go (1)

16-17: Good improvements to deletion validation.

The changes improve the validation by:

  1. Adding temporal precision with IsDeletedAt(at) to check deletion status at a specific time
  2. Aligning the error message format with camelCase field naming conventions
openmeter/productcatalog/plan/plan.go (1)

37-68: Excellent refactoring to modular validation pattern.

The refactoring improves the code by:

  • Separating validation concerns into focused, reusable functions
  • Following the established ValidatorFunc[T] pattern for consistency
  • Properly accumulating all validation errors in ValidatePlanPhases()

This aligns well with the PR objective of improving validation handling.

openmeter/productcatalog/effectiveperiod_test.go (3)

15-15: Good refactoring to improve readability.

Extracting the calculation into a yesterday variable eliminates repetition and makes the test cases more readable.


20-23: Excellent enhancement to test validation error details.

The addition of ExpectedValidationIssues and the specific validation issue checks significantly improve test coverage. This ensures that not only do errors occur when expected, but they also contain the correct error codes and attributes, which aligns perfectly with the PR's goal of improving validation error reporting.

Also applies to: 55-61, 69-75


81-86: Robust validation error verification.

The enhanced error checking that converts errors to ValidationIssues and compares them with expected values ensures comprehensive validation testing. This approach validates both the error occurrence and its detailed content.

openmeter/productcatalog/plan/httpdriver/plan.go (1)

127-128: LGTM! Consistent implementation of validation severity handling.

The addition of IgnoreNonCriticalIssues = true in both CreatePlan and UpdatePlan handlers aligns well with the new validation error severity system. This ensures that non-critical validation issues (warnings) won't block plan operations while still reporting them in the validationErrors field.

Also applies to: 177-178

openmeter/productcatalog/phase.go (5)

64-83: LGTM! Good use of error constants.

The migration from inline error creation to error constants improves consistency and maintainability across the codebase.


86-89: LGTM! Proper interface implementation.

Adding the models.CustomValidator[Phase] interface enables the new composable validation pattern.


98-117: Excellent refactoring to composable validation pattern.

The introduction of ValidateWith and refactoring of Validate() to use it creates a flexible validation system that allows for easy extension and testing of individual validation rules.


119-134: Well-structured validation functions.

The separation of validation logic into ValidatePhaseMeta() and ValidatePhaseRateCards() improves modularity and follows the single responsibility principle.


136-148: Good error handling with field selectors.

The ValidatePhaseHasBillingCadenceAligned() function properly uses field selectors to provide precise error location information, which aligns with the PR's goal of enhancing error reporting.

openmeter/productcatalog/plan/phase.go (5)

39-47: LGTM! Consistent use of error constants.

The use of productcatalog.ErrNamespaceEmpty and productcatalog.ErrIDEmpty maintains consistency with the error handling approach across the package.


58-61: Proper interface compliance.

The addition of models.CustomValidator[Phase] interface maintains consistency with the validation pattern.


91-100: LGTM! Consistent validation pattern.

The implementation mirrors the pattern from the productcatalog package, ensuring consistency across the codebase.


102-104: Useful accessor method.

The AsProductCatalogPhase() method provides clean access to the embedded Phase, improving API usability.


106-116: Well-structured validation functions.

The validation functions follow the same pattern as in the productcatalog package, promoting consistency.

openmeter/productcatalog/entitlement.go (3)

162-162: Good error message clarification.

The updated error message "invalid entitlement template type" is more precise and accurately describes what is being validated.


331-355: Excellent validation error handling improvement.

The refactoring to accumulate all validation errors instead of returning on the first error provides comprehensive feedback to users. The addition of field prefix using models.ErrorWithFieldPrefix enhances error location reporting, making it easier to identify which field has validation issues.


391-391: Consistent use of error constants.

Using ErrEntitlementTemplateInvalidJSONConfig instead of an inline error message maintains consistency with the validation error handling approach.

openmeter/productcatalog/http/mapping.go (2)

926-943: LGTM!

The FromValidationErrors function is well-implemented and properly uses the new FromAnnotations helper.


926-943: Clean implementation of validation error conversion!

The function properly handles empty issues and correctly uses getter methods to access the unexported fields of ValidationIssue.

pkg/models/errors.go (3)

296-313: Excellent refactoring of ErrorSeverity!

The change from string-based to int8-based enum with iota is a good improvement for type safety and performance. The String() method properly handles unknown values.


322-327: Good addition of ErrorContext struct.

The ErrorContext struct properly encapsulates all error-related context, improving code organization.


335-336: Well-implemented error formatting improvements.

The changes properly handle field selectors and component names in error messages, preventing unnecessary prefixes when components are empty.

Also applies to: 361-365

openmeter/productcatalog/ratecard.go (4)

176-178: Good addition of ValidateWith methods.

The consistent implementation of ValidateWith methods across all rate card types enables flexible validation with custom validator functions.

Also applies to: 310-312, 464-466, 591-593


185-224: Excellent error context improvements in RateCardMeta validation.

The use of ErrorWithFieldPrefix with proper field selectors significantly improves error reporting by providing precise location information for validation failures.


595-623: Well-implemented collection validation function.

The ValidateRateCards function properly validates the collection by checking for duplicate keys and validating each rate card with precise field context using key attributes.


666-668: Comprehensive error context improvements in overlay validators.

The enhanced field selectors with key attributes and proper nesting provide excellent error localization, making it much easier to identify exactly where validation failures occur.

Also applies to: 685-687, 717-719, 734-736, 753-755, 810-817, 832-845

openmeter/productcatalog/discount.go (5)

15-18: LGTM! Good addition of the CustomValidator interface.

Adding the models.CustomValidator[PercentageDiscount] interface enables more flexible validation patterns and aligns with the broader validation refactoring in this PR.


34-36: LGTM! Clean implementation of ValidateWith.

The method properly delegates to models.Validate, providing extensibility for custom validation scenarios.


38-46: LGTM! Proper percentage validation.

The validator correctly ensures the percentage is within the valid range [0, 100] and returns a descriptive error.


176-198: LGTM! Excellent error handling improvements.

The use of models.ErrorWithFieldPrefix and models.NewGenericValidationError provides clear field context for validation errors, making it easier to identify which specific field caused the issue.


237-239: LGTM! Good use of utility function.

Using lo.IsEmpty simplifies the implementation and maintains consistency with other parts of the codebase.

openmeter/productcatalog/addon/httpdriver/mapping.go (1)

19-35: LGTM! Proper integration of validation errors.

The addition of ValidationErrors field using http.FromValidationErrors() aligns perfectly with the PR's objective to enhance validation error reporting.

openmeter/productcatalog/planaddon/httpdriver/mapping.go (1)

10-10: LGTM! Good consolidation of conversion utilities.

The refactoring to use centralized conversion functions (http.FromAnnotations, http.FromMetadata, http.FromValidationErrors) from the imported http package improves code consistency and maintainability across the codebase.

Also applies to: 31-33

api/openapi.cloud.yaml (2)

11219-11223: Confirm inclusion of validationErrors in required for Addon schema
Adding validationErrors to the required list will enforce that every Addon response includes this field (even if null). Please verify this aligns with the API contract; if it should be optional, consider removing it from required or defaulting it to an empty array.


19218-19225: Verify indentation and placement of validationErrors under PlanPhase
The validationErrors property appears to be misaligned relative to its sibling keys (title, description). Ensure it’s defined under the correct object and adjust indentation to match other properties. Also confirm whether it needs to be added to the required list for this schema.

openmeter/productcatalog/plan/httpdriver/mapping.go (2)

29-29: Good improvements for consistency and error reporting.

The changes to use centralized metadata conversion and include validation errors in the response are well-aligned with the PR objectives.

Also applies to: 36-36


72-72: Consistent metadata conversion approach.

Good use of the centralized http.FromMetadata function for consistency across the codebase.

openmeter/productcatalog/plan/service.go (4)

96-100: Well-designed input options for validation flexibility.

The inputOptions struct provides a clean way to control validation severity filtering, allowing resources to be created with expected non-critical validation issues.


111-132: Excellent validation pattern implementation.

The validation method now properly:

  • Collects all validation errors before returning
  • Converts errors to structured validation issues
  • Filters by severity when IgnoreNonCriticalIssues is set
  • Uses proper error wrapping for non-validation errors

This provides better error reporting and flexibility.


207-246: Consistent validation pattern across input types.

The UpdatePlanInput validation follows the same robust pattern as CreatePlanInput, maintaining consistency across the codebase.


270-282: Consistent error handling across all validation methods.

All validation methods now follow a consistent pattern of collecting errors and returning structured validation errors. The methods that don't need severity filtering (Get, Delete, Publish, Archive, Next) appropriately omit the inputOptions embedding.

Also applies to: 288-300, 309-347, 357-378, 392-404

openmeter/productcatalog/planaddon.go (1)

65-119: Excellent error context improvements with field selectors.

The addition of field selectors throughout the validation logic provides precise error location information, making it much easier to identify which specific plan/addon combination and field is causing validation issues. The consistent use of models.ErrorWithFieldPrefix improves error diagnostics significantly.

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

96-100: Good architectural choice for validation flexibility.

The inputOptions struct provides a clean way to control validation behavior. The field name and comment clearly indicate its purpose.


107-109: Consistent application of validation options.

Good use of struct embedding to share the validation options across both create and update operations.

Also applies to: 162-164


111-132: Excellent refactoring of validation logic.

The changes improve error handling by:

  • Using predefined error constants for consistency
  • Converting to structured validation issues
  • Supporting severity-based filtering when IgnoreNonCriticalIssues is true
  • Properly wrapping errors for better error chain handling

202-243: Consistent validation pattern applied.

The validation logic follows the same improved pattern as CreateAddonInput, ensuring consistency across the service.


270-270: Consistent use of predefined error constants.

All validation methods now use predefined error constants instead of inline error messages, improving maintainability and ensuring consistent error messages across the codebase.

Also applies to: 274-274, 288-289, 292-293, 309-310, 313-314, 357-358, 361-362

openmeter/productcatalog/plan.go (5)

46-50: Useful addition for structured error reporting.

The ValidationErrors() method provides a convenient way to get validation issues in a structured format, which aligns with the overall validation improvements in this PR.


56-60: Clean separation of validation concerns.

Good extraction of metadata validation into a dedicated validator function.


62-103: Comprehensive and well-structured phase validation.

Excellent implementation that:

  • Validates phase structure requirements (duration for non-last phases)
  • Uses field selectors for precise error location reporting
  • Properly accumulates and joins errors
  • Conditionally validates billing cadence alignment

105-110: Clean and composable validation design.

The refactored method elegantly delegates to specialized validators, improving modularity and testability.


164-178: Consistent error handling improvements.

Good replacement of inline error messages with predefined constants (ErrCurrencyInvalid, ErrResourceKeyEmpty, ErrResourceNameEmpty), maintaining consistency with the rest of the codebase.

api/client/javascript/src/client/schemas.ts (1)

2227-2233:

Details

❌ Incorrect review comment

Verify that manual changes to auto-generated files are preserved.

This appears to be an auto-generated TypeScript client schema file. Please ensure that these manual changes won't be overwritten when the OpenAPI specification is regenerated. The proper approach would be to update the OpenAPI specification source and regenerate this file.


🏁 Script executed:

#!/bin/bash
# Description: Check if this is an auto-generated file and locate the OpenAPI spec source

# Check for generation markers or comments at the top of the file
head -20 api/client/javascript/src/client/schemas.ts | grep -i -E "(generated|auto|openapi|swagger)"

# Look for OpenAPI/Swagger specification files
fd -e yaml -e yml -e json | grep -E "(openapi|swagger|spec)" | head -10

# Check for code generation configuration or scripts
fd -e json | xargs grep -l "openapi-generator" 2>/dev/null | head -5

Length of output: 365


🏁 Script executed:

#!/bin/bash
# Inspect the header of the schemas.ts file for generation markers
echo "----- schemas.ts header -----"
head -50 api/client/javascript/src/client/schemas.ts

# Inspect api/spec package.json for any codegen scripts
echo "----- api/spec/package.json -----"
head -50 api/spec/package.json

# Inspect root package.json for codegen scripts
if [ -f package.json ]; then
  echo "----- root package.json -----"
  head -50 package.json
fi

# Search the repo for common TS OpenAPI codegen tools
rg "openapi-generator" -A3 || true
rg "swagger-codegen" -A3 || true
rg "openapi-typescript-codegen" -A3 || true
rg "@openapitools" -A3 || true

Length of output: 2713


No auto-generation detected—manual edits are safe

We searched for generation markers in api/client/javascript/src/client/schemas.ts and for any codegen scripts or dependencies in the repo—and found none. It appears this client schema file isn’t automatically regenerated in this repository, so your additions to validationErrors won’t be overwritten.

• File confirmed: api/client/javascript/src/client/schemas.ts
• No OpenAPI-Generator, Swagger-Codegen, or related scripts/config found
• No package.json scripts or headers indicating auto-generated code

You can proceed with these changes as-is.

Likely an incorrect or invalid review comment.

api/openapi.yaml (2)

11074-11081: Verify schema reference for ValidationError
The new property references #/components/schemas/ValidationError, but the PR narrative mentions a common ValidationIssue structure. Confirm that ValidationError is the correct, existing schema name.


19614-19621: Verify schema reference for ValidationError
Ensure the ValidationError schema is defined and aligned with backend models (e.g. ValidationIssue). Update the $ref if the intended schema name differs.

pkg/models/validationissue.go (2)

48-53: Good use of compile-time interface checks!

These declarations ensure that ValidationIssue properly implements both the error and json.Marshaler interfaces at compile time.


284-347: Well-structured error unwrapping implementation!

The refactored asValidationIssues function properly handles various error wrapping scenarios with recursive processing. The addition of prefix, component, and unknownAsValidationIssue parameters provides better context for error conversion.

pkg/models/fieldselector.go (2)

107-123: Clean singleton implementation for wildcard expressions!

The wildcard implementation correctly uses the singleton pattern and returns appropriate values for JSONPath expressions.


188-191: Appropriate JSON marshaling implementation!

Marshaling directly to the JSONPath string representation is the right approach for this use case.

openmeter/productcatalog/addon.go (2)

178-189: Excellent addition of structured validation error reporting!

The new ValidationErrors() method provides a clean way to get structured validation issues, and the refactored Validate() method properly delegates to modular validation functions.


272-283: Good use of field selectors for error context!

The implementation properly uses the new field selector mechanism to indicate that the error applies to all rate cards.

openmeter/productcatalog/price.go (4)

230-233: Good defensive programming practice!

Adding a nil check at the beginning of the Validate() method prevents potential runtime panics from nil pointer dereferences. This is a solid improvement for robustness.


246-246: Nice error message improvement!

Using the %q verb to quote the invalid price type makes the error message clearer and helps identify edge cases like empty strings.


230-233: Good defensive programming practice!

Adding a nil check prevents potential runtime panics when Validate() is called on a nil pointer. This aligns well with the PR's objective of improving validation error handling.


246-246: Nice improvement to error message clarity.

Adding quotes around the price type value makes the error message more readable and helps distinguish the actual value from the surrounding text.

openmeter/productcatalog/plan/addon.go (1)

24-30:

Details

✅ Verification successful

Verify completeness of validation replacement.

The explicit namespace and ID validation replaces the call to a.NamespacedID.Validate(). This change aligns well with the structured error approach using predefined error constants. However, please ensure that NamespacedID.Validate() doesn't perform any additional validation that should be preserved.

Run the following script to check what validation NamespacedID.Validate() performs:


🏁 Script executed:

#!/bin/bash
# Description: Check the implementation of NamespacedID.Validate() to ensure no validation logic is lost

# Find and display the NamespacedID type and its Validate method
ast-grep --pattern 'type NamespacedID struct {
  $$$
}'

echo "---"

# Find the Validate method for NamespacedID
ast-grep --pattern 'func ($_ NamespacedID) Validate() error {
  $$$
}'

Length of output: 725


Validation completeness confirmed

I’ve verified that NamespacedID.Validate() in pkg/models/id.go only checks for empty Namespace and ID. The new explicit checks in openmeter/productcatalog/plan/addon.go fully cover that logic (and even accumulate both errors), so nothing is missing.

openmeter/productcatalog/plan/adapter/phase.go (2)

33-33: Good use of predefined error constants!

Using productcatalog.ErrNamespaceEmpty and productcatalog.ErrResourceNameEmpty improves consistency across the codebase and aligns with the PR's goal of standardizing validation errors.

Also applies to: 41-41


48-48: Good standardization of error wrapping!

Wrapping the joined errors with models.NewNillableGenericValidationError() ensures consistent error formatting and aligns with the PR's goal of structured validation error reporting.

pkg/models/validationissue_test.go (4)

13-81: Well-structured JSON serialization tests!

The test cases comprehensively cover various ValidationIssue configurations, including empty, bare, generic, and with attributes scenarios. The expected JSON format is properly validated.


90-119: Good immutability test coverage!

The test properly verifies that WithAttrs returns a new instance without modifying the original, which is essential for the functional options pattern.


149-181: Thorough clone functionality test!

The test properly verifies that Clone creates an exact copy of the ValidationIssue, covering both populated and empty cases.


391-406: Good round-trip conversion test!

The test effectively verifies that ValidationIssues can be converted to an error and back without losing information.

Comment thread openmeter/productcatalog/errors.go Resolved
Comment thread openmeter/productcatalog/errors.go Resolved
Comment thread openmeter/productcatalog/errors.go Resolved
Comment thread api/openapi.yaml Resolved
Comment thread pkg/models/validationissue.go Resolved
Comment thread openmeter/productcatalog/addon.go Resolved
@chrisgacsal
chrisgacsal force-pushed the refactor/productcatalog branch from 408442b to db2ecae Compare May 26, 2025 14:53
@chrisgacsal
chrisgacsal force-pushed the refactor/productcatalog branch from db2ecae to 6922060 Compare May 28, 2025 12:12
@chrisgacsal
chrisgacsal marked this pull request as ready for review May 28, 2025 12:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/api release-note/misc Miscellaneous changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants