Repository navigation
refactor(productcatalog): validation errors - #2895
Conversation
|
Caution Review failedThe pull request is closed. 📝 WalkthroughWalkthroughThis change systematically adds a Changes
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 📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (49)
✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 11
🔭 Outside diff range comments (5)
openmeter/productcatalog/http/mapping.go (4)
103-103:⚠️ Potential issueUse FromMetadata for consistency.
This line should use the new
FromMetadatafunction 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 suggestionUse FromAnnotations for metadata fields in entitlement templates.
The metadata fields in entitlement templates should use
FromAnnotationsinstead 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 suggestionUse
FromMetadatafor consistency.For consistency with line 70, use the
FromMetadatafunction instead of direct conversion.- Metadata: lo.EmptyableToPtr(api.Metadata(meta.Metadata)), + Metadata: FromMetadata(meta.Metadata),
278-278: 💡 Verification agent🧩 Analysis chain
Consider using
FromAnnotationsfor consistency.The entitlement template metadata fields are using direct conversion instead of the new
FromAnnotationsfunction. However, verify if these should useFromMetadataorFromAnnotationsbased 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.goecho
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
FromMetadatahelper for entitlement template metadataThe
metadatafields in the Metered, Static, and Boolean entitlement mappings should call the existingFromMetadatahelper instead of performing a directapi.Metadatacast. This ensures empty metadata is serialized asniland 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 issueRemove 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 ofvalidationErrorsinrequiredfor Plan schema
The same consideration from the Addon schema applies here—addingvalidationErrorstorequiredmandates 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
Addonschema 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 defaultingvalidationErrorsto an empty array
Currently,validationErrorsis marked asnullableso clients must handlenull. To simplify client logic and avoid null checks, you may adddefault: []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.ErrPhaseKeyOrPlanIDEmptyto 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
📒 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()toValidate()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 genericValidate()implementation invokes bothValidatePlanMeta()andValidatePlanPhases(), 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
validationErrorsfield 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
validationErrorsfield 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()toValidate()improves the error message with better context. However, please ensure that the newValidate()method includes all the validation checks that were previously performed byValidForCreatingSubscriptions(), 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 goLength 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 goLength 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." fiLength 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 checksI wasn’t able to locate the
Validate()implementation on theproductcatalog.Plantype. Please confirm that it fully replaces the oldValidForCreatingSubscriptions()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
CreateAddonandUpdateAddonhandlers 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:
- Is this the intended default behavior for all addon operations?
- Should this be configurable via API parameters instead of hardcoded?
- 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
expectedStringandexpectedJSONPathare 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()toValidate()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.ErrNamespaceEmptyandproductcatalog.ErrIDEmptyimproves 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 goLength of output: 5645
Approved: Error constants are properly defined
Verified that
productcatalog.ErrNamespaceEmptyandproductcatalog.ErrIDEmptyare defined inopenmeter/productcatalog/errors.goviamodels.NewValidationIssuewith 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
AddonWithAllowedStatustoValidateAddonWithStatusmakes 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:
- Adding temporal precision with
IsDeletedAt(at)to check deletion status at a specific time- 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
yesterdayvariable eliminates repetition and makes the test cases more readable.
20-23: Excellent enhancement to test validation error details.The addition of
ExpectedValidationIssuesand 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
ValidationIssuesand 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 = truein 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 thevalidationErrorsfield.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
ValidateWithand refactoring ofValidate()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()andValidatePhaseRateCards()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.ErrNamespaceEmptyandproductcatalog.ErrIDEmptymaintains 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 embeddedPhase, 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.ErrorWithFieldPrefixenhances error location reporting, making it easier to identify which field has validation issues.
391-391: Consistent use of error constants.Using
ErrEntitlementTemplateInvalidJSONConfiginstead of an inline error message maintains consistency with the validation error handling approach.openmeter/productcatalog/http/mapping.go (2)
926-943: LGTM!The
FromValidationErrorsfunction is well-implemented and properly uses the newFromAnnotationshelper.
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
ValidateWithmethods 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
ErrorWithFieldPrefixwith proper field selectors significantly improves error reporting by providing precise location information for validation failures.
595-623: Well-implemented collection validation function.The
ValidateRateCardsfunction 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.ErrorWithFieldPrefixandmodels.NewGenericValidationErrorprovides 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.IsEmptysimplifies 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
ValidationErrorsfield usinghttp.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 importedhttppackage improves code consistency and maintainability across the codebase.Also applies to: 31-33
api/openapi.cloud.yaml (2)
11219-11223: Confirm inclusion ofvalidationErrorsinrequiredfor Addon schema
AddingvalidationErrorsto therequiredlist will enforce that every Addon response includes this field (even ifnull). Please verify this aligns with the API contract; if it should be optional, consider removing it fromrequiredor defaulting it to an empty array.
19218-19225: Verify indentation and placement ofvalidationErrorsunder PlanPhase
ThevalidationErrorsproperty 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 therequiredlist 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.FromMetadatafunction for consistency across the codebase.openmeter/productcatalog/plan/service.go (4)
96-100: Well-designed input options for validation flexibility.The
inputOptionsstruct 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
IgnoreNonCriticalIssuesis 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
UpdatePlanInputvalidation follows the same robust pattern asCreatePlanInput, 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
inputOptionsembedding.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.ErrorWithFieldPrefiximproves error diagnostics significantly.openmeter/productcatalog/addon/service.go (5)
96-100: Good architectural choice for validation flexibility.The
inputOptionsstruct 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
IgnoreNonCriticalIssuesis 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 -5Length 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 || trueLength of output: 2713
No auto-generation detected—manual edits are safe
We searched for generation markers in
api/client/javascript/src/client/schemas.tsand 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 tovalidationErrorswon’t be overwritten.• File confirmed:
api/client/javascript/src/client/schemas.ts
• No OpenAPI-Generator, Swagger-Codegen, or related scripts/config found
• Nopackage.jsonscripts or headers indicating auto-generated codeYou can proceed with these changes as-is.
Likely an incorrect or invalid review comment.
api/openapi.yaml (2)
11074-11081: Verify schema reference forValidationError
The new property references#/components/schemas/ValidationError, but the PR narrative mentions a commonValidationIssuestructure. Confirm thatValidationErroris the correct, existing schema name.
19614-19621: Verify schema reference forValidationError
Ensure theValidationErrorschema is defined and aligned with backend models (e.g.ValidationIssue). Update the$refif the intended schema name differs.pkg/models/validationissue.go (2)
48-53: Good use of compile-time interface checks!These declarations ensure that
ValidationIssueproperly implements both theerrorandjson.Marshalerinterfaces at compile time.
284-347: Well-structured error unwrapping implementation!The refactored
asValidationIssuesfunction 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 refactoredValidate()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
%qverb 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 thatNamespacedID.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()inpkg/models/id.goonly checks for emptyNamespaceandID. The new explicit checks inopenmeter/productcatalog/plan/addon.gofully 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.ErrNamespaceEmptyandproductcatalog.ErrResourceNameEmptyimproves 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
WithAttrsreturns 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
Clonecreates 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.
408442b to
db2ecae
Compare
db2ecae to
6922060
Compare
Overview
Rework validation of CRUD inputs and resources in productcatalog:
ValidationIssuefor validation errorsvalidationErrorsfield 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