Repository navigation
refactor(balance): add optional customer to snapshot events - #3279
Conversation
📝 WalkthroughWalkthroughAdds 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
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 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: 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→dataremoves import shadowing and improves readability. As a small perf nit, you can pass the marshaled bytes to Redis directly to skip thestring(...)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 signaturePassing
customerServiceand settingWorkerOptions.Customeralign 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
calculatedAterror.- Consider clarifying “balance” vs “value” wording.
- Optionally enforce that
Valueis 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.
📒 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.Customercorrectly 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 — LGTMCreation, error path cleanup ordering, and passing
customerServiceintoNewBalanceWorkerOptionslook correct. No manual edits needed.app/common/openmeter_balanceworker.go (1)
14-14: Import customer package — LGTMopenmeter/entitlement/balanceworker/worker.go (4)
49-50: Add Customer service to WorkerOptions — LGTMMatches DI changes and enables customer attribution in handlers.
91-97: Strengthen validation for Subject and Customer — LGTMNil checks are appropriate given downstream usage.
156-176: Router var rename and assignments — LGTMLocal
rplus explicit assignment toworker.routerimproves clarity. Handler registrations updated consistently.
107-109: No lingering references to removed Worker fields
Package- and repo-wide searches forw.entitlementandw.reporeturned no results.openmeter/entitlement/snapshot/event.go (2)
64-65: Optional Customer on SnapshotEvent — LGTMSchema addition is backward compatible via
omitempty.
91-99: No changes required for EntityCustomer path
metadata.EntityCustomeris defined inevent/metadata/resourcepath.goandComposeResourcePath(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.
Overview
Summary by CodeRabbit