Skip to content

feat(api): add validation errors to plan add-on assignment - #2820

Merged
chrisgacsal merged 5 commits into
mainfrom
refactor/planaddon-comp
May 14, 2025
Merged

chrisgacsal merged 5 commits into
mainfrom
refactor/planaddon-comp

Conversation

@chrisgacsal

@chrisgacsal chrisgacsal commented May 14, 2025 •

Copy link
Copy Markdown
Collaborator

Overview

Extend plan add-on assignments with validation errors describing compatibility issues between plans and add-ons.

Summary by CodeRabbit

  • New Features

    • Added structured validation error reporting for plan add-ons, providing detailed error information related to specific resources and fields.
    • Introduced new validation error and resource models, enabling clients to receive comprehensive feedback on validation issues.
  • Bug Fixes

    • Improved consistency in documentation and field descriptions for plan add-ons and related schemas.
    • Enhanced error handling with more specific error types for rate card and plan add-on validations.
  • Tests

    • Added tests for extracting and reporting validation errors and for resource path construction logic.
    • Updated test expectations for rate card key mismatch error messages.
  • Documentation

    • Updated schema and model descriptions for clarity and accuracy.

@chrisgacsal chrisgacsal self-assigned this May 14, 2025
@coderabbitai

coderabbitai Bot commented May 14, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

"""

Walkthrough

This 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

Files / Areas Change Summary
api/api.gen.go, api/client/go/client.gen.go, api/client/javascript/src/client/schemas.ts Added ValidationError and ValidationResource types; updated PlanAddon to include optional validationErrors field; corrected comments and schema descriptions.
api/openapi.cloud.yaml, api/openapi.yaml Extended OpenAPI schemas for PlanAddon to include validationErrors; added ValidationError and ValidationResource schema definitions; updated some property descriptions.
api/spec/src/productcatalog/errors.tsp Introduced new TypeSpec models: ValidationResource and ValidationError for structured error reporting.
api/spec/src/productcatalog/planaddon.tsp Updated PlanAddon model comment; added optional validationErrors property; updated add-on version field description.
api/spec/src/productcatalog/main.tsp Imported new errors.tsp module for error models.
openmeter/productcatalog/resource.go Introduced Resource struct with hierarchy, attributes, and validation methods.
openmeter/productcatalog/errors.go Added InvalidResourceError type, error interface implementation, constructor, and generic UnwrapErrors function.
openmeter/productcatalog/planaddon.go Refactored validation logic to produce and aggregate InvalidResourceError instances; added ValidationErrors() method to extract errors.
openmeter/productcatalog/ratecard.go Updated rate card validation functions to return structured InvalidResourceError instead of generic errors.
openmeter/productcatalog/addon/service/addon.go Changed error returns to use structured validation and not-found error types.
openmeter/productcatalog/planaddon/httpdriver/mapping.go Updated mapping to include ValidationErrors in API output; added FromValidationErrors helper; improved handling of empty annotations/metadata.
openmeter/productcatalog/planaddon/service/planaddon.go Removed intermediate validation of constructed PlanAddon in service methods.
openmeter/productcatalog/resource_test.go, openmeter/productcatalog/errors_test.go Added tests for resource path construction and error unwrapping logic.
openmeter/subscription/addon/extend_test.go Updated test error message expectations for rate card key mismatch.

Possibly related PRs

  • openmeterio/openmeter#2635: Introduces the foundational PlanAddonAssignment type and validation logic, upon which this PR builds for enhanced validation error reporting.
  • openmeterio/openmeter#2689: Modifies plan status validation logic in PlanAddon.Validate(), related to validation but focusing on rules rather than error structure.
  • openmeterio/openmeter#2704: Removes explicit validation calls from plan add-on service methods, complementing this PR’s changes at validation and error reporting layers.
    """

Warning

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

🔧 golangci-lint (1.64.8)

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

[!ANNOUNCEMENT]

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


[!ANNOUNCEMENT]

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@chrisgacsal chrisgacsal added the release-note/misc Miscellaneous changes label May 14, 2025
Comment thread api/spec/src/productcatalog/errors.tsp Resolved
@chrisgacsal
chrisgacsal force-pushed the refactor/planaddon-comp branch from fb3fbe9 to 1aa56e2 Compare May 14, 2025 21:38
@chrisgacsal
chrisgacsal marked this pull request as ready for review May 14, 2025 21:41
@chrisgacsal
chrisgacsal requested a review from a team as a code owner May 14, 2025 21:41
tothandras
tothandras previously approved these changes May 14, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 5

♻️ Duplicate comments (3)
api/spec/src/productcatalog/errors.tsp (1)

27-29: Comment left over from annotations

This 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 the dueAfter description.


7271-7273: Duplicate: apply shared description refactor.
Refer to the suggestion at lines 6406–6408 for extracting and refining the dueAfter description.

🧹 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 checks

These 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 validation

On 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: New validationErrors property is well-defined
The array of ValidationError objects with nullable: true and readOnly: true correctly captures the optional error details. Consider adding a default: [] instead of nullable: true to convey “no errors” as an empty list rather than a null value.

api/spec/src/productcatalog/errors.tsp (2)

34-36: Documentation mismatch for ValidationError

The documentation comment above ValidationError incorrectly 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 semicolons

There's an inconsistency in the use of semicolons - the ValidationError model ends with a semicolon while the ValidationResource model does not. Consider being consistent across model definitions.

-};
+}
openmeter/productcatalog/errors.go (2)

37-70: Consider adding documentation for the complex error unwrapping function

The UnwrapErrors function 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 flexible

The generic constraint T InvalidResourceError restricts this function to only work with InvalidResourceError types. 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: Add validationErrors to required PlanAddon properties
Including validationErrors in the required list ensures the field is always present in responses. However, since it’s marked nullable: true, clients will need to handle both null and non-null cases. Consider adding a default empty array (default: []) or revisiting the nullable flag to simplify client implementations.


19077-19077: Clarify description wording for version property
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: Define validationErrors property in PlanAddon schema
This adds the validationErrors array referencing ValidationError, marked read-only and nullable. To streamline client-side handling, you might set a default empty array (default: []) instead of allowing null. Also verify the indentation aligns exactly with other properties under PlanAddon.

openmeter/productcatalog/planaddon.go (1)

100-108: Update validation message or rule for maxQuantity (multiple-instance add-on)

The logic only errors when MaxQuantity is present and <= 0, but the detail says “must be set to positive number”.
If nil is meant to mean “unlimited”, the wording should reflect that; otherwise, the rule should also reject nil.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 30dc43d and 1aa56e2.

📒 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.tsp import enables the use of the newly introduced ValidationError and ValidationResource models, 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.NewGenericValidationError improves 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.NewGenericValidationError for 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.NewGenericNotFoundError for 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 AsPath method 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 UnwrapErrors function 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 validationErrors field 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 Resource struct 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.Join to combine multiple errors
  • Returns nil when validation passes via NewNillableGenericValidationError

This 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 InvalidResourceError provides 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 good

This 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 validation

Consistent with the other validation functions, this change enhances error reporting for feature ID mismatches.


730-761: Comprehensive error handling for billing cadence validation

The structured errors now provide specific details about billing cadence mismatches, including the actual vs expected values. This covers all possible mismatch scenarios:

  1. Base has billing cadence but overlay doesn't
  2. Both have billing cadence but they're not equal
  3. 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 errors

This 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 improved

The comment now more clearly describes that PlanAddon represents the association between a plan and an add-on, which improves code readability and understanding.


5044-5046: Documentation clarity improved

The added comment clarifies that the Version field 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 struct

Added a new ValidationErrors field to the PlanAddon struct 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 reporting

This 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.go and matches the TypeScript definitions, ensuring consistency across the API surface.


6428-6438: New ValidationResource type for attaching resource context to errors

This 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 updated

Changes 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 updated

These 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: ValidationResource schema looks correct
The required fields (key, kind) and optional attributes are properly modeled, and the description accurately reflects its purpose. LGTM.

api/spec/src/productcatalog/errors.tsp (4)

1-6: Model structure looks good

The imports and namespace declaration are well-organized, providing a clear structure for the validation error models.


11-32: ValidationResource model looks well-structured

The ValidationResource model is well-defined with appropriate properties and documentation. The use of @visibility and @example annotations provides clear guidance for API consumers.


37-58: ValidationError model implementation looks good

Apart from the documentation issue mentioned earlier, the ValidationError model itself is well-structured with clear property definitions and appropriate annotations.


31-31:

Details

✅ Verification successful

Verify the Annotations type

The Annotations type 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/src

Length of output: 184


Annotations type confirmed
The Annotations model 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 struct

The updated comment provides a more precise description of what the PlanAddon represents in the system.


5505-5506: Clear description of the version field's purpose

The 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 reporting

This 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 fields

The 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 ValidationResource

The 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 changes

The 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 good

This 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 function

The FromValidationErrors function 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 pointers

Returning nil instead of empty pointers for annotations is more consistent with Go idioms and will result in null rather than {} in JSON responses, making the API more consistent.


79-82: Good update to return nil rather than empty pointers

Similar 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 type

The InvalidResourceError type 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 formatting

The Error method 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 updateInvoiceBodyWorkflowWorkflowInvoicingDueAfterDefault from '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 createBillingProfileBodyWorkflowCollectionIntervalDefault to 'PT1H' correctly adjusts the collection interval to every hour. This matches the intended update.


7062-7062: Approve updated updateBillingProfile dueAfter default.

Updating updateBillingProfileBodyWorkflowInvoicingDueAfterDefault to 'P30D' maintains consistency with the invoice due period change.

api/openapi.cloud.yaml (1)

21735-21756: Add ValidationResource schema
The ValidationResource object is correctly defined with required key and kind fields, plus optional attributes via the Annotations schema. The description accurately reflects its purpose in relation to ValidationError. Looks good.

openmeter/productcatalog/planaddon.go (1)

155-161: Potentially missing validation when add-on introduces unknown rate cards

The 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:

  1. Keep the current behaviour and document that “extra” add-on rate cards are allowed, or
  2. 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

Comment thread api/openapi.yaml Resolved
Comment thread api/openapi.yaml Resolved
Comment thread api/openapi.cloud.yaml Resolved
Comment thread openmeter/productcatalog/planaddon.go Resolved
tothandras
tothandras previously approved these changes May 14, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 suggestion

Inconsistent 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 suggestion

Another 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/planaddon

Length of output: 4633


Verify propagation of adapter validation errors

The adapter’s CreatePlanAddon returns structured validation errors via models.NewGenericValidationError/NewNillableGenericValidationError, but in the service layer we unconditionally wrap all errors with fmt.Errorf(…%w). This wrapping will prevent the HTTP driver from recognizing and converting validation errors into the API’s ValidationError payload.

• 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: Remove validationErrors from required list
The validationErrors field is defined as nullable and intended to be optional. Keeping it in the required array contradicts its nullable design and forces clients to include it (even if null). Please remove validationErrors from the required properties.


22281-22303: Fix ValidationError schema description
The description currently 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 addressed

As raised earlier, lumping Addon.Status() and Addon.EffectiveTo under 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 incorrect ValidationError description.

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 message

There'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 preservation

While 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 assertions

For cases where the order of errors might not matter, consider using assert.ElementsMatch instead of index-based comparisons. This would allow the test to pass even if the UnwrapErrors function 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: Refine version property 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: Improve validationErrors property 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 to ValidationResource schema
To improve clarity for API consumers, consider providing an example of a ValidationResource, e.g.:

example:
  key: "addon_123"
  kind: "PlanAddon"
  attributes:
    tier: "premium"
api/spec/src/productcatalog/errors.tsp (1)

34-36: Docstring references the wrong concept

The block comment still describes “Add-on” behaviour, but this file defines the ValidationError model.
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

  1. Map iteration order over r.Resource.Attributes is random; error messages (and therefore tests or logs) will vary run-to-run.
    Sort the keys before appending for deterministic output.

  2. Using %+v for r.Detail is unnecessary and slightly misleading – Detail is already a string. %s is 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: UnwrapErrors skips the current error when it also embeds children

When err both satisfies Unwrap() []error and is itself an InvalidResourceError, the current implementation only dives into the children and never checks the parent.
Although errors.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 in FromValidationErrors for minor perf & GC wins

The function already knows the final length (len(errs)), yet it relies on repeated append calls 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 in FromAnnotations

After the early return, the second if len(annotations) > 0 is 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 to FromMetadata

See 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 issue

Fix 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

errs gets both a generic errors.New("incompatible price payment terms") and an InvalidResourceError describing 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 error keeps the new structured contract clear and avoids redundant noise upstream.
Consider applying the same clean-up to the other validators that append both generic and InvalidResourceError entries.

📝 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

fromPlanPhase error should reference the plan resource, not the add-on

The 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
openmeter/productcatalog/planaddon.go (1)

79-95: Status and effectiveTo validation should be separated

The 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 (with omitempty) instead of a *[] for ValidationErrors

Using a pointer to a slice creates two “nil” states (nil pointer vs. non-nil empty slice) that rarely convey additional semantic value but complicate marshaling/unmarshaling and testing. A plain slice is already nil when 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 null value, 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": null so that adopting omitempty will not cause contract breakage.


6953-6963: Minor nit: make Resource a pointer for consistency with other optional fields

ValidationError’s Resource field 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 add omitempty) to align with the handling of Attributes inside ValidationResource.

No change needed if the field is truly required.

openmeter/productcatalog/planaddon.go (1)

148-170: More efficient rate card validation with improved error handling

The 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 InvalidResourceError for rate card compatibility issues instead of using a generic error with fmt.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

📥 Commits

Reviewing files that changed from the base of the PR and between ada588f and 4001e27.

📒 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 PlanAddon type eliminates previous confusion for readers and tooling that parse Go doc comments.


7005-7015: LGTM on the new ValidationResource structure

The struct is clear, field names follow existing conventions, and the pointer on Attributes correctly marks it optional. Nice addition.

openmeter/productcatalog/planaddon.go (5)

46-55: Good addition of a dedicated method for validation error extraction

The 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 information

The introduction of the Resource type 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 quantity

The 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 mismatch

The currency validation now uses a structured error with a specific field name, which improves error clarity.


126-143: Improved phase validation with structured errors

Using lo.FindIndexOf simplifies the code, and the structured error for missing plan phases provides better context for the validation failure.

@chrisgacsal
chrisgacsal enabled auto-merge (squash) May 14, 2025 22:05
@chrisgacsal
chrisgacsal merged commit f5f16c6 into main May 14, 2025
@chrisgacsal
chrisgacsal deleted the refactor/planaddon-comp branch May 14, 2025 22:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/misc Miscellaneous changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants