Skip to content

refactor(balance): add optional customer to snapshot events - #3279

Merged
chrisgacsal merged 4 commits into
mainfrom
refactor/balance-worker
Aug 28, 2025
Merged

chrisgacsal merged 4 commits into
mainfrom
refactor/balance-worker

Conversation

@chrisgacsal

@chrisgacsal chrisgacsal commented Aug 28, 2025 •

Copy link
Copy Markdown
Collaborator

Overview

  • add support for Customer to snapshot events if exists based on Customers usage attribution
  • add some code improvements

Summary by CodeRabbit

  • New Features
    • Entitlement snapshot and recalculation events now include associated Customer details when available.
    • Event resource paths become customer-scoped when Customer data is present.
  • Validation
    • Snapshot event validation now aggregates multiple issues into a single error for clearer feedback, including optional Customer validation.
  • Refactor
    • Unified service access via worker options; worker structure simplified; dependency wiring updated.
  • Style
    • Minor variable renaming for clarity in filtering logic.

@coderabbitai

coderabbitai Bot commented Aug 28, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds Customer service integration across the balance worker: updates DI/wiring to construct and pass customer.Service; extends WorkerOptions and RecalculatorOptions; modifies handlers to source subject/feature/customer via opts; emits Customer on snapshot events; removes the old subject resolver helper; includes minor variable rename in a filter.

Changes

Cohort / File(s) Summary of changes
Dependency injection and wiring
app/common/openmeter_balanceworker.go, cmd/balance-worker/wire.go, cmd/balance-worker/wire_gen.go
NewBalanceWorkerOptions now accepts a customer.Service and populates WorkerOptions.Customer; wire adds Customer to provider set and constructs customerService; wire_gen updated to build customer service and pass it; error cleanup path extended.
Balance worker core
openmeter/entitlement/balanceworker/worker.go
WorkerOptions gains Customer field and Validate checks it; Worker struct simplified (drops entitlement and repo fields); router variable naming adjusted.
Event handlers
openmeter/entitlement/balanceworker/entitlementhandler.go, openmeter/entitlement/balanceworker/ingesthandler.go
Refactors to use w.opts.{Entitlement,Subject,Customer,Repo}; adds customer attribution on snapshot events; aggregates per-entitlement errors in ingest; replaces helper-based subject resolution with direct Subject.GetByKey and NotFound fallback.
Recalculation flow
openmeter/entitlement/balanceworker/recalculate.go
RecalculatorOptions adds Customer service; validates it; introduces subject→customer cache; fetches customer by usage attribution; includes Customer in emitted SnapshotEvents; subject resolution uses Subject.GetByKey with NotFound fallback.
Snapshot event model
openmeter/entitlement/snapshot/event.go
SnapshotEvent adds optional Customer field; EventMetadata builds customer-scoped resource when present; Validate aggregates errors and validates Customer if set.
Filters minor rename
openmeter/entitlement/balanceworker/filters/highwatermark.go
Local variable renamed from json to data in marshaling; no functional change.
Removed helper
openmeter/entitlement/balanceworker/subject.go
Deletes resolveSubjectIfExists; logic in callers replaced with direct Subject.GetByKey and fallback.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ 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/balance-worker

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 28, 2025
@chrisgacsal chrisgacsal changed the title Refactor/balance worker refactor(balance): add optional customer to snapshot events Aug 28, 2025
@chrisgacsal chrisgacsal self-assigned this Aug 28, 2025
@chrisgacsal
chrisgacsal requested review from GAlexIHU and turip August 28, 2025 11:14
@chrisgacsal
chrisgacsal marked this pull request as ready for review August 28, 2025 11:16
@chrisgacsal
chrisgacsal requested a review from a team as a code owner August 28, 2025 11:16

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
openmeter/entitlement/balanceworker/ingesthandler.go (1)

73-90: ListEntitlements pagination missing; large result sets may be truncated.

Current call relies on defaults. Add paging to avoid missing entitlements.

Apply:

-entitlements, err := w.opts.Entitlement.Entitlement.ListEntitlements(ctx, entitlement.ListEntitlementsParams{
-	Namespaces:  []string{namespace},
-	SubjectKeys: []string{subject},
-	FeatureIDs:  featureIDs,
-})
-if err != nil {
-	return nil, err
-}
-
-entitlementIDs := make([]pkgmodels.NamespacedID, 0, len(entitlements.Items))
-for _, ent := range entitlements.Items {
-	entitlementIDs = append(entitlementIDs, pkgmodels.NamespacedID{
-		ID:        ent.ID,
-		Namespace: ent.Namespace,
-	})
-}
+page := 1
+var all []entitlement.Entitlement
+for {
+	resp, err := w.opts.Entitlement.Entitlement.ListEntitlements(ctx, entitlement.ListEntitlementsParams{
+		Namespaces:  []string{namespace},
+		SubjectKeys: []string{subject},
+		FeatureIDs:  featureIDs,
+		Page:        pagination.Page{PageNumber: page, PageSize: 20_000},
+	})
+	if err != nil {
+		return nil, err
+	}
+	if len(resp.Items) == 0 {
+		break
+	}
+	all = append(all, resp.Items...)
+	if len(all) >= resp.TotalCount {
+		break
+	}
+	page++
+}
+
+entitlementIDs := make([]pkgmodels.NamespacedID, 0, len(all))
+for _, ent := range all {
+	entitlementIDs = append(entitlementIDs, pkgmodels.NamespacedID{
+		ID:        ent.ID,
+		Namespace: ent.Namespace,
+	})
+}
🧹 Nitpick comments (5)
openmeter/entitlement/balanceworker/filters/highwatermark.go (2)

225-232: Good rename; also avoid extra allocation by writing bytes directly.

Renaming json → data removes import shadowing and improves readability. As a small perf nit, you can pass the marshaled bytes to Redis directly to skip the string(...) allocation.

-        data, err := json.Marshal(newEntry)
+        data, err := json.Marshal(newEntry)
         if err != nil {
             return err
         }

         _, err = tx.TxPipelined(ctx, func(pipe redis.Pipeliner) error {
-            return pipe.SetEx(ctx, cacheKey, string(data), b.Expiration).Err()
+            return pipe.SetEx(ctx, cacheKey, data, b.Expiration).Err()
         })

153-155: Error message wording nit: align with field name.

The validation error says "ttl" while the field is Expiration. Recommend aligning wording for clarity.

-    return errors.New("ttl must be greater than 0")
+    return errors.New("expiration must be greater than 0")
app/common/openmeter_balanceworker.go (1)

90-106: Plumb Customer into WorkerOptions — LGTM; consider future-proofing signature

Passing customerService and setting WorkerOptions.Customer align with the new validation in worker. As this list grows, consider migrating to a constructor opts struct to reduce churn in call sites.

openmeter/entitlement/snapshot/event.go (1)

106-147: Validation aggregation — minor message fixes; optional stricter delete semantics

  • Remove trailing space in the calculatedAt error.
  • Consider clarifying “balance” vs “value” wording.
  • Optionally enforce that Value is nil on delete to match the comment (“empty”).
- if e.CalculatedAt == nil {
-   errs = append(errs, errors.New("calculatedAt is required "))
- }
+ if e.CalculatedAt == nil {
+   errs = append(errs, errors.New("calculatedAt is required"))
+ }

- case ValueOperationUpdate, ValueOperationReset:
+ case ValueOperationUpdate, ValueOperationReset:
   if e.Value == nil {
-    errs = append(errs, errors.New("balance is required for balance update/reset"))
+    errs = append(errs, errors.New("value is required for update/reset"))
   }
+ case ValueOperationDelete:
+   if e.Value != nil {
+     errs = append(errs, errors.New("value must be empty for delete"))
+   }
openmeter/entitlement/balanceworker/entitlementhandler.go (1)

360-367: Use consistent customer lookup keys from the event envelope.

Namespace/SubjectKey should come from the same source as the Subject fallback (event.Namespace.ID & event.SubjectKey) for consistency.

Apply:

-	cus, err := w.opts.Customer.GetCustomerByUsageAttribution(ctx, customer.GetCustomerByUsageAttributionInput{
-		Namespace:  event.Entitlement.Namespace,
-		SubjectKey: event.Entitlement.SubjectKey,
-	})
+	cus, err := w.opts.Customer.GetCustomerByUsageAttribution(ctx, customer.GetCustomerByUsageAttributionInput{
+		Namespace:  event.Namespace.ID,
+		SubjectKey: event.SubjectKey,
+	})
📜 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 2f34c77 and 4c8c674.

📒 Files selected for processing (10)
  • app/common/openmeter_balanceworker.go (3 hunks)
  • cmd/balance-worker/wire.go (1 hunks)
  • cmd/balance-worker/wire_gen.go (1 hunks)
  • openmeter/entitlement/balanceworker/entitlementhandler.go (9 hunks)
  • openmeter/entitlement/balanceworker/filters/highwatermark.go (1 hunks)
  • openmeter/entitlement/balanceworker/ingesthandler.go (3 hunks)
  • openmeter/entitlement/balanceworker/recalculate.go (11 hunks)
  • openmeter/entitlement/balanceworker/subject.go (0 hunks)
  • openmeter/entitlement/balanceworker/worker.go (5 hunks)
  • openmeter/entitlement/snapshot/event.go (3 hunks)
💤 Files with no reviewable changes (1)
  • openmeter/entitlement/balanceworker/subject.go
🧰 Additional context used
🧬 Code graph analysis (8)
cmd/balance-worker/wire.go (1)
app/common/customer.go (1)
  • Customer (22-24)
openmeter/entitlement/snapshot/event.go (3)
openmeter/customer/customer.go (1)
  • Customer (18-28)
openmeter/subject/subject.go (1)
  • Subject (8-16)
openmeter/event/metadata/resourcepath.go (2)
  • ComposeResourcePath (29-31)
  • EntitySubjectKey (15-15)
openmeter/entitlement/balanceworker/ingesthandler.go (6)
openmeter/entitlement/balanceworker/worker.go (1)
  • Worker (106-116)
openmeter/sink/flushhandler/ingestnotification/events/events.go (1)
  • EventBatchedIngest (17-28)
pkg/models/id.go (1)
  • NamespacedID (7-10)
openmeter/entitlement/balanceworker/entitlementhandler.go (3)
  • WithSource (52-56)
  • WithEventAt (58-62)
  • WithRawIngestedEvents (70-74)
openmeter/registry/entitlement.go (1)
  • Entitlement (11-21)
openmeter/entitlement/connector.go (1)
  • ListEntitlementsParams (32-50)
cmd/balance-worker/wire_gen.go (2)
app/common/customer.go (1)
  • NewCustomerService (26-57)
app/common/openmeter_balanceworker.go (1)
  • NewBalanceWorkerOptions (80-107)
openmeter/entitlement/balanceworker/entitlementhandler.go (5)
openmeter/subject/subject.go (2)
  • Subject (8-16)
  • SubjectKey (30-32)
pkg/models/key.go (1)
  • NamespacedKey (5-8)
pkg/models/errors.go (1)
  • IsGenericNotFoundError (57-65)
openmeter/customer/customer.go (1)
  • GetCustomerByUsageAttributionInput (163-166)
openmeter/entitlement/snapshot/event.go (2)
  • SnapshotEvent (59-74)
  • EntitlementValue (42-57)
openmeter/entitlement/balanceworker/recalculate.go (6)
openmeter/subject/service.go (1)
  • Service (11-24)
pkg/lrux/lruitemttl.go (3)
  • CacheWithItemTTL (15-20)
  • NewCacheWithItemTTL (41-66)
  • WithTTL (35-39)
pkg/models/key.go (1)
  • NamespacedKey (5-8)
pkg/models/id.go (1)
  • NamespacedID (7-10)
pkg/models/errors.go (1)
  • IsGenericNotFoundError (57-65)
openmeter/customer/customer.go (1)
  • GetCustomerByUsageAttributionInput (163-166)
openmeter/entitlement/balanceworker/worker.go (3)
openmeter/ent/schema/customer.go (5)
  • Customer (17-19)
  • Customer (21-29)
  • Customer (31-39)
  • Customer (41-54)
  • Customer (56-68)
openmeter/subject/service.go (1)
  • Service (11-24)
openmeter/watermill/router/router.go (1)
  • NewDefaultRouter (56-148)
app/common/openmeter_balanceworker.go (2)
app/common/customer.go (1)
  • Customer (22-24)
openmeter/ent/schema/customer.go (5)
  • Customer (17-19)
  • Customer (21-29)
  • Customer (31-39)
  • Customer (41-54)
  • Customer (56-68)
🔇 Additional comments (12)
cmd/balance-worker/wire.go (1)

35-35: Customer DI provider inclusion — LGTM

common.Customer correctly added to the provider set; dependencies are already present in the graph.

cmd/balance-worker/wire_gen.go (1)

283-295: Generated wiring for Customer service — LGTM

Creation, error path cleanup ordering, and passing customerService into NewBalanceWorkerOptions look correct. No manual edits needed.

app/common/openmeter_balanceworker.go (1)

14-14: Import customer package — LGTM

openmeter/entitlement/balanceworker/worker.go (4)

49-50: Add Customer service to WorkerOptions — LGTM

Matches DI changes and enables customer attribution in handlers.


91-97: Strengthen validation for Subject and Customer — LGTM

Nil checks are appropriate given downstream usage.


156-176: Router var rename and assignments — LGTM

Local r plus explicit assignment to worker.router improves clarity. Handler registrations updated consistently.


107-109: No lingering references to removed Worker fields
Package- and repo-wide searches for w.entitlement and w.repo returned no results.

openmeter/entitlement/snapshot/event.go (2)

64-65: Optional Customer on SnapshotEvent — LGTM

Schema addition is backward compatible via omitempty.


91-99: No changes required for EntityCustomer path
metadata.EntityCustomer is defined in event/metadata/resourcepath.go and ComposeResourcePath(e.Namespace.ID, metadata.EntityCustomer, e.Customer.ID, metadata.EntitySubjectKey, e.Subject.Key) matches existing event patterns (namespace/<ns>/customer/<id>/subjectKey/<key>).

openmeter/entitlement/balanceworker/recalculate.go (1)

168-171: Customer cache initialization LGTM.

TTL cache for subject->customer attribution is appropriate; NotFound collapses to nil and is cached, which is desirable.

openmeter/entitlement/balanceworker/entitlementhandler.go (2)

103-111: Entitlement fetch path looks good.

Includes deleted and narrows by ID/namespace; guards 0/1/many cases correctly.


329-336: Feature/value resolution via opts is correct and consistent.

Good move to centralize through w.opts; metrics timing and mapping are correct.

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