Skip to content

refactor: order of subject customer lookup - #3207

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

chrisgacsal merged 1 commit into
mainfrom
refactor/subject-customer

Conversation

@chrisgacsal

@chrisgacsal chrisgacsal commented Aug 11, 2025 •

Copy link
Copy Markdown
Collaborator

Overview

Reorder the lookup process for Customer by Subject.

Summary by CodeRabbit

  • Bug Fixes
    • Improved customer resolution by prioritizing usage-attribution before subject-key lookup, returning only active customers and avoiding matches to deleted records.
    • Standardized error handling to return generic Not Found or Conflict responses with clear context, reducing ambiguity and improving API predictability.
    • Removed redundant fallback lookups to minimize edge-case inconsistencies and ensure a single, explicit outcome when no matching customer is found.

@coderabbitai

coderabbitai Bot commented Aug 11, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Refactors customer lookup in subject hook to first query by usage attribution, then by subject key while excluding deleted customers. Adjusts error handling to return generic conflict and not-found errors with context. Removes redundant second usage-attribution lookup and simplifies local variable usage.

Changes

Cohort / File(s) Summary of Changes
Subject customer lookup flow
openmeter/customer/service/hooks/subject.go
Added initial GetCustomerByUsageAttribution lookup; ignore deleted customers; revised subject-key path to filter deleted, check attribution match, and return generic conflict; consolidated final path to generic not-found with namespace/key; removed redundant fallback lookup and simplified variable declarations.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

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 (2.2.2)

level=warning msg="[runner] Can't run linter goanalysis_metalinter: inspect: failed to load package router: could not load export data: no export data for "github.com/openmeterio/openmeter/openmeter/watermill/router""
level=error msg="Running error: can't run linter goanalysis_metalinter\ninspect: failed to load package router: could not load export data: no export data for "github.com/openmeterio/openmeter/openmeter/watermill/router""

✨ 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/subject-customer

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.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai 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:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai 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 comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @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

Documentation and Community

  • 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 11, 2025
@chrisgacsal chrisgacsal self-assigned this Aug 11, 2025
@chrisgacsal
chrisgacsal requested review from hekike and turip August 11, 2025 11:38
@chrisgacsal
chrisgacsal marked this pull request as ready for review August 11, 2025 11:38
@chrisgacsal
chrisgacsal requested a review from a team as a code owner August 11, 2025 11:38

@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: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1197d9e and 8bc5c7d.

📒 Files selected for processing (1)
  • openmeter/customer/service/hooks/subject.go (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
openmeter/customer/service/hooks/subject.go (2)
openmeter/customer/customer.go (1)
  • GetCustomerByUsageAttributionInput (143-146)
pkg/models/errors.go (3)
  • IsGenericNotFoundError (57-65)
  • NewGenericConflictError (68-70)
  • NewGenericNotFoundError (38-40)
🔇 Additional comments (2)
openmeter/customer/service/hooks/subject.go (2)

192-203: Reordered lookup by usage attribution: LGTM

Querying by usage attribution first, short-circuiting on non-deleted hits, and only treating non-generic-not-found as errors is correct and simplifies the flow. No issues spotted.


228-229: Unified not-found error with context: LGTM

Returning a GenericNotFound with explicit namespace and subject.key context is clear and consistent with the rest of the codebase.

Comment on lines +220 to 226
if cus != nil && cus.DeletedAt == nil {
if lo.Contains(cus.UsageAttribution.SubjectKeys, sub.Key) {
return cus, nil
}

return nil, ErrCustomerKeyConflict
return nil, models.NewGenericConflictError(ErrCustomerKeyConflict)
}

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.

💡 Verification agent

🧩 Analysis chain

Conflict wrapping: verify errors.Is compatibility and add context

Returning a GenericConflictError is fine, but EnsureCustomer uses errors.Is(err, ErrCustomerKeyConflict). Please verify that GenericConflictError implements Unwrap() so errors.Is will match the sentinel. Also, consider preserving context in the wrapped error to aid diagnostics.

Suggested improvement to include context while preserving the sentinel:

-        return nil, models.NewGenericConflictError(ErrCustomerKeyConflict)
+        return nil, models.NewGenericConflictError(fmt.Errorf(
+          "customer key conflict (customer found by key but subject not attributed) [namespace=%s subject.key=%s customer.id=%s]: %w",
+          sub.Namespace, sub.Key, cus.ID, ErrCustomerKeyConflict))

Run this to confirm GenericConflictError supports unwrapping (and thus errors.Is):


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Show GenericConflictError definition and check for Unwrap method
rg -n "type GenericConflictError" -A 30
rg -n $'func \\(.*\\*GenericConflictError\\) Unwrap\\(\\) error'

# Bonus: also show GenericNotFoundError for consistency
rg -n "type GenericNotFoundError" -A 30
rg -n $'func \\(.*\\*GenericNotFoundError\\) Unwrap\\(\\) error'

Length of output: 3210


Conflict wrapping is correct—add context for diagnostics

Verified that GenericConflictError in pkg/models/errors.go implements an Unwrap() method, so
errors.Is(err, ErrCustomerKeyConflict) will work as intended. To improve troubleshooting, wrap the sentinel with contextual details:

• File: openmeter/customer/service/hooks/subject.go
Lines: 220–226

Suggested diff:

-        return nil, models.NewGenericConflictError(ErrCustomerKeyConflict)
+        return nil, models.NewGenericConflictError(fmt.Errorf(
+            "customer key conflict (namespace=%s subject.key=%s customer.id=%s): %w",
+            sub.Namespace, sub.Key, cus.ID, ErrCustomerKeyConflict))
📝 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.

Suggested change
if cus != nil && cus.DeletedAt == nil {
if lo.Contains(cus.UsageAttribution.SubjectKeys, sub.Key) {
return cus, nil
}
return nil, ErrCustomerKeyConflict
return nil, models.NewGenericConflictError(ErrCustomerKeyConflict)
}
if cus != nil && cus.DeletedAt == nil {
if lo.Contains(cus.UsageAttribution.SubjectKeys, sub.Key) {
return cus, nil
}
- return nil, models.NewGenericConflictError(ErrCustomerKeyConflict)
+ return nil, models.NewGenericConflictError(fmt.Errorf(
+ "customer key conflict (namespace=%s subject.key=%s customer.id=%s): %w",
+ sub.Namespace, sub.Key, cus.ID, ErrCustomerKeyConflict))
}
🤖 Prompt for AI Agents
In openmeter/customer/service/hooks/subject.go around lines 220 to 226, the
conflict return should wrap the sentinel ErrCustomerKeyConflict with contextual
details for diagnostics; replace the current return nil,
models.NewGenericConflictError(ErrCustomerKeyConflict) with a wrapped error that
includes customer id and subject key, e.g. return nil, fmt.Errorf("customer %s
already has subject key %s: %w", cus.ID, sub.Key, ErrCustomerKeyConflict), and
add the fmt import if missing.

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