Repository navigation
refactor: balance worker - #2735
Conversation
📝 WalkthroughWalkthroughThis change refactors the entitlement balance worker's event handling logic by introducing a functional options pattern for passing metadata and context to event handler methods. It removes the handling and definition of entitlement cache miss events, including associated event structs and methods. The worker's options struct is updated to include a metric meter, with added validation and centralized metric initialization. Several method signatures are updated to accept variadic options instead of positional arguments, and the event creation logic is modularized for improved extensibility and maintainability. Changes
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 (1.64.8)Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2 📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (6)
💤 Files with no reviewable changes (2)
✅ Files skipped from review due to trivial changes (1)
🚧 Files skipped from review as they are similar to previous changes (3)
⏰ Context from checks skipped due to timeout of 90000ms (9)
✨ Finishing Touches
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:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
739847e to
9432f02
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
🔭 Outside diff range comments (1)
openmeter/entitlement/balanceworker/worker.go (1)
161-165: 🛠️ Refactor suggestionUse the validated meter rather than
opts.Router.MetricMeterAfter introducing a dedicated
MetricMeterfield (and validating it), the constructor still suppliesopts.Router.MetricMetertoeventHandler.
This can re-introducenil-meter bugs if someone forgets to set the router’s meter while providingopts.MetricMeter.- eventHandler, err := worker.eventHandler(opts.Router.MetricMeter) + eventHandler, err := worker.eventHandler(opts.MetricMeter) if err != nil { return nil, err }Ensures the same, already-validated meter instance is used consistently.
🧹 Nitpick comments (4)
openmeter/entitlement/balanceworker/ingesthandler.go (1)
29-36: Avoid shadowing theeventparameter inside the loopRe-using the identifier
eventfor the result returned byw.handleEntitlementEventshadows the function argumentevent ingestevents.EventBatchedIngest.
Although it compiles, the double meaning is confusing and makes the code harder to read or debug.- for _, entitlement := range affectedEntitlements { - event, err := w.handleEntitlementEvent( + for _, entitlement := range affectedEntitlements { + sysEvent, err := w.handleEntitlementEvent( ctx, NamespacedID{Namespace: entitlement.Namespace, ID: entitlement.EntitlementID}, WithSource(metadata.ComposeResourcePath(entitlement.Namespace, metadata.EntityEvent)), WithEventAt(event.StoredAt), WithRawIngestedEvents(event.RawEvents), ) if err != nil { - err = fmt.Errorf("handling entitlement event for %s: %w", entitlement.EntitlementID, err) + err = fmt.Errorf("handling entitlement event for %s: %w", entitlement.EntitlementID, err) handlingError = errors.Join(handlingError, err) continue } - if err := w.opts.EventBus.Publish(ctx, event); err != nil { + if err := w.opts.EventBus.Publish(ctx, sysEvent); err != nil { handlingError = errors.Join(handlingError, fmt.Errorf("handling entitlement event for %s: %w", entitlement.EntitlementID, err)) } }Renaming removes the ambiguity and clearly distinguishes the input (
event) from the output (sysEvent).openmeter/entitlement/balanceworker/worker.go (1)
61-91: Solid validation, but include the router subscriber check
Validate()now guards against missing critical dependencies – great improvement.
One additional candidate iso.Router.Subscriber; passing anilsubscriber will panic the router later on.if o.IngestEventsTopic == "" { return errors.New("ingest events topic is required") } + if o.Router.Subscriber == nil { + return errors.New("router subscriber is required") + }openmeter/entitlement/balanceworker/entitlementhandler.go (2)
22-30: UnusedrawIngestedEventsfield – remove or wire-it-up
handleEntitlementEventOptionsexposesrawIngestedEvents, yet no logic in this file (or in the other files referenced in the PR) reads that slice.
Keeping dormant state increases cognitive load and invites accidental drift.If the field is meant for a follow-up, leave a
// TODO:with a link to the ticket; otherwise remove it to keep the option payload minimal.
106-116: Redundant option parsing – avoid double work
handleEntitlementEventbuildsopts := getOptions(options...)but then forwards the raw slice toprocessEntitlementEntity, which immediately re-callsgetOptions. This duplicate construction is negligible here but easy to avoid and keeps the call chain clearer:- return w.processEntitlementEntity(ctx, &entitlementEntity, calculatedAt, options...) + return w.processEntitlementEntity(ctx, &entitlementEntity, calculatedAt, opts)…and adjust
processEntitlementEntityto accepthandleEntitlementEventOptionsinstead of the variadic slice.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (6)
app/common/openmeter_balanceworker.go(1 hunks)openmeter/entitlement/balanceworker/cachehandler.go(0 hunks)openmeter/entitlement/balanceworker/entitlementhandler.go(4 hunks)openmeter/entitlement/balanceworker/ingesthandler.go(1 hunks)openmeter/entitlement/balanceworker/worker.go(7 hunks)openmeter/entitlement/edge/event.go(0 hunks)
💤 Files with no reviewable changes (2)
- openmeter/entitlement/balanceworker/cachehandler.go
- openmeter/entitlement/edge/event.go
🧰 Additional context used
🧬 Code Graph Analysis (2)
openmeter/entitlement/balanceworker/ingesthandler.go (2)
openmeter/entitlement/balanceworker/entitlementhandler.go (3)
WithSource(34-38)WithEventAt(40-44)WithRawIngestedEvents(46-50)openmeter/event/metadata/resourcepath.go (2)
ComposeResourcePath(28-30)EntityEvent(25-25)
openmeter/entitlement/balanceworker/entitlementhandler.go (6)
openmeter/ingest/kafkaingest/serializer/serializer.go (1)
CloudEventsKafkaPayload(20-28)openmeter/entitlement/balanceworker/worker.go (2)
Worker(98-111)SubjectResolver(38-40)openmeter/entitlement/snapshot/event.go (1)
SnapshotEvent(39-53)openmeter/productcatalog/feature/connector.go (1)
IncludeArchivedFeatureTrue(39-39)openmeter/entitlement/driver/parser.go (1)
MapEntitlementValueToAPI(154-184)pkg/convert/ptr.go (1)
ToPointer(10-12)
⏰ Context from checks skipped due to timeout of 90000ms (9)
- GitHub Check: CI
- GitHub Check: E2E
- GitHub Check: Quickstart
- GitHub Check: Developer environment
- GitHub Check: Commit hooks
- GitHub Check: Lint
- GitHub Check: Test
- GitHub Check: Build
- GitHub Check: Analyze (go)
🔇 Additional comments (3)
app/common/openmeter_balanceworker.go (1)
90-97: Metric meter propagation looks goodAdding
MetricMeter: routerOptions.MetricMeterkeeps the options struct in sync with the new validation logic inbalanceworker.WorkerOptions.
No issues spotted here. 👍openmeter/entitlement/balanceworker/worker.go (1)
113-133: Metric initialisation is correctHistogram and counter are created via the injected meter with proper error checks – looks good.
openmeter/entitlement/balanceworker/entitlementhandler.go (1)
65-71:Details
❌ Incorrect review comment
Silent drop of events with missing
eventAtrisks data lossWhen
eventAtis zero you log a warning and return(nil, nil), signalling success to the caller.
Up-stream code therefore cannot distinguish “ignored” from “handled”, which might permanently lose an entitlement update.Consider propagating an explicit error (e.g.
ErrMissingEventTimestamp) so callers can decide whether to retry, DLQ or alert:- if opts.eventAt.IsZero() { - // TODO: set to error when the queue has been flushed - w.opts.Logger.Warn("eventAt is zero, ignoring event", "entitlementID", entitlementID, "source", opts.source) - return nil, nil - } + if opts.eventAt.IsZero() { + return nil, fmt.Errorf("handleEntitlementEvent: missing eventAt for entitlement %s (source=%s)", entitlementID, opts.source) + }
🏁 Script executed:
#!/bin/bash set -e # Locate the entitlementhandler.go file file=$(fd --max-depth 4 entitlementhandler.go openmeter/entitlement) echo "File found at: $file" echo "----- Showing context around the eventAt check -----" sed -n '50,110p' "$file" echo echo "----- Signature of handleEntitlementEvent -----" grep -R "func .*handleEntitlementEvent" -n openmeter/entitlement/balanceworker/entitlementhandler.go echo echo "----- Caller of handleEntitlementEvent -----" grep -R "handleEntitlementEvent" -n openmeterLength of output: 5207
🏁 Script executed:
#!/bin/bash set -e # Show the definition of PublishIfNoError in worker.go echo "----- Definition of PublishIfNoError -----" grep -R "func PublishIfNoError" -n openmeter/entitlement/balanceworker/worker.go sed -n '180,260p' openmeter/entitlement/balanceworker/worker.go | sed -n '1,80p' echo # Show ingesthandler usage of handleEntitlementEvent echo "----- Context in ingesthandler.go -----" sed -n '1,200p' openmeter/entitlement/balanceworker/ingesthandler.goLength of output: 186
🏁 Script executed:
#!/bin/bash set -e echo "----- Searching for PublishIfNoError definition across the repo -----" grep -R "PublishIfNoError" -n . echo echo "----- Context in worker.go around PublishIfNoError calls -----" grep -R "PublishIfNoError" -n openmeter/entitlement/balanceworker/worker.go sed -n '150,300p' openmeter/entitlement/balanceworker/worker.go echo echo "----- Listing openmeter/entitlement/balanceworker directory -----" ls -l openmeter/entitlement/balanceworker echo echo "----- Contents of ingesthandler.go (with line numbers) -----" cat -n openmeter/entitlement/balanceworker/ingesthandler.goLength of output: 10359
No risk of silent event loss – branch never executed
All calls tohandleEntitlementEventin this package explicitly pass aneventAt(e.g.CreatedAt,DeletedAt,StoredAt), soopts.eventAtcan never be zero at runtime. The zero-timestamp check is only a safety guard during the upcoming queue-flush migration (see TODO).• All existing invocations include
WithEventAt(…), so the warning path is effectively unreachable.
• The planned migration will flip this to an error once the old queue is drained.No changes required now – please retain the warning/TODO until you’re ready to switch to an error.
Likely an incorrect or invalid review comment.
9432f02 to
cb19308
Compare
Use option pattern for handlers Make create snapshot reusable Add validators for balance worker config
cb19308 to
d84edb7
Compare
Overview
Use option pattern for handlers
Make create snapshot reusable
Add validators for balance worker config
Remove edge events
Summary by CodeRabbit
Refactor
Chores
No changes to user-facing features or functionality.