Repository navigation
Remove feature.Feature from productcatalog.RateCard - #2637
Conversation
📝 WalkthroughWalkthroughThe pull request refactors the representation of feature information within rate card-related structures by removing the legacy 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 (1)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ Context from checks skipped due to timeout of 90000ms (12)
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (9)
openmeter/productcatalog/addon/service/addon.go (1)
30-181: Consider simplifying the repeated merging logic.Within
resolveFeatures, you switch based on rate card types and manually construct new instances before merging. Extracting a helper function to handle the repetitive “merge meta and set new pointers” steps could reduce complexity and make the code more maintainable. Additionally, the existing TODO/FIXME comments acknowledge brittleness in pointer handling.I can help outline a dedicated helper to unify the repeated switch statements and pointer merges if needed.
openmeter/productcatalog/plan/serializer_test.go (1)
70-71: Consider using distinct values for key and ID.Using
"feature-1"for bothFeatureKeyandFeatureIDmay be a bit confusing in real-world contexts. Slightly differentiating them in tests can clarify that these fields are truly separate.openmeter/productcatalog/plan/service/plan.go (4)
30-36: NewresolveFeaturesfunction and initial docstring.
Renaming fromexpandFeaturesclarifies usage. The current approach is correct, but consider addressing theFIXMEabout pointer-based implementations for RateCard to reduce brittleness.
40-50: Aggregating feature keys and IDs in a slice.
Collecting all references for a single API call avoids multiple lookups. Note that using a set instead of a slice could prevent duplicates and reduce overhead if there are many repeated keys/IDs.
108-141: Populating missingFeatureKeywhen onlyFeatureIDis set.
Merging the new metadata into a newly constructed rate card is a bit verbose, but it’s logically correct. Eventually, refactoring to pointer-based or a builder pattern might simplify these merges.
142-175: Populating missingFeatureIDwhen onlyFeatureKeyis set.
Same approach as above, seems consistent. A shared helper function might reduce duplication of the logic for building new rate cards.openmeter/productcatalog/ratecard_test.go (3)
148-162: Consider removing unused Feature struct creation.The code still creates a
feature.Featureinstance which is only used to extract its Key and ID fields. Since the PR aims to removefeature.Featurefromproductcatalog.RateCard, consider directly initializing the values or creating a helper function to generate test values consistently.-feat1 := &feature.Feature{ - Namespace: "namespace-1", - ID: "01JBP3SGZ20Y7VRVC351TDFXYZ", - Name: "Feature 1", - Key: "feat-1", - MeterSlug: lo.ToPtr("meter-1"), - MeterGroupByFilters: nil, - Metadata: map[string]string{ - "name": "Feature 1", - }, - ArchivedAt: &time.Time{}, - CreatedAt: time.Time{}, - UpdatedAt: time.Time{}, -} +// Define test feature key and ID constants +const ( + testFeatureKey = "feat-1" + testFeatureID = "01JBP3SGZ20Y7VRVC351TDFXYZ" +)
258-259: Consider using consistent initialization in all test cases.In these test cases, you're still using
lo.ToPtr(feat1.Key)andlo.ToPtr(feat1.ID)which depends on thefeat1object. For consistency with other test cases and to fully eliminate the dependency on thefeature.Featurestructure, consider using direct string literals or the constants suggested earlier.Example replacement for one instance:
-FeatureKey: lo.ToPtr(feat1.Key), -FeatureID: lo.ToPtr(feat1.ID), +FeatureKey: lo.ToPtr(testFeatureKey), +FeatureID: lo.ToPtr(testFeatureID),Also applies to: 286-287, 312-313, 337-338
1-12: Consider removing unused imports.The file still imports the
featurepackage, but if the refactoring suggestions above are implemented to eliminate thefeat1object, this import could be removed since the feature package would no longer be used.-import ( - "testing" - "time" - - decimal "github.com/alpacahq/alpacadecimal" - "github.com/samber/lo" - "github.com/stretchr/testify/assert" - - "github.com/openmeterio/openmeter/openmeter/productcatalog/feature" - "github.com/openmeterio/openmeter/pkg/isodate" - "github.com/openmeterio/openmeter/pkg/models" -) +import ( + "testing" + "time" + + decimal "github.com/alpacahq/alpacadecimal" + "github.com/samber/lo" + "github.com/stretchr/testify/assert" + + "github.com/openmeterio/openmeter/pkg/isodate" + "github.com/openmeterio/openmeter/pkg/models" +)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (23)
openmeter/billing/worker/subscription/sync_test.go(12 hunks)openmeter/productcatalog/addon/adapter/adapter_test.go(2 hunks)openmeter/productcatalog/addon/adapter/mapping.go(2 hunks)openmeter/productcatalog/addon/assert.go(1 hunks)openmeter/productcatalog/addon/ratecard_test.go(6 hunks)openmeter/productcatalog/addon/service/addon.go(3 hunks)openmeter/productcatalog/http/mapping.go(3 hunks)openmeter/productcatalog/plan/adapter/adapter_test.go(2 hunks)openmeter/productcatalog/plan/adapter/mapping.go(2 hunks)openmeter/productcatalog/plan/assert.go(1 hunks)openmeter/productcatalog/plan/ratecard_test.go(6 hunks)openmeter/productcatalog/plan/serializer.go(4 hunks)openmeter/productcatalog/plan/serializer_test.go(1 hunks)openmeter/productcatalog/plan/service/plan.go(3 hunks)openmeter/productcatalog/plan/service/service_test.go(4 hunks)openmeter/productcatalog/ratecard.go(8 hunks)openmeter/productcatalog/ratecard_test.go(14 hunks)openmeter/productcatalog/subscription/plan.go(1 hunks)openmeter/subscription/aligment_test.go(2 hunks)openmeter/subscription/testutils/ratecard.go(3 hunks)openmeter/subscription/workflow/service/subscription_test.go(4 hunks)test/subscription/scenario_editaligned_test.go(2 hunks)test/subscription/scenario_editcancel_test.go(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (14)
openmeter/productcatalog/subscription/plan.go (1)
openmeter/ent/db/subscriptionitem/where.go (1)
FeatureKey(142-144)
openmeter/productcatalog/plan/adapter/adapter_test.go (4)
openmeter/ent/db/billinginvoiceusagebasedlineconfig/where.go (1)
FeatureKey(73-75)openmeter/ent/db/subscriptionitem/where.go (1)
FeatureKey(142-144)openmeter/ent/db/planratecard/where.go (2)
FeatureKey(106-108)FeatureID(122-124)openmeter/ent/db/entitlement/where.go (2)
FeatureKey(105-107)FeatureID(90-92)
openmeter/subscription/testutils/ratecard.go (3)
openmeter/ent/db/subscriptionitem/where.go (1)
FeatureKey(142-144)openmeter/ent/db/entitlement/where.go (2)
FeatureKey(105-107)FeatureID(90-92)openmeter/subscription/testutils/feature.go (1)
ExampleFeatureKey(12-12)
openmeter/productcatalog/addon/adapter/mapping.go (1)
openmeter/ent/db/addonratecard/where.go (2)
FeatureKey(106-108)FeatureID(122-124)
openmeter/productcatalog/plan/service/service_test.go (3)
openmeter/ent/db/subscriptionitem/where.go (2)
FeatureKey(142-144)ID(15-17)openmeter/ent/db/planratecard/where.go (3)
FeatureKey(106-108)FeatureID(122-124)ID(16-18)openmeter/ent/db/entitlement/where.go (3)
FeatureKey(105-107)FeatureID(90-92)ID(15-17)
openmeter/billing/worker/subscription/sync_test.go (2)
openmeter/ent/db/subscriptionitem/where.go (4)
Key(105-107)Name(132-134)FeatureKey(142-144)ID(15-17)openmeter/ent/db/subscription/where.go (2)
Name(105-107)ID(15-17)
openmeter/productcatalog/plan/service/plan.go (4)
openmeter/productcatalog/ratecard.go (2)
RateCard(27-37)RateCardMeta(48-79)openmeter/productcatalog/feature/connector.go (1)
ListFeaturesParams(62-74)openmeter/productcatalog/feature/feature.go (1)
Feature(87-110)openmeter/productcatalog/plan/ratecard.go (1)
RateCard(64-67)
openmeter/productcatalog/plan/assert.go (2)
openmeter/ent/db/billinginvoiceusagebasedlineconfig/where.go (1)
FeatureKey(73-75)openmeter/ent/db/planratecard/where.go (2)
FeatureKey(106-108)FeatureID(122-124)
openmeter/subscription/aligment_test.go (1)
openmeter/subscription/testutils/feature.go (1)
ExampleFeature(16-21)
openmeter/subscription/workflow/service/subscription_test.go (2)
openmeter/subscription/testutils/feature.go (1)
ExampleFeatureKey(12-12)openmeter/subscription/testutils/plan.go (1)
GetExamplePlanInput(20-70)
openmeter/productcatalog/http/mapping.go (1)
openmeter/productcatalog/ratecard.go (1)
RateCardMeta(48-79)
openmeter/productcatalog/plan/ratecard_test.go (4)
openmeter/ent/db/billinginvoiceusagebasedlineconfig/where.go (1)
FeatureKey(73-75)openmeter/ent/db/subscriptionitem/where.go (1)
FeatureKey(142-144)openmeter/ent/db/planratecard/where.go (2)
FeatureKey(106-108)FeatureID(122-124)openmeter/ent/db/entitlement/where.go (2)
FeatureKey(105-107)FeatureID(90-92)
openmeter/productcatalog/ratecard.go (8)
openmeter/productcatalog/subscription/plan.go (1)
RateCard(130-133)openmeter/productcatalog/addon/ratecard.go (1)
RateCard(60-63)openmeter/productcatalog/plan/ratecard.go (1)
RateCard(64-67)pkg/models/metadata.go (1)
Metadata(9-9)openmeter/productcatalog/entitlement.go (1)
EntitlementTemplate(34-39)openmeter/productcatalog/tax.go (1)
TaxConfig(36-39)openmeter/productcatalog/price.go (1)
Price(84-91)openmeter/productcatalog/discount.go (1)
Discounts(346-346)
openmeter/productcatalog/ratecard_test.go (5)
openmeter/ent/db/billinginvoiceusagebasedlineconfig/where.go (2)
FeatureKey(73-75)ID(13-15)openmeter/ent/db/subscriptionitem/where.go (3)
FeatureKey(142-144)Key(105-107)ID(15-17)openmeter/ent/db/planratecard/where.go (4)
FeatureKey(106-108)FeatureID(122-124)Key(101-103)ID(16-18)openmeter/ent/db/entitlement/where.go (3)
FeatureKey(105-107)FeatureID(90-92)ID(15-17)openmeter/ent/db/plan/where.go (2)
Key(99-101)ID(14-16)
⏰ Context from checks skipped due to timeout of 90000ms (12)
- GitHub Check: Artifacts / Container image
- GitHub Check: Quickstart
- GitHub Check: E2E
- GitHub Check: CI
- GitHub Check: Commit hooks
- GitHub Check: Test
- GitHub Check: Migration Checks
- GitHub Check: Lint
- GitHub Check: Developer environment
- GitHub Check: Analyze (javascript)
- GitHub Check: Build
- GitHub Check: Analyze (go)
🔇 Additional comments (71)
openmeter/productcatalog/plan/assert.go (1)
188-189: Feature comparison logic updated to use direct field checks.The code now directly compares
FeatureKeyandFeatureIDfields instead of extracting them from a nestedFeatureobject, aligning with the PR objective of removing theFeaturefield fromproductcatalog.RateCard.openmeter/productcatalog/http/mapping.go (3)
27-29: Feature handling simplified to use direct field access.The code now directly accesses
meta.FeatureKeyinstead of extracting it from a nestedFeatureobject, aligning with the PR's goal of removingfeature.Featurefromproductcatalog.RateCard.
486-487: Direct assignment of FeatureKey replaces Feature object creation.The code now directly assigns
flat.FeatureKeytorc.RateCardMeta.FeatureKeyinstead of creating afeature.Featureobject, which streamlines the code and maintains consistency with the PR objective.
560-561: Simplified feature handling in UsageBasedRateCard.Similar to the FlatFeeRateCard changes, the code now directly assigns
usage.FeatureKeytorc.RateCardMeta.FeatureKeyinstead of creating afeature.Featureobject.openmeter/subscription/aligment_test.go (2)
51-53: Replaced Feature object with direct FeatureID and FeatureKey fields.The test now directly assigns string pointers to
FeatureIDandFeatureKeyinstead of creating aFeatureobject, consistent with the pattern established across the codebase.
68-72: Feature field replaced with direct ID and Key fields in second phase.Similar to the changes in the first phase, the test now assigns values directly to
FeatureKeyandFeatureIDfields instead of using aFeatureobject.openmeter/subscription/workflow/service/subscription_test.go (3)
264-265: Added clock reset to prevent test interference.Added
defer clock.ResetTime()ensures that time manipulation during tests doesn't affect subsequent tests that rely on the clock.
755-757: Replaced Feature field with FeatureKey and FeatureID in rate card.Test now directly uses
FeatureKeyandFeatureIDfields instead of aFeatureobject, in alignment with the changes made throughout the codebase.
952-953: Moved plan input declaration inside withDeps function.Moving
examplePlanInput1inside thewithDepsfunction ensures it's recreated for each test case, preventing potential test interference from shared state.Also applies to: 1078-1079
openmeter/productcatalog/ratecard.go (6)
35-35: Interface extension looks good.
No issues with adding theClone()method to theRateCardinterface.
61-66: New fields for FeatureKey and FeatureID are clear and consistent.
The introduction ofFeatureKeyandFeatureIDmakes the feature representation more explicit.
191-195: Verify the enforced key match.
This code enforces thatr.Keymust equal*r.FeatureKey. If you intendRateCard.KeyandFeatureKeyto be interchangeable, that’s fine. Otherwise, consider removing or relaxing this check.Would you like a script to search the codebase and confirm no references rely on distinct feature keys?
297-308: Cloning of FlatFeeRateCard looks consistent with the interface.
Implementation correctly callsRateCardMeta.Clone()and duplicates the billing cadence.
324-329: UsageBasedRateCard.Clone() is straightforward and consistent.
The copy logic forRateCardMetaandBillingCadenceis properly handled.
411-417: RateCards.Clone() implementation is sound.
Each individual rate card is cloned, ensuring a proper independent copy of the slice contents.openmeter/productcatalog/addon/assert.go (1)
119-120: Using testify'sassert.Equalffor pointer-to-string fields is correct.
assert.Equalfperforms a reflection-based equality check, which compares the actual string values rather than pointer addresses.openmeter/productcatalog/subscription/plan.go (1)
146-146: Forwarding FeatureKey directly is consistent with the new field usage.
This straightforward assignment aligns with the updated RateCard structure.test/subscription/scenario_editcancel_test.go (1)
71-75: Field structure refactoring looks goodThe refactoring correctly removes the direct
Featurefield reference and replaces it with explicitFeatureKeyandFeatureIDpointers, which aligns with the PR objective. The code appropriately useslo.ToPtrto convert the feature key and ID to pointers.openmeter/subscription/testutils/ratecard.go (3)
21-22: Field refactoring implementation is correctProperly replaced the
Featurefield withFeatureKeyandFeatureID. Usinglo.ToPtr(ExampleFeatureKey)references the existing constant correctly.
43-44: Nil values for feature identifiers look intentionalBoth
FeatureKeyandFeatureIDare set tonilfor this test rate card, which appears to be intentional for a rate card not associated with any specific feature.
59-60: Consistent with earlier changesThe changes to
ExampleRateCardWithDiscountsmirror those inExampleRateCard1, maintaining consistency across the test data structures.openmeter/productcatalog/plan/adapter/adapter_test.go (2)
58-59: Test data initialization looks correctSetting both
FeatureKeyandFeatureIDtonilis appropriate for this test case where the rate card doesn't need to be associated with a specific feature.
90-91: Maintains consistency with previous changesThe same approach is correctly applied to the Pro RateCard structure, maintaining consistency throughout the test data.
test/subscription/scenario_editaligned_test.go (2)
73-76: Field replacement properly implementedThe changes correctly replace the direct
Featurefield reference withFeatureKeyandFeatureIDpointers, consistent with the PR objectives. The pointers are properly initialized from the feature object.
246-249: Consistent implementation across test functionsThe same field replacement pattern is correctly applied to the second test function, ensuring consistent behavior between aligned and unaligned subscription tests.
openmeter/billing/worker/subscription/sync_test.go (6)
177-179: Changes look good - Replaced Feature field with FeatureKey and FeatureIDThe refactoring correctly replaces the Feature field with separate FeatureKey and FeatureID fields, making the code more explicit and reducing dependencies between components.
196-198: Code refactoring maintains consistencyThese changes maintain consistency with the previous review comment, applying the same pattern throughout the codebase.
216-219: Consistent pattern applicationThe refactoring pattern is consistently applied to all RateCardMeta instances in the test file.
1600-1602: Refactoring pattern maintained across test casesThe same refactoring pattern is correctly applied to the TestAlignedSubscriptionCancellation test case.
1618-1621: Consistent pattern throughout test fileThe changes maintain consistency throughout the entire test file, ensuring that all RateCardMeta instances use the new field structure.
2305-2306: Consistent refactoring in usage-based test casesThe refactoring pattern is correctly applied to usage-based test cases as well, maintaining consistency throughout the codebase.
openmeter/productcatalog/plan/adapter/mapping.go (2)
134-135: Refactoring replaces Feature resolution with direct field assignmentsThe change correctly removes the feature resolution logic in favor of directly assigning FeatureID and FeatureKey fields from the row data. This simplifies the mapping process and reduces dependencies.
216-217: Direct field mapping instead of feature resolutionThe mapping now directly assigns the FeatureKey and FeatureID from meta to ratecard, which is cleaner and more efficient than the previous approach.
openmeter/productcatalog/addon/adapter/mapping.go (2)
74-75: Consistent refactoring in addon adapterSimilar to the plan adapter, the addon adapter now uses direct field assignments for FeatureKey and FeatureID instead of resolving a Feature object.
143-144: Consistent field mapping in asAddonRateCardRowThe changes ensure that the asAddonRateCardRow function consistently maps the FeatureKey and FeatureID fields directly, maintaining consistency with the fromAddonRateCardRow function.
openmeter/productcatalog/plan/service/service_test.go (4)
141-142: Test code updated to use new field structureThe test code correctly uses the new field structure, setting FeatureKey and FeatureID directly instead of using a Feature object.
256-257: Consistent usage of nil for FeatureKey and FeatureIDWhere the code previously set Feature to nil, it now correctly sets both FeatureKey and FeatureID to nil, maintaining the same semantics.
659-660: Test data consistently updated throughout the fileTest data creation in NewProPlan has been consistently updated to use the new field structure.
691-692: Consistency in test dataThe refactoring is consistently applied throughout all test data creation, ensuring that all test cases use the new field structure.
openmeter/productcatalog/addon/adapter/adapter_test.go (2)
103-104: Use of separate fields for feature key and ID looks correct.This nicely decouples the feature reference into two clear identifiers.
261-262: Confirm nil assignments for absent features.Replacing the old
Feature: nilwithFeatureKey: nilandFeatureID: nilcorrectly follows the refactored structure.openmeter/productcatalog/addon/service/addon.go (1)
408-409: Renamed function and parameter checks look good.The updated call to
resolveFeaturesensures each add-on update seamlessly aligns with the new feature resolution flow. No concerns here.openmeter/productcatalog/plan/serializer.go (4)
22-23: Consistent replacement of theFeaturefield.
These new pointer fields (FeatureKeyandFeatureID) align with the overall removal of theFeatureobject. Storing them as*stringis appropriate to represent optional values without needing complex structs.
72-73: Straightforward serialization of feature references.
Passingmeta.FeatureKeyandmeta.FeatureIDinto the JSON struct is clean and avoids the overhead of marshaling nested feature objects.
121-122: Symmetrical structure for unmarshaling.
Mirroring the same pointer fields for JSON unmarshaling maintains consistency. Theomitemptytag remains suitable for optional fields.
181-182: Properly assigning feature fields from local alias struct.
AssigningFeatureKeyandFeatureIDhere matches the new approach of storing references instead of raw feature data.openmeter/productcatalog/plan/service/plan.go (8)
54-55: Early return if no feature references exist.
This short-circuit is good, reducing unnecessary processing.
59-59: PopulatingListFeaturesParamswith keys/IDs.
Having a single call toListFeaturesis beneficial for performance. Ensure that large arrays won't exceed any backend limits.Would you like to confirm any potential pagination or size constraints for the feature list endpoint in extremely large plan definitions?
67-76: Cloning rate cards before mutation.
This prevents side effects on the original slice during iteration. Skipping cards without features is clear and safe.
79-96: Usinglo.Findfor feature lookup.
The approach is straightforward and readable. Consider handling duplicates in future if performance demands require it, but it's fine for typical usage.
98-107: Validating consistency of bothFeatureIDandFeatureKey.
It’s crucial to confirm these match in the data store. The error messages should be helpful for debugging.
178-178: Replacing the original slice with the updated clone.
This final assignment ensures all changes are preserved in the caller.
229-229: CallingresolveFeaturesinCreatePlan.
This replaces the oldexpandFeaturescall. The rename clarifies the new logic for setting and validating keys/IDs.
368-368: CallingresolveFeaturesinUpdatePlan.
Ensuring that feature references are updated whenever plan phases change is consistent with the new approach.openmeter/productcatalog/addon/ratecard_test.go (6)
47-48: ReplacedFeaturewithFeatureKeyandFeatureIDin test.
This accurately reflects the data representation change for feature references.
93-94: Maintaining parallel fields forFeatureKeyandFeatureID.
These tests ensure that the usage-based rate card can store both references properly.
180-181: FlatFeeRateCard test setup uses new feature fields.
The transition looks consistent, with no apparent regression in test coverage.
227-228: Valid test scenario with new feature fields.
Test remains aligned with the new data structure, verifying negative or invalid conditions as expected.
298-299: Usage-based rate card referencing replaced fields.
This helps confirm the correct marshalling/unmarshalling of bothFeatureKeyandFeatureID.
353-354: Test with potentially invalid feature references.
Retaining the same structure in tests ensures error conditions are still handled properly.openmeter/productcatalog/plan/ratecard_test.go (6)
47-48: Feature field replacement looks good.The replacement of the
Featurefield with directFeatureKeyandFeatureIDfields is properly implemented here. Thelo.ToPtr()function correctly converts the string literals to pointers as required.
93-94: Feature field replacement is consistent.The implementation of
FeatureKeyandFeatureIDfields is consistent with the previous change, maintaining the same pattern throughout the test cases.
180-181: Consistent replacement in FlatFeeRateCard validation test case.The test cases for
FlatFeeRateCardvalidation have been properly updated with the new field structure, ensuring that validation logic continues to work with the new fields.
227-228: Invalid test case properly updated with new field structure.The invalid test case for
FlatFeeRateCardcorrectly uses the new field structure, maintaining test coverage for validation of erroneous input.
298-299: UsageBasedRateCard tests properly updated.The
UsageBasedRateCardtest cases have been updated to use the new field structure, maintaining consistent behavior across all rate card types.
353-354: Invalid test case for UsageBasedRateCard properly updated.The test case for invalid
UsageBasedRateCardconfigurations has been correctly updated to use the new field structure, preserving test coverage for validation logic.openmeter/productcatalog/ratecard_test.go (5)
33-34: Feature field replacement looks good in test case.The
Featurefield has been correctly replaced withFeatureKeyandFeatureIDin theFlatFeeRateCardtest case, properly using string pointers.
66-67: Invalid test case properly updated.The invalid test case for
FlatFeeRateCardvalidation now correctly uses the new field structure instead ofFeature.
180-181: Feature fields properly populated in UsageBasedRateCard test.The replacement of the
Featurefield with directFeatureKeyandFeatureIDfields is properly implemented in the UsageBasedRateCard test case.
221-222: Consistent implementation in invalid test case.The test case for invalid
UsageBasedRateCardcorrectly uses the new field structure, ensuring consistent testing approach.
402-403: Rate card equality test cases properly updated.The test cases for checking rate card equality have been properly updated to use the new field structure, ensuring that the equality comparison still works as expected.
Also applies to: 449-450, 539-540, 576-577, 607-608
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (3)
openmeter/productcatalog/addon/service/addon.go (2)
35-35: Consider addressing the FIXME comment about pointer implementationThe FIXME comment highlights a potential fragility in the code. You might want to enforce that all
RateCardimplementations are pointers, or adapt the code to handle both pointer and non-pointer implementations.
113-143: Consider extracting common rate card creation logicThe rate card creation logic is duplicated in multiple places. Consider extracting this into a helper function to reduce duplication.
You could refactor this into a helper function:
- // FIXME: merging like this is a pain, we should just use pointers... - mNew := rateCard.AsMeta() - mNew.FeatureKey = lo.ToPtr(featureByID.Key) - var rcNew productcatalog.RateCard - - switch rateCard.Type() { - case productcatalog.FlatFeeRateCardType: - rcNew = &productcatalog.FlatFeeRateCard{ - RateCardMeta: mNew, - BillingCadence: rateCard.GetBillingCadence(), - } - case productcatalog.UsageBasedRateCardType: - bc := rateCard.GetBillingCadence() - if bc == nil { - return fmt.Errorf("BillingCadence is required for UsageBasedRateCard") - } - - rcNew = &productcatalog.UsageBasedRateCard{ - RateCardMeta: mNew, - BillingCadence: *bc, - } - default: - return fmt.Errorf("unsupported RateCard type: %s", rateCard.Type()) - } - - if err := rateCard.Merge(rcNew); err != nil { - return fmt.Errorf("failed to merge RateCard: %w", err) - } + if err := createAndMergeRateCard(rateCard, func(meta productcatalog.RateCardMeta) productcatalog.RateCardMeta { + meta.FeatureKey = lo.ToPtr(featureByID.Key) + return meta + }); err != nil { + return err + }And define the helper function:
func createAndMergeRateCard(rateCard productcatalog.RateCard, metaUpdater func(productcatalog.RateCardMeta) productcatalog.RateCardMeta) error { mNew := metaUpdater(rateCard.AsMeta()) var rcNew productcatalog.RateCard switch rateCard.Type() { case productcatalog.FlatFeeRateCardType: rcNew = &productcatalog.FlatFeeRateCard{ RateCardMeta: mNew, BillingCadence: rateCard.GetBillingCadence(), } case productcatalog.UsageBasedRateCardType: bc := rateCard.GetBillingCadence() if bc == nil { return fmt.Errorf("BillingCadence is required for UsageBasedRateCard") } rcNew = &productcatalog.UsageBasedRateCard{ RateCardMeta: mNew, BillingCadence: *bc, } default: return fmt.Errorf("unsupported RateCard type: %s", rateCard.Type()) } if err := rateCard.Merge(rcNew); err != nil { return fmt.Errorf("failed to merge RateCard: %w", err) } return nil }openmeter/productcatalog/plan/service/plan.go (1)
35-35: Consider addressing the FIXME comment about pointer implementationThe FIXME comment highlights a potential fragility in the code. Consider enforcing that all
RateCardimplementations are pointers, or adapting the code to handle both pointer and non-pointer implementations.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
openmeter/productcatalog/addon/service/addon.go(3 hunks)openmeter/productcatalog/plan/service/plan.go(3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
openmeter/productcatalog/addon/service/addon.go (3)
openmeter/productcatalog/ratecard.go (4)
RateCard(27-37)FlatFeeRateCard(208-215)RateCardMeta(48-79)UsageBasedRateCard(312-318)openmeter/ent/db/feature.go (2)
Feature(17-45)Feature(88-103)pkg/models/error.go (1)
NewGenericNotFoundError(38-40)
openmeter/productcatalog/plan/service/plan.go (4)
openmeter/productcatalog/ratecard.go (2)
RateCard(27-37)RateCardMeta(48-79)openmeter/productcatalog/feature/connector.go (1)
ListFeaturesParams(62-74)openmeter/productcatalog/feature/feature.go (1)
Feature(87-110)pkg/models/error.go (1)
NewGenericNotFoundError(38-40)
⏰ Context from checks skipped due to timeout of 90000ms (11)
- GitHub Check: Test
- GitHub Check: Quickstart
- GitHub Check: Migration Checks
- GitHub Check: Lint
- GitHub Check: E2E
- GitHub Check: Developer environment
- GitHub Check: Build
- GitHub Check: CI
- GitHub Check: Commit hooks
- GitHub Check: Analyze (javascript)
- GitHub Check: Analyze (go)
🔇 Additional comments (13)
openmeter/productcatalog/addon/service/addon.go (9)
30-36: Function name change and improved docstringThe renaming from
expandFeaturestoresolveFeaturesbetter reflects the function's purpose of bidirectional resolution of feature references. The detailed comments provide clear guidance on the function's behavior.
40-52: Improved data collection logicThis change simplifies the feature collection by gathering both keys and IDs in a single slice, which is more maintainable than the previous approach with separate maps.
54-66: Improved query parameter handlingThe change correctly uses the collected IDs and keys for querying features. However, on line 62, the PageSize is explicitly set based on the number of collected keys/IDs, which is good for limiting the query results.
70-81: Good defensive programming with cloningCreating a clone of the rate cards before modification is an excellent practice to avoid side effects. The early continue for rate cards without feature information is also a nice optimization.
82-99: Well-structured feature lookupThe code clearly organizes the feature lookup logic by ID and key, making it easier to understand and maintain.
101-110: Thorough validation for feature mismatchThe validation logic properly checks for feature existence and key/ID consistency, providing specific error messages.
178-183: Good update mechanism for original rate cardsAssigning the cloned and modified rate cards back to the original pointer is a clean approach to update the caller's data.
276-278: Updated function call in CreateAddonThe call has been correctly updated to use the new function name.
409-411: Updated function call in UpdateAddonThe call has been correctly updated to use the new function name.
openmeter/productcatalog/plan/service/plan.go (4)
30-36: Function name change and improved docstringThe renaming from
expandFeaturestoresolveFeaturesbetter reflects the function's purpose. The detailed comments clearly explain how feature references are resolved bidirectionally.
40-52: Improved data collection logicThe collection of feature keys and IDs in a single slice simplifies the code and makes it more maintainable.
229-231: Updated function call in CreatePlanThe call has been correctly updated to use the new function name.
368-370: Updated function call in UpdatePlanThe call has been correctly updated to use the new function name.
| } else if fID == nil && fK != nil { | ||
| // We need to populate FeatureID | ||
| if !featureByKeyOk { | ||
| return fmt.Errorf("feature with key %s not found", *fK) | ||
| } | ||
|
|
||
| // FIXME: merging like this is a pain, we should just use pointers... | ||
| mNew := rateCard.AsMeta() | ||
| mNew.FeatureID = lo.ToPtr(featureByKey.ID) | ||
| var rcNew productcatalog.RateCard | ||
|
|
||
| return models.NewGenericValidationError(fmt.Errorf("non-existing features: %+v", missing)) | ||
| switch rateCard.Type() { | ||
| case productcatalog.FlatFeeRateCardType: | ||
| rcNew = &productcatalog.FlatFeeRateCard{ | ||
| RateCardMeta: mNew, | ||
| BillingCadence: rateCard.GetBillingCadence(), | ||
| } | ||
| case productcatalog.UsageBasedRateCardType: | ||
| bc := rateCard.GetBillingCadence() | ||
| if bc == nil { | ||
| return fmt.Errorf("billing cadence is required for usage-based rate card") | ||
| } | ||
|
|
||
| rcNew = &productcatalog.UsageBasedRateCard{ | ||
| RateCardMeta: mNew, | ||
| BillingCadence: *bc, | ||
| } | ||
| default: | ||
| return fmt.Errorf("unsupported RateCard type: %s", rateCard.Type()) | ||
| } | ||
|
|
||
| if err := rateCard.Merge(rcNew); err != nil { | ||
| return fmt.Errorf("failed to merge RateCard: %w", err) | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Inconsistent error handling between feature ID and key lookup
There's an inconsistency in error handling between feature ID and key lookup failure:
- When a feature ID is not found (line 113), it uses
models.NewGenericNotFoundError - When a feature key is not found (line 147), it uses a direct
fmt.Errorf
Consider using the same error type for both cases for consistency.
- return fmt.Errorf("feature with key %s not found", *fK)
+ return models.NewGenericNotFoundError(fmt.Errorf("feature with key %s not found", *fK))📝 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.
| } else if fID == nil && fK != nil { | |
| // We need to populate FeatureID | |
| if !featureByKeyOk { | |
| return fmt.Errorf("feature with key %s not found", *fK) | |
| } | |
| // FIXME: merging like this is a pain, we should just use pointers... | |
| mNew := rateCard.AsMeta() | |
| mNew.FeatureID = lo.ToPtr(featureByKey.ID) | |
| var rcNew productcatalog.RateCard | |
| return models.NewGenericValidationError(fmt.Errorf("non-existing features: %+v", missing)) | |
| switch rateCard.Type() { | |
| case productcatalog.FlatFeeRateCardType: | |
| rcNew = &productcatalog.FlatFeeRateCard{ | |
| RateCardMeta: mNew, | |
| BillingCadence: rateCard.GetBillingCadence(), | |
| } | |
| case productcatalog.UsageBasedRateCardType: | |
| bc := rateCard.GetBillingCadence() | |
| if bc == nil { | |
| return fmt.Errorf("billing cadence is required for usage-based rate card") | |
| } | |
| rcNew = &productcatalog.UsageBasedRateCard{ | |
| RateCardMeta: mNew, | |
| BillingCadence: *bc, | |
| } | |
| default: | |
| return fmt.Errorf("unsupported RateCard type: %s", rateCard.Type()) | |
| } | |
| if err := rateCard.Merge(rcNew); err != nil { | |
| return fmt.Errorf("failed to merge RateCard: %w", err) | |
| } | |
| } else if fID == nil && fK != nil { | |
| // We need to populate FeatureID | |
| if !featureByKeyOk { | |
| return models.NewGenericNotFoundError(fmt.Errorf("feature with key %s not found", *fK)) | |
| } | |
| // FIXME: merging like this is a pain, we should just use pointers... | |
| mNew := rateCard.AsMeta() | |
| mNew.FeatureID = lo.ToPtr(featureByKey.ID) | |
| var rcNew productcatalog.RateCard | |
| switch rateCard.Type() { | |
| case productcatalog.FlatFeeRateCardType: | |
| rcNew = &productcatalog.FlatFeeRateCard{ | |
| RateCardMeta: mNew, | |
| BillingCadence: rateCard.GetBillingCadence(), | |
| } | |
| case productcatalog.UsageBasedRateCardType: | |
| bc := rateCard.GetBillingCadence() | |
| if bc == nil { | |
| return fmt.Errorf("billing cadence is required for usage-based rate card") | |
| } | |
| rcNew = &productcatalog.UsageBasedRateCard{ | |
| RateCardMeta: mNew, | |
| BillingCadence: *bc, | |
| } | |
| default: | |
| return fmt.Errorf("unsupported RateCard type: %s", rateCard.Type()) | |
| } | |
| if err := rateCard.Merge(rcNew); err != nil { | |
| return fmt.Errorf("failed to merge RateCard: %w", err) | |
| } |
There was a problem hiding this comment.
@chrisgacsal i forgot about this, could you please fix this in your follow-up? 🥺
There was a problem hiding this comment.
Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!
|
|
||
| if err := rateCard.Merge(rcNew); err != nil { | ||
| return fmt.Errorf("failed to merge RateCard: %w", err) | ||
| } | ||
| } else if fID == nil && fK != nil { | ||
| // We need to populate FeatureID | ||
| if !featureByKeyOk { | ||
| return fmt.Errorf("feature with key %s not found", *fK) | ||
| } | ||
|
|
||
| // FIXME: merging like this is a pain, we should just use pointers... | ||
| mNew := rateCard.AsMeta() | ||
| mNew.FeatureID = lo.ToPtr(featureByKey.ID) | ||
| var rcNew productcatalog.RateCard | ||
|
|
||
| return models.NewGenericValidationError(fmt.Errorf("non-existing Features: %+v", missing)) | ||
| switch rateCard.Type() { | ||
| case productcatalog.FlatFeeRateCardType: | ||
| rcNew = &productcatalog.FlatFeeRateCard{ | ||
| RateCardMeta: mNew, | ||
| BillingCadence: rateCard.GetBillingCadence(), | ||
| } | ||
| case productcatalog.UsageBasedRateCardType: | ||
| bc := rateCard.GetBillingCadence() | ||
| if bc == nil { | ||
| return fmt.Errorf("billing cadence is required for usage-based rate card") | ||
| } | ||
|
|
||
| rcNew = &productcatalog.UsageBasedRateCard{ | ||
| RateCardMeta: mNew, | ||
| BillingCadence: *bc, | ||
| } | ||
| default: | ||
| return fmt.Errorf("unsupported RateCard type: %s", rateCard.Type()) | ||
| } | ||
|
|
||
| if err := rateCard.Merge(rcNew); err != nil { | ||
| return fmt.Errorf("failed to merge RateCard: %w", err) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| *rateCards = rateCardsClone |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Code duplication between addon and plan services
The feature resolution logic is nearly identical between the addon and plan services. Consider extracting this logic into a common utility package to avoid duplication and ensure consistent behavior.
You could create a shared utility function in a common package:
// package productcatalog/util
func ResolveFeatures(ctx context.Context, featureService FeatureService, namespace string, rateCards *productcatalog.RateCards) error {
// Implementation here
}
// Define a minimal interface for the feature service
type FeatureService interface {
ListFeatures(ctx context.Context, params feature.ListFeaturesParams) (pagination.PagedResponse[feature.Feature], error)
}Then both services could use this function:
func (s service) resolveFeatures(ctx context.Context, namespace string, rateCards *productcatalog.RateCards) error {
return util.ResolveFeatures(ctx, s.feature, namespace, rateCards)
}| featureList, err := s.feature.ListFeatures(ctx, feature.ListFeaturesParams{ | ||
| IDsOrKeys: rateCardFeatureKeys, | ||
| IDsOrKeys: rateCardFeatureKeysOrIDs, | ||
| Namespace: namespace, | ||
| Page: pagination.Page{ | ||
| PageSize: len(rateCardFeatures), | ||
| PageNumber: 1, | ||
| }, | ||
| Page: pagination.Page{}, // lets return all features | ||
| }) | ||
| if err != nil { | ||
| return fmt.Errorf("failed to list Features for RateCards: %w", err) | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Consider specifying a page size for feature listing
Unlike in the addon service implementation, the page size is not specified here, which could potentially lead to fetching more data than needed. Consider adding a specific page size based on the number of collected keys/IDs.
featureList, err := s.feature.ListFeatures(ctx, feature.ListFeaturesParams{
IDsOrKeys: rateCardFeatureKeysOrIDs,
Namespace: namespace,
- Page: pagination.Page{}, // lets return all features
+ Page: pagination.Page{
+ PageSize: len(rateCardFeatureKeysOrIDs), // limit to what we need
+ PageNumber: 1,
+ },
})📝 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.
| featureList, err := s.feature.ListFeatures(ctx, feature.ListFeaturesParams{ | |
| IDsOrKeys: rateCardFeatureKeys, | |
| IDsOrKeys: rateCardFeatureKeysOrIDs, | |
| Namespace: namespace, | |
| Page: pagination.Page{ | |
| PageSize: len(rateCardFeatures), | |
| PageNumber: 1, | |
| }, | |
| Page: pagination.Page{}, // lets return all features | |
| }) | |
| if err != nil { | |
| return fmt.Errorf("failed to list Features for RateCards: %w", err) | |
| } | |
| featureList, err := s.feature.ListFeatures(ctx, feature.ListFeaturesParams{ | |
| IDsOrKeys: rateCardFeatureKeysOrIDs, | |
| Namespace: namespace, | |
| Page: pagination.Page{ | |
| PageSize: len(rateCardFeatureKeysOrIDs), // limit to what we need | |
| PageNumber: 1, | |
| }, | |
| }) | |
| if err != nil { | |
| return fmt.Errorf("failed to list Features for RateCards: %w", err) | |
| } |
Overview
subscription.RateCardcan be replaced withproductcatalog.RateCardSummary by CodeRabbit