Repository navigation
feat: redis high watermark cache - #3038
Conversation
📝 WalkthroughWalkthroughThis change introduces a pluggable filter state storage abstraction with support for Redis and in-memory drivers, integrating it into the balance worker, entitlement filters, and recalculation logic. Configuration structures, validation, and initialization are updated to support the new abstraction, and related test and wiring code is adapted accordingly. Changes
Possibly related PRs
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 ✨ 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 (
|
c5d6db4 to
b552a75
Compare
b552a75 to
b51a844
Compare
b51a844 to
85ed34f
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (6)
openmeter/entitlement/balanceworker/filterstate.go (1)
27-44: Consider using explicit union type constraint for clarity.While the current generic implementation works correctly, you could make the constraint more explicit:
-func NewFilterStateStorage[T FilterStateStorageRedis | FilterStateStorageInMemory](storage T) (FilterStateStorage, error) { +type FilterStateStorageBackend interface { + FilterStateStorageRedis | FilterStateStorageInMemory +} + +func NewFilterStateStorage[T FilterStateStorageBackend](storage T) (FilterStateStorage, error) {This would make the API contract clearer, but the current implementation is also acceptable.
openmeter/entitlement/balanceworker/filters/highwatermark.go (2)
148-162: Fix error message consistency.The error message refers to "ttl" but the field is named "Expiration":
- return errors.New("ttl must be greater than 0") + return errors.New("expiration must be greater than 0")
206-247: Excellent Redis implementation with optimistic locking!The use of WATCH/MULTI/EXEC for concurrency control is well-implemented. Consider enhancing the log message for better debugging:
- b.Logger.Info("high watermark cache update skipped due to parallel updates", "entry.key", cacheKey, "entry.highwatermark", req.CalculatedAt, "entry.isdeleted", req.IsDeleted) + b.Logger.Info("high watermark cache update skipped due to parallel updates", "entitlement.id", req.Entitlement.ID, "entry.key", cacheKey, "entry.highwatermark", req.CalculatedAt, "entry.isdeleted", req.IsDeleted)app/config/balanceworker.go (3)
19-19: Add mapstructure tag for consistency.The
StateStoragefield should have a mapstructure tag for proper decoding:- StateStorage BalanceWorkerStateStorageConfiguration + StateStorage BalanceWorkerStateStorageConfiguration `mapstructure:"stateStorage"`
92-92: Use consistent error slice initialization.For consistency with other methods in the codebase, consider using
var errs []errorinstead oferrs := []error{}:- errs := []error{} + var errs []error
122-125: Improve type assertion error message.The error message could be more descriptive about what went wrong:
- return BalanceWorkerStateStorageRedisBackendConfiguration{}, fmt.Errorf("state storage backend configuration is not a redis configuration") + return BalanceWorkerStateStorageRedisBackendConfiguration{}, fmt.Errorf("state storage backend configuration has unexpected type %T, expected BalanceWorkerStateStorageRedisBackendConfiguration", c.BalanceWorkerStateStorageBackendConfiguration)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (11)
app/common/openmeter_balanceworker.go(4 hunks)app/config/balanceworker.go(2 hunks)app/config/config_test.go(1 hunks)app/config/testdata/complete.yaml(1 hunks)cmd/balance-worker/wire_gen.go(1 hunks)cmd/jobs/entitlement/recalculatesnapshots.go(1 hunks)openmeter/entitlement/balanceworker/filters.go(3 hunks)openmeter/entitlement/balanceworker/filters/highwatermark.go(3 hunks)openmeter/entitlement/balanceworker/filterstate.go(1 hunks)openmeter/entitlement/balanceworker/recalculate.go(3 hunks)openmeter/entitlement/balanceworker/worker.go(3 hunks)
🧰 Additional context used
🧠 Learnings (2)
openmeter/entitlement/balanceworker/recalculate.go (1)
Learnt from: GAlexIHU
PR: openmeterio/openmeter#2383
File: openmeter/entitlement/metered/lateevents_test.go:37-45
Timestamp: 2025-03-07T12:17:43.129Z
Learning: In the OpenMeter codebase, test files like `openmeter/entitlement/metered/lateevents_test.go` may use variables like `meterSlug` and `namespace` without explicit declarations visible in the same file. This appears to be an accepted pattern in their test structure.
openmeter/entitlement/balanceworker/filters.go (1)
Learnt from: GAlexIHU
PR: openmeterio/openmeter#2383
File: openmeter/entitlement/metered/lateevents_test.go:37-45
Timestamp: 2025-03-07T12:17:43.129Z
Learning: In the OpenMeter codebase, test files like `openmeter/entitlement/metered/lateevents_test.go` may use variables like `meterSlug` and `namespace` without explicit declarations visible in the same file. This appears to be an accepted pattern in their test structure.
🧬 Code Graph Analysis (5)
cmd/jobs/entitlement/recalculatesnapshots.go (3)
openmeter/entitlement/balanceworker/filterstate.go (3)
NewFilterStateStorage(27-44)FilterStateStorageInMemory(101-101)FilterStateStorage(22-25)openmeter/entitlement/balanceworker/recalculate.go (2)
NewRecalculator(107-157)RecalculatorOptions(54-63)cmd/jobs/internal/globals.go (1)
App(7-7)
openmeter/entitlement/balanceworker/worker.go (2)
openmeter/entitlement/balanceworker/filterstate.go (1)
FilterStateStorage(22-25)pkg/models/validator.go (1)
Validate(16-26)
openmeter/entitlement/balanceworker/recalculate.go (5)
openmeter/entitlement/balanceworker/filterstate.go (1)
FilterStateStorage(22-25)pkg/models/validator.go (1)
Validate(16-26)openmeter/entitlement/balanceworker/worker.go (1)
New(124-179)openmeter/subject/httphandler/handler.go (1)
New(46-60)openmeter/notification/service/service.go (1)
New(41-78)
openmeter/entitlement/balanceworker/filters/highwatermark.go (1)
openmeter/entitlement/balanceworker/filters/filter.go (4)
NamedFilter(46-50)CalculationTimeRecorder(58-62)EntitlementFilterRequest(13-17)RecordLastCalculationRequest(52-56)
app/config/balanceworker.go (4)
app/config/events.go (2)
ConsumerConfiguration(74-86)ConfigureConsumer(195-207)pkg/models/validator.go (1)
Validate(16-26)pkg/errorsx/errorsx.go (1)
WithPrefix(9-32)app/config/viper.go (1)
DecodeHook(8-15)
⏰ Context from checks skipped due to timeout of 90000ms (11)
- GitHub Check: Artifacts / Container image
- GitHub Check: Developer environment
- GitHub Check: CI
- GitHub Check: E2E
- GitHub Check: Quickstart
- GitHub Check: Lint
- GitHub Check: Commit hooks
- GitHub Check: Build
- GitHub Check: Test
- GitHub Check: Migration Checks
- GitHub Check: Analyze (go)
🔇 Additional comments (26)
app/config/config_test.go (1)
327-335: Configuration structure looks correct and comprehensive.The new
StateStorageconfiguration block properly specifies the Redis driver with appropriate expiration time and connection details. This aligns well with the test data and validates the new filter state storage functionality.app/config/testdata/complete.yaml (1)
121-126: Test configuration is well-structured and consistent.The YAML configuration properly defines the new balance worker state storage with Redis backend. The values align with the test expectations and provide good coverage for the Redis driver functionality.
cmd/balance-worker/wire_gen.go (1)
258-268: Dependency injection implementation is correct and well-integrated.The filter state storage initialization follows the established error handling pattern with proper cleanup. The integration into the worker options maintains the clean dependency injection approach used throughout the codebase.
cmd/jobs/entitlement/recalculatesnapshots.go (2)
17-20: Appropriate choice of in-memory storage for job context.Using
FilterStateStorageInMemoryfor the recalculation command is a smart architectural decision. It satisfies the interface requirements without introducing external Redis dependencies for one-time job execution.
27-28: Clean integration of new dependencies.The addition of
FilterStateStorageandLoggerto theRecalculatorOptionsproperly aligns with the enhanced interface requirements while maintaining code clarity.openmeter/entitlement/balanceworker/worker.go (3)
53-53: Clean addition of FilterStateStorage dependency.The new field is appropriately placed within the
WorkerOptionsstruct and aligns with the overall architecture for managing worker dependencies.
89-91: Proper validation implementation.The validation for
FilterStateStoragefollows the established pattern used for other required dependencies, providing clear error messages and proper error wrapping.
132-133: Correct integration with EntitlementFilters.The
FilterStateStorageandLoggerare properly passed to theEntitlementFiltersConfig, enabling the filters to leverage the pluggable state storage abstraction.app/common/openmeter_balanceworker.go (3)
27-35: LGTM!The wire set correctly includes the new filter state storage provider.
79-104: LGTM!The filter state storage is properly injected as a dependency and passed to the worker options.
115-137: Well-structured provider function with proper error handling.The function correctly creates the appropriate storage backend based on configuration and follows Go error handling conventions.
openmeter/entitlement/balanceworker/recalculate.go (3)
54-63: LGTM!The new fields are properly added to support filter state storage and structured logging.
65-93: Excellent validation improvement!Accumulating multiple validation errors provides better developer experience by reporting all issues at once instead of failing on the first error.
128-133: LGTM!The new dependencies are correctly passed to the entitlement filters.
openmeter/entitlement/balanceworker/filters.go (3)
38-43: LGTM!The new fields properly support configurable state storage and structured logging.
45-65: Consistent validation improvement!The error accumulation pattern matches other files in the PR, providing a consistent developer experience.
88-113: Excellent dynamic backend selection implementation!The code properly selects and configures the appropriate high watermark cache backend based on the state storage driver, with proper error handling for unsupported drivers.
openmeter/entitlement/balanceworker/filterstate.go (1)
46-64: Well-structured validation!The validation properly checks all required fields and provides clear error messages.
openmeter/entitlement/balanceworker/filters/highwatermark.go (2)
33-43: Excellent refactoring to support pluggable backends!The abstraction is clean and follows good design principles.
249-271: Well-thought-out cache update logic!The conditions for updating the cache entry are comprehensive and handle all edge cases correctly.
app/config/balanceworker.go (6)
5-14: LGTM! Well-organized imports.The new imports are properly grouped and necessary for the state storage functionality.
29-34: LGTM! Proper validation with error prefixing.The validation follows the established pattern and provides good error context.
36-52: LGTM! Well-structured type definitions.Good use of constants for driver types and clean separation between raw and typed configurations.
130-151: LGTM! Clean interface design and validation.The backend configuration interface and Redis implementation are well-structured with proper validation.
158-159: LGTM! Sensible default values.Good defaults: in-memory driver for simplicity and 24-hour expiration for Redis.
84-86: ```shell
#!/bin/bashLocate the Validate method for BalanceWorkerStateStorageConfiguration
rg -n 'func (c *BalanceWorkerStateStorageConfiguration) Validate' -n app/config/balanceworker.go
</details> </blockquote></details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
This patch adds support for using redis as a shared cache on for balance-worker pool, for high watermark cache entries.
Summary by CodeRabbit
New Features
Bug Fixes
Tests