Repository navigation
refactor: validation error for plan add-on assignment - #2842
Conversation
📝 WalkthroughWalkthroughThis change refactors validation error handling across the codebase by removing the Changes
Possibly related PRs
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 golangci-lint (1.64.8)Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2 📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (15)
💤 Files with no reviewable changes (3)
🚧 Files skipped from review as they are similar to previous changes (10)
🧰 Additional context used🧬 Code Graph Analysis (1)openmeter/productcatalog/errors.go (1)
⏰ Context from checks skipped due to timeout of 90000ms (3)
🔇 Additional comments (2)
✨ 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 (
|
2e308dd to
a13ebc3
Compare
a13ebc3 to
b31a1d2
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: 5
🧹 Nitpick comments (16)
api/client/go/client.gen.go (4)
6399-6401: Consider usingmap[string]anydirectly or exposing a read-only accessor to avoid accidental mutation
Attributesis a pointer toAnnotations, which ismap[string]interface{}.
Because maps are reference types, callers can still mutate the contents even when the pointer itself is non-nil.
If the intention is to expose arbitrary, read-only annotations, think about:
- Returning a copy in a getter (
GetAttributes() map[string]any) and omitting the field from the public struct, or- Documenting that the caller must treat the map as immutable.
Both patterns guard against data races when the same instance is shared across goroutines – a common scenario for generated client models transported through channels.
6402-6404: Expose error-code enumerations for stronger compile-time guarantees
Code string \json:"code"`` leaves the caller with a free-form string.
To prevent typos and improve autocompletion it helps to provide a generated const block, e.g.:const ( ValidationCodeUnknown = "unknown" ValidationCodeIncompatibleAddOn = "incompatible_addon" // … )That way SDK consumers can reference the symbolic name instead of hard-coding literals.
6408-6409: Internationalisation (i18n) hint – separate message localisation from the transport modelEmbedding the final human-readable
Messagein the wire format hard-codes one language (English) into the API.
If multi-language support is on the roadmap, consider transporting a language-agnostic key plus arguments and letting clients/locales render the final string.For now, at least document the language guarantees (e.g., always English).
39348-39355: Huge base64-encoded swagger blob hurts diff readability & binary sizeThe embedded swagger string has grown again (>3 MB diff). Re-generating the client always touches this constant, which:
- Bloats the git history/diffs.
- Slows
go vet/go testdue to large string literal compilation.- Makes IDE navigation cumbersome.
The Go tool-chain now supports
//go:embed(Go 1.16+).
Storing the spec as a compressed JSON/YAML file and embedding it like://go:embed swagger.json.gz var swaggerSpec []bytewould keep diffs tight and compilation fast.
api/openapi.cloud.yaml (1)
21689-21703: Enhance error detail schema and optional annotations
- The
codeandmessageproperties correctly split machine-readable vs. human-readable information.- Consider tightening
codewith apatternor enumerated list of known error codes to prevent typos and improve client validation.- For
attributes, adding anexampleor marking it explicitly asnullable: truecould help clarify that it’s optional and may be omitted when no extra metadata is present.api/openapi.yaml (2)
22334-22338: Refine machine-readable error description
Consider hyphenating “machine-readable” and tightening the description for consistency. For example:-def description: The machine readable description of the error. +description: The machine-readable identifier for this error.
22339-22343: Refine human-readable error message
Similarly, hyphenate “human-readable” and adjust the wording to emphasize clarity. For example:-def description: The human readable description of the error. +description: A human-readable explanation of the validation failure.openmeter/productcatalog/planaddon.go (1)
146-148: Consider propagating structured validation issues instead of plainfmt.ErrorfWrapping rate-card validation failures with
fmt.Errorf(... %w)preserves the error chain, but the added text adds an extra, non-machine-readable layer around the underlyingmodels.ValidationIssues.
Down-stream tooling that maps issues to JSON may end up with duplicated or harder-to-parse messages.A lighter alternative is to delegate prefixing directly and avoid the textual decoration, e.g.:
if err := NewRateCardWithOverlay(phaseRateCard, addonRateCard).Validate(); err != nil { errs = append(errs, models.ErrorWithFieldPrefix( models.FieldPathFromParts(planPrefix, "phases", phase.Key, "ratecards", phaseRateCard.Key()), err, ), ) }This keeps the structured issue intact while still attaching the correct field path.
api/spec/src/productcatalog/errors.tsp (1)
14-19: Property name may confuse consumers (path vs. field)The comment says “The path to the field”, but the property is still called
field.
Renaming the property topath(orfieldPath) would make its semantics explicit and eliminate ambiguity with single-field names.If the rename is not feasible, consider updating the description to “The affected field (path notation)”.
api/client/javascript/src/client/schemas.ts (1)
9899-9919: Consider documenting the error code patterns.The overall ValidationError schema looks solid. One suggestion would be to document any patterns or constraints for error codes to ensure consistency across the API.
Consider adding TypeScript documentation that describes error code patterns:
/** * @description The machine readable description of the error. * @example invalid_feature_key + * @pattern ^[a-z]+(_[a-z]+)*$ */ readonly code: stringopenmeter/productcatalog/planaddon_test.go (2)
352-384: Leverage the predefined error constants to buildexpectedIssuesThe literals duplicate messages / codes that already live in
productcatalog/errors.go. If the source messages change, the test will silently diverge.
Prefer constructing expectations with the shared constants andmodels.ErrorWithPathPrefix(or an equivalent helper) e.g.:expectedIssues := models.ValidationIssues{ models.ErrorWithPathPrefix("/plans/pro/versions/2", ErrPlanAddonIncompatibleStatus), models.ErrorWithPathPrefix("/addons/storage/versions/1", ErrPlanAddonIncompatibleStatus), // … }This keeps tests DRY and future-proof.
Also applies to: 540-570
1-581: High duplication inflates maintenance costThe three scenarios embed ~550 lines of almost-identical JSON-like structs differing only in a handful of fields. Subsequent spec tweaks will require triple edits and invite divergence bugs.
Consider extracting minimal helpers/builders:
func makePlan(version int, currency currency.Code, effectiveFrom *time.Time, price any /* … */) Plan { … } func makeAddon(instanceType AddonInstanceType, cur currency.Code, …) Addon { … }Then each case only specifies the deltas. This shrinks the test, highlights what differs, and accelerates future edits.
openmeter/productcatalog/errors.go (4)
15-20: Minor grammar polish for clarity
"maximum quantity must be set to positive number …"→ missing article.- "maximum quantity must be set to positive number for add-on with multiple instance type", + "maximum quantity must be set to a positive number for add-on with multiple instance type",
22-27: Message phrasing
"maximum quantity must not be set for add-on with single instance type"→ consider inserting the article:- "maximum quantity must not be set for add-on with single instance type", + "maximum quantity must not be set for an add-on with single instance type",
75-80: Typo in error message
"feature identifiers id must match"– the double noun reads oddly.- "feature identifiers id must match", + "feature identifier id must match",
1-120: Consider grouping error vars by functional domainThe flat list is getting long; grouping into nested structs or prefixing with domain comments (e.g.
// PlanAddon,// RateCard/Price,// RateCard/Entitlement) will aid discoverability and reduce merge conflicts when multiple contributors append new issues simultaneously.
🛑 Comments failed to post (5)
api/client/go/client.gen.go (1)
6405-6406: 🛠️ Refactor suggestion
Make
Fieldoptional to reflect root-level errorsSome validation errors apply to the whole resource rather than a specific field.
Using a non-pointerstringforces the empty string ("") in such cases, which is ambiguous in JSON and loses the “unset vs. set-to-empty” distinction.- Field string `json:"field"` + Field *string `json:"field,omitempty"`Downstream, helpers such as
GetField()can safely dereference while preserving backward compatibility.Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In api/client/go/client.gen.go around lines 6405 to 6406, the Field property should be changed from a non-pointer string to a pointer to string to make it optional. This change allows distinguishing between an unset Field (nil) and an empty string, which is important for representing root-level errors accurately. Update the Field declaration to use *string instead of string, ensuring that downstream code can safely handle the pointer while maintaining backward compatibility.openmeter/productcatalog/planaddon.go (2)
121-124: 🛠️ Refactor suggestion
Incorrect field-path root for unknown plan-phase error
ErrPlanAddonUnknownPlanPhaseKeyrelates to a plan attribute (FromPlanPhase), yet the error is associated withaddonPrefix:models.FieldPathFromParts(addonPrefix)Using the add-on prefix misleads API clients and UI tooling that rely on the
fieldpath to highlight the problematic plan configuration.-errs = append(errs, models.ErrorWithFieldPrefix(models.FieldPathFromParts(addonPrefix), +errs = append(errs, models.ErrorWithFieldPrefix(models.FieldPathFromParts(planPrefix), ErrPlanAddonUnknownPlanPhaseKey, ))Switching to
planPrefix(or a more specificplans/.../fromPlanPhase) keeps the path consistent with the actual data location.🤖 Prompt for AI Agents
In openmeter/productcatalog/planaddon.go around lines 121 to 124, the error for ErrPlanAddonUnknownPlanPhaseKey is incorrectly associated with addonPrefix, which misleads clients about the error location. Change the field path prefix from addonPrefix to planPrefix or a more specific path pointing to the plan's FromPlanPhase attribute to correctly reflect the error's data location.
89-97:
⚠️ Potential issue
MaxQuantityforMULTIPLEinstance type is not enforced when omittedThe current check only fails when
MaxQuantityis present and<= 0.
Given the error constant is namedErrPlanAddonMaxQuantityMustBeSet, the intent seems to be that the field is mandatory forAddonInstanceTypeMultiple.
As written,nil(omitted) values silently pass validation, which contradicts the wording and may hide configuration errors.case AddonInstanceTypeMultiple: - if c.MaxQuantity != nil && *c.MaxQuantity <= 0 { + if c.MaxQuantity == nil || *c.MaxQuantity <= 0 { errs = append(errs, models.ErrorWithFieldPrefix(addonPrefix, ErrPlanAddonMaxQuantityMustBeSet, )) }This guarantees the value is provided and strictly positive.
Please verify the desired business rule and adjust tests accordingly.🤖 Prompt for AI Agents
In openmeter/productcatalog/planaddon.go around lines 89 to 97, the validation for AddonInstanceTypeMultiple does not enforce that MaxQuantity is set; it only checks if MaxQuantity is present and <= 0. To fix this, update the validation to also check if MaxQuantity is nil and append an error if it is, ensuring MaxQuantity is both provided and strictly positive for the MULTIPLE instance type. Adjust related tests to cover the case where MaxQuantity is omitted.openmeter/productcatalog/planaddon_test.go (1)
574-579: 🛠️ Refactor suggestion
Avoid capturing the loop variable directly in sub-test closures
testis reused for every loop iteration. Althought.Runexecutes the closure synchronously today, relying on this behaviour is brittle and can bite when the test body is later parallelised (t.Parallel()) or refactored.
Create a copy per iteration:-for _, test := range tests { - t.Run(test.name, func(t *testing.T) { +for _, tc := range tests { + tc := tc // capture + t.Run(tc.name, func(t *testing.T) { + // use tc instead of testThis guarantees each sub-test sees the correct data regardless of execution order.
Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In openmeter/productcatalog/planaddon_test.go around lines 574 to 579, the loop variable 'test' is captured directly in the sub-test closure, which can cause issues if the test is parallelized or refactored. To fix this, create a new local variable inside the loop that copies the current 'test' value, and use this local copy within the t.Run closure to ensure each sub-test has the correct data independent of execution order.openmeter/productcatalog/errors.go (1)
96-120: 💡 Verification agent
🧩 Analysis chain
Severity missing on several RateCard issues
ErrRateCardStaticEntitlementTemplateNotAllowed,ErrRateCardMeteredEntitlementTemplateUsagePeriodMismatch, andErrRateCardPercentageDiscountNotAllowedomitmodels.WithCriticalSeverity(), whereas all previous RateCard issues are critical.
If these should also block saving a catalog entry, add the severity flag for consistency; if not, add a comment explaining why their severity differs.- models.NewValidationIssue( + models.NewValidationIssue( …, models.WithCriticalSeverity(), )
I’ll verify how
ErrRateCard*issues are defined and the default severity inNewValidationIssue.
🏁 Script executed:
#!/bin/bash # List all RateCard error definitions with context rg -n "ErrRateCard" -A3 openmeter/productcatalog/errors.go # Find the signature and default options for NewValidationIssue rg -n "func NewValidationIssue" -C5 .Length of output: 3053
I’ll inspect the severity defaults and see which RateCard errors already use critical severity:
🏁 Script executed:
#!/bin/bash # Show the full NewValidationIssue implementation rg -n "func NewValidationIssue" -C20 pkg/models/validationissue.go # Show the ValidationIssue struct rg -n "type ValidationIssue" -C5 pkg/models/validationissue.go # List all severity-related constants and options rg -n "ErrorSeverity" -C5 pkg/models/validationissue.go rg -n "WithCriticalSeverity" -C5 pkg/models/validationissue.go # Check which RateCard errors include CriticalSeverity rg -n "WithCriticalSeverity" -n openmeter/productcatalog/errors.goLength of output: 5558
Enforce consistent critical severity on RateCard validation issues
All existing
ErrRateCard*validations includemodels.WithCriticalSeverity(), but the following three do not, leaving their severity at the default (no severity set):
- openmeter/productcatalog/errors.go:
- Line 103 –
ErrRateCardStaticEntitlementTemplateNotAllowed- Line 109 –
ErrRateCardMeteredEntitlementTemplateUsagePeriodMismatch- Line 115 –
ErrRateCardPercentageDiscountNotAllowedIf these conditions should block saving a catalog entry like the others, add
models.WithCriticalSeverity():models.NewValidationIssue( "rate_card_static_entitlement_template_not_allowed", "static entitlement template is not allowed", models.WithPath("entitlementTemplate", "type"), + models.WithCriticalSeverity(), )Otherwise, explicitly document the intended severity—either by using
models.WithWarningSeverity()or by adding a code comment explaining why they differ from the critical-severity defaults.📝 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.ErrRateCardEntitlementTemplateTypeMismatch = models.NewValidationIssue( "rate_card_entitlement_template_type_mismatch", "entitlement template type must match", models.WithPath("entitlementTemplate", "type"), models.WithCriticalSeverity(), ) ErrRateCardStaticEntitlementTemplateNotAllowed = models.NewValidationIssue( "rate_card_static_entitlement_template_not_allowed", "static entitlement template is not allowed", models.WithPath("entitlementTemplate", "type"), models.WithCriticalSeverity(), ) ErrRateCardMeteredEntitlementTemplateUsagePeriodMismatch = models.NewValidationIssue( "rate_card_metered_entitlement_template_usage_period_mismatch", "usage period for metered entitlement template must match", models.WithPath("entitlementTemplate", "usagePeriod"), models.WithCriticalSeverity(), ) ErrRateCardPercentageDiscountNotAllowed = models.NewValidationIssue( "rate_card_percentage_discount_not_allowed", "percentage discount is not allowed", models.WithPath("discounts", "percentage"), models.WithCriticalSeverity(), )🤖 Prompt for AI Agents
In openmeter/productcatalog/errors.go around lines 96 to 120, the RateCard validation errors ErrRateCardStaticEntitlementTemplateNotAllowed, ErrRateCardMeteredEntitlementTemplateUsagePeriodMismatch, and ErrRateCardPercentageDiscountNotAllowed lack the models.WithCriticalSeverity() option present in other RateCard errors. To fix this, add models.WithCriticalSeverity() to these three error definitions if they should block saving a catalog entry for consistency. If not critical, add a comment explaining why their severity differs or set an explicit severity like models.WithWarningSeverity().
Overview
Adopt
ValidationIssuefor describing validation errors for plan add-on assignments.Summary by CodeRabbit
New Features
Bug Fixes
Refactor
Tests