Skip to content

Conversation

@turip
Copy link
Member

@turip turip commented May 1, 2025

Overview

Fix entitlement.reset serialization issues
When apps are not present in the eventinvoice let's not throw an error, instead send empty apps (schema allows)
Use billing service for test invoice creation, so that the invoice is always up to date with latest schemantics.

Summary by CodeRabbit

  • New Features
    • Added support for entitlement reset notifications and event types.
    • Enhanced test notification event generation to dynamically simulate invoice events using current billing data.
  • Improvements
    • Improved error handling and validation across invoice simulation and notification event mapping.
    • Refined customer and address handling in invoice simulation for greater flexibility.
    • Enhanced error traceability in entitlement snapshot event processing.
  • Refactor
    • Modularized test event payload generation for notifications, increasing maintainability and extensibility.

Fix entitlement.reset serialization issues
Use billing service for test invoice creation, so that the invoice is
always up to date with latest schemantics.
@turip turip requested a review from a team as a code owner May 1, 2025 11:50
@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 1, 2025

Warning

Rate limit exceeded

@turip has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 9 minutes and 29 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 d07aa57 and 8317e57.

📒 Files selected for processing (3)
  • openmeter/billing/service/invoice.go (5 hunks)
  • openmeter/notification/eventhandler/handler.go (1 hunks)
  • openmeter/notification/httpdriver/mapping.go (4 hunks)
📝 Walkthrough

Walkthrough

This set of changes introduces enhancements and refactoring to the billing and notification components. The invoice simulation flow is updated to allow simulation using either an existing customer ID or a full customer object, with corresponding adjustments in data validation, service logic, and mapping to API models. Notification event handling is expanded to support a new event type, EntitlementReset, with serialization, deserialization, and mapping logic added throughout relevant modules. The test event generation mechanism is modularized, now dynamically generating invoice payloads via the billing service. Error handling and dependency injection are improved for better traceability and testability.

Changes

Files/Paths Change Summary
openmeter/billing/invoice.go, openmeter/billing/service/invoice.go, openmeter/billing/httpdriver/invoice.go Refactored invoice simulation to support both customer ID and full customer object; updated struct signatures, validation, and service logic; improved mapping of event invoices and customer data to API models.
openmeter/notification/internal/rule.go, openmeter/notification/httpdriver/rule.go, openmeter/notification/httpdriver/handler.go, openmeter/server/router/router.go Modularized test event generation with a TestEventGenerator struct; replaced static payloads with dynamic generation via billing service; updated handler and router to inject billing dependency and use new generator.
openmeter/ent/schema/notification.go Added serialization/deserialization support for EventTypeEntitlementReset in notification rule config value scanning.
openmeter/notification/httpdriver/mapping.go Added support for EventTypeEntitlementReset in event mapping and payload extraction logic with improved error handling.
openmeter/notification/consumer/entitlementsnapshot.go Enhanced error handling in entitlement snapshot event processing with contextual error wrapping.

Possibly related PRs

  • fix: invoice app serialization #2724: Refactors EventInvoice app metadata mapping, which is directly related to the main PR’s changes in how event invoice apps are conditionally mapped and serialized.
✨ 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.

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 added release-note/bug-fix Release note: Bug Fixes area/notification labels May 1, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🔭 Outside diff range comments (2)
openmeter/notification/httpdriver/mapping.go (1)

535-547: 🛠️ Refactor suggestion

Second nil-pointer risk inside payload mapper

FromEventAsEntitlementResetPayload again assumes e.Payload.EntitlementReset
is non-nil. Either add a guard or document the pre-condition very visibly.

 func FromEventAsEntitlementResetPayload(e notification.Event) api.NotificationEventResetPayload {
-	return api.NotificationEventResetPayload{
+	if e.Payload.EntitlementReset == nil {
+		// This should never happen – the caller is expected to validate – but protect anyway.
+		return api.NotificationEventResetPayload{}
+	}
+	return api.NotificationEventResetPayload{
openmeter/notification/internal/rule.go (1)

94-98: ⚠️ Potential issue

Event type is incorrect for entitlement-reset test payload

newTestEntitlementResetPayload() returns a payload whose meta‐type is BalanceThreshold, so callers requesting EntitlementReset receive the wrong event type.

-			Type: notification.EventTypeBalanceThreshold,
+			Type: notification.EventTypeEntitlementReset,

This will otherwise cause rule-matching logic to ignore the test event.

🧹 Nitpick comments (8)
openmeter/ent/schema/notification.go (2)

304-313: Avoid duplicate serialization logic & handle nil Data cleanly

The two new EntitlementReset branches are a verbatim copy of the existing pattern.
Although that works, the switch is now getting unwieldy and easy to forget when a new
event type is added.

  1. Consider extracting the common serde := ruleConfigSerde[...] { … } construction
    into a helper to reduce copy-paste.
  2. When config.EntitlementReset is nil, json.Marshal will emit "data":null.
    If you prefer to omit empty fields (consistent with the API), add an
    omitempty tag to the Data field or make the field non-pointer in the
    wrapper and set it conditionally.

358-374: Missing nil-check during deserialization could panic later

serde.Data is always initialised (&notification.EntitlementResetRuleConfig{}), but
if the inbound JSON contains "data":null we end up with an empty struct instead of
nil, whereas other branches leave the pointer nil.
For consistency – and to be able to distinguish “no config supplied” –
explicitly set serde.Data = nil when the raw json value is null.

openmeter/notification/httpdriver/mapping.go (2)

500-505: Minor: keep FromEventType in lexicographic (or logical) order

Placing the new case after BalanceThreshold keeps the list sorted and makes future
diffs cleaner.


566-599: Avoid mutating input & tighten app-mapping logic

event.Invoice.Workflow.Apps = nil mutates the argument.
If the caller re-uses the same EventInvoice elsewhere this could be surprising.
Create a shallow copy instead.

Also, you silently ignore invalid event.Apps.* (empty Type). Consider returning
an error if all three app objects are empty – that would signal an upstream bug
instead of emitting an invoice with an empty apps block.

-	// Prefer the apps from the event
-	event.Invoice.Workflow.Apps = nil
+	// Work on a copy so the original event is not mutated.
+	evCopy := event
+	evCopy.Invoice.Workflow.Apps = nil
openmeter/billing/httpdriver/invoice.go (1)

623-642: MapInvoiceCustomerToAPI: avoid nil map allocation on every call

When a == nil you still allocate out.Addresses later on. Early-return
avoids that extra allocation:

-	out := api.BillingParty{
-		Id:   lo.ToPtr(c.CustomerID),
-		Name: lo.EmptyableToPtr(c.Name),
-	}
-
-	if a != nil {
-		out.Addresses = lo.ToPtr([]api.Address{ … })
-	}
-
-	return out
+	if a == nil {
+		return api.BillingParty{
+			Id:   lo.ToPtr(c.CustomerID),
+			Name: lo.EmptyableToPtr(c.Name),
+		}
+	}
+
+	return api.BillingParty{
+		Id:   lo.ToPtr(c.CustomerID),
+		Name: lo.EmptyableToPtr(c.Name),
+		Addresses: lo.ToPtr([]api.Address{ … }),
+	}

A micro-optimisation, but this function may be called in tight loops.

openmeter/billing/service/invoice.go (2)

1099-1112: Avoid mutating caller-supplied Line objects in-place

lo.Map rewrites the slice elements directly, which means any *billing.Line instances the caller re-uses after calling SimulateInvoice will now contain mutated state (namespace, currency, IDs, timestamps, invoice-ID).
Defensive copying keeps the API free from surprising side-effects.

-	invoice.Lines = billing.NewLineChildren(
-		lo.Map(inputLines, func(line *billing.Line, _ int) *billing.Line {
-			line.Namespace = input.Namespace
-			...
-			return line
-		}),
-	)
+	invoice.Lines = billing.NewLineChildren(
+		lo.Map(inputLines, func(src *billing.Line, _ int) *billing.Line {
+			cloned := *src // shallow copy – deep-copy nested structs if needed
+			cloned.Namespace = input.Namespace
+			...
+			return &cloned
+		}),
+	)

1120-1128: Duplicate per-line validation – consider removing

invoice.Validate() already validates child lines; the additional loop immediately afterwards validates each line again, doubling the work.

Unless you need a different validation rule set here, you can safely drop the second pass and return the (already aggregated) issues from invoice.Validate().

openmeter/notification/internal/rule.go (1)

165-176: Prefer clock.Now() for deterministic timestamps in tests

Using wall-clock time makes golden-file / snapshot tests flaky.
The billing service already depends on the clock package – re-use it here for the same reasons explained in the billing comment.

-	now := time.Now().Truncate(time.Second).In(time.UTC)
+	now := clock.Now().Truncate(time.Second).In(time.UTC)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ce00a20 and a4c5acf.

📒 Files selected for processing (10)
  • openmeter/billing/httpdriver/invoice.go (4 hunks)
  • openmeter/billing/invoice.go (1 hunks)
  • openmeter/billing/service/invoice.go (5 hunks)
  • openmeter/ent/schema/notification.go (2 hunks)
  • openmeter/notification/consumer/entitlementsnapshot.go (2 hunks)
  • openmeter/notification/httpdriver/handler.go (3 hunks)
  • openmeter/notification/httpdriver/mapping.go (3 hunks)
  • openmeter/notification/httpdriver/rule.go (1 hunks)
  • openmeter/notification/internal/rule.go (3 hunks)
  • openmeter/server/router/router.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (4)
openmeter/notification/httpdriver/rule.go (3)
openmeter/notification/internal/rule.go (1)
  • EventGeneratorInput (33-37)
openmeter/notification/event.go (2)
  • EventType (26-26)
  • CreateEventInput (136-148)
pkg/models/model.go (1)
  • NamespacedModel (180-182)
openmeter/server/router/router.go (1)
app/common/billing.go (1)
  • Billing (25-28)
openmeter/ent/schema/notification.go (2)
openmeter/notification/entitlements.go (2)
  • EventTypeEntitlementReset (12-12)
  • EntitlementResetRuleConfig (118-120)
openmeter/notification/rule.go (2)
  • RuleConfigMeta (71-73)
  • RuleConfig (80-89)
openmeter/notification/httpdriver/mapping.go (4)
openmeter/notification/entitlements.go (1)
  • EventTypeEntitlementReset (12-12)
api/api.gen.go (4)
  • NotificationEventTypeEntitlementsReset (559-559)
  • Entitlement (2497-2499)
  • Feature (2946-2975)
  • Subject (6290-6307)
api/client/go/client.gen.go (4)
  • NotificationEventTypeEntitlementsReset (516-516)
  • Entitlement (2297-2299)
  • Feature (2714-2743)
  • Subject (5757-5774)
api/client/javascript/src/client/schemas.ts (3)
  • Entitlement (10367-10367)
  • Feature (10392-10392)
  • Subject (10676-10676)
🔇 Additional comments (11)
openmeter/server/router/router.go (1)

293-298: Properly injected billing service for notification event generation.

The notification handler now accepts the billing service as a dependency, which is needed for generating test events with realistic invoice payloads. This integration allows for more accurate notification simulation during testing.

openmeter/notification/consumer/entitlementsnapshot.go (3)

5-5: Added fmt import for error wrapping.

This import is needed for the improved error handling below.


19-21: Improved error context for better traceability.

The error from handleAsSnapshotEvent is now properly wrapped with contextual information, making debugging easier when issues occur.


25-27: Improved error context for better traceability.

The error from handleAsEntitlementResetEvent is now properly wrapped with contextual information, making debugging easier when issues occur.

openmeter/notification/httpdriver/rule.go (2)

318-324: Improved test event generation with dynamic payload creation.

The code now uses the new testEventGenerator to dynamically generate test event payloads based on the rule type and namespace, replacing the previous static payload approach. This change makes test events more realistic and consistent with actual production events.


329-329: Updated to use dynamically generated test event.

The code now uses the dynamically generated test event as the payload for the created notification event.

openmeter/notification/httpdriver/handler.go (5)

8-8: Added billing service import.

This import enables the notification handler to access the billing service functionality.


11-11: Updated internal package import.

This change ensures access to the new test event generation functionality implemented in the internal package.


47-50: Added test event generator field to handler struct.

The handler now includes a testEventGenerator field, which will be used to dynamically generate test event payloads for notification rules.


65-65: Added billing service parameter to constructor.

The notification handler constructor now accepts a billing service parameter, which is necessary for initializing the test event generator.


69-73: Updated handler initialization with test event generator.

The handler now properly initializes the test event generator using the provided billing service, enabling dynamic generation of test notification events.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

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 (1)
openmeter/notification/httpdriver/mapping.go (1)

459-470: Add more diagnostic context to error wrapping

Great job extracting the payload conversion into FromEventAsBalanceThresholdPayload and guarding against a nil payload – that removes the panic path.
To make troubleshooting easier when this branch still fails (e.g. malformed event coming from storage), consider injecting the event ID and type into the wrapped error before bubbling it up. This helps ops trace the exact record that triggered the failure without having to add extra logs later.

-        return event, fmt.Errorf("failed to cast notification event payload: %w", err)
+        return event, fmt.Errorf("failed to cast balance-threshold payload for event %s (%s): %w",
+            e.ID, e.Type, err)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a4c5acf and d07aa57.

📒 Files selected for processing (2)
  • openmeter/billing/service/invoice.go (5 hunks)
  • openmeter/notification/httpdriver/mapping.go (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • openmeter/billing/service/invoice.go
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: CI
  • GitHub Check: Test
  • GitHub Check: Lint
  • GitHub Check: Developer environment
  • GitHub Check: Commit hooks
  • GitHub Check: Analyze (go)
🔇 Additional comments (1)
openmeter/notification/httpdriver/mapping.go (1)

513-515: 👍 Correct event-type mapping added

Mapping notification.EventTypeEntitlementReset to api.NotificationEventTypeEntitlementsReset fills the missing link noted in previous reviews. Looks good.

@turip turip force-pushed the fix/notification-errors branch from d07aa57 to 8317e57 Compare May 1, 2025 12:20
@turip turip requested review from chrisgacsal, hekike and tothandras May 1, 2025 12:27
@turip turip merged commit 9a32bdc into main May 1, 2025
31 checks passed
@turip turip deleted the fix/notification-errors branch May 1, 2025 13:32
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