Skip to content

refactor: optimize updating usage attribution - #3289

Merged
chrisgacsal merged 1 commit into
mainfrom
refactor/customer-subject-diff
Aug 29, 2025
Merged

chrisgacsal merged 1 commit into
mainfrom
refactor/customer-subject-diff

Conversation

@chrisgacsal

@chrisgacsal chrisgacsal commented Aug 29, 2025 •

Copy link
Copy Markdown
Collaborator

Overview

Optimize updating Customers usage attribution.

Summary by CodeRabbit

  • Refactor
    • Simplified customer update logic to compute added vs. removed usage attribution subjects via a single diff, unifying create/remove flows and final assembly.
    • Error handling updated to correctly report conflicting subject keys during add/remove operations.
    • No changes to public APIs.

@chrisgacsal
chrisgacsal requested a review from tothandras August 29, 2025 09:29
@chrisgacsal chrisgacsal self-assigned this Aug 29, 2025
@chrisgacsal
chrisgacsal requested a review from a team as a code owner August 29, 2025 09:29
@coderabbitai

coderabbitai Bot commented Aug 29, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Replaced 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

Cohort / File(s) Summary of changes
Subject diff computation refactor
openmeter/customer/adapter/customer.go
Replaced manual nested diff loops with lo.Difference to produce subKeysToAdd / subKeysToRemove; unified subject creation into a single bulk Create using subKeysToAdd, unified removals into a single Update marking subKeysToRemove as deleted; updated error handling to return NewSubjectKeyConflictError for constraint errors; adjusted iteration and final entity.Edges.Subjects assembly; removed obsolete variables and logic.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor/customer-subject-diff

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbit in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbit in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbit gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbit read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbit help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbit ignore or @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbit summary or @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbit or @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@chrisgacsal chrisgacsal added the release-note/ignore Ignore this change when generating release notes label Aug 29, 2025
tothandras
tothandras previously approved these changes Aug 29, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

📥 Commits

Reviewing files that changed from the base of the PR and between 0d424fd and b30bc52.

📒 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)

Comment thread openmeter/customer/adapter/customer.go Resolved
Comment thread openmeter/customer/adapter/customer.go Resolved
@chrisgacsal
chrisgacsal enabled auto-merge (squash) August 29, 2025 10:02

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

📥 Commits

Reviewing files that changed from the base of the PR and between b30bc52 and e043850.

📒 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.

Comment thread openmeter/customer/adapter/customer.go Resolved
Comment thread openmeter/customer/adapter/customer.go Resolved
@chrisgacsal
chrisgacsal merged commit 38012fb into main Aug 29, 2025
@chrisgacsal
chrisgacsal deleted the refactor/customer-subject-diff branch August 29, 2025 10:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/ignore Ignore this change when generating release notes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants