Repository navigation
fix: missing usage attribution for deleted customer - #3327
Conversation
📝 WalkthroughWalkthroughApply time-aware deletion semantics and SQL join-based subject filtering in the customer adapter, enforce not-updatable-if-deleted, set subject CreatedAt/DeletedAt consistently, add CustomerService integration tests, and introduce test environment utilities for DB/migration and wiring. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
✨ Finishing Touches
🧪 Generate unit tests
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 |
4a5d92e to
ae4d594
Compare
ae4d594 to
2aee61e
Compare
|
This is an alternative solution to: #3326 |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (10)
openmeter/customer/adapter/customer.go (3)
229-231: Set CreatedAt on subjects on create — mirror this on updates for consistency/auditability.When adding subject keys during UpdateCustomer, also set CreatedAt so subject timelines are explicit (today it relies on DB default).
Apply in the update subject-create block:
- return repo.db.CustomerSubjects.Create(). + return repo.db.CustomerSubjects.Create(). SetNamespace(input.CustomerID.Namespace). SetCustomerID(input.CustomerID.ID). - SetSubjectKey(subjectKey) + SetSubjectKey(subjectKey). + SetCreatedAt(clock.Now().UTC())
336-341: ID vs Key disambiguation: make ID take precedence deterministically.With Or(ID, And(Key, not deleted)) + Order(ByID ASC), if both match (key equals another customer’s ID), the returned row is implementation-defined. Prefer explicit precedence:
- Try ID first; if not found, try Key; or
- Order by CASE (id = input) first.
Example approach (two-step):
// Try ID path first ent, err := repo.db.Customer. Query(). Where(customerdb.Namespace(ns), customerdb.ID(s)). First(ctx) if ent == nil && entdb.IsNotFound(err) { // Fallback to Key (non-deleted) ent, err = repo.db.Customer. Query(). Where(customerdb.Namespace(ns), customerdb.Key(s), customerdb.DeletedAtIsNil()). First(ctx) }Add a test where one customer’s Key equals another’s ID to lock in behavior.
651-673: SQL join-based subject filtering is reasonable; consider indexing for join/filter pattern.The equality/temporal logic matches the deletion rules. For performance at scale, ensure indexes exist on:
- customer_subjects(customer_id, deleted_at)
- customers(id, deleted_at)
Would you like me to open a follow-up to add these indexes (if missing)?
openmeter/customer/service/service_test.go (4)
46-48: Fix self-comparisons in assertions.These assert the value against itself and never fail. Compare to the expected literals.
Apply:
- assert.Equalf(t, cus.Key, cus.Key, "customer key must match") - assert.Equalf(t, cus.Name, cus.Name, "customer name must match") + assert.Equalf(t, lo.FromPtr(cus.Key), "acme-inc", "customer key must match") + assert.Equalf(t, cus.Name, "ACME Inc.", "customer name must match")
75-75: Typo in subtest name.- t.Run("ByIDDOrKey", func(t *testing.T) { + t.Run("ByIDOrKey", func(t *testing.T) {
176-205: The “ByIDOrKey” post-delete subtests don’t exercise IDOrKey; they rerun ID/Key paths.Use CustomerIDOrKey to verify the new precedence/semantics after deletion.
Apply:
- cusByID, err := env.CustomerService.GetCustomer(ctx, customer.GetCustomerInput{ - CustomerID: &customer.CustomerID{ - Namespace: cus.Namespace, - ID: cus.ID, - }, - }) + cusByID, err := env.CustomerService.GetCustomer(ctx, customer.GetCustomerInput{ + CustomerIDOrKey: &customer.CustomerIDOrKey{ + Namespace: cus.Namespace, + IDOrKey: cus.ID, + }, + }) @@ - cusByKey, err := env.CustomerService.GetCustomer(ctx, customer.GetCustomerInput{ - CustomerKey: &customer.CustomerKey{ - Namespace: cus.Namespace, - Key: lo.FromPtr(cus.Key), - }, - }) + cusByKey, err := env.CustomerService.GetCustomer(ctx, customer.GetCustomerInput{ + CustomerIDOrKey: &customer.CustomerIDOrKey{ + Namespace: cus.Namespace, + IDOrKey: lo.FromPtr(cus.Key), + }, + })Additionally, add a case where a customer’s Key equals another customer’s ID to validate deterministic ID precedence.
140-147: Missing coverage: updating a deleted customer must fail.Add a subtest asserting GenericValidationError when updating after delete.
Apply near the end of the “Delete” block:
t.Run("Delete", func(t *testing.T) { @@ }) + + t.Run("Update after delete must fail", func(t *testing.T) { + _, err := env.CustomerService.UpdateCustomer(ctx, customer.UpdateCustomerInput{ + CustomerID: customer.CustomerID{ + Namespace: cus.Namespace, + ID: cus.ID, + }, + CustomerMutate: customer.CustomerMutate{ + Key: cus.Key, + Name: cus.Name, + UsageAttribution: customer.CustomerUsageAttribution{ + SubjectKeys: []string{"should-not-apply"}, + }, + }, + }) + var vErr *models.GenericValidationError + assert.ErrorAs(t, err, &vErr, "update after delete should be a validation error") + })openmeter/customer/testutils/env.go (3)
64-66: Typo in error message.- t.Errorf("failed to postgres driver: %v", err) + t.Errorf("failed to close postgres driver: %v", err)
89-97: Unused meterAdapter — remove or wire it where needed.It’s created but not used. Simplify the test env unless another service will soon consume it.
- // Init meter service - meterAdapter, err := meteradapter.New(nil) - require.NoErrorf(t, err, "initializing meter adapter must not fail") - require.NotNilf(t, meterAdapter, "meter adapter must not be nil")Also drop the meteradapter import if unused.
55-75: Close order: prefer closing ent Client before underlying drivers.Minor, but avoids potential surprises if client flushes state on Close.
Reorder Close to:
- e.Client.Close()
- e.db.EntDriver.Close()
- e.db.PGDriver.Close()
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
openmeter/customer/adapter/customer.go(6 hunks)openmeter/customer/service/service_test.go(1 hunks)openmeter/customer/testutils/env.go(1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-03-07T12:17:43.129Z
Learnt from: GAlexIHU
PR: openmeterio/openmeter#2383
File: openmeter/entitlement/metered/lateevents_test.go:37-45
Timestamp: 2025-03-07T12:17:43.129Z
Learning: In the OpenMeter codebase, test files like `openmeter/entitlement/metered/lateevents_test.go` may use variables like `meterSlug` and `namespace` without explicit declarations visible in the same file. This appears to be an accepted pattern in their test structure.
Applied to files:
openmeter/customer/testutils/env.go
🧬 Code graph analysis (3)
openmeter/customer/testutils/env.go (3)
openmeter/testutils/pg_driver.go (2)
TestDB(54-58)InitPostgresDB(60-96)openmeter/testutils/logger.go (1)
NewDiscardLogger(14-18)openmeter/watermill/eventbus/eventbus.go (2)
NewMock(150-162)Publisher(61-73)
openmeter/customer/service/service_test.go (3)
openmeter/customer/testutils/env.go (2)
NewTestEnv(77-130)NewTestNamespace(33-33)openmeter/customer/customer.go (7)
CreateCustomerInput(208-211)CustomerMutate(67-77)GetCustomerInput(247-254)CustomerIDOrKey(130-133)GetCustomerByUsageAttributionInput(162-165)ListCustomersInput(180-197)UpdateCustomerInput(226-229)pkg/models/errors.go (1)
GenericNotFoundError(44-46)
openmeter/customer/adapter/customer.go (6)
openmeter/ent/db/customer/where.go (7)
Or(1439-1441)DeletedAtIsNil(348-350)DeletedAtGT(328-330)And(1434-1436)Key(137-139)DeletedAt(86-88)ID(16-18)openmeter/ent/db/customersubjects/where.go (7)
Or(397-399)DeletedAtIsNil(359-361)DeletedAtGT(339-341)And(392-394)CustomerID(64-66)DeletedAt(79-81)ID(14-16)openmeter/ent/db/customer_query.go (1)
CustomerQuery(27-43)openmeter/ent/db/customersubjects_query.go (1)
CustomerSubjectsQuery(21-32)openmeter/ent/db/customer/customer.go (3)
Table(66-66)FieldID(16-16)FieldDeletedAt(26-26)openmeter/ent/db/customersubjects/customersubjects.go (4)
Table(30-30)FieldID(16-16)FieldCustomerID(20-20)FieldDeletedAt(26-26)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
- GitHub Check: Quickstart
- GitHub Check: E2E
- GitHub Check: Analyze (go)
🔇 Additional comments (2)
openmeter/customer/adapter/customer.go (2)
42-45: Broadened default filter looks correct for “scheduled deletions”.Including customers with DeletedAt > now (in addition to null) aligns with “future deletion” semantics.
429-441: The requested verification is in progress.
2aee61e to
64c4196
Compare
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
openmeter/customer/service/customer.go (1)
56-58: Potential type mismatch: passing DeleteCustomerInput where CustomerID is expectedThis is inconsistent with the later usage (Lines 81–86) and likely a compile-time/type error unless DeleteCustomerInput is a type alias of CustomerID. Prefer constructing CustomerID explicitly.
Apply:
- cus, err := s.adapter.GetCustomer(ctx, customer.GetCustomerInput{ - CustomerID: &input, - }) + cus, err := s.adapter.GetCustomer(ctx, customer.GetCustomerInput{ + CustomerID: &customer.CustomerID{ + Namespace: input.Namespace, + ID: input.ID, + }, + })
🧹 Nitpick comments (1)
openmeter/customer/service/customer.go (1)
161-164: Optional: align read-only paths by dropping the transaction wrapper in CustomerExistsFor consistency with List/Get paths and to avoid unnecessary txn overhead.
- return transaction.RunWithNoValue(ctx, s.adapter, func(ctx context.Context) error { - return s.adapter.CustomerExists(ctx, customer) - }) + return s.adapter.CustomerExists(ctx, customer)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
openmeter/customer/service/customer.go(2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
openmeter/customer/service/customer.go (3)
openmeter/customer/service.go (1)
Service(10-15)openmeter/customer/service/service.go (1)
Service(13-19)openmeter/customer/customer.go (2)
GetCustomerByUsageAttributionInput(162-165)Customer(17-27)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
- GitHub Check: E2E
- GitHub Check: Quickstart
- GitHub Check: Migration Checks
- GitHub Check: Lint
- GitHub Check: Build
- GitHub Check: Test
- GitHub Check: Code Generators
- GitHub Check: Analyze (go)
🔇 Additional comments (3)
openmeter/customer/service/customer.go (3)
17-17: LGTM: removing transaction wrapper for ListCustomers simplifies the read pathRead-only list doesn’t need an explicit transaction; passing ctx directly is fine.
108-109: LGTM: GetCustomer passthrough keeps txn context when upstream provides oneSince ctx is forwarded, calls from within transaction.Run(...) (e.g., DeleteCustomer) still execute in the same txn.
113-114: LGTM: direct adapter call for GetCustomerByUsageAttributionConsistent with other read paths and aligns with adapter-driven deletion semantics.
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
openmeter/customer/adapter/customer.go (2)
218-235: Guard CreateBulk against empty inputs.ent’s CreateBulk can error on zero specs; wrap it to no-op when there are no subject keys.
Apply:
- customerSubjects, err := repo.db.CustomerSubjects. - CreateBulk( - lo.Map( - input.UsageAttribution.SubjectKeys, - func(subjectKey string, _ int) *entdb.CustomerSubjectsCreate { - return repo.db.CustomerSubjects.Create(). - SetNamespace(customerEntity.Namespace). - SetCustomerID(customerEntity.ID). - SetSubjectKey(subjectKey). - SetCreatedAt(customerEntity.CreatedAt) - }, - )..., - ). - Save(ctx) - if err != nil { - if entdb.IsConstraintError(err) { - return nil, customer.NewSubjectKeyConflictError( - input.Namespace, - input.UsageAttribution.SubjectKeys, - ) - } - - return nil, fmt.Errorf("failed to create customer: failed to add subject keys: %w", err) - } + var customerSubjects []*entdb.CustomerSubjects + if len(input.UsageAttribution.SubjectKeys) > 0 { + customerSubjects, err = repo.db.CustomerSubjects. + CreateBulk( + lo.Map( + input.UsageAttribution.SubjectKeys, + func(subjectKey string, _ int) *entdb.CustomerSubjectsCreate { + return repo.db.CustomerSubjects.Create(). + SetNamespace(customerEntity.Namespace). + SetCustomerID(customerEntity.ID). + SetSubjectKey(subjectKey). + SetCreatedAt(customerEntity.CreatedAt) + }, + )..., + ). + Save(ctx) + if err != nil { + if entdb.IsConstraintError(err) { + return nil, customer.NewSubjectKeyConflictError( + input.Namespace, + input.UsageAttribution.SubjectKeys, + ) + } + return nil, fmt.Errorf("failed to create customer: failed to add subject keys: %w", err) + } + }
392-395: Use GTE for subject DeletedAt in usage-attribution lookup.For consistency with other predicates and to avoid boundary misses at exact “now”, switch DeletedAtGT(now) → DeletedAtGTE(now).
customersubjectsdb.Or( customersubjectsdb.DeletedAtIsNil(), - customersubjectsdb.DeletedAtGT(now), + customersubjectsdb.DeletedAtGTE(now), ),
🧹 Nitpick comments (3)
openmeter/customer/adapter/customer.go (3)
437-441: Fix typo in validation message.“cannot updated” → “cannot update”.
- fmt.Errorf("cannot updated already deleted customer [namespace=%s customer.id=%s]", input.CustomerID.Namespace, input.CustomerID.ID), + fmt.Errorf("cannot update already deleted customer [namespace=%s customer.id=%s]", input.CustomerID.Namespace, input.CustomerID.ID),
546-560: Use a single consistent timestamp across the mutation.You set now := clock.Now().UTC() here; SetUpdatedAt earlier uses a separate clock.Now().UTC(). Define now once before building the update and reuse it (UpdatedAt, CreatedAt for new subjects, DeletedAt for removals) to guarantee coherence.
Example:
- query := repo.db.Customer.UpdateOneID(previousCustomer.ID). - Where(customerdb.Namespace(previousCustomer.Namespace)). - SetUpdatedAt(clock.Now().UTC()). + now := clock.Now().UTC() + query := repo.db.Customer.UpdateOneID(previousCustomer.ID). + Where(customerdb.Namespace(previousCustomer.Namespace)). + SetUpdatedAt(now). SetName(input.Name). ... - now := clock.Now().UTC()
654-676: Join-based, time-aware subject loading looks solid.
- Deleted customers: equality on DeletedAt ensures we return subjects active at deletion time.
- Active customers: include non-deleted or future-deleting subjects via GTE.
Performance note: consider an index on customer_subjects(customer_id, deleted_at) to support the join and predicates at scale.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
openmeter/customer/adapter/customer.go(10 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
openmeter/customer/adapter/customer.go (7)
openmeter/ent/db/customer/where.go (9)
Or(1439-1441)DeletedAtIsNil(348-350)DeletedAtGTE(333-335)CreatedAt(76-78)And(1434-1436)Key(137-139)DeletedAt(86-88)Namespace(71-73)ID(16-18)openmeter/ent/db/customersubjects/where.go (9)
Or(397-399)DeletedAtIsNil(359-361)DeletedAtGTE(344-346)CreatedAt(74-76)And(392-394)CustomerID(64-66)DeletedAt(79-81)Namespace(59-61)ID(14-16)openmeter/customer/customer.go (3)
CustomerIDOrKey(130-133)GetCustomerInput(247-254)CustomerID(97-97)pkg/models/errors.go (1)
NewGenericValidationError(138-140)pkg/clock/clock.go (1)
Now(14-21)openmeter/ent/db/customer/customer.go (3)
Table(66-66)FieldID(16-16)FieldDeletedAt(26-26)openmeter/ent/db/customersubjects/customersubjects.go (4)
Table(30-30)FieldID(16-16)FieldCustomerID(20-20)FieldDeletedAt(26-26)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
- GitHub Check: E2E
- GitHub Check: Quickstart
- GitHub Check: Migration Checks
- GitHub Check: Lint
- GitHub Check: Test
- GitHub Check: Code Generators
- GitHub Check: Build
- GitHub Check: Analyze (go)
🔇 Additional comments (4)
openmeter/customer/adapter/customer.go (4)
42-45: Good fix: GTE removes microsecond edge cases.Using DeletedAtGTE(now) (instead of GT) avoids dropping customers whose deletion timestamp equals “now” due to Postgres’ microsecond precision.
61-69: Subject filter precision looks correct.Aligning subjects to Or(DeletedAtIsNil, DeletedAtGTE(now)) is consistent with the customer-side predicate and prevents boundary skips.
336-339: Key path restricted to non-deleted customers—good.ID remains fetchable post-deletion; key requires DeletedAtIsNil(), which matches the PR intent.
584-585: Correct soft-delete semantics for subject removals.Setting DeletedAt(now) ensures removals are time-aware and compatible with the new predicates.
Overview
Summary by CodeRabbit
New Features
Bug Fixes
Tests