Repository navigation
refactor: optimize updating usage attribution - #3289
Conversation
📝 WalkthroughWalkthroughReplaced per-key diff loops in UpdateCustomer with a single lo.Difference-based delta to compute subject keys to add/remove; consolidated subject creation into a bulk Create, removal into a single Update marking keys deleted, and updated final entity.Edges.Subjects assembly and error handling accordingly (no exported signature changes). Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
openmeter/customer/adapter/customer.go (1)
516-529: Guard CreateBulk when there’s nothing to add (ent CreateBulk panics on empty input).Calling CreateBulk with zero builders can error/panic. Short-circuit when no additions.
- // Add subjects - _, err = repo.db.CustomerSubjects. - CreateBulk( - lo.Map( - subKeysToAdd, - func(subjectKey string, _ int) *entdb.CustomerSubjectsCreate { - return repo.db.CustomerSubjects.Create(). - SetNamespace(input.CustomerID.Namespace). - SetCustomerID(input.CustomerID.ID). - SetSubjectKey(subjectKey) - }, - )..., - ). - Save(ctx) + // Add subjects + if len(subKeysToAdd) > 0 { + builders := lo.Map( + subKeysToAdd, + func(subjectKey string, _ int) *entdb.CustomerSubjectsCreate { + return repo.db.CustomerSubjects.Create(). + SetNamespace(input.CustomerID.Namespace). + SetCustomerID(input.CustomerID.ID). + SetSubjectKey(subjectKey) + }, + ) + _, err = repo.db.CustomerSubjects.CreateBulk(builders...).Save(ctx) + }
🧹 Nitpick comments (2)
openmeter/customer/adapter/customer.go (2)
584-586: Avoid O(n²): use a set for membership check.lo.Contains over and over scales poorly with many subjects.
Add this near the diff computation (after Line 515):
removeSet := make(map[string]struct{}, len(subKeysToRemove)) for _, k := range subKeysToRemove { removeSet[k] = struct{}{} }Then change the condition:
- if lo.Contains(subKeysToRemove, subjectKey) { + if _, exists := removeSet[subjectKey]; exists { continue }
596-602: Optional: assemble edges directly from the final desired state.Instead of previous-minus-removed plus added, you can map input.UsageAttribution.SubjectKeys to edges. Simpler and avoids drift.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled
- Linear integration is disabled
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
openmeter/customer/adapter/customer.go(4 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
openmeter/customer/adapter/customer.go (5)
openmeter/ent/schema/customer.go (5)
CustomerSubjects(71-73)CustomerSubjects(75-79)CustomerSubjects(81-99)CustomerSubjects(101-111)CustomerSubjects(113-130)openmeter/ent/db/customersubjects.go (2)
CustomerSubjects(17-35)CustomerSubjects(58-73)openmeter/ent/db/customersubjects/where.go (5)
CustomerID(64-66)ID(14-16)Namespace(59-61)SubjectKeyIn(224-226)DeletedAtIsNil(359-361)openmeter/ent/db/ent.go (1)
IsConstraintError(367-373)openmeter/customer/errors.go (1)
NewSubjectKeyConflictError(67-71)
⏰ 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). (7)
- GitHub Check: Artifacts / Container image
- GitHub Check: Lint
- GitHub Check: Migration Checks
- GitHub Check: Code Generators
- GitHub Check: Test
- GitHub Check: Build
- GitHub Check: Analyze (go)
b30bc52 to
e043850
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
openmeter/customer/adapter/customer.go (1)
547-566: Don’t map soft-delete errors to “subject key conflict”; keep the empty-guard, drop constraint-branch.An Update that sets DeletedAt cannot hit a unique constraint; returning SubjectKeyConflict here is misleading. Keep the len(subKeysToRemove) > 0 guard (nice) and surface the original error.
if len(subKeysToRemove) > 0 { err = repo.db.CustomerSubjects. Update(). Where(customersubjectsdb.CustomerID(input.CustomerID.ID)). Where(customersubjectsdb.Namespace(input.CustomerID.Namespace)). Where(customersubjectsdb.SubjectKeyIn(subKeysToRemove...)). Where(customersubjectsdb.DeletedAtIsNil()). SetDeletedAt(clock.Now().UTC()). Exec(ctx) if err != nil { - if entdb.IsConstraintError(err) { - return nil, customer.NewSubjectKeyConflictError( - input.CustomerID.Namespace, - subKeysToRemove, - ) - } - - return nil, fmt.Errorf("failed to remove customer subjects: %w", err) + // Soft-delete cannot cause a unique-constraint conflict; surface the underlying error. + return nil, fmt.Errorf("failed to remove customer subjects: %w", err) } }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled
- Linear integration is disabled
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
openmeter/customer/adapter/customer.go(3 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
openmeter/customer/adapter/customer.go (5)
openmeter/ent/db/customersubjects.go (2)
CustomerSubjects(17-35)CustomerSubjects(58-73)openmeter/ent/db/customersubjects/where.go (5)
CustomerID(64-66)Namespace(59-61)ID(14-16)SubjectKeyIn(224-226)DeletedAtIsNil(359-361)openmeter/ent/db/ent.go (1)
IsConstraintError(367-373)openmeter/customer/errors.go (1)
NewSubjectKeyConflictError(67-71)pkg/clock/clock.go (1)
Now(14-21)
⏰ 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). (7)
- GitHub Check: Artifacts / Container image
- GitHub Check: Lint
- GitHub Check: Migration Checks
- GitHub Check: Build
- GitHub Check: Code Generators
- GitHub Check: Test
- GitHub Check: Analyze (go)
🔇 Additional comments (2)
openmeter/customer/adapter/customer.go (2)
519-544: Bulk add path looks correct and defensive.Deduped inputs, guarded on empty, bulk insert, and proper conflict mapping. No further changes needed.
602-602: LGTM on assembling newly added subjects.Clean and consistent with the delta.
Overview
Optimize updating Customers usage attribution.
Summary by CodeRabbit