Skip to content

feat(statemachine): promotional credit purchase statemachine#4457

Merged
mark-vass-konghq merged 6 commits into
mainfrom
feat/promotional-credit-purchase-statemachine
Jun 1, 2026
Merged

feat(statemachine): promotional credit purchase statemachine#4457
mark-vass-konghq merged 6 commits into
mainfrom
feat/promotional-credit-purchase-statemachine

Conversation

@mark-vass-konghq
Copy link
Copy Markdown
Contributor

@mark-vass-konghq mark-vass-konghq commented May 29, 2026

Summary by CodeRabbit

  • Refactor

    • Credit purchase billing reworked to a state‑machine-driven flow for more reliable, validated processing.
  • Bug Fixes

    • Promotional credit grants now detect and prevent duplicate grants and ensure proper finalization.
  • Improvements

    • Safer charge handling with clearer read/update flows and construction-time validation to catch misconfiguration early.
  • Tests

    • Added comprehensive tests covering promotional credit state transitions, validations, and error scenarios.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 29, 2026

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: c99fbdfe-5f0a-4b39-851a-49cd7eeedd90

📥 Commits

Reviewing files that changed from the base of the PR and between 1cba13a and d2c72a4.

📒 Files selected for processing (1)
  • openmeter/billing/charges/creditpurchase/service/create.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • openmeter/billing/charges/creditpurchase/service/create.go

📝 Walkthrough

Walkthrough

Adds a promotional credit-purchase state machine with persistence wiring, Charge accessor methods, an EntryFunc helper, replaces the prior promotional handler call in Create with state-machine advancement, and adds comprehensive tests for promotional flows and constructor validation.

Changes

Promotional Credit Purchase State Machine

Layer / File(s) Summary
Charge accessor and mutator methods
openmeter/billing/charges/creditpurchase/charge.go
Added GetStatus/WithStatus and GetBase/WithBase methods to enable immutable-style updates and field access on the Charge type.
State machine infrastructure and configuration
openmeter/billing/charges/creditpurchase/service/statemachine.go
Defined StateMachine type alias, StateMachineConfig struct with validation requiring a charge ID and adapter, and newStateMachineBase to wire persistence callbacks that delegate charge updates to the adapter and refetch from storage with realizations expansion.
Promotional state machine and grant logic
openmeter/billing/charges/creditpurchase/service/promotional.go
Tightened grantPromotionalCredit validation to reject duplicate realizations; implemented PromotionalCreditpurchaseStateMachine with Created→Active→Final transitions and OnEntry for StatusFinal that delegates credit-grant creation to the service and assigns the returned charge.
Promotional state machine tests and infrastructure
openmeter/billing/charges/creditpurchase/service/promotional_test.go
Added tests covering advancement from Created/Active to Final, rejection for existing credit-grant realizations, no-op for already-Final charges, constructor validation (non-promotional, missing adapter/service), plus test helpers and stubs for adapter, handler, and lineage service.
EntryFunc helper
pkg/statelessx/actions.go
Added EntryFunc utility to adapt ActionFn to the variadic action signature used by state-machine actions.
Create service promotional settlement refactor
openmeter/billing/charges/creditpurchase/service/create.go
Replaced onPromotionalCreditPurchase call with direct NewPromotionalCreditPurchaseStateMachine construction and AdvanceUntilStateStable, wrapping errors and using the advanced charge when returned.

Sequence Diagram

sequenceDiagram
  participant CreateService
  participant PromotionalStateMachine
  participant RuntimeService
  participant Adapter

  CreateService->>PromotionalStateMachine: NewPromotionalCreditPurchaseStateMachine(config)
  PromotionalStateMachine->>PromotionalStateMachine: AdvanceUntilStateStable(ctx)
  PromotionalStateMachine->>RuntimeService: GrantPromotionalCredit(ctx)
  RuntimeService->>Adapter: CreateCreditGrant / UpdateCharge
  Adapter-->>RuntimeService: persisted charge / credit-grant ref
  RuntimeService-->>PromotionalStateMachine: updated Charge
  PromotionalStateMachine-->>CreateService: advanced Charge (optional)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • openmeterio/openmeter#4145: Introduces the shared chargestatemachine framework that this state machine builds on.
  • openmeterio/openmeter#4287: Tests and tax-config propagation touching credit-purchase promotional/invoice paths that exercise the modified promotional execution path.
  • openmeterio/openmeter#4129: Related changes to credit-purchase realization persistence and grant handling referenced by the new accessors and state-machine wiring.

Suggested reviewers

  • tothandras
  • turip
  • GAlexIHU
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: introducing a promotional credit purchase state machine, which is central to this PR's refactoring of promotional credit handling.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/promotional-credit-purchase-statemachine

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

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Member

@turip turip left a comment

Choose a reason for hiding this comment

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

Thank you! Nice 🙇

Comment thread openmeter/billing/charges/creditpurchase/service/promotional.go Outdated
Comment thread openmeter/billing/charges/creditpurchase/service/promotional.go
Comment thread openmeter/billing/charges/creditpurchase/service/promotional.go Outdated
@mark-vass-konghq mark-vass-konghq force-pushed the feat/promotional-credit-purchase-statemachine branch from 6f8a027 to 183525e Compare May 29, 2026 16:16
@mark-vass-konghq mark-vass-konghq marked this pull request as ready for review May 29, 2026 21:03
@mark-vass-konghq mark-vass-konghq requested a review from a team as a code owner May 29, 2026 21:03
Copy link
Copy Markdown
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: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@openmeter/billing/charges/creditpurchase/service/promotional.go`:
- Around line 53-60: NewPromotionalCreditPurchaseStateMachine must validate that
the runtime Service is non-nil before constructing the state machine because
GrantPromotionalCredit dereferences s.Service (used when reaching StatusFinal);
update NewPromotionalCreditPurchaseStateMachine to check config.Service (or the
specific field that provides s.Service) and return a descriptive error if nil so
the machine is not created with a nil Service.

In `@openmeter/billing/charges/creditpurchase/service/statemachine.go`:
- Around line 34-38: The Validate method on StateMachineConfig currently only
checks Charge.ID and allows a nil Adapter through; update
StateMachineConfig.Validate to also check that c.Adapter is not nil and return a
descriptive error (e.g. "adapter is required") so construction fails fast
instead of causing panics later in methods like UpdateBase or Refetch; reference
the StateMachineConfig.Validate function and the Adapter field to locate where
to add this nil-check and error return.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 3f95e466-817d-4084-b55c-9e426c71694b

📥 Commits

Reviewing files that changed from the base of the PR and between 819c22b and 7ada3c1.

📒 Files selected for processing (6)
  • openmeter/billing/charges/creditpurchase/charge.go
  • openmeter/billing/charges/creditpurchase/service/create.go
  • openmeter/billing/charges/creditpurchase/service/promotional.go
  • openmeter/billing/charges/creditpurchase/service/promotional_test.go
  • openmeter/billing/charges/creditpurchase/service/statemachine.go
  • pkg/statelessx/actions.go

Comment thread openmeter/billing/charges/creditpurchase/service/promotional.go
Comment thread openmeter/billing/charges/creditpurchase/service/statemachine.go
@mark-vass-konghq mark-vass-konghq force-pushed the feat/promotional-credit-purchase-statemachine branch from 7ada3c1 to 1bc5a97 Compare June 1, 2026 08:25
@mark-vass-konghq mark-vass-konghq requested a review from turip June 1, 2026 08:25
@mark-vass-konghq mark-vass-konghq force-pushed the feat/promotional-credit-purchase-statemachine branch from 1bc5a97 to 81e00dd Compare June 1, 2026 08:26
@mark-vass-konghq mark-vass-konghq force-pushed the feat/promotional-credit-purchase-statemachine branch from 81e00dd to 1cba13a Compare June 1, 2026 08:34
Comment thread openmeter/billing/charges/creditpurchase/service/create.go Outdated
Comment thread openmeter/billing/charges/creditpurchase/service/create.go Outdated
@mark-vass-konghq mark-vass-konghq merged commit 1175288 into main Jun 1, 2026
28 checks passed
@mark-vass-konghq mark-vass-konghq deleted the feat/promotional-credit-purchase-statemachine branch June 1, 2026 09:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/billing release-note/feature Release note: Exciting New Features

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants