Skip to content

feat: redis high watermark cache - #3038

Merged
turip merged 1 commit into
mainfrom
feat/redis-high-watermark-cache
Jun 26, 2025
Merged

turip merged 1 commit into
mainfrom
feat/redis-high-watermark-cache

Conversation

@turip

@turip turip commented Jun 25, 2025 •

Copy link
Copy Markdown
Member

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

    • Added configurable filter state storage for balance worker and entitlement recalculation, supporting both Redis and in-memory backends.
    • Introduced backend selection for high watermark cache, allowing use of Redis or in-memory storage.
    • Enhanced configuration options to specify state storage driver and settings.
    • Improved validation and error reporting for configuration and initialization.
  • Bug Fixes

    • Improved validation logic now accumulates and reports multiple configuration errors at once.
  • Tests

    • Updated test configurations to cover new state storage options.

@coderabbitai

coderabbitai Bot commented Jun 25, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This 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

Files/Paths Change Summary
openmeter/entitlement/balanceworker/filterstate.go Introduces FilterStateStorage abstraction with Redis and in-memory drivers, validation, and accessors.
app/config/balanceworker.go, app/config/config_test.go, app/config/testdata/complete.yaml Adds StateStorage configuration for balance worker, supporting Redis/in-memory drivers, validation, decoding, and updates test config and test data to include new state storage options.
app/common/openmeter_balanceworker.go, cmd/balance-worker/wire_gen.go Adds provider for FilterStateStorage, updates worker wiring to inject and validate the new storage dependency, and extends worker options accordingly.
openmeter/entitlement/balanceworker/worker.go, openmeter/entitlement/balanceworker/recalculate.go, cmd/jobs/entitlement/recalculatesnapshots.go Integrates FilterStateStorage and logger into worker and recalculator options, updates constructors and validation to use the new abstraction, and adapts command logic to initialize the appropriate storage backend.
openmeter/entitlement/balanceworker/filters.go Updates entitlement filters to accept and validate FilterStateStorage and logger, dynamically selects high watermark cache backend (Redis or in-memory) based on storage driver, and aggregates validation errors.
openmeter/entitlement/balanceworker/filters/highwatermark.go Refactors high watermark cache to use a backend interface, adds Redis and in-memory backend implementations with concurrency control, serialization, and error handling, and updates cache logic to delegate to the backend abstraction.

Possibly related PRs

  • openmeterio/openmeter#3036: Refactors the high watermark cache into the filter framework and adds Redis support; both PRs modify the high watermark cache backend and filtering logic, but this PR introduces a more general filter state storage abstraction and wiring, making their changes related but focused on different layers of the same functionality.

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

✨ 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 feat/redis-high-watermark-cache branch from c5d6db4 to b552a75 Compare June 25, 2025 11:10
@turip
turip changed the base branch from main to refactor/high-watermark-cache-to-filter-framework June 25, 2025 11:11
@turip
turip force-pushed the feat/redis-high-watermark-cache branch from b552a75 to b51a844 Compare June 25, 2025 13:01
Base automatically changed from refactor/high-watermark-cache-to-filter-framework to main June 26, 2025 13:59
@turip
turip force-pushed the feat/redis-high-watermark-cache branch from b51a844 to 85ed34f Compare June 26, 2025 14:11
@turip
turip marked this pull request as ready for review June 26, 2025 14:11
@turip
turip requested a review from a team as a code owner June 26, 2025 14:11

@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: 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 StateStorage field 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 []error instead of errs := []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

📥 Commits

Reviewing files that changed from the base of the PR and between ab2020c and 85ed34f.

📒 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 StateStorage configuration 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 FilterStateStorageInMemory for 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 FilterStateStorage and Logger to the RecalculatorOptions properly 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 WorkerOptions struct and aligns with the overall architecture for managing worker dependencies.


89-91: Proper validation implementation.

The validation for FilterStateStorage follows the established pattern used for other required dependencies, providing clear error messages and proper error wrapping.


132-133: Correct integration with EntitlementFilters.

The FilterStateStorage and Logger are properly passed to the EntitlementFiltersConfig, 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/bash

Locate 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 -->

Comment thread app/config/balanceworker.go Resolved
@turip turip changed the title Feat/redis high watermark cache feat: redis high watermark cache Jun 26, 2025
@turip
turip enabled auto-merge (squash) June 26, 2025 14:34
@turip
turip requested a review from tothandras June 26, 2025 14:34
@turip
turip merged commit 8525675 into main Jun 26, 2025
@turip
turip deleted the feat/redis-high-watermark-cache branch June 26, 2025 14:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants