Skip to content

chore: only execute balance worker for namespaces with active notifications - #2928

Merged
turip merged 1 commit into
mainfrom
chore/only-execute-balance-worker-for-namespaces-with-affected-entitlements
Jun 2, 2025
Merged

turip merged 1 commit into
mainfrom
chore/only-execute-balance-worker-for-namespaces-with-affected-entitlements

Conversation

@turip

@turip turip commented Jun 2, 2025 •

Copy link
Copy Markdown
Member

This patch makes sure that we are only executing balance worker for namespaces that has active notifications for balance snapshots.

Other namespaces are ignored.

The patch also intruces an LRU cache with TTL, which fixes an issue that recalculator might use old version of subjects or fatures.

Summary by CodeRabbit

  • New Features
    • Introduced entitlement event filtering based on notification rules, allowing events to be processed only if they match configured notification criteria.
    • Added a cache system with per-item time-to-live (TTL) for improved performance and up-to-date filtering.
    • Integrated notification services into balance worker and entitlement recalculation processes for enhanced notification handling.
  • Bug Fixes
    • Improved validation and error handling for new dependencies and cache operations.
  • Tests
    • Added tests for the TTL cache to ensure correct caching and expiration behavior.
  • Documentation
    • Enhanced inline documentation for new filtering and caching components.

@coderabbitai

coderabbitai Bot commented Jun 2, 2025 •

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@turip has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 14 minutes and 26 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 9ababe9 and 52597a7.

📒 Files selected for processing (16)
  • app/common/notification.go (2 hunks)
  • app/common/openmeter_balanceworker.go (2 hunks)
  • cmd/balance-worker/wire.go (1 hunks)
  • cmd/balance-worker/wire_gen.go (2 hunks)
  • cmd/jobs/entitlement/recalculatesnapshots.go (1 hunks)
  • cmd/jobs/internal/wire.go (3 hunks)
  • cmd/jobs/internal/wire_gen.go (4 hunks)
  • openmeter/entitlement/balanceworker/entitlementhandler.go (2 hunks)
  • openmeter/entitlement/balanceworker/filters.go (1 hunks)
  • openmeter/entitlement/balanceworker/filters/filter.go (1 hunks)
  • openmeter/entitlement/balanceworker/filters/notifications.go (1 hunks)
  • openmeter/entitlement/balanceworker/recalculate.go (9 hunks)
  • openmeter/entitlement/balanceworker/worker.go (5 hunks)
  • pkg/lrux/lruitemttl.go (1 hunks)
  • pkg/lrux/lruitemttl_test.go (1 hunks)
  • pkg/models/key.go (1 hunks)
📝 Walkthrough

Walkthrough

This change introduces entitlement filtering and notification-based scoping to the balance worker and entitlement recalculation logic. It adds a TTL-aware LRU cache utility, new filter interfaces and implementations, and integrates notification services into various application components through dependency injection. New exported types and methods support namespace and entitlement-level filtering, with metrics and caching.

Changes

Files / Areas Change Summary
app/common/notification.go Added a new Wire provider set NotificationService and a no-op notification webhook handler constructor for dependency injection.
app/common/openmeter_balanceworker.go, openmeter/entitlement/balanceworker/worker.go Updated worker and options to require and use a notification service; worker now creates entitlement filters.
cmd/balance-worker/wire.go, cmd/balance-worker/wire_gen.go, cmd/jobs/internal/wire.go, cmd/jobs/internal/wire_gen.go Integrated notification service and feature connector into dependency injection and application struct; updated initialization and cleanup logic.
cmd/jobs/entitlement/recalculatesnapshots.go Injected notification service into recalculator options during command initialization.
openmeter/entitlement/balanceworker/entitlementhandler.go Added namespace and entitlement scope checks using new filters before processing events.
openmeter/entitlement/balanceworker/filters.go, openmeter/entitlement/balanceworker/filters/filter.go, openmeter/entitlement/balanceworker/filters/notifications.go Introduced new filter interfaces, entitlement filters, and a notification-based filter with LRU+TTL caching and OpenTelemetry metrics.
openmeter/entitlement/balanceworker/recalculate.go Replaced old cache with TTL-aware cache using typed keys; added entitlement filtering and updated subject/feature retrieval; integrated filters into recalculation logic.
pkg/lrux/lruitemttl.go, pkg/lrux/lruitemttl_test.go Added a generic LRU cache with per-item TTL and corresponding tests for cache and error handling.
pkg/models/key.go Introduced NamespacedKey struct with validation for use as typed keys in caching and filtering.

Possibly related PRs

✨ 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.
    • 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.
    • @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 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.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 force-pushed the chore/only-execute-balance-worker-for-namespaces-with-affected-entitlements branch 4 times, most recently from 83a837a to 9ababe9 Compare June 2, 2025 16:05
@turip turip changed the title chore: only execute balance worker for namespaces with affected entit… chore: only execute balance worker for namespaces with active notifications Jun 2, 2025
@turip
turip marked this pull request as ready for review June 2, 2025 16:07
@turip
turip requested a review from a team as a code owner June 2, 2025 16:07

@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

🧹 Nitpick comments (6)
pkg/lrux/lruitemttl.go (1)

68-86: Consider adding documentation about concurrent fetch behavior.

The Get method correctly implements TTL expiration logic using clock.Now() and handles cache misses appropriately. However, the lack of mutex protection (line 76 comment) means multiple goroutines could fetch the same expired item simultaneously.

Consider adding documentation to clarify the concurrent behavior:

-// Get fetches the item from the cache if it exists and is not expired, otherwise it fetches the item from the fetcher
+// Get fetches the item from the cache if it exists and is not expired, otherwise it fetches the item from the fetcher.
+// Note: Multiple concurrent calls for the same expired key may result in multiple fetcher invocations.
pkg/models/key.go (2)

10-20: Consider enhancing validation and error messages.

The validation logic could be improved in several ways:

  1. Error messages could include the struct type for better context
  2. Consider trimming whitespace before validation
  3. Could leverage the generic validation pattern from pkg/models/validator.go

Apply this diff to improve the validation:

+import (
+	"fmt"
+	"strings"
+)
+
 func (k NamespacedKey) Validate() error {
-	if k.Namespace == "" {
-		return fmt.Errorf("namespace is required")
+	if strings.TrimSpace(k.Namespace) == "" {
+		return fmt.Errorf("NamespacedKey: namespace is required")
 	}

-	if k.Key == "" {
-		return fmt.Errorf("key is required")
+	if strings.TrimSpace(k.Key) == "" {
+		return fmt.Errorf("NamespacedKey: key is required")
 	}

 	return nil
 }

Alternatively, consider using the generic validation pattern:

func (k NamespacedKey) Validate() error {
	return Validate(k,
		func(nk NamespacedKey) error {
			if strings.TrimSpace(nk.Namespace) == "" {
				return fmt.Errorf("namespace is required")
			}
			return nil
		},
		func(nk NamespacedKey) error {
			if strings.TrimSpace(nk.Key) == "" {
				return fmt.Errorf("key is required")
			}
			return nil
		},
	)
}

5-8: Consider adding utility methods for better usability.

Since this struct is used as a cache key, consider adding:

  1. A String() method for better debugging and logging
  2. A constructor that validates inputs

Add these methods after the struct definition:

// NewNamespacedKey creates a new NamespacedKey with validation
func NewNamespacedKey(namespace, key string) (NamespacedKey, error) {
	nk := NamespacedKey{
		Namespace: namespace,
		Key:       key,
	}
	if err := nk.Validate(); err != nil {
		return NamespacedKey{}, err
	}
	return nk, nil
}

// String implements the fmt.Stringer interface for better debugging
func (k NamespacedKey) String() string {
	return fmt.Sprintf("%s/%s", k.Namespace, k.Key)
}
pkg/lrux/lruitemttl_test.go (1)

15-56: Consider adding more comprehensive test coverage

The tests cover basic functionality but could benefit from additional edge cases:

  • Concurrent access scenarios
  • Cache eviction when at capacity
  • Multiple keys with different TTLs
  • Refresh behavior when items are expired vs. valid

Would you like me to generate additional test cases to improve coverage?

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

150-150: Consider removing TODO comment

The TODO comment suggests moving high watermark cache to filters, but this seems out of scope for the current PR focused on notification-based filtering.

Consider either:

  • Removing the TODO if it's not actionable in the near term
  • Creating a proper issue to track this refactoring
- // TODO[later]: move to filters
openmeter/entitlement/balanceworker/filters.go (1)

75-77: Potential issue with constructor return pattern

The constructor creates a value type EntitlementFilters{} but then calls WithMetrics() which expects a receiver. This pattern works but could be more explicit.

- 	return EntitlementFilters{
- 		filters: []filters.NamedFilter{notificationFilter},
- 	}.WithMetrics(cfg.MetricMeter)
+ 	entitlementFilters := &EntitlementFilters{
+ 		filters: []filters.NamedFilter{notificationFilter},
+ 	}
+ 	return entitlementFilters.WithMetrics(cfg.MetricMeter)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4f51b68 and 9ababe9.

📒 Files selected for processing (16)
  • app/common/notification.go (2 hunks)
  • app/common/openmeter_balanceworker.go (2 hunks)
  • cmd/balance-worker/wire.go (1 hunks)
  • cmd/balance-worker/wire_gen.go (2 hunks)
  • cmd/jobs/entitlement/recalculatesnapshots.go (1 hunks)
  • cmd/jobs/internal/wire.go (3 hunks)
  • cmd/jobs/internal/wire_gen.go (4 hunks)
  • openmeter/entitlement/balanceworker/entitlementhandler.go (2 hunks)
  • openmeter/entitlement/balanceworker/filters.go (1 hunks)
  • openmeter/entitlement/balanceworker/filters/filter.go (1 hunks)
  • openmeter/entitlement/balanceworker/filters/notifications.go (1 hunks)
  • openmeter/entitlement/balanceworker/recalculate.go (9 hunks)
  • openmeter/entitlement/balanceworker/worker.go (5 hunks)
  • pkg/lrux/lruitemttl.go (1 hunks)
  • pkg/lrux/lruitemttl_test.go (1 hunks)
  • pkg/models/key.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
pkg/models/key.go (1)
pkg/models/validator.go (1)
  • Validate (16-26)
cmd/jobs/entitlement/recalculatesnapshots.go (2)
cmd/jobs/internal/globals.go (1)
  • App (7-7)
app/common/notification.go (1)
  • NotificationService (30-34)
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: E2E
  • GitHub Check: Quickstart
  • GitHub Check: Lint
  • GitHub Check: Developer environment
  • GitHub Check: CI
  • GitHub Check: Test
  • GitHub Check: Analyze (go)
🔇 Additional comments (25)
app/common/notification.go (2)

28-34: LGTM! Well-designed dependency injection pattern.

The new NotificationService wire set provides a clean separation for use cases requiring only the notification service without the full webhook infrastructure. The documentation comment clearly explains the purpose and usage.


99-103: LGTM! Consistent provider function implementation.

The NewNoopNotificationWebhookHandler function follows the established pattern of other provider functions in this file and correctly returns a no-operation webhook handler instance.

pkg/lrux/lruitemttl.go (3)

41-66: LGTM! Robust constructor with proper validation.

The constructor properly validates inputs and handles error cases:

  • Checks for nil fetcher (required dependency)
  • Validates TTL is not negative
  • Handles underlying LRU cache creation errors

The options pattern provides clean configurability for TTL settings.


88-98: LGTM! Clean refresh implementation.

The Refresh method provides a clear way to force cache updates regardless of expiration state, which is useful for invalidation scenarios.


100-110: LGTM! Proper error handling and TTL calculation.

The fetchItem helper correctly:

  • Invokes the fetcher function
  • Handles errors appropriately
  • Calculates expiration time using clock.Now().Add(c.ttl)
  • Returns zero value on error (proper Go pattern)
cmd/balance-worker/wire.go (1)

36-36: LGTM! Proper dependency injection for notification-based filtering.

The addition of common.Feature and common.Notification to the wire build aligns with the PR objectives to enable balance worker execution only for namespaces with active notifications. These dependencies support the new entitlement filtering and notification-based scoping functionality.

Also applies to: 42-42

cmd/jobs/internal/wire.go (3)

26-26: LGTM! Proper import addition.

The notification package import is correctly added to support the new NotificationService field in the Application struct.


58-58: LGTM! Consistent struct field addition.

The NotificationService field is properly added to the Application struct with the correct type notification.Service, enabling notification-based functionality in job processing.


85-85: LGTM! Proper wire provider inclusion.

The common.Notification provider is correctly added to the wire.Build call, ensuring the NotificationService field will be properly injected by the dependency injection framework.

cmd/jobs/entitlement/recalculatesnapshots.go (1)

15-20:

Details

❌ Incorrect review comment

Consider adding nil check for NotificationService.

While the change correctly adds the notification service, consider adding defensive nil checking to prevent potential runtime panics.


🏁 Script executed:

#!/bin/bash
# Description: Check if NotificationService can be nil in the Application struct

# Search for Application struct definition to see if NotificationService is a pointer
ast-grep --pattern 'type Application struct {
  $$$
}'

# Search for NotificationService field specifically
rg -A 2 -B 2 "NotificationService.*notification\." --type go

Length of output: 22499


Ignore nil check for NotificationService

The internal.App.NotificationService is wired via Google Wire in cmd/jobs/internal/wire.go and always initialized (or the build will fail). Adding a nil check here isn’t needed.

Likely an incorrect or invalid review comment.

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

1-4: This is a generated file - changes should be made in wire.go.

This file is auto-generated by Wire. Any manual changes will be overwritten on the next generation.

The notification service integration looks correct with proper error handling and cleanup. However, I noticed that the variable names (v2, v3, v4) are not descriptive. Consider updating the source wire.go file to use more meaningful names like clickHouseDB, svixConfig, and telemetryServer.

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

117-123: LGTM! Efficient namespace filtering implementation.

The namespace scope check is correctly placed before expensive operations like entitlement lookup, providing good performance optimization by filtering early in the process.


149-156: LGTM! Proper entitlement filtering after entity load.

The entitlement scope check is correctly positioned after loading the entitlement entity, which allows the filter to access the full entitlement data for filtering decisions. The error handling and early return pattern is consistent with the namespace filtering above.

app/common/openmeter_balanceworker.go (1)

78-101: LGTM! Clean dependency injection implementation.

The notification service is properly injected into the balance worker options following the established pattern. The changes are minimal and maintain consistency with the existing function signature and struct field assignment pattern.

openmeter/entitlement/balanceworker/filters/filter.go (1)

9-18: Excellent interface design following Go best practices.

The filter interfaces are well-designed with:

  • Proper context parameter for cancellation/timeout support
  • Clear boolean return for filtering decisions with error handling
  • Single responsibility principle - focused on scope checking
  • NamedFilter extension allows for filter identification and debugging
  • Clean separation of concerns between namespace and entitlement filtering
cmd/jobs/internal/wire_gen.go (1)

380-412: Generated code looks correct with proper dependency injection setup.

The generated wire code properly integrates the notification service with:

  • Correct error handling and cleanup chain propagation
  • Proper assignment to Application struct fields
  • Consistent pattern with other service dependencies

Since this is generated code, any issues would likely originate from the source wire.go file rather than this generated output.

Also applies to: 434-434, 474-474

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

94-96: LGTM: Proper validation added

The validation for the notification service is correctly implemented and follows the existing pattern.


156-162: LGTM: Clean initialization of filters

The filter initialization is well-structured with proper error handling. The dependency injection pattern is consistent with the existing codebase.

openmeter/entitlement/balanceworker/filters/notifications.go (3)

109-119: LGTM: Efficient caching strategy

The cache loader function correctly fetches rules filtered by namespace and event type, which is optimal for the use case.


24-38: LGTM: Comprehensive validation

The configuration validation properly checks all required fields and validates positive values for cache parameters.


86-103:

Details

✅ Verification successful

Verify filtering logic for entitlement scope

The entitlement filtering logic checks if rules apply to specific features, but there's a potential logical issue:

  1. Lines 96-97: Checks if ent.FeatureKey is in the rule's features list
  2. Lines 100-101: Checks if ent.FeatureID is in the same list

This assumes that rule.Config.BalanceThreshold.Features can contain both feature keys and feature IDs, which might not be the intended design.


🏁 Script executed:

#!/bin/bash
# Description: Check the notification service interface and rule structure to understand the expected feature identifier format

# Search for BalanceThreshold config structure
ast-grep --pattern 'type $_ struct {
  $$$
  Features []$_
  $$$
}'

# Search for notification rule definitions
rg -A 10 "BalanceThreshold.*Features"

Length of output: 9399


Filtering logic correctly handles both FeatureKey and FeatureID

Verified that BalanceThresholdRuleConfig.Features is a []string and that existing tests explicitly set it to both feature.Key and feature.ID. The consumer implementation likewise checks for both FeatureKey and FeatureID. No changes are needed.

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

128-157: LGTM: Well-designed filter execution with comprehensive metrics

The executeFilters method provides a clean abstraction for running filters with proper error handling and metric collection. The metric labeling strategy enables detailed observability.


68-69:

Details

❌ Incorrect review comment

Missing constant definitions

The code references defaultCacheTTL and defaultLRUCacheSize constants that are not defined in this file or imported.


🏁 Script executed:

#!/bin/bash
# Description: Search for missing constant definitions
rg "defaultCacheTTL|defaultLRUCacheSize" --type go

Length of output: 745


No missing constants – definitions are in recalculate.go
The constants defaultCacheTTL and defaultLRUCacheSize are declared in openmeter/entitlement/balanceworker/recalculate.go and accessible across the package. No changes needed.

Likely an incorrect or invalid review comment.

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

79-80: Well-designed cache implementation with TTL

The TTL-aware cache implementation with typed keys effectively addresses the stale data issue mentioned in the PR objectives. The 15-second TTL provides a good balance between performance and data freshness.

Also applies to: 125-133


147-154: Efficient scope filtering implementation

The namespace and entitlement scope checks effectively implement the PR objective of only executing the balance worker for entities with active notifications. The early returns/continues optimize performance by avoiding unnecessary processing.

Also applies to: 199-206

Comment thread pkg/lrux/lruitemttl_test.go Resolved
@turip
turip force-pushed the chore/only-execute-balance-worker-for-namespaces-with-affected-entitlements branch from 9ababe9 to 52597a7 Compare June 2, 2025 16:22
@turip
turip merged commit 799ce91 into main Jun 2, 2025
@turip
turip deleted the chore/only-execute-balance-worker-for-namespaces-with-affected-entitlements branch June 2, 2025 16:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants