Repository navigation
feat(api): add validation errors to plan add-on assignment - #2820
Conversation
📝 Walkthrough""" WalkthroughThis change introduces structured validation error reporting for plan add-ons. It adds new types for validation errors and resources, updates schema definitions and OpenAPI specifications to include these errors, and refactors validation logic to generate and propagate detailed error information. Related API, client, and mapping code are updated to handle and expose these new error structures. 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
✨ 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 (
|
fb3fbe9 to
1aa56e2
Compare
There was a problem hiding this comment.
Actionable comments posted: 5
♻️ Duplicate comments (3)
api/spec/src/productcatalog/errors.tsp (1)
27-29: Comment left over fromannotationsThis comment appears to be referring to annotations rather than attributes, matching the previous review comment. Consider updating the documentation to be consistent with your terminology.
api/client/javascript/src/zod/index.ts (2)
6940-6942: Duplicate: apply shared description refactor.
Refer to the suggestion at lines 6406–6408 for extracting and refining thedueAfterdescription.
7271-7273: Duplicate: apply shared description refactor.
Refer to the suggestion at lines 6406–6408 for extracting and refining thedueAfterdescription.
🧹 Nitpick comments (15)
openmeter/productcatalog/resource_test.go (1)
80-80: Minor typo in assertion message.There's a small typo in the assertion message: "reource" should be "resource".
- assert.Equalf(t, tt.expectedPath, path, "reource path mismatch") + assert.Equalf(t, tt.expectedPath, path, "resource path mismatch")openmeter/productcatalog/planaddon/service/planaddon.go (2)
321-321: Fix typo in error message.There's a typo in the error message: "udpate" should be "update".
- fmt.Errorf("failed to udpate plan add-on assignment [namespace=%s plan.id=%s addon.id=%s]: %w", + fmt.Errorf("failed to update plan add-on assignment [namespace=%s plan.id=%s addon.id=%s]: %w",
333-334: Fix the same typo in this error message.The same typo exists here: "udpate" should be "update".
- return nil, fmt.Errorf("failed to udpate plan add-on assignment [namespace=%s plan.id=%s addon.id=%s]: %w", + return nil, fmt.Errorf("failed to update plan add-on assignment [namespace=%s plan.id=%s addon.id=%s]: %w",openmeter/productcatalog/ratecard.go (2)
636-644: Improved error reporting for price compatibility checksThese structured errors now provide detailed context about price compatibility issues. I particularly like the inclusion of specific information like the incompatible price types in the error detail.
Note that on line 652, there's an old error message that is still present before adding the new structured error on lines 653-661. Consider removing this line:
- errs = append(errs, errors.New("incompatible price payment terms"))Also applies to: 653-661, 663-671, 674-674
837-848: Duplicate error message in discount validationOn line 836, there's an old error message that's still present before adding the new structured error on lines 837-845. Consider removing this line:
- errs = append(errs, errors.New("percentage discount is not allowed"))api/openapi.yaml (1)
19497-19508: NewvalidationErrorsproperty is well-defined
The array ofValidationErrorobjects withnullable: trueandreadOnly: truecorrectly captures the optional error details. Consider adding adefault: []instead ofnullable: trueto convey “no errors” as an empty list rather than a null value.api/spec/src/productcatalog/errors.tsp (2)
34-36: Documentation mismatch for ValidationErrorThe documentation comment above
ValidationErrorincorrectly describes add-ons functionality rather than validation errors. This appears to be a copy-paste error as it doesn't match the model being defined.-/** - * Add-on allows extending subscriptions with compatible plans with additional ratecards. - */ +/** + * ValidationError represents a validation error for a specific resource. + */
58-58: Inconsistent use of semicolonsThere's an inconsistency in the use of semicolons - the
ValidationErrormodel ends with a semicolon while theValidationResourcemodel does not. Consider being consistent across model definitions.-}; +}openmeter/productcatalog/errors.go (2)
37-70: Consider adding documentation for the complex error unwrapping functionThe
UnwrapErrorsfunction handles different error wrapping patterns well, but its complexity merits some additional documentation to explain its behavior to developers who might not be familiar with Go's error wrapping concepts.-func UnwrapErrors[T InvalidResourceError](err error) []T { +// UnwrapErrors recursively extracts and returns all errors of type T from err. +// It handles both single error unwrapping (Unwrap() error) and multiple error +// unwrapping (Unwrap() []error), traversing the entire error tree. +func UnwrapErrors[T InvalidResourceError](err error) []T {
37-38: Consider making the generic constraint more flexibleThe generic constraint
T InvalidResourceErrorrestricts this function to only work withInvalidResourceErrortypes. If the intent is to make this utility more reusable, you might want to consider a more flexible constraint.-func UnwrapErrors[T InvalidResourceError](err error) []T { +func UnwrapErrors[T error](err error) []T {api/client/javascript/src/zod/index.ts (1)
6406-6408: Refine description grammar and consider DRY.The
.describe()text could be clearer (e.g., “only applicable to manual collection methods”) and this same description is repeated in three places. Consider extracting into a shared constant:-export const DUE_AFTER_DESCRIPTION = - "The period after which the invoice is due.\nWith some payment solutions it's only applicable to manual collection methods."; +export const DUE_AFTER_DESCRIPTION = + "The period after which the invoice is due. Only applicable to manual collection methods for certain payment solutions.";Then use
.describe(DUE_AFTER_DESCRIPTION).api/openapi.cloud.yaml (3)
19023-19023: AddvalidationErrorsto required PlanAddon properties
IncludingvalidationErrorsin therequiredlist ensures the field is always present in responses. However, since it’s markednullable: true, clients will need to handle bothnulland non-nullcases. Consider adding a default empty array (default: []) or revisiting thenullableflag to simplify client implementations.
19077-19077: Clarify description wording forversionproperty
The description “The version of the add-on which templates this instance.” is a bit unclear. Consider rephrasing to:
“The version of the add-on used to template this instance.”
19104-19112: DefinevalidationErrorsproperty in PlanAddon schema
This adds thevalidationErrorsarray referencingValidationError, marked read-only and nullable. To streamline client-side handling, you might set a default empty array (default: []) instead of allowingnull. Also verify the indentation aligns exactly with other properties underPlanAddon.openmeter/productcatalog/planaddon.go (1)
100-108: Update validation message or rule formaxQuantity(multiple-instance add-on)The logic only errors when
MaxQuantityis present and<= 0, but the detail says “must be set to positive number”.
Ifnilis meant to mean “unlimited”, the wording should reflect that; otherwise, the rule should also rejectnil.Example wording fix:
- Detail: "must be set to positive number for add-on with multiple instance type", + Detail: "if provided, must be a positive number for add-on with multiple instance type",
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (19)
api/api.gen.go(6 hunks)api/client/go/client.gen.go(7 hunks)api/client/javascript/src/client/schemas.ts(9 hunks)api/client/javascript/src/zod/index.ts(6 hunks)api/openapi.cloud.yaml(5 hunks)api/openapi.yaml(5 hunks)api/spec/src/productcatalog/errors.tsp(1 hunks)api/spec/src/productcatalog/main.tsp(1 hunks)api/spec/src/productcatalog/planaddon.tsp(3 hunks)openmeter/productcatalog/addon/service/addon.go(2 hunks)openmeter/productcatalog/errors.go(1 hunks)openmeter/productcatalog/errors_test.go(1 hunks)openmeter/productcatalog/planaddon.go(2 hunks)openmeter/productcatalog/planaddon/httpdriver/mapping.go(3 hunks)openmeter/productcatalog/planaddon/service/planaddon.go(2 hunks)openmeter/productcatalog/ratecard.go(9 hunks)openmeter/productcatalog/resource.go(1 hunks)openmeter/productcatalog/resource_test.go(1 hunks)openmeter/subscription/addon/extend_test.go(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (5)
openmeter/subscription/addon/extend_test.go (1)
openmeter/productcatalog/ratecard.go (2)
FlatFeeRateCard(215-222)RateCardMeta(52-83)
openmeter/productcatalog/resource_test.go (1)
openmeter/productcatalog/resource.go (1)
Resource(10-15)
openmeter/productcatalog/resource.go (2)
pkg/models/validator.go (1)
Validate(16-26)pkg/models/error.go (1)
NewNillableGenericValidationError(129-135)
api/api.gen.go (4)
api/client/javascript/src/client/schemas.ts (3)
ValidationError(10824-10824)ValidationResource(10828-10828)Annotations(10284-10284)api/client/go/client.gen.go (3)
ValidationError(6377-6386)ValidationResource(6429-6438)Annotations(941-941)openmeter/ent/db/ent.go (1)
ValidationError(255-258)openmeter/productcatalog/resource.go (1)
Resource(10-15)
api/client/go/client.gen.go (4)
api/client/javascript/src/client/schemas.ts (3)
ValidationError(10824-10824)ValidationResource(10828-10828)Annotations(10284-10284)api/api.gen.go (3)
ValidationError(6954-6963)ValidationResource(7006-7015)Annotations(1026-1026)openmeter/ent/db/ent.go (1)
ValidationError(255-258)openmeter/productcatalog/resource.go (1)
Resource(10-15)
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: CI
- GitHub Check: Analyze (go)
🔇 Additional comments (58)
api/spec/src/productcatalog/main.tsp (1)
18-18: Import for new error handling module looks good.The addition of the
./errors.tspimport enables the use of the newly introducedValidationErrorandValidationResourcemodels, supporting structured validation error reporting for plan add-ons.openmeter/subscription/addon/extend_test.go (1)
160-160: Test case updated to match new error message format.The error message expectation has been updated from "incompatible rate card keys" to "key mismatch between ratecards", reflecting improvements in error messaging for validation errors.
Also applies to: 168-168
openmeter/productcatalog/addon/service/addon.go (3)
130-131: Improved error classification using structured error types.Replacing generic errors with
models.NewGenericValidationErrorimproves error classification and provides better error handling for missing billing cadence in UsageBasedRateCard.
138-139: Consistent error typing for unsupported rate card types.Using
models.NewGenericValidationErrorfor unsupported RateCard types maintains consistency in error handling and improves error classification throughout the codebase.
147-148: Appropriate error classification for not found conditions.Switching to
models.NewGenericNotFoundErrorfor missing features provides clearer error classification and aligns with the error handling improvements in the product catalog.openmeter/productcatalog/resource_test.go (1)
9-83: Comprehensive test coverage for Resource path construction.This test thoroughly verifies the
AsPathmethod functionality across multiple scenarios:
- Resources without parents
- Resources with single parent
- Resources with attributes (confirming attributes don't affect the path)
- Resources with multiple nested parents
The test cases ensure that resource paths are correctly constructed for all expected use cases, which is essential for proper resource identification in validation errors.
openmeter/productcatalog/planaddon/service/planaddon.go (2)
128-130: Validation logic has been refactored appropriately.The explicit validation of plan add-on assignments has been moved elsewhere, aligning with the broader refactoring of validation logic into centralized components. This change promotes better separation of concerns.
325-330: Validation logic now delegated to the adapter layer.The service layer now focuses solely on orchestration, while the validation has been moved to the adapter layer, maintaining the debug log for traceability. This improves separation of concerns.
openmeter/productcatalog/errors_test.go (1)
11-252: Well-structured and comprehensive test suite for error unwrapping.This test suite thoroughly covers the
UnwrapErrorsfunction with a wide range of scenarios including:
- Handling nil errors
- Unwrapping single errors
- Processing errors wrapped with fmt.Errorf
- Handling errors.Join scenarios
- Extracting nested errors
- Processing complex parent-child resource relationships
The table-driven test pattern is effectively implemented with descriptive test cases and comprehensive assertions.
api/spec/src/productcatalog/planaddon.tsp (3)
79-84: Good addition of structured validation errors.The addition of the
validationErrorsfield allows for detailed validation feedback to be returned to API clients. The field is properly defined with:
- Appropriate read-only visibility
- Clear type definition (array or null)
- Good documentation
This enhancement will significantly improve the developer experience by providing specific validation context instead of generic error messages.
8-8: Documentation comment fixed.The comment now correctly identifies this as a "PlanAddon" instead of "AddonAssignment," ensuring consistency with the model name.
49-49: Documentation consistency improved.The documentation now uses lowercase "add-on" for consistency with the rest of the codebase.
openmeter/productcatalog/resource.go (3)
10-15: Well-designed Resource struct for hierarchical resources.The
Resourcestruct provides a solid foundation for representing hierarchical resources with:
- Parent reference for nested resources
- Key and Kind fields for identification
- Support for additional attributes
This structure enables detailed context for validation errors.
17-27: Clean implementation of path generation.The
AsPath()method effectively constructs path representations for resources by:
- Recursively including parent paths
- Appending the current resource's kind and key
- Joining with slashes for a clean hierarchical representation
This provides a human-readable identifier for resources in error messages.
29-42: Effective validation implementation.The
Validate()method follows established validation patterns in the codebase:
- Collects errors for missing required fields
- Uses
errors.Jointo combine multiple errors- Returns nil when validation passes via
NewNillableGenericValidationErrorThis implementation ensures resources are properly defined before use.
openmeter/productcatalog/ratecard.go (5)
611-618: Great implementation of structured validation errors!The change from generic error messages to structured
InvalidResourceErrorprovides much better context for validation failures. This will improve the developer experience by giving clearer information about what went wrong and where.
685-693: Structured errors for feature key validation - looks goodThis change provides clear context about feature key compatibility issues, including the specific mismatched values in the error detail.
706-714: Structured error implementation for feature ID validationConsistent with the other validation functions, this change enhances error reporting for feature ID mismatches.
730-761: Comprehensive error handling for billing cadence validationThe structured errors now provide specific details about billing cadence mismatches, including the actual vs expected values. This covers all possible mismatch scenarios:
- Base has billing cadence but overlay doesn't
- Both have billing cadence but they're not equal
- Base doesn't have billing cadence but overlay does
Using
errors.Join()allows multiple validation errors to be returned together, which is a good practice.Also applies to: 763-763
777-824: Well-structured entitlement template validation errorsThis implementation provides detailed error messages for various entitlement template compatibility issues, with specific field names and values in the error details. Good job handling the different entitlement types and their validation conditions.
api/client/go/client.gen.go (7)
5031-5032: Documentation clarity improvedThe comment now more clearly describes that
PlanAddonrepresents the association between a plan and an add-on, which improves code readability and understanding.
5044-5046: Documentation clarity improvedThe added comment clarifies that the
Versionfield refers to the version of the add-on which templates this instance, providing better context for developers using this API.
5069-5071: Key addition: validation errors field to PlanAddon structAdded a new
ValidationErrorsfield to thePlanAddonstruct which enables the structured reporting of validation errors. This field implementation (as a pointer to a slice) follows the Go idiom for optional JSON fields.
6376-6386: New ValidationError type for structured error reportingThis new type implements the structured validation error reporting as described in the PR objectives. The type includes fields for error detail, affected field, and resource information, providing comprehensive context for validation errors.
The implementation aligns with the corresponding structures in
api/api.gen.goand matches the TypeScript definitions, ensuring consistency across the API surface.
6428-6438: New ValidationResource type for attaching resource context to errorsThis type captures resource metadata including attributes, key, and kind, allowing validation errors to precisely identify which resource is affected and its context. The type structure aligns with the main API implementation in
api/api.gen.go.
39057-39066: Certificate/binary data updatedChanges to these string literals appear to be updates to binary data, likely certificates or security-related information that's embedded in the client.
Also applies to: 39079-39120
39121-39175: Generated client code updatedThese changes to the generated client code reflect the API specification updates. The Swagger definition has been regenerated to include the new validation error types and resource information.
api/openapi.yaml (2)
19470-19476: Description update is clear and consistent
The new description uses “add-on” uniformly and accurately conveys the purpose of this field. LGTM.
22380-22402:ValidationResourceschema looks correct
The required fields (key,kind) and optionalattributesare properly modeled, and the description accurately reflects its purpose. LGTM.api/spec/src/productcatalog/errors.tsp (4)
1-6: Model structure looks goodThe imports and namespace declaration are well-organized, providing a clear structure for the validation error models.
11-32: ValidationResource model looks well-structuredThe
ValidationResourcemodel is well-defined with appropriate properties and documentation. The use of@visibilityand@exampleannotations provides clear guidance for API consumers.
37-58: ValidationError model implementation looks goodApart from the documentation issue mentioned earlier, the
ValidationErrormodel itself is well-structured with clear property definitions and appropriate annotations.
31-31:Details
✅ Verification successful
Verify the Annotations type
The
Annotationstype is used here but not explicitly defined in this file. Ensure it's properly defined in one of the imported files (likely in "../types.tsp").
🏁 Script executed:
#!/bin/bash # Check if the Annotations type is defined in the imported files echo "Searching for Annotations type definition..." grep -r "model Annotations" api/spec/srcLength of output: 184
Annotations type confirmed
TheAnnotationsmodel is defined in api/spec/src/types.tsp and is correctly imported in api/spec/src/productcatalog/errors.tsp. No changes needed.api/api.gen.go (6)
5492-5492: Improved documentation clarity for PlanAddon structThe updated comment provides a more precise description of what the PlanAddon represents in the system.
5505-5506: Clear description of the version field's purposeThe comment explains that the version relates to the template for the add-on instance, which helps API consumers understand the versioning model.
5531-5532: Good addition of ValidationErrors field to support error reportingThis new field enables the API to return structured validation errors for plan add-ons, aligning with the PR objective to enhance validation error reporting for plan add-on assignments.
6953-6963: Well-structured ValidationError type with appropriate fieldsThe ValidationError type includes all necessary components for comprehensive error reporting:
- A detailed error description
- The specific field causing the error
- Resource context information
This structure will provide clear guidance to API consumers about compatibility issues between plans and add-ons.
7005-7015: Appropriate structure for ValidationResourceThe ValidationResource type provides the necessary context about the resource with validation errors:
- Optional attributes for system-managed metadata
- Resource key for identification
- Resource kind for type information
This complements the ValidationError type and matches the structure from
openmeter/productcatalog/resource.go.
18772-19244: Auto-generated content updated to reflect the model changesThe encoded content appears to be auto-generated from the API definition and has been updated to incorporate the new validation error structures. This ensures consistency between the API models and documentation.
openmeter/productcatalog/planaddon/httpdriver/mapping.go (4)
32-32: New validation error handling looks goodThis adds validation error handling to the API response, which aligns well with the PR objectives of enhancing plan add-on validation error reporting.
38-58: Well-implemented validation error mapping functionThe
FromValidationErrorsfunction correctly transforms internal validation errors to API representations. The nil check for empty error slices is a good practice that prevents returning empty arrays in the API response.
60-63: Good update to return nil rather than empty pointersReturning nil instead of empty pointers for annotations is more consistent with Go idioms and will result in
nullrather than{}in JSON responses, making the API more consistent.
79-82: Good update to return nil rather than empty pointersSimilar to the annotations change, returning nil instead of empty pointers for metadata is a good practice that improves API consistency.
openmeter/productcatalog/errors.go (2)
9-15: Well-structured validation error typeThe
InvalidResourceErrortype is well-designed with appropriate fields for resource information, invalid field, and detailed error message. The compile-time interface check is a good practice.
17-27: Comprehensive error message formattingThe
Errormethod produces detailed error messages that include all relevant context about the validation error, which will be helpful for debugging.api/client/javascript/src/zod/index.ts (3)
5178-5178: Approve updated default dueAfter duration.Changing the
updateInvoiceBodyWorkflowWorkflowInvoicingDueAfterDefaultfrom'P1W'to'P30D'aligns with the updated billing policy for a 30-day period. No issues detected.
6688-6688: Approve new billing profile collection interval default.Setting
createBillingProfileBodyWorkflowCollectionIntervalDefaultto'PT1H'correctly adjusts the collection interval to every hour. This matches the intended update.
7062-7062: Approve updated updateBillingProfile dueAfter default.Updating
updateBillingProfileBodyWorkflowInvoicingDueAfterDefaultto'P30D'maintains consistency with the invoice due period change.api/openapi.cloud.yaml (1)
21735-21756: AddValidationResourceschema
TheValidationResourceobject is correctly defined with requiredkeyandkindfields, plus optionalattributesvia theAnnotationsschema. The description accurately reflects its purpose in relation toValidationError. Looks good.openmeter/productcatalog/planaddon.go (1)
155-161: Potentially missing validation when add-on introduces unknown rate cardsThe current implementation silently skips add-on rate cards that are absent from the plan phase:
if !ok { continue }If an add-on is allowed to add new rate cards, this is fine.
If, however, every add-on rate card must correspond to a rate card on the plan, the lack of a validation error could allow incompatible combinations to slip through.Please verify the intended business rule and either:
- Keep the current behaviour and document that “extra” add-on rate cards are allowed, or
- Treat the absence as an
InvalidResourceError, e.g.:if !ok { errs = append(errs, InvalidResourceError{ Resource: addonResource, Field: "rateCards", Detail: fmt.Sprintf("rate card %q not present in plan phase", addonRateCard.Key()), }) continue }api/client/javascript/src/client/schemas.ts (8)
2794-2794: Default billing interval updated appropriately.The default billing period alignment interval has been changed from "PT2H" to "PT1H", which is a valid ISO8601 duration format representing 1 hour instead of 2 hours.
2830-2832: Invoice due period updated with improved documentation.The default invoice due period has been extended from "P1W" (1 week) to "P30D" (30 days), and helpful clarification has been added about its applicability with certain payment solutions. This change improves both the default value and the documentation clarity.
6321-6323: Consistent documentation update across duplicate schema references.The same documentation improvements to the invoice due period have been applied consistently across multiple schema definitions in the file.
7873-7873: Improved description of PlanAddon relationship.The documentation has been enhanced to clearly describe that PlanAddon represents the association between a plan and an add-on.
7924-7924: Clearer description of add-on version field.The documentation for the version field has been improved to clarify that it refers to the version of the add-on which templates this instance.
7945-7951: New validationErrors field added to support PR objectives.This is a key addition that implements the main PR objective - adding validation errors to plan add-on assignment. The field properly allows for either an array of validation errors or null, and is correctly marked as readonly since it will be populated by the system, not clients.
9947-9961: Well-structured ValidationResource schema added.The new ValidationResource schema is well-defined with appropriate fields for key, kind, and optional attributes. All properties are correctly marked as readonly and include helpful documentation and examples.
10824-10824: Type exports added for new validation schemas.Type aliases have been correctly added for the new ValidationError and ValidationResource schemas, following the pattern used for other schemas in the file.
Also applies to: 10828-10828
1aa56e2 to
ada588f
Compare
ada588f to
4001e27
Compare
There was a problem hiding this comment.
Caution
Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.
Actionable comments posted: 3
🔭 Outside diff range comments (3)
openmeter/productcatalog/addon/service/addon.go (2)
164-165: 🛠️ Refactor suggestionInconsistent error wrapping
Similar to line 130, this error for missing billing cadence should use models.NewGenericValidationError for consistency.
- return fmt.Errorf("billing cadence is required for usage-based rate card") + return models.NewGenericValidationError(fmt.Errorf("billing cadence is required for usage-based rate card"))
172-173: 🛠️ Refactor suggestionAnother inconsistent error wrapping
Similar to line 138, this error for unsupported RateCard type should use models.NewGenericValidationError for consistency.
- return fmt.Errorf("unsupported RateCard type: %s", rateCard.Type()) + return models.NewGenericValidationError(fmt.Errorf("unsupported RateCard type: %s", rateCard.Type()))openmeter/productcatalog/planaddon/service/planaddon.go (1)
132-138: 💡 Verification agent🧩 Analysis chain
Verify error handling behavior
Since validation is now delegated to the adapter layer, verify that any validation errors from the adapter are properly propagated to the client with the structured validation error format.
🏁 Script executed:
#!/bin/bash # Search for how validation errors are handled and transformed in the adapter implementation rg -A 10 "ValidationError" openmeter/productcatalog/planaddonLength of output: 4633
Verify propagation of adapter validation errors
The adapter’s
CreatePlanAddonreturns structured validation errors viamodels.NewGenericValidationError/NewNillableGenericValidationError, but in the service layer we unconditionally wrap all errors withfmt.Errorf(…%w). This wrapping will prevent the HTTP driver from recognizing and converting validation errors into the API’sValidationErrorpayload.• Service file:
openmeter/productcatalog/planaddon/service/planaddon.go
- Around line 132:
planAddon, err = s.adapter.CreatePlanAddon(ctx, params) if err != nil { return nil, fmt.Errorf( "failed to create plan add-on assignment [namespace=%s plan.id=%s addon.id=%s]: %w", params.Namespace, params.PlanID, params.AddonID, err, ) }- Fix: unwrap and re‐return adapter validation errors directly, e.g.:
if err != nil { - return nil, fmt.Errorf("failed to create plan add-on assignment …: %w", err) + var vErr *models.GenericValidationError + if errors.As(err, &vErr) { + return nil, err + } + return nil, fmt.Errorf("failed to create plan add-on assignment …: %w", err) }Please update the service to detect and propagate validation errors unchanged so the HTTP driver can map them to structured API errors.
♻️ Duplicate comments (5)
api/openapi.yaml (2)
19419-19419: RemovevalidationErrorsfrom required list
ThevalidationErrorsfield is defined as nullable and intended to be optional. Keeping it in therequiredarray contradicts its nullable design and forces clients to include it (even if null). Please removevalidationErrorsfrom the required properties.
22281-22303: FixValidationErrorschema description
Thedescriptioncurrently reads “Add-on allows extending subscriptions with compatible plans with additional ratecards,” which describes add-ons, not validation errors. Update it to something like:description: A structured error indicating why a plan add-on assignment failed validation.openmeter/productcatalog/planaddon.go (1)
88-95: Still combining status & effective-period validation — previous feedback not addressedAs raised earlier, lumping
Addon.Status()andAddon.EffectiveTounder the same"status"field obscures which property is actually wrong.
Splitting them gives callers actionable feedback.api/client/javascript/src/client/schemas.ts (1)
9882-9882: Fix incorrect documentation for ValidationError schema.The JSDoc comment for the ValidationError schema is incorrect - it's describing an add-on functionality rather than explaining what a validation error is.
-/** @description Add-on allows extending subscriptions with compatible plans with additional ratecards. */ +/** @description ValidationError captures information about a validation failure when associating plans and add-ons. */api/openapi.cloud.yaml (1)
21636-21658: Duplicate: fix incorrectValidationErrordescription.As noted in a previous review, the schema’s description is unrelated to validation errors. It should read something like:
@@ -21658 - description: Add-on allows extending subscriptions with compatible plans with additional ratecards. + description: A validation error detailing compatibility issues between a plan and its add-on.
🧹 Nitpick comments (14)
openmeter/productcatalog/resource_test.go (1)
80-80: Fix typo in error messageThere's a typo in the assertion message: "reource" should be "resource".
- assert.Equalf(t, tt.expectedPath, path, "reource path mismatch") + assert.Equalf(t, tt.expectedPath, path, "resource path mismatch")api/client/go/client.gen.go (1)
6376-6386: Fix comment for ValidationError struct.The comment for ValidationError appears to be describing add-ons rather than validation errors. It would be more appropriate to have a comment that describes what ValidationError represents.
-// ValidationError Add-on allows extending subscriptions with compatible plans with additional ratecards. +// ValidationError represents an error that occurred during validation of a plan add-on assignment. type ValidationError struct {openmeter/productcatalog/errors_test.go (2)
217-251: Consider adding a specific test case for empty result order preservationWhile your test suite is comprehensive, you might consider adding a specific test case that verifies the order of errors is preserved when unwrapping. Currently, you're checking that each expected error matches with the corresponding result error at the same index, which implies order preservation, but an explicit test case would make this requirement clearer.
227-249: Consider using testify's assert.ElementsMatch for more flexible assertionsFor cases where the order of errors might not matter, consider using
assert.ElementsMatchinstead of index-based comparisons. This would allow the test to pass even if theUnwrapErrorsfunction returns errors in a different order than expected.- if len(tt.expectedErrors) > 0 { - for i, expectedErr := range tt.expectedErrors { - // Check basic fields - assert.Equal(t, expectedErr.Field, result[i].Field) - assert.Equal(t, expectedErr.Detail, result[i].Detail) - - // Check resource fields - assert.Equal(t, expectedErr.Resource.Key, result[i].Resource.Key) - assert.Equal(t, expectedErr.Resource.Kind, result[i].Resource.Kind) - - // If there's a parent, check it too - if expectedErr.Resource.Parent != nil { - assert.NotNil(t, result[i].Resource.Parent) - assert.Equal(t, expectedErr.Resource.Parent.Key, result[i].Resource.Parent.Key) - assert.Equal(t, expectedErr.Resource.Parent.Kind, result[i].Resource.Parent.Kind) - } - - // Check attributes if they exist - if expectedErr.Resource.Attributes != nil { - assert.Equal(t, expectedErr.Resource.Attributes, result[i].Resource.Attributes) - } - } - } + // Only use this if the order of errors doesn't matter in your implementation + assert.ElementsMatch(t, tt.expectedErrors, result)If order matters in your implementation (which seems likely), then the current approach is appropriate. Either way, it would be helpful to document this requirement.
api/openapi.yaml (3)
19473-19473: Refineversionproperty description
The current description “The version of the add-on which templates this instance.” could be clearer. Consider rewording to:
“The version of the add-on template used for this instance.”
19500-19508: ImprovevalidationErrorsproperty description
Rather than “List of validation errors,” a more descriptive text will help API consumers understand the context. For example:
“An array of structured validation errors explaining why this plan–add-on assignment is invalid or incompatible.”
22380-22401: Add an example toValidationResourceschema
To improve clarity for API consumers, consider providing an example of aValidationResource, e.g.:example: key: "addon_123" kind: "PlanAddon" attributes: tier: "premium"api/spec/src/productcatalog/errors.tsp (1)
34-36: Docstring references the wrong conceptThe block comment still describes “Add-on” behaviour, but this file defines the
ValidationErrormodel.
Replace the sentence with something like “ValidationError represents a single validation failure attached to a specific catalog resource.” to prevent confusion for spec consumers and generated documentation.openmeter/productcatalog/errors.go (2)
18-26: Non-deterministic & verbose error string construction
Map iteration order over
r.Resource.Attributesis random; error messages (and therefore tests or logs) will vary run-to-run.
Sort the keys before appending for deterministic output.Using
%+vforr.Detailis unnecessary and slightly misleading –Detailis already a string.%sis clearer.Suggested patch:
- for k, v := range r.Resource.Attributes { - attrs = append(attrs, fmt.Sprintf("%s=%v", k, v)) + keys := make([]string, 0, len(r.Resource.Attributes)) + for k := range r.Resource.Attributes { + keys = append(keys, k) + } + slices.Sort(keys) + for _, k := range keys { + attrs = append(attrs, fmt.Sprintf("%s=%v", k, r.Resource.Attributes[k])) } - return fmt.Sprintf("invalid %q field of %s [%s]: %+v", r.Field, r.Resource.Kind, strings.Join(attrs, " "), r.Detail) + return fmt.Sprintf("invalid %q field of %s [%s]: %s", r.Field, r.Resource.Kind, strings.Join(attrs, " "), r.Detail)
37-70:UnwrapErrorsskips the current error when it also embeds childrenWhen
errboth satisfiesUnwrap() []errorand is itself anInvalidResourceError, the current implementation only dives into the children and never checks the parent.
Althougherrors.Join(Go 1.20+) doesn’t exhibit this dual-interface today, defensive handling is cheap:- if e, ok := err.(wrappedErrors); ok { - var targets []T + if e, ok := err.(wrappedErrors); ok { + // Check if the parent itself matches before descending. + if tgt := matchSelf[T](err); tgt != nil { + targets = append(targets, *tgt) + } + var targets []T for _, unwrappedErr := range e.Unwrap() { errs := UnwrapErrors[T](unwrappedErr) if len(errs) > 0 { targets = append(targets, errs...) } } return targets } - - target := new(T) - if errors.As(err, target) { - return []T{*target} - } + if tgt := matchSelf[T](err); tgt != nil { + return []T{*tgt} + } return nil } + +func matchSelf[T InvalidResourceError](err error) *T { + target := new(T) + if errors.As(err, target) { + return target + } + return nil +}This guarantees the top-level error is not silently dropped if Go ever introduces such an implementation.
openmeter/productcatalog/planaddon/httpdriver/mapping.go (3)
38-58: Pre-allocate the slice inFromValidationErrorsfor minor perf & GC winsThe function already knows the final length (
len(errs)), yet it relies on repeatedappendcalls that may trigger re-allocations.
Pre-allocating avoids that cost and is a one-liner change.- var result []api.ValidationError + result := make([]api.ValidationError, 0, len(errs))Everything else stays the same.
60-76: Redundant length check inFromAnnotationsAfter the early return, the second
if len(annotations) > 0is always true and therefore unnecessary noise.- 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 + }Same simplification can be applied to
FromMetadata.
78-94: Apply the same simplification toFromMetadataSee the explanation for
FromAnnotations; the logic here is identical.api/openapi.cloud.yaml (1)
19077-19077: Refine the description grammar.The phrase “which templates this instance” is slightly awkward. Consider clarifying that this version is used to template the instance.
- description: The version of the add-on which templates this instance. + description: The version of the add-on used to template this instance.
🛑 Comments failed to post (3)
api/api.gen.go (1)
6953-6963:
⚠️ Potential issueFix incorrect comment for ValidationError type
The comment for ValidationError doesn't describe what a validation error is - it seems to be describing what an add-on does.
-// ValidationError Add-on allows extending subscriptions with compatible plans with additional ratecards. +// ValidationError Represents a validation issue with a field of a resource. type ValidationError struct {📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.// ValidationError Represents a validation issue with a field of a resource. type ValidationError struct { // Detail The detailed description of the error. Detail string `json:"detail"` // Field The field of the resource the error relates to. Field string `json:"field"` // Resource The resource information. Resource ValidationResource `json:"resource"` }🤖 Prompt for AI Agents
In api/api.gen.go around lines 6953 to 6963, the comment for the ValidationError type incorrectly describes add-on functionality instead of what a validation error represents. Update the comment to accurately describe that ValidationError represents an error related to validation failures, detailing the error message, the field involved, and the resource context.openmeter/productcatalog/ratecard.go (1)
651-660: 🛠️ Refactor suggestion
Avoid duplicating generic and structured errors
errsgets both a genericerrors.New("incompatible price payment terms")and anInvalidResourceErrordescribing the very same condition.
This inflates the error list with two semantically-identical entries, forcing callers to deduplicate or ignore one of them.Diff showing one possible clean-up:
- if rFlat.PaymentTerm != vFlat.PaymentTerm { - errs = append(errs, errors.New("incompatible price payment terms")) - errs = append(errs, InvalidResourceError{ + if rFlat.PaymentTerm != vFlat.PaymentTerm { + errs = append(errs, InvalidResourceError{ Resource: Resource{ Key: r.base.Key(), Kind: "ratecard", }, Field: "price", Detail: fmt.Sprintf("incompatible price payment terms: %s, %s", rFlat.PaymentTerm, vFlat.PaymentTerm), }) }Removing the generic
errorkeeps the new structured contract clear and avoids redundant noise upstream.
Consider applying the same clean-up to the other validators that append both generic andInvalidResourceErrorentries.📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.if rFlat.PaymentTerm != vFlat.PaymentTerm { errs = append(errs, InvalidResourceError{ Resource: Resource{ Key: r.base.Key(), Kind: "ratecard", }, Field: "price", Detail: fmt.Sprintf("incompatible price payment terms: %s, %s", rFlat.PaymentTerm, vFlat.PaymentTerm), }) }🤖 Prompt for AI Agents
In openmeter/productcatalog/ratecard.go around lines 651 to 660, the code appends both a generic error and a structured InvalidResourceError for the same payment term incompatibility, causing redundant error entries. Remove the generic errors.New call and keep only the structured InvalidResourceError to maintain a clear and concise error list. Apply this cleanup consistently to other validators that similarly append both generic and structured errors.openmeter/productcatalog/planaddon.go (1)
126-143: 🛠️ Refactor suggestion
fromPlanPhaseerror should reference the plan resource, not the add-onThe missing phase belongs to the plan, yet the code reports the error on
addonResource.
Clients receiving this payload will mis-attribute the problem.- errs = append(errs, InvalidResourceError{ - Resource: addonResource, + errs = append(errs, InvalidResourceError{ + Resource: planResource, Field: "fromPlanPhase", Detail: fmt.Sprintf("plan does not have phase with key: %s", c.FromPlanPhase), })🤖 Prompt for AI Agents
In openmeter/productcatalog/planaddon.go around lines 126 to 143, the error for a missing phase incorrectly references the add-on resource instead of the plan resource. Update the error construction to use the plan resource identifier instead of addonResource for the Resource field in the InvalidResourceError to correctly attribute the error to the plan.
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
openmeter/productcatalog/planaddon.go (1)
79-95: Status and effectiveTo validation should be separatedThe current implementation still combines the status check and EffectiveTo check under a single error with the "status" field, which obscures the specific cause of the validation failure.
Split these checks into two distinct validations as suggested in the previous review:
-if c.Addon.Status() != AddonStatusActive || c.Addon.EffectiveTo != nil { - errs = append(errs, InvalidResourceError{ - Resource: addonResource, - Field: "status", - Detail: fmt.Sprintf("invalid status %s, add-on must be active", c.Addon.Status()), - }) -} +if c.Addon.Status() != AddonStatusActive { + errs = append(errs, InvalidResourceError{ + Resource: addonResource, + Field: "status", + Detail: fmt.Sprintf("invalid status %s, add-on must be active", c.Addon.Status()), + }) +} + +if c.Addon.EffectiveTo != nil { + errs = append(errs, InvalidResourceError{ + Resource: addonResource, + Field: "effectiveTo", + Detail: "add-on must have an open-ended effective period", + }) +}
🧹 Nitpick comments (3)
api/api.gen.go (2)
5531-5533: Consider using a slice (withomitempty) instead of a*[]forValidationErrorsUsing a pointer to a slice creates two “nil” states (
nilpointer vs. non-nil empty slice) that rarely convey additional semantic value but complicate marshaling/unmarshaling and testing. A plain slice is alreadynilwhen unset and keeps the API surface simpler.- // ValidationErrors List of validation errors. - ValidationErrors *[]ValidationError `json:"validationErrors"` + // ValidationErrors List of validation errors. + // Omit when no validation errors are present. + ValidationErrors []ValidationError `json:"validationErrors,omitempty"`If the OpenAPI spec genuinely requires the property to be present with a JSON
nullvalue, keeping the pointer is fine—but in most cases the more idiomatic approach above suffices and avoids an extra heap allocation.Ensure the OpenAPI schema does not mandate
"validationErrors": nullso that adoptingomitemptywill not cause contract breakage.
6953-6963: Minor nit: makeResourcea pointer for consistency with other optional fields
ValidationError’sResourcefield is compulsory according to the current tag, yet the comment does not indicate it is always present. If callers might omit it, switch to*ValidationResource(and addomitempty) to align with the handling ofAttributesinsideValidationResource.No change needed if the field is truly required.
openmeter/productcatalog/planaddon.go (1)
148-170: More efficient rate card validation with improved error handlingThe refactored rate card validation is more efficient by using a map for lookups instead of nested loops. The improved error reporting will help users understand compatibility issues between plan and add-on rate cards.
One suggestion: consider adding a structured
InvalidResourceErrorfor rate card compatibility issues instead of using a generic error withfmt.Errorf. This would maintain consistency with the rest of the validation.-if err := NewRateCardWithOverlay(phaseRateCard, addonRateCard).Validate(); err != nil { - errs = append(errs, fmt.Errorf("plan ratecard is not compatible with add-on ratecard [key=%s]: %w", - phaseRateCard.Key(), err)) -} +if err := NewRateCardWithOverlay(phaseRateCard, addonRateCard).Validate(); err != nil { + errs = append(errs, InvalidResourceError{ + Resource: Resource{ + Key: addonRateCard.Key(), + Kind: "ratecard", + Parent: &Resource{ + Key: c.Addon.Key, + Kind: "addon", + }, + }, + Field: "compatibility", + Detail: fmt.Sprintf("not compatible with plan rate card: %v", err), + }) +}
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (18)
api/api.gen.go(6 hunks)api/client/go/client.gen.go(11 hunks)api/client/javascript/src/client/schemas.ts(6 hunks)api/openapi.cloud.yaml(5 hunks)api/openapi.yaml(5 hunks)api/spec/src/productcatalog/errors.tsp(1 hunks)api/spec/src/productcatalog/main.tsp(1 hunks)api/spec/src/productcatalog/planaddon.tsp(3 hunks)openmeter/productcatalog/addon/service/addon.go(2 hunks)openmeter/productcatalog/errors.go(1 hunks)openmeter/productcatalog/errors_test.go(1 hunks)openmeter/productcatalog/planaddon.go(2 hunks)openmeter/productcatalog/planaddon/httpdriver/mapping.go(3 hunks)openmeter/productcatalog/planaddon/service/planaddon.go(2 hunks)openmeter/productcatalog/ratecard.go(9 hunks)openmeter/productcatalog/resource.go(1 hunks)openmeter/productcatalog/resource_test.go(1 hunks)openmeter/subscription/addon/extend_test.go(1 hunks)
✅ Files skipped from review due to trivial changes (1)
- api/spec/src/productcatalog/main.tsp
🚧 Files skipped from review as they are similar to previous changes (15)
- openmeter/productcatalog/resource_test.go
- openmeter/subscription/addon/extend_test.go
- openmeter/productcatalog/planaddon/service/planaddon.go
- api/spec/src/productcatalog/planaddon.tsp
- openmeter/productcatalog/planaddon/httpdriver/mapping.go
- openmeter/productcatalog/resource.go
- openmeter/productcatalog/addon/service/addon.go
- openmeter/productcatalog/ratecard.go
- openmeter/productcatalog/errors_test.go
- api/spec/src/productcatalog/errors.tsp
- api/openapi.yaml
- openmeter/productcatalog/errors.go
- api/client/javascript/src/client/schemas.ts
- api/client/go/client.gen.go
- api/openapi.cloud.yaml
🧰 Additional context used
🧬 Code Graph Analysis (1)
api/api.gen.go (5)
api/client/javascript/src/client/schemas.ts (3)
ValidationError(10824-10824)ValidationResource(10828-10828)Annotations(10284-10284)api/client/go/client.gen.go (3)
ValidationError(6377-6386)ValidationResource(6429-6438)Annotations(941-941)openmeter/billing/errors.go (1)
ValidationError(119-119)openmeter/ent/db/ent.go (1)
ValidationError(255-258)openmeter/productcatalog/resource.go (1)
Resource(10-15)
⏰ Context from checks skipped due to timeout of 90000ms (3)
- GitHub Check: CI
- GitHub Check: E2E
- GitHub Check: Analyze (go)
🔇 Additional comments (7)
api/api.gen.go (2)
5492-5495: Corrected doc-string reads better – thanks!Updating the comment to reference the proper
PlanAddontype eliminates previous confusion for readers and tooling that parse Go doc comments.
7005-7015: LGTM on the newValidationResourcestructureThe struct is clear, field names follow existing conventions, and the pointer on
Attributescorrectly marks it optional. Nice addition.openmeter/productcatalog/planaddon.go (5)
46-55: Good addition of a dedicated method for validation error extractionThe
ValidationErrors()method provides a clean interface for consumers to access structured validation errors without having to understand the internal error wrapping mechanisms. This improves the API usability.
62-65: Improved validation context with structured resource informationThe introduction of the
Resourcetype for plan validation provides much better context in error messages, making it easier to identify which resource has validation issues.Also applies to: 70-74
99-116: Good structured validation for instance types and max quantityThe switch statement provides clear, differentiated validation logic for different add-on instance types. The structured errors with specific field names and detailed messages will greatly help API consumers understand validation issues.
119-123: Proper structured error for currency mismatchThe currency validation now uses a structured error with a specific field name, which improves error clarity.
126-143: Improved phase validation with structured errorsUsing
lo.FindIndexOfsimplifies the code, and the structured error for missing plan phases provides better context for the validation failure.
Overview
Extend plan add-on assignments with validation errors describing compatibility issues between plans and add-ons.
Summary by CodeRabbit
New Features
Bug Fixes
Tests
Documentation