Skip to content

feat: reset balance events - #2750

Merged
turip merged 2 commits into
mainfrom
feat/reset-balance-events
Apr 30, 2025
Merged

turip merged 2 commits into
mainfrom
feat/reset-balance-events

Conversation

@turip

@turip turip commented Apr 30, 2025 •

Copy link
Copy Markdown
Member

Overview

Make sure that we are generating an internal event on resets, that contains the snapshot exactly at the period's start. The operation is set to reset in such cases.

Example event:

{
	"specversion": "1.0",
	"id": "01JT3AECGVGZ7CTHNRTE5FD0ZR",
	"source": "//openmeter.io/namespace/org_2l3uuzkgTdvCyom82y11jeZO2u5/entitlement/01JT3987GH49S9CBYYKX0BGNS1",
	"type": "io.openmeter.entitlement.v2.entitlement.snapshot",
	"subject": "//openmeter.io/namespace/org_2l3uuzkgTdvCyom82y11jeZO2u5/subjectKey/test",
	"datacontenttype": "application/json",
	"time": "2025-04-30T12:23:46.459268Z",
	"data": {
		"entitlement": {
			"namespace": "org_2l3uuzkgTdvCyom82y11jeZO2u5",
			"createdAt": "2025-04-30T12:02:56.145752Z",
			"updatedAt": "2025-04-30T12:23:46.427412Z",
			"Annotations": null,
			"activeFrom": "2025-04-30T12:02:56.142814Z",
			"id": "01JT3987GH49S9CBYYKX0BGNS1",
			"featureId": "01JT38V68VS69NCRAZR6KK9FTD",
			"featureKey": "api_requests_total",
			"subjectKey": "test",
			"type": "metered",
			"usagePeriod": {
				"period": "P1D",
				"anchor": "2025-04-30T12:23:00Z"
			},
			"currentUsagePeriod": {
				"from": "2025-04-30T12:23:00Z",
				"to": "2025-05-01T12:23:00Z"
			},
			"originalUsagePeriodAnchor": "2025-04-30T12:02:00Z",
			"measureUsageFrom": "2025-04-30T14:02:00+02:00",
			"issueAfterReset": 123,
			"issueAfterResetPriority": 1,
			"isSoftLimit": true,
			"lastReset": "2025-04-30T12:23:00Z"
		},
		"namespace": {
			"id": "org_2l3uuzkgTdvCyom82y11jeZO2u5"
		},
		"subject": {
			"id": "01JT38VH8H8SA86G0TWN0Z8HVZ",
			"key": "test",
			"metadata": {}
		},
		"feature": {
			"namespace": "org_2l3uuzkgTdvCyom82y11jeZO2u5",
			"id": "01JT38V68VS69NCRAZR6KK9FTD",
			"name": "api_requests_total",
			"key": "api_requests_total",
			"meterSlug": "api_requests_total",
			"createdAt": "2025-04-30T11:55:48.891454Z",
			"updatedAt": "2025-04-30T11:55:48.891454Z"
		},
		"operation": "reset",
		"calculatedAt": "2025-04-30T12:23:00Z",
		"value": {
			"balance": 123,
			"hasAccess": true,
			"overage": 0,
			"usage": 0
		},
		"currentUsagePeriod": {
			"from": "2025-04-30T12:23:00Z",
			"to": "2025-05-01T12:23:00Z"
		}
	}
}

Summary by CodeRabbit

  • New Features
    • Added support for a new "reset" operation type in entitlement event handling, enabling explicit reset actions for entitlements.
  • Bug Fixes
    • Reset events now use the correct timestamp and are properly marked as reset operations in event metadata.
  • Improvements
    • Expanded validation and processing to recognize and handle reset operations consistently across entitlement and notification systems.
    • Enhanced event processing flow with high watermark cache checks to optimize entitlement event handling.

@coderabbitai

coderabbitai Bot commented Apr 30, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This change introduces explicit support for a new "reset" operation type in entitlement event handling. It adds the ValueOperationReset constant, updates event validation logic to recognize and validate this operation, and modifies event processing to allow reset operations to propagate through the system. The entitlement event handler is refactored to check a high watermark cache before processing events, and special handling is implemented for reset operations to ensure snapshots are created at the start of the current usage period. The notification consumer is also updated to treat reset events as valid for balance threshold checks.

Changes

Files/Paths Change Summary
openmeter/entitlement/balanceworker/entitlementhandler.go Added support for a new reset operation type in entitlement event handling. Introduced sourceOperation field and setter, high watermark cache check logic, and reset-specific snapshot creation. Extended snapshot event creation to allow operation override.
openmeter/entitlement/snapshot/event.go Added ValueOperationReset to the operation type enum. Implemented operation validation methods. Updated event validation logic to accept and properly check the new reset operation, ensuring events of this type are handled as valid.
openmeter/entitlement/balanceworker/worker.go Updated entitlement reset event handling to use the correct timestamp and explicitly set the source operation to reset in event metadata. Added import for the snapshot package.
openmeter/notification/consumer/balancetreshold.go Modified balance threshold event logic to treat both update and reset operations as valid for notification purposes. Updated comments to clarify the change.

Possibly related PRs

  • refactor: balance worker #2735: Refactored handleEntitlementEvent and related methods, laying the groundwork for the new options and logic for handling reset operations and high watermark cache checks implemented in this PR.

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 6feaf90 and b2baa10.

📒 Files selected for processing (1)
  • openmeter/entitlement/snapshot/event.go (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • openmeter/entitlement/snapshot/event.go
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: CI
  • GitHub Check: Quickstart
  • GitHub Check: E2E
  • GitHub Check: Developer environment
  • GitHub Check: Commit hooks
  • GitHub Check: Migration Checks
  • GitHub Check: Lint
  • GitHub Check: Test
  • GitHub Check: Build
  • GitHub Check: Analyze (javascript)
  • 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 force-pushed the feat/reset-balance-events branch 2 times, most recently from 73522d4 to 8578b82 Compare April 30, 2025 12:24
@turip turip added release-note/ignore Ignore this change when generating release notes area/notification labels Apr 30, 2025
@turip
turip marked this pull request as ready for review April 30, 2025 12:26
@turip
turip requested a review from a team as a code owner April 30, 2025 12:26
@turip
turip force-pushed the feat/reset-balance-events branch from 8578b82 to 6feaf90 Compare April 30, 2025 12:26

@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 (4)
openmeter/entitlement/snapshot/event.go (2)

118-121: Remove redundant Operation.Validate() call

Operation.Validate() is invoked twice in SnapshotEvent.Validate() (lines 94–96 and again here).
The second invocation is superfluous and slightly inflates the hot-path of every snapshot validation.

-	if err := e.Operation.Validate(); err != nil {
-		return err
-	}

Removing these four lines keeps behaviour unchanged while shaving a small amount of CPU cycles and allocations during event validation.


25-31: Micro-optimise Values() (optional)

Values() allocates a fresh slice on every call. As it is only used by Validate(), consider:

-var _allValueOperations = []ValueOperationType{
-	ValueOperationReset,
-	ValueOperationUpdate,
-	ValueOperationDelete,
-}
-
-func (o ValueOperationType) Values() []ValueOperationType {
-	return _allValueOperations
-}
+var _allValueOperations = [...]ValueOperationType{
+	ValueOperationReset,
+	ValueOperationUpdate,
+	ValueOperationDelete,
+}
+
+func (o ValueOperationType) Values() []ValueOperationType {
+	// slice over the array – zero alloc
+	return _allValueOperations[:]
+}

This is entirely optional, but brings Validate() down to a single allocation-free slice header construction.

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

51-55: Avoid storing a pointer to a captured variable (minor)

WithSourceOperation keeps the address of the function-parameter sourceOperation.
Although the variable is heap-escaped and safe, using a value copy avoids subtle lifetime surprises:

-func WithSourceOperation(sourceOperation snapshot.ValueOperationType) handleOption {
-	return func(o *handleEntitlementEventOptions) {
-		o.sourceOperation = &sourceOperation
-	}
+func WithSourceOperation(op snapshot.ValueOperationType) handleOption {
+	return func(o *handleEntitlementEventOptions) {
+		tmp := op // guarantees unique address per call
+		o.sourceOperation = &tmp
+	}
 }

Purely optional; existing code works, but the rewrite removes an indirection to a shared variable.


80-104: High-watermark cache bypass for reset events looks correct but skips cache update

checkHighWatermarkCache always returns recalculateAction for reset events, yet handleEntitlementEvent never adds a cache entry along the reset fast-path (lines 179-192).
That means identical reset events (same entitlement + time) will trigger full recalculation on every delivery attempt/replay.

Consider either:

  1. updating the cache after emitting the reset snapshot, or
  2. including the operation type in the cache key so that non-reset events are unaffected.

This would prevent unnecessary recalculations while keeping semantics intact.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f133c7f and 6feaf90.

📒 Files selected for processing (4)
  • openmeter/entitlement/balanceworker/entitlementhandler.go (10 hunks)
  • openmeter/entitlement/balanceworker/worker.go (2 hunks)
  • openmeter/entitlement/snapshot/event.go (4 hunks)
  • openmeter/notification/consumer/balancetreshold.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
openmeter/entitlement/balanceworker/worker.go (2)
openmeter/entitlement/balanceworker/entitlementhandler.go (2)
  • WithEventAt (45-49)
  • WithSourceOperation (51-55)
openmeter/entitlement/snapshot/event.go (1)
  • ValueOperationReset (20-20)
openmeter/notification/consumer/balancetreshold.go (1)
openmeter/entitlement/snapshot/event.go (3)
  • ValueOperationType (17-17)
  • ValueOperationUpdate (21-21)
  • ValueOperationReset (20-20)
⏰ Context from checks skipped due to timeout of 90000ms (12)
  • GitHub Check: Artifacts / Container image
  • GitHub Check: Quickstart
  • GitHub Check: E2E
  • GitHub Check: CI
  • GitHub Check: Test
  • GitHub Check: Migration Checks
  • GitHub Check: Lint
  • GitHub Check: Developer environment
  • GitHub Check: Commit hooks
  • GitHub Check: Build
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (3)
openmeter/notification/consumer/balancetreshold.go (1)

216-218: LGTM – reset events now correctly pass balance-threshold filter

Accepting both update and reset operations makes the consumer consistent with the new snapshot semantics.

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

179-192: Good: snapshot taken at period start for reset events

Reset snapshots use CurrentUsagePeriod.From as calculatedAt, guaranteeing an accurate “period-initial” balance.


238-243: Validation guard is solid

Nice touch performing validation on OverrideOperation; catches typos at call-site early.

Comment thread openmeter/entitlement/snapshot/event.go Resolved
@turip
turip enabled auto-merge (squash) April 30, 2025 12:36
@turip
turip merged commit 30b7a9c into main Apr 30, 2025
@turip
turip deleted the feat/reset-balance-events branch April 30, 2025 12:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/notification 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