Repository navigation
feat(feature): migrate meter_slug to meter_id - #3987
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughMigrate feature-to-meter association from slug-based ( Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant ProductCatalog as ProductCatalog Service
participant MeterSvc as MeterService
participant EntDB as Ent/Postgres
participant FeatureRepo as FeatureRepo
Client->>ProductCatalog: CreateFeature(inputs with MeterID or meterSlug)
ProductCatalog->>MeterSvc: GetMeterByIDOrSlug(IDOrSlug = incoming MeterID or slug)
MeterSvc->>EntDB: Query meters by ID or slug
EntDB-->>MeterSvc: Meter (ID, Key)
MeterSvc-->>ProductCatalog: ResolvedMeter (ID, Key)
ProductCatalog->>EntDB: Create Feature (set meter_id = resolved.ID)
EntDB-->>FeatureRepo: Feature record created (meter_id, edge to Meter)
FeatureRepo-->>ProductCatalog: CreatedFeature (includes Meter edge for legacy MeterSlug)
ProductCatalog-->>Client: Return created feature (MeterID + legacy MeterSlug)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Possibly related PRs
Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 9
🧹 Nitpick comments (6)
openmeter/entitlement/service/scheduling_test.go (1)
577-592: Consider: Features inTestSupersedingdon't useMeterID.The features created here (lines 578-592) don't set
MeterID, unlikeTestCreateEntitlementWithGrantsandTestSchedulingwhich were updated. If these features intentionally don't need a meter association, that's fine. But if they should follow the same pattern, you might want to add a meter and link it viaMeterIDfor consistency.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/entitlement/service/scheduling_test.go` around lines 577 - 592, TestSuperseding creates features feat and feat2 via featureRepo.CreateFeature without setting MeterID; if they should be associated with a meter for consistency with TestCreateEntitlementWithGrants/TestScheduling, create a meter (e.g., via deps.meterRepo.CreateMeter or existing helper) inside TestSuperseding and pass its ID in the CreateFeatureInputs.MeterID field when calling featureRepo.CreateFeature for both feat and feat2 so the features are linked to the meter.openmeter/entitlement/service/utils_test.go (1)
175-193: Useful helper — tiny context consistency tweak.This is a solid addition. Minor nit: at
Line 189, usingt.Context()instead ofcontext.Background()keeps DB calls tied to test lifecycle/cancellation.Suggested tweak
- Save(context.Background()) + Save(t.Context())🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/entitlement/service/utils_test.go` around lines 175 - 193, In createMeterInPG, replace the hard-coded context.Background() used for the DB Save call with the test's context by calling t.Context() so the database operation is tied to the test lifecycle and cancellation; update the Save(context.Background()) invocation in createMeterInPG to Save(t.Context()).openmeter/entitlement/adapter/entitlement.go (1)
266-285: Small DB-path optimization: short-circuit on empty matches.Nice move to edge-based filtering. One quick improvement: after
Line 271, early-return when customer or feature lists are empty to skip the entitlement query and avoid relying on emptyIN (...)semantics.Suggested refactor
features, err := repo.db.Feature.Query().Where( db_feature.Namespace(eventFilter.Namespace), db_feature.HasMeterWith(db_meter.KeyIn(eventFilter.MeterSlugs...)), db_feature.ArchivedAtIsNil(), ).All(ctx) if err != nil { return nil, fmt.Errorf("failed to query features by meters: %w", err) } + + if len(customers) == 0 || len(features) == 0 { + return result, nil + } entitlements, err := repo.db.Entitlement.Query(). Where(🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/entitlement/adapter/entitlement.go` around lines 266 - 285, After resolving customers and features via repo.db.Feature.Query and the customer query (using eventFilter.Namespace and eventFilter.MeterSlugs), add a short-circuit: if the customers slice or the features slice is empty, return an empty entitlement result and nil error instead of executing repo.db.Entitlement.Query with empty IN(...) predicates (i.e., avoid calling db_entitlement.CustomerIDIn or db_entitlement.FeatureIDIn with empty lists); place this check immediately after the features are loaded so the entitlement query is skipped when there are no matching customers or features.openmeter/entitlement/metered/utils_test.go (1)
126-141: Populateslugon the direct PG meter fixture too.This helper now bypasses the migration and inserts meters straight into Postgres. Right now it only satisfies the
meter_idFK, so any path that resolvesmeter_id -> meters.slugagainst the DB won’t get exercised here even though that’s part of the rollout.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/entitlement/metered/utils_test.go` around lines 126 - 141, The PG fixture creation loop for meters (the block invoking dbClient.Meter.Create().SetID(...).SetNamespace(...).SetKey(...).Save(...)) omits the meter slug, so add SetSlug(met.Slug) to the builder chain when creating each meter so the direct-DB fixture populates the slug field and satisfies any code paths resolving meter_id -> meters.slug; ensure you use the same met.Slug value from the testMeters fixture when calling SetSlug on the Create builder.openmeter/productcatalog/feature/repository.go (1)
41-41: Consider renaming the method for extra clarity — while the parameter is already namedmeterID, explicitly encoding "ID" in the method name (likeHasActiveFeatureForMeterID) would make the API contract even more obvious to callers and reduce the chance of confusion in the future.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/productcatalog/feature/repository.go` at line 41, Rename the repository method HasActiveFeatureForMeter to explicitly indicate it expects a meter ID by renaming it to HasActiveFeatureForMeterID; update the function signature in the interface and all implementing types/methods (e.g., any struct methods named HasActiveFeatureForMeter) and then update all callers to use HasActiveFeatureForMeterID; ensure you run tests/compile to catch missed references and consider adding a short forwarding shim (old name calling new name) only if you need a transitional compatibility layer.openmeter/entitlement/metered/lateevents_test.go (1)
144-155: Mirrorslugin the direct meter fixture too.This helper writes the meter row straight through Ent, so it’s worth seeding the new slug column here as well. That keeps the late-event fixture aligned with migrated data instead of silently skipping the reverse-lookup part of the change.
As per coding guidelines,
**/*_test.go: Make sure the tests are comprehensive and cover the changes.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/entitlement/metered/lateevents_test.go` around lines 144 - 155, The meter fixture creation currently sets fields via dbClient.Meter.Create().SetID(...).SetNamespace(...).SetName(...).SetKey(...).SetGroupBy(...).SetAggregation(...).SetEventType(...).SetNillableValueProperty(...).Save(...) but does not populate the new slug column; update the builder chain for the meter fixture to also set the slug value (e.g. call SetSlug(met.Slug) or the appropriate SetNillableSlug if slug can be nil) so the Ent seed matches migrated data and the late-events test exercises the reverse-lookup logic.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@openmeter/entitlement/metered/connector.go`:
- Around line 154-156: The nil-only guard around feature.MeterID is insufficient
because an empty string (e.g. ptr("")) can slip through; update the check in the
connector code that currently inspects feature.MeterID so it returns the same
entitlement.InvalidFeatureError when feature.MeterID is nil OR when
*feature.MeterID == "" (i.e., empty string), referencing the same FeatureID and
Message values to keep behavior consistent.
In `@openmeter/meter/mockadapter/adapter.go`:
- Around line 72-78: Change SetDBClient to return an error (func (c *adapter)
SetDBClient(client *entdb.Client) error), call ReplaceMeters and surface its
error instead of discarding it: after setting c.dbClient = client, if
len(c.meters) > 0 call err := c.ReplaceMeters(context.Background(), c.meters);
if err != nil reset c.dbClient = nil (to avoid partial setup) and return err;
otherwise return nil. Update all callers of adapter.SetDBClient to handle the
returned error.
In `@openmeter/meter/mockadapter/meter.go`:
- Around line 103-119: The current lookup swallows DB lookup errors and always
falls through to Create; update the logic around c.dbClient.Meter.Get(ctx, m.ID)
so that if err != nil you return that error immediately (fail fast) and only
call Create when exists == nil; also ensure the created row mirrors the migrated
slug-backed shape by seeding slug from m.Key (use SetSlug(m.Key)) in the Create
chain alongside the existing SetKey and other setters; reference Meter.Get and
Meter.Create (and the SetSlug/SetKey setters) when making the changes.
In `@openmeter/meter/service.go`:
- Line 67: The Validate() method currently checks SlugFilter for empty strings
but omits the new IDFilter; update Validate() to mirror the SlugFilter check for
IDFilter: if IDFilter is non-nil iterate its entries, trim/inspect each string
and return an error when any entry is empty (same error text/format used for
SlugFilter) so empty IDs are rejected before reaching the DB; ensure you
reference IDFilter and the Validate() method and keep behavior consistent with
SlugFilter validation.
In `@openmeter/productcatalog/adapter/feature.go`:
- Around line 213-215: The MeterSlugs filter must fall back to the legacy
features.meter_slug column when the meter edge is nil; update the query
condition where params.MeterSlugs is used so it matches either the meter edge or
the legacy column. Replace the single predicate
query.Where(db_feature.HasMeterWith(db_meter.KeyIn(params.MeterSlugs...))) with
a combined predicate that ORs db_feature.HasMeterWith(db_meter.KeyIn(...)) and
db_feature.MeterSlugIn(params.MeterSlugs...), and apply the same change at the
other occurrence referenced (lines ~303-306) so legacy rows with
features.meter_slug still match; keep repo-level writes hydrating the meter edge
as noted.
- Around line 49-50: CreateFeature currently returns a feature without the Meter
edge populated (it only calls SetNillableMeterID(feat.MeterID)), causing a shape
mismatch with GetByIdOrKey and ListFeatures which preload Edges.Meter and
populate MeterSlug; fix by making CreateFeature return the same shape as
reads—either persist MeterSlug alongside MeterID or, after saving in
CreateFeature, re-query the saved entity with the same preload used by
GetByIdOrKey/ListFeatures (Preload("Edges.Meter")) and map that result so
MeterSlug is set (or explicitly set feat.MeterSlug = feat.Edges.Meter.Slug)
before returning. Ensure the change targets CreateFeature and keeps
SetNillableMeterID/Edges.Meter/MeterSlug consistent with the mapping used by
GetByIdOrKey and ListFeatures.
In `@openmeter/productcatalog/feature/connector.go`:
- Around line 120-125: The code currently converts any error from
meterService.GetMeterByIDOrSlug into NewMeterNotFoundError; change this to only
translate genuine not-found errors: call c.meterService.GetMeterByIDOrSlug as
before, then if err != nil check the concrete not-found condition (e.g.
errors.Is(err, meterpkg.ErrNotFound) or meterpkg.IsNotFound(err) or type-assert
to meterpkg.MeterNotFoundError) and only then return
meterpkg.NewMeterNotFoundError(meterID); for all other errors return the
original/wrapped error (e.g. return Feature{}, fmt.Errorf("get meter %s: %w",
meterID, err)) so transient DB/service failures are preserved.
In `@openmeter/subscription/testutils/feature.go`:
- Around line 18-20: The test fixture currently uses a process-global mutable
variable ExampleFeatureMeterID (set in SetupServices), which can be overwritten
by parallel tests; change the fixture APIs to stop using ExampleFeatureMeterID
and instead accept and propagate the meter ID as a parameter: update
SetupServices to return the created meter ID (or return a context/fixture struct
containing it) and modify any helpers/functions that currently read
ExampleFeatureMeterID (including the functions referenced around lines 23-49 and
62-70) to take a meterID string argument so state is local to each test and no
shared global mutable ExampleFeatureMeterID is used.
In `@openmeter/subscription/testutils/service.go`:
- Around line 78-82: ExampleFeatureMeterID is currently a package-level var that
gets reassigned inside NewService, causing order-dependent tests; remove the
package global ExampleFeatureMeterID and instead generate the ULID inside
NewService and place that generated ID into the returned dependencies struct so
callers read the meter ID from the returned value. Update the code that builds
meteradapter.New([...ManagedResource{ ID: ... }]) to use the locally generated
id, add a field on the returned struct (or existing return type) to expose that
meter ID, and update tests to read the meter ID from the returned dependencies
instead of the global ExampleFeatureMeterID; ensure no other code relies on the
removed package variable.
---
Nitpick comments:
In `@openmeter/entitlement/adapter/entitlement.go`:
- Around line 266-285: After resolving customers and features via
repo.db.Feature.Query and the customer query (using eventFilter.Namespace and
eventFilter.MeterSlugs), add a short-circuit: if the customers slice or the
features slice is empty, return an empty entitlement result and nil error
instead of executing repo.db.Entitlement.Query with empty IN(...) predicates
(i.e., avoid calling db_entitlement.CustomerIDIn or db_entitlement.FeatureIDIn
with empty lists); place this check immediately after the features are loaded so
the entitlement query is skipped when there are no matching customers or
features.
In `@openmeter/entitlement/metered/lateevents_test.go`:
- Around line 144-155: The meter fixture creation currently sets fields via
dbClient.Meter.Create().SetID(...).SetNamespace(...).SetName(...).SetKey(...).SetGroupBy(...).SetAggregation(...).SetEventType(...).SetNillableValueProperty(...).Save(...)
but does not populate the new slug column; update the builder chain for the
meter fixture to also set the slug value (e.g. call SetSlug(met.Slug) or the
appropriate SetNillableSlug if slug can be nil) so the Ent seed matches migrated
data and the late-events test exercises the reverse-lookup logic.
In `@openmeter/entitlement/metered/utils_test.go`:
- Around line 126-141: The PG fixture creation loop for meters (the block
invoking
dbClient.Meter.Create().SetID(...).SetNamespace(...).SetKey(...).Save(...))
omits the meter slug, so add SetSlug(met.Slug) to the builder chain when
creating each meter so the direct-DB fixture populates the slug field and
satisfies any code paths resolving meter_id -> meters.slug; ensure you use the
same met.Slug value from the testMeters fixture when calling SetSlug on the
Create builder.
In `@openmeter/entitlement/service/scheduling_test.go`:
- Around line 577-592: TestSuperseding creates features feat and feat2 via
featureRepo.CreateFeature without setting MeterID; if they should be associated
with a meter for consistency with
TestCreateEntitlementWithGrants/TestScheduling, create a meter (e.g., via
deps.meterRepo.CreateMeter or existing helper) inside TestSuperseding and pass
its ID in the CreateFeatureInputs.MeterID field when calling
featureRepo.CreateFeature for both feat and feat2 so the features are linked to
the meter.
In `@openmeter/entitlement/service/utils_test.go`:
- Around line 175-193: In createMeterInPG, replace the hard-coded
context.Background() used for the DB Save call with the test's context by
calling t.Context() so the database operation is tied to the test lifecycle and
cancellation; update the Save(context.Background()) invocation in
createMeterInPG to Save(t.Context()).
In `@openmeter/productcatalog/feature/repository.go`:
- Line 41: Rename the repository method HasActiveFeatureForMeter to explicitly
indicate it expects a meter ID by renaming it to HasActiveFeatureForMeterID;
update the function signature in the interface and all implementing
types/methods (e.g., any struct methods named HasActiveFeatureForMeter) and then
update all callers to use HasActiveFeatureForMeterID; ensure you run
tests/compile to catch missed references and consider adding a short forwarding
shim (old name calling new name) only if you need a transitional compatibility
layer.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 52e86071-4bff-4cce-8604-fd0b2ac192b7
⛔ Files ignored due to path filters (16)
go.sumis excluded by!**/*.sum,!**/*.sumopenmeter/ent/db/client.gois excluded by!**/ent/db/**openmeter/ent/db/feature.gois excluded by!**/ent/db/**openmeter/ent/db/feature/feature.gois excluded by!**/ent/db/**openmeter/ent/db/feature/where.gois excluded by!**/ent/db/**openmeter/ent/db/feature_create.gois excluded by!**/ent/db/**openmeter/ent/db/feature_query.gois excluded by!**/ent/db/**openmeter/ent/db/meter.gois excluded by!**/ent/db/**openmeter/ent/db/meter/meter.gois excluded by!**/ent/db/**openmeter/ent/db/meter/where.gois excluded by!**/ent/db/**openmeter/ent/db/meter_create.gois excluded by!**/ent/db/**openmeter/ent/db/meter_query.gois excluded by!**/ent/db/**openmeter/ent/db/meter_update.gois excluded by!**/ent/db/**openmeter/ent/db/migrate/schema.gois excluded by!**/ent/db/**openmeter/ent/db/mutation.gois excluded by!**/ent/db/**tools/migrate/migrations/atlas.sumis excluded by!**/*.sum,!**/*.sum
📒 Files selected for processing (55)
api/v3/handlers/featurecost/query.goopenmeter/billing/worker/subscriptionsync/service/suitebase_test.goopenmeter/cost/adapter/adapter.goopenmeter/ent/schema/feature.goopenmeter/ent/schema/meter.goopenmeter/entitlement/adapter/entitlement.goopenmeter/entitlement/metered/balance_test.goopenmeter/entitlement/metered/connector.goopenmeter/entitlement/metered/grant_owner_adapter.goopenmeter/entitlement/metered/grant_owner_adapter_test.goopenmeter/entitlement/metered/lateevents_test.goopenmeter/entitlement/metered/reset_test.goopenmeter/entitlement/metered/utils_test.goopenmeter/entitlement/service/access_test.goopenmeter/entitlement/service/scheduling_test.goopenmeter/entitlement/service/utils_test.goopenmeter/meter/adapter/manage.goopenmeter/meter/adapter/meter.goopenmeter/meter/mockadapter/adapter.goopenmeter/meter/mockadapter/meter.goopenmeter/meter/service.goopenmeter/meter/service/manage.goopenmeter/notification/consumer/entitlementbalancethreshold_test.goopenmeter/notification/service/service.goopenmeter/productcatalog/adapter/feature.goopenmeter/productcatalog/adapter/feature_test.goopenmeter/productcatalog/driver/parser.goopenmeter/productcatalog/feature/connector.goopenmeter/productcatalog/feature/feature.goopenmeter/productcatalog/feature/featuremeter.goopenmeter/productcatalog/feature/repository.goopenmeter/productcatalog/ratecard_test.goopenmeter/productcatalog/testutils/env.goopenmeter/productcatalog/testutils/feature.goopenmeter/subscription/testutils/feature.goopenmeter/subscription/testutils/service.gotest/app/custominvoicing/invocing_test.gotest/app/stripe/invoice_test.gotest/app/testenv.gotest/billing/discount_test.gotest/billing/invoice_test.gotest/billing/schemamigration_test.gotest/billing/suite.gotest/billing/tax_test.gotest/customer/subject.gotest/entitlement/regression/framework_test.gotest/entitlement/regression/scenario_test.gotest/notification/consumer_balance.gotest/notification/event.gotest/notification/rule.gotest/notification/testenv.gotest/subscription/scenario_editaligned_test.gotest/subscription/scenario_editcancel_test.gotools/migrate/migrations/20260320171954_feature-meter-id.down.sqltools/migrate/migrations/20260320171954_feature-meter-id.up.sql
There was a problem hiding this comment.
🧹 Nitpick comments (1)
openmeter/productcatalog/adapter/feature.go (1)
15-16: Duplicate import with different aliases.The same package is imported twice with two different aliases (
db_meteranddbmeter). This is a bit confusing to read—pick one alias and stick with it throughout the file.✨ Suggested consolidation
- db_meter "github.com/openmeterio/openmeter/openmeter/ent/db/meter" - dbmeter "github.com/openmeterio/openmeter/openmeter/ent/db/meter" + dbmeter "github.com/openmeterio/openmeter/openmeter/ent/db/meter"Then update line 227 to use
dbmeter.KeyIn(params.MeterSlugs...)instead ofdb_meter.KeyIn(...).🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/productcatalog/adapter/feature.go` around lines 15 - 16, Remove the duplicate import: pick one alias (e.g., dbmeter) and delete the other (db_meter) in feature.go, then update all usages to the chosen alias — specifically replace db_meter.KeyIn(params.MeterSlugs...) with dbmeter.KeyIn(params.MeterSlugs...) and any other occurrences of db_meter in functions that reference the ent/db/meter package so the file consistently uses a single import alias.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@openmeter/productcatalog/adapter/feature.go`:
- Around line 15-16: Remove the duplicate import: pick one alias (e.g., dbmeter)
and delete the other (db_meter) in feature.go, then update all usages to the
chosen alias — specifically replace db_meter.KeyIn(params.MeterSlugs...) with
dbmeter.KeyIn(params.MeterSlugs...) and any other occurrences of db_meter in
functions that reference the ent/db/meter package so the file consistently uses
a single import alias.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 21380e18-661b-48fc-952a-30b93651417e
📒 Files selected for processing (1)
openmeter/productcatalog/adapter/feature.go
There was a problem hiding this comment.
🧹 Nitpick comments (1)
openmeter/productcatalog/feature/connector.go (1)
146-148: Dead code — this check is unreachable.At this point,
erris guaranteed to benil:
- If
GetMeterByIDOrSlugfailed, we already returned on lines 126-128- If
MeterGroupByFilters.Validatefailed, we returned on line 143This block can be safely removed to clean things up.
🧹 Suggested cleanup
if err != nil { return Feature{}, err } } - if err != nil { - return Feature{}, err - } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/productcatalog/feature/connector.go` around lines 146 - 148, The nil-check and return block that tests err after MeterGroupByFilters.Validate is unreachable and should be removed: in the function containing the calls to GetMeterByIDOrSlug and MeterGroupByFilters.Validate (the code that returns Feature{} on earlier failures), delete the redundant "if err != nil { return Feature{}, err }" block so control flow does not contain dead code; keep existing error returns from GetMeterByIDOrSlug and MeterGroupByFilters.Validate and do not add a new error variable or return.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@openmeter/productcatalog/feature/connector.go`:
- Around line 146-148: The nil-check and return block that tests err after
MeterGroupByFilters.Validate is unreachable and should be removed: in the
function containing the calls to GetMeterByIDOrSlug and
MeterGroupByFilters.Validate (the code that returns Feature{} on earlier
failures), delete the redundant "if err != nil { return Feature{}, err }" block
so control flow does not contain dead code; keep existing error returns from
GetMeterByIDOrSlug and MeterGroupByFilters.Validate and do not add a new error
variable or return.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: c85c672f-7c26-4e57-b8e2-1598a4903113
📒 Files selected for processing (13)
openmeter/entitlement/adapter/entitlement.goopenmeter/entitlement/metered/connector.goopenmeter/entitlement/service/utils_test.goopenmeter/meter/mockadapter/adapter.goopenmeter/meter/mockadapter/meter.goopenmeter/meter/service.goopenmeter/productcatalog/feature/connector.goopenmeter/productcatalog/testutils/env.goopenmeter/subscription/testutils/service.gotest/app/testenv.gotest/billing/suite.gotest/entitlement/regression/framework_test.gotest/notification/testenv.go
✅ Files skipped from review due to trivial changes (2)
- test/app/testenv.go
- openmeter/entitlement/metered/connector.go
🚧 Files skipped from review as they are similar to previous changes (5)
- openmeter/meter/service.go
- openmeter/entitlement/service/utils_test.go
- openmeter/entitlement/adapter/entitlement.go
- test/entitlement/regression/framework_test.go
- openmeter/meter/mockadapter/adapter.go
Re-fetch the feature with meter edge after creation so MeterSlug is populated from the meter's key, consistent with GetByIdOrKey. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
8d70fab to
07ccb62
Compare
There was a problem hiding this comment.
Actionable comments posted: 4
♻️ Duplicate comments (1)
openmeter/productcatalog/adapter/feature.go (1)
225-227:⚠️ Potential issue | 🟠 MajorKeep the legacy
meter_slugfallback during phase 1.
tools/migrate/feature_meter_id_test.gointentionally leaves unmatched legacy rows withmeter_id = NULL. With the edge-only slug filter here and the edge-only mapping below, those rows stop matchingMeterSlugsqueries and come back withMeterSlug == nileven thoughfeatures.meter_slugis still populated. Please keep the old column as a fallback until phase 2.🧭 Minimal fallback
if len(params.MeterSlugs) > 0 { - query = query.Where(dbfeature.HasMeterWith(dbmeter.KeyIn(params.MeterSlugs...))) + query = query.Where(dbfeature.Or( + dbfeature.MeterSlugIn(params.MeterSlugs...), + dbfeature.HasMeterWith(dbmeter.KeyIn(params.MeterSlugs...)), + )) } @@ // Deprecated: kept for v1 API backward compatibility if entity.Edges.Meter != nil { f.MeterSlug = &entity.Edges.Meter.Key +} else if entity.MeterSlug != nil { + f.MeterSlug = entity.MeterSlug }Also applies to: 315-318
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/productcatalog/adapter/feature.go` around lines 225 - 227, The current MeterSlugs filter only matches via the new edge mapping (dbfeature.HasMeterWith(dbmeter.KeyIn(...))) and omits legacy rows with features.meter_slug populated; modify the query building in the MeterSlugs branch to OR-in the legacy column as a fallback so rows match if either the mapped relation matches OR the legacy features.meter_slug equals one of params.MeterSlugs (e.g., wrap the existing dbfeature.HasMeterWith(...) predicate in an OR with a predicate that checks the legacy column values), and apply the same change at the other occurrence noted (the block around lines 315-318).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@openmeter/entitlement/metered/utils_test.go`:
- Around line 126-141: The test currently seeds meters directly via
dbClient.Meter.Create(), duplicating mapping logic and omitting
slug/reverse-lookup data; instead, seed the testMeters through the existing
meter adapter used elsewhere (e.g., the adapter/meterAdapter helper) so the DB
fixture aligns with the in-memory adapter and production mapping (replace the
loop that calls dbClient.Meter.Create() with calls to the adapter's seed/create
method for each entry in testMeters, ensuring the adapter persists slug and
reverse-lookup fields).
In `@openmeter/meter/mockadapter/meter.go`:
- Around line 99-129: ReplaceMeters currently swaps c.meters before syncing PG;
instead, perform the PostgreSQL reconciliation first and only assign c.meters on
success: inside ReplaceMeters, gather the incoming meters slice and the current
PG rows (via c.dbClient.Meter.Get/List methods), compute which IDs to create,
update (upsert), and delete; run those ops in a DB transaction (use c.dbClient
transactional APIs) using Get/Create/Update/Delete (and entdb.IsNotFound checks)
so removed meters are deleted and changed meters are updated, failing the
transaction on any error; only after the transaction commits, set c.meters =
slices.Clone(meters); ensure any early error returns without mutating c.meters
to avoid partial in-memory commit.
In `@test/notification/testenv.go`:
- Around line 139-141: On failure of meterService.SetDBClient(entClient) you
must close the already-opened DB handles to avoid leaking resources: call the
appropriate shutdowns for entClient and driver (e.g., entClient.Close() and
driver.Close()/sqlDB.Close() or the migration instance's Close) before returning
the error; alternatively extract a small cleanup helper (e.g.,
cleanupDBResources(driver, entClient)) and invoke it on this error path so
resources opened earlier in the function are always closed when SetDBClient
fails. Ensure the closer built on the success path is still returned only on
full success.
In `@tools/migrate/feature_meter_id_test.go`:
- Around line 94-156: Add assertions that the migration also backfills
meters.slug from meters.key: for the meter rows referenced in the test use the
existing activeMeterID and deletedMeterNewID values and run queries like "SELECT
slug, key FROM meters WHERE id = $1" and assert slug is valid and equal to key
for both IDs; also assert the meters.slug column exists in information_schema
(similar to the features column check) to ensure the meter-side backfill is
covered.
---
Duplicate comments:
In `@openmeter/productcatalog/adapter/feature.go`:
- Around line 225-227: The current MeterSlugs filter only matches via the new
edge mapping (dbfeature.HasMeterWith(dbmeter.KeyIn(...))) and omits legacy rows
with features.meter_slug populated; modify the query building in the MeterSlugs
branch to OR-in the legacy column as a fallback so rows match if either the
mapped relation matches OR the legacy features.meter_slug equals one of
params.MeterSlugs (e.g., wrap the existing dbfeature.HasMeterWith(...) predicate
in an OR with a predicate that checks the legacy column values), and apply the
same change at the other occurrence noted (the block around lines 315-318).
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 5f466d12-4431-47a0-9fc8-cc0a626edde8
⛔ Files ignored due to path filters (15)
openmeter/ent/db/client.gois excluded by!**/ent/db/**openmeter/ent/db/feature.gois excluded by!**/ent/db/**openmeter/ent/db/feature/feature.gois excluded by!**/ent/db/**openmeter/ent/db/feature/where.gois excluded by!**/ent/db/**openmeter/ent/db/feature_create.gois excluded by!**/ent/db/**openmeter/ent/db/feature_query.gois excluded by!**/ent/db/**openmeter/ent/db/meter.gois excluded by!**/ent/db/**openmeter/ent/db/meter/meter.gois excluded by!**/ent/db/**openmeter/ent/db/meter/where.gois excluded by!**/ent/db/**openmeter/ent/db/meter_create.gois excluded by!**/ent/db/**openmeter/ent/db/meter_query.gois excluded by!**/ent/db/**openmeter/ent/db/meter_update.gois excluded by!**/ent/db/**openmeter/ent/db/migrate/schema.gois excluded by!**/ent/db/**openmeter/ent/db/mutation.gois excluded by!**/ent/db/**tools/migrate/migrations/atlas.sumis excluded by!**/*.sum,!**/*.sum
📒 Files selected for processing (57)
api/v3/handlers/featurecost/query.goopenmeter/billing/worker/subscriptionsync/service/suitebase_test.goopenmeter/cost/adapter/adapter.goopenmeter/ent/schema/feature.goopenmeter/ent/schema/meter.goopenmeter/entitlement/adapter/entitlement.goopenmeter/entitlement/metered/balance_test.goopenmeter/entitlement/metered/connector.goopenmeter/entitlement/metered/grant_owner_adapter.goopenmeter/entitlement/metered/grant_owner_adapter_test.goopenmeter/entitlement/metered/lateevents_test.goopenmeter/entitlement/metered/reset_test.goopenmeter/entitlement/metered/utils_test.goopenmeter/entitlement/service/access_test.goopenmeter/entitlement/service/scheduling_test.goopenmeter/entitlement/service/utils_test.goopenmeter/meter/adapter/manage.goopenmeter/meter/adapter/meter.goopenmeter/meter/errors.goopenmeter/meter/mockadapter/adapter.goopenmeter/meter/mockadapter/meter.goopenmeter/meter/service.goopenmeter/meter/service/manage.goopenmeter/notification/consumer/entitlementbalancethreshold_test.goopenmeter/notification/service/service.goopenmeter/productcatalog/adapter/feature.goopenmeter/productcatalog/adapter/feature_test.goopenmeter/productcatalog/driver/parser.goopenmeter/productcatalog/feature/connector.goopenmeter/productcatalog/feature/feature.goopenmeter/productcatalog/feature/featuremeter.goopenmeter/productcatalog/feature/repository.goopenmeter/productcatalog/ratecard_test.goopenmeter/productcatalog/testutils/env.goopenmeter/productcatalog/testutils/feature.goopenmeter/subscription/testutils/feature.goopenmeter/subscription/testutils/service.gotest/app/custominvoicing/invocing_test.gotest/app/stripe/invoice_test.gotest/app/testenv.gotest/billing/discount_test.gotest/billing/invoice_test.gotest/billing/schemamigration_test.gotest/billing/suite.gotest/billing/tax_test.gotest/customer/subject.gotest/entitlement/regression/framework_test.gotest/entitlement/regression/scenario_test.gotest/notification/consumer_balance.gotest/notification/event.gotest/notification/rule.gotest/notification/testenv.gotest/subscription/scenario_editaligned_test.gotest/subscription/scenario_editcancel_test.gotools/migrate/feature_meter_id_test.gotools/migrate/migrations/20260320171954_feature-meter-id.down.sqltools/migrate/migrations/20260320171954_feature-meter-id.up.sql
💤 Files with no reviewable changes (1)
- openmeter/notification/service/service.go
✅ Files skipped from review due to trivial changes (8)
- test/notification/rule.go
- openmeter/notification/consumer/entitlementbalancethreshold_test.go
- openmeter/entitlement/service/utils_test.go
- openmeter/productcatalog/ratecard_test.go
- test/app/custominvoicing/invocing_test.go
- test/billing/schemamigration_test.go
- openmeter/productcatalog/adapter/feature_test.go
- openmeter/meter/adapter/meter.go
🚧 Files skipped from review as they are similar to previous changes (22)
- test/app/testenv.go
- openmeter/entitlement/metered/connector.go
- test/notification/event.go
- openmeter/entitlement/service/scheduling_test.go
- openmeter/productcatalog/testutils/feature.go
- openmeter/entitlement/metered/grant_owner_adapter.go
- openmeter/entitlement/adapter/entitlement.go
- openmeter/ent/schema/meter.go
- tools/migrate/migrations/20260320171954_feature-meter-id.down.sql
- api/v3/handlers/featurecost/query.go
- openmeter/productcatalog/feature/repository.go
- openmeter/meter/mockadapter/adapter.go
- openmeter/cost/adapter/adapter.go
- openmeter/meter/service/manage.go
- test/app/stripe/invoice_test.go
- openmeter/subscription/testutils/feature.go
- openmeter/entitlement/metered/balance_test.go
- test/billing/tax_test.go
- tools/migrate/migrations/20260320171954_feature-meter-id.up.sql
- openmeter/productcatalog/driver/parser.go
- openmeter/entitlement/metered/lateevents_test.go
- test/billing/suite.go
When ReplaceMeters is called multiple times with the same template DB (e.g., TestEditRunning calling NewService twice), reuse the existing DB meter ID instead of failing on the unique constraint. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
ReplaceMeters already syncs meters to PG via the mock adapter's DB client, so the manual Meter.Create() call caused a duplicate key violation. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Summary
meter_idfield to the Feature entity, replacingmeter_slugfor meter referencesmeter_idforeign keyslugfield to Meter entity for reverse lookupsmeter_idfrom meters table usingmeter_slug, then populate meterslugfromkeymeter_idinstead ofmeter_slugValidation Results
All tests performed against
http://localhost:8888with the server running from thefeat/feature-meter-idbranch.V1 Feature API (
/api/v1/features)meterSlugPOST /api/v1/featuresmeterSlugPOST /api/v1/featuresGET /api/v1/features/{id}meterSlugpopulated via meter edgeGET /api/v1/featuresmeterSlugGET /api/v1/features?meterSlug=...DELETE /api/v1/features/{id}Summary by CodeRabbit
Release Notes
Summary by CodeRabbit
Refactor
Chores