Skip to content

refactor: balance worker - #2735

Merged
turip merged 1 commit into
mainfrom
refactor/balance-worker
Apr 28, 2025
Merged

turip merged 1 commit into
mainfrom
refactor/balance-worker

Conversation

@turip

@turip turip commented Apr 28, 2025 •

Copy link
Copy Markdown
Member

Overview

Use option pattern for handlers

Make create snapshot reusable

Add validators for balance worker config

Remove edge events

Summary by CodeRabbit

  • Refactor

    • Improved event handling by introducing a more flexible options pattern for passing event metadata.
    • Centralized and validated metric initialization for better reliability.
    • Enhanced extensibility and consistency in event processing logic.
  • Chores

    • Removed unused entitlement cache miss event handling and related code for simplification and maintainability.

No changes to user-facing features or functionality.

@coderabbitai

coderabbitai Bot commented Apr 28, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This 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

Files/Paths Change Summary
app/common/openmeter_balanceworker.go Modified NewBalanceWorkerOptions to propagate MetricMeter from router options into the returned worker options struct.
openmeter/entitlement/balanceworker/cachehandler.go Removed the file and the handleCacheMissEvent method, eliminating cache miss event handling logic from the worker.
openmeter/entitlement/edge/event.go Removed the file and the definition of EntitlementCacheMissEvent struct along with its methods, fully eliminating the cache miss event type from the codebase.
openmeter/entitlement/balanceworker/entitlementhandler.go Refactored event handling methods to use a functional options pattern (handleOption, handleEntitlementEventOptions). Updated signatures of handleEntitlementEvent and processEntitlementEntity to accept variadic options. Added option helpers (WithSource, WithEventAt, WithRawIngestedEvents). Split and modularized snapshot event creation logic into snapshotToEventInput and snapshotToEvent. No changes to createDeletedSnapshotEvent except minor formatting.
openmeter/entitlement/balanceworker/ingesthandler.go Updated calls to handleEntitlementEvent to use the new functional options (WithSource, WithEventAt, WithRawIngestedEvents) instead of positional source and timestamp arguments.
openmeter/entitlement/balanceworker/worker.go Removed import of the edge package. Added MetricMeter field to WorkerOptions struct and a Validate() method for required fields. Centralized metric initialization in a new initMetrics() method. Updated event handler setup to use functional options for event metadata. Removed all cache miss event handling and related event bus publishing.

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
Failed executing command with error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9432f02 and d84edb7.

📒 Files selected for processing (6)
  • app/common/openmeter_balanceworker.go (1 hunks)
  • openmeter/entitlement/balanceworker/cachehandler.go (0 hunks)
  • openmeter/entitlement/balanceworker/entitlementhandler.go (5 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
✅ Files skipped from review due to trivial changes (1)
  • app/common/openmeter_balanceworker.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • openmeter/entitlement/balanceworker/ingesthandler.go
  • openmeter/entitlement/balanceworker/worker.go
  • openmeter/entitlement/balanceworker/entitlementhandler.go
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: E2E
  • GitHub Check: CI
  • GitHub Check: Quickstart
  • GitHub Check: Developer environment
  • GitHub Check: Lint
  • GitHub Check: Commit hooks
  • GitHub Check: Test
  • GitHub Check: Build
  • GitHub Check: Analyze (go)
✨ Finishing Touches
  • 📝 Generate Docstrings

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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @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 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.

@turip turip added the release-note/ignore Ignore this change when generating release notes label Apr 28, 2025
@turip
turip force-pushed the refactor/balance-worker branch 2 times, most recently from 739847e to 9432f02 Compare April 28, 2025 12:14
@turip
turip marked this pull request as ready for review April 28, 2025 12:14
@turip
turip requested a review from a team as a code owner April 28, 2025 12:14

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

🔭 Outside diff range comments (1)
openmeter/entitlement/balanceworker/worker.go (1)

161-165: 🛠️ Refactor suggestion

Use the validated meter rather than opts.Router.MetricMeter

After introducing a dedicated MetricMeter field (and validating it), the constructor still supplies opts.Router.MetricMeter to eventHandler.
This can re-introduce nil-meter bugs if someone forgets to set the router’s meter while providing opts.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 the event parameter inside the loop

Re-using the identifier event for the result returned by w.handleEntitlementEvent shadows the function argument event 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 is o.Router.Subscriber; passing a nil subscriber 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: Unused rawIngestedEvents field – remove or wire-it-up

handleEntitlementEventOptions exposes rawIngestedEvents, 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

handleEntitlementEvent builds opts := getOptions(options...) but then forwards the raw slice to processEntitlementEntity, which immediately re-calls getOptions. 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 processEntitlementEntity to accept handleEntitlementEventOptions instead of the variadic slice.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cd2a38f and 9432f02.

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

Adding MetricMeter: routerOptions.MetricMeter keeps the options struct in sync with the new validation logic in balanceworker.WorkerOptions.
No issues spotted here. 👍

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

113-133: Metric initialisation is correct

Histogram 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 eventAt risks data loss

When eventAt is 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 openmeter

Length 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.go

Length 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.go

Length of output: 10359


No risk of silent event loss – branch never executed
All calls to handleEntitlementEvent in this package explicitly pass an eventAt (e.g. CreatedAt, DeletedAt, StoredAt), so opts.eventAt can 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.

@turip
turip force-pushed the refactor/balance-worker branch from 9432f02 to cb19308 Compare April 28, 2025 12:22
Use option pattern for handlers

Make create snapshot reusable

Add validators for balance worker config
@turip
turip force-pushed the refactor/balance-worker branch from cb19308 to d84edb7 Compare April 28, 2025 12:23

@chrisgacsal chrisgacsal left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Awesome! :shipit:

@turip
turip enabled auto-merge (squash) April 28, 2025 12:33
@turip
turip merged commit c1033e6 into main Apr 28, 2025
@turip
turip deleted the refactor/balance-worker branch April 28, 2025 12:34
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