Repository navigation
chore: only execute balance worker for namespaces with active notifications - #2928
Conversation
|
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 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. 📒 Files selected for processing (16)
📝 WalkthroughWalkthroughThis 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
Possibly related PRs
✨ 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:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
83a837a to
9ababe9
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (6)
pkg/lrux/lruitemttl.go (1)
68-86: Consider adding documentation about concurrent fetch behavior.The
Getmethod correctly implements TTL expiration logic usingclock.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:
- Error messages could include the struct type for better context
- Consider trimming whitespace before validation
- Could leverage the generic validation pattern from
pkg/models/validator.goApply 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:
- A
String()method for better debugging and logging- 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 coverageThe 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 commentThe 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 filtersopenmeter/entitlement/balanceworker/filters.go (1)
75-77: Potential issue with constructor return patternThe constructor creates a value type
EntitlementFilters{}but then callsWithMetrics()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
📒 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
NotificationServicewire 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
NewNoopNotificationWebhookHandlerfunction 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
Refreshmethod 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
fetchItemhelper 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.Featureandcommon.Notificationto 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
NotificationServicefield is properly added to the Application struct with the correct typenotification.Service, enabling notification-based functionality in job processing.
85-85: LGTM! Proper wire provider inclusion.The
common.Notificationprovider 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 goLength of output: 22499
Ignore nil check for NotificationService
The
internal.App.NotificationServiceis wired via Google Wire incmd/jobs/internal/wire.goand 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 sourcewire.gofile to use more meaningful names likeclickHouseDB,svixConfig, andtelemetryServer.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
NamedFilterextension 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.gofile rather than this generated output.Also applies to: 434-434, 474-474
openmeter/entitlement/balanceworker/worker.go (2)
94-96: LGTM: Proper validation addedThe validation for the notification service is correctly implemented and follows the existing pattern.
156-162: LGTM: Clean initialization of filtersThe 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 strategyThe cache loader function correctly fetches rules filtered by namespace and event type, which is optimal for the use case.
24-38: LGTM: Comprehensive validationThe 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:
- Lines 96-97: Checks if
ent.FeatureKeyis in the rule's features list- Lines 100-101: Checks if
ent.FeatureIDis in the same listThis assumes that
rule.Config.BalanceThreshold.Featurescan 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.Featuresis a[]stringand that existing tests explicitly set it to bothfeature.Keyandfeature.ID. The consumer implementation likewise checks for bothFeatureKeyandFeatureID. No changes are needed.openmeter/entitlement/balanceworker/filters.go (2)
128-157: LGTM: Well-designed filter execution with comprehensive metricsThe
executeFiltersmethod 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
defaultCacheTTLanddefaultLRUCacheSizeconstants that are not defined in this file or imported.
🏁 Script executed:
#!/bin/bash # Description: Search for missing constant definitions rg "defaultCacheTTL|defaultLRUCacheSize" --type goLength of output: 745
No missing constants – definitions are in recalculate.go
The constantsdefaultCacheTTLanddefaultLRUCacheSizeare declared inopenmeter/entitlement/balanceworker/recalculate.goand 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 TTLThe 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 implementationThe 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
9ababe9 to
52597a7
Compare
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