Repository navigation
refactor(ledger): account pkg cleanup - #4286
Conversation
|
Caution Review failedFailed to post review comments 📝 WalkthroughWalkthroughThis PR refactors ledger balance querying by introducing an explicit ChangesCore Ledger API Refactor
Dependency Injection Wiring
Charges & Transaction Resolution
Billing & Customer Balance
Test Updates & Account Resolution
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes This is a substantial, multi-layer refactoring touching the ledger core interfaces, dependency injection across multiple applications, charge/billing logic, and numerous test environments. While individual changes follow a consistent pattern (replacing direct balance-query method calls with Possibly related PRs
Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Tip 💬 Introducing Slack Agent: The best way for teams to turn conversations into code.Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.
Built for teams:
One agent for your entire SDLC. Right inside Slack. 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. Review rate limit: 7/8 reviews remaining, refill in 7 minutes and 30 seconds.Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (3)
openmeter/ledger/recognizer/service_test.go (1)
35-39: 💤 Low valueMinor duplication with
resolverDeps()
newRecognizerTestEnvbuilds the sameResolverDependencies(lines 35–39) thatresolverDeps()(lines 71–75) returns verbatim. If a fourth field lands onResolverDependenciesthere are two spots to update. You could partially construct the env, then callresolverDeps()for both uses:♻️ Optional simplification
func newRecognizerTestEnv(t *testing.T) *recognizerTestEnv { t.Helper() base := ledgertestutils.NewIntegrationEnv(t, "recognizer") - deps := transactions.ResolverDependencies{ - AccountService: base.Deps.ResolversService, - AccountCatalog: base.Deps.AccountService, - BalanceQuerier: base.Deps.HistoricalLedger, - } + env := &recognizerTestEnv{IntegrationEnv: base} + deps := env.resolverDeps() // ... rest of construction unchanged ... - return &recognizerTestEnv{ - IntegrationEnv: base, - recognizer: recSvc, - lineage: lngeSvc, - } + env.recognizer = recSvc + env.lineage = lngeSvc + return env }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/ledger/recognizer/service_test.go` around lines 35 - 39, The block in newRecognizerTestEnv duplicates construction of transactions.ResolverDependencies already produced by resolverDeps(); replace the inline construction in newRecognizerTestEnv with a call to resolverDeps() (or call resolverDeps() and merge any additional test-only overrides) so both places use the same source of truth; update newRecognizerTestEnv to consume the resolverDeps() result rather than re-creating transactions.ResolverDependencies.openmeter/ledger/transactions/collection.go (1)
147-170: 💤 Low valueConsider adding matching nil checks here for consistency.
listCustomerFBOSourcesnow validates thatAccountCatalogandBalanceQuerierare non-nil before using them, butcollectFromAttributableCustomerAccrueduses the same deps without validation. While upstream code likely validates, adding the same checks here would be consistent and provide defense-in-depth.♻️ Optional: Add nil checks for consistency
func collectFromAttributableCustomerAccrued( ctx context.Context, customerID customer.CustomerID, currency currencyx.Code, target alpacadecimal.Decimal, deps ResolverDependencies, ) ([]subAccountAmount, error) { + if deps.AccountCatalog == nil { + return nil, fmt.Errorf("account catalog is required") + } + + if deps.BalanceQuerier == nil { + return nil, fmt.Errorf("balance querier is required") + } + customerAccounts, err := deps.AccountService.GetCustomerAccounts(ctx, customerID)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/ledger/transactions/collection.go` around lines 147 - 170, collectFromAttributableCustomerAccrued currently assumes dependencies exist; add the same nil checks used in listCustomerFBOSources at the start of collectFromAttributableCustomerAccrued to defend against nil deps. Validate deps.AccountService, deps.AccountCatalog (and deps.BalanceQuerier if the function later queries balances) and return an error like "missing AccountCatalog in resolver dependencies" (or "missing BalanceQuerier in resolver dependencies") so callers get consistent, descriptive failures before calling GetCustomerAccounts or ListSubAccounts.app/common/charges.go (1)
55-106: ⚡ Quick winConsider reducing repeated
transactions.ResolverDependenciesconstruction.
NewChargesCollectorService,NewChargesFlatFeeHandler, andNewChargesUsageBasedHandlerall build identicaltransactions.ResolverDependencies{}structs inline. Since all three are called fromnewChargesRegistrywith the exact same(balanceQuerier, accountResolver, accountService)triple, if the struct ever gains a new required field you'll need to update three sites instead of one.Two easy options:
- Build
depsonce innewChargesRegistryand thread it through (mirrors howNewChargesFlatFeeHandleralready forwards a completedepstoledgerchargeadapter.NewFlatFeeHandler).- Change the public signatures to accept
transactions.ResolverDependenciesdirectly, which also makes them easier to call and test in isolation.✨ Option 1 – build deps once in the private registry
func newChargesRegistry( db *entdb.Client, ... ledgerService ledger.Ledger, balanceQuerier ledger.BalanceQuerier, accountResolver ledger.AccountResolver, accountService ledgeraccount.Service, fsNamespaceLockdown []string, ) (*ChargesRegistry, error) { + resolverDeps := transactions.ResolverDependencies{ + AccountService: accountResolver, + AccountCatalog: accountService, + BalanceQuerier: balanceQuerier, + } ... - collectorService := NewChargesCollectorService(ledgerService, balanceQuerier, accountResolver, accountService) + collectorService := NewChargesCollectorService(ledgerService, resolverDeps) - recognizerService, err := NewRecognizerService(db, ledgerService, balanceQuerier, accountResolver, accountService, lineageService) + recognizerService, err := NewRecognizerService(db, ledgerService, resolverDeps, lineageService) - flatFeeHandler := NewChargesFlatFeeHandler(ledgerService, balanceQuerier, accountResolver, accountService, collectorService) + flatFeeHandler := NewChargesFlatFeeHandler(ledgerService, resolverDeps, collectorService) - usageBasedHandler := NewChargesUsageBasedHandler(ledgerService, balanceQuerier, accountResolver, accountService, collectorService) + usageBasedHandler := NewChargesUsageBasedHandler(ledgerService, resolverDeps, collectorService)The public function signatures would change to accept
transactions.ResolverDependenciesinstead of the three individual fields:func NewChargesCollectorService( ledgerService ledger.Ledger, - balanceQuerier ledger.BalanceQuerier, - accountResolver ledger.AccountResolver, - accountService ledgeraccount.Service, + deps transactions.ResolverDependencies, ) ledgercollector.Service { return ledgercollector.NewService(ledgercollector.Config{ Ledger: ledgerService, - Dependencies: transactions.ResolverDependencies{ - AccountService: accountResolver, - AccountCatalog: accountService, - BalanceQuerier: balanceQuerier, - }, + Dependencies: deps, }) }(Same pattern for
NewChargesFlatFeeHandler,NewChargesUsageBasedHandler,NewRecognizerService.)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@app/common/charges.go` around lines 55 - 106, Multiple constructors (NewChargesCollectorService, NewChargesFlatFeeHandler, NewChargesUsageBasedHandler) duplicate building transactions.ResolverDependencies; change them to accept a single transactions.ResolverDependencies parameter (or build one deps in newChargesRegistry and pass it) and update newChargesRegistry to construct that deps once from (balanceQuerier, accountResolver, accountService) and pass it into those functions; update all calls (including where ledgerchargeadapter.NewFlatFeeHandler and ledgerchargeadapter.NewUsageBasedHandler are invoked) to forward the shared deps so you only maintain one ResolverDependencies construction site.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@openmeter/ledger/account.go`:
- Around line 110-116: CreateAccountInput.Validate() currently only validates
the Type and misses checking that Namespace is non-empty, causing inconsistency
with CreateSubAccountInput.Validate(); update CreateAccountInput.Validate() to
mirror the sub-account validation by returning an error when c.Namespace is
empty (use the same or similar error message used in
CreateSubAccountInput.Validate()), and keep the existing Type validation (i.e.,
validate Namespace first, then call c.Type.Validate()).
In `@openmeter/ledger/account/service/service.go`:
- Around line 127-130: The current switch only adds FBO and receivable accounts
to byID, which allows accrued/business accounts (posted by
TranslateCustomerAccruedCostBasisTemplate via historical.Ledger.CommitGroup) to
escape locking; change the logic in service.go so accrued/business accounts are
not skipped—either add the specific accrued/business account type constants to
the case list alongside ledger.AccountTypeCustomerFBO and
ledger.AccountTypeCustomerReceivable, or remove the switch/filter entirely and
unconditionally set byID[acc.ID()] = acc so all customer-related accounts
(including those touched by TranslateCustomerAccruedCostBasisTemplate) are
locked.
In `@openmeter/ledger/historical/balance.go`:
- Around line 76-80: The historical ledger function is returning a
QuerySummedResult with PendingSum equal to total, which incorrectly marks
settled funds as pending; change the returned object in the function that
currently constructs ledger.QuerySummedResult (the one using the local variable
total) to set SettledSum: total and PendingSum: zero (the appropriate zero value
for the sum type) so pending remains zero for historical balances.
---
Nitpick comments:
In `@app/common/charges.go`:
- Around line 55-106: Multiple constructors (NewChargesCollectorService,
NewChargesFlatFeeHandler, NewChargesUsageBasedHandler) duplicate building
transactions.ResolverDependencies; change them to accept a single
transactions.ResolverDependencies parameter (or build one deps in
newChargesRegistry and pass it) and update newChargesRegistry to construct that
deps once from (balanceQuerier, accountResolver, accountService) and pass it
into those functions; update all calls (including where
ledgerchargeadapter.NewFlatFeeHandler and
ledgerchargeadapter.NewUsageBasedHandler are invoked) to forward the shared deps
so you only maintain one ResolverDependencies construction site.
In `@openmeter/ledger/recognizer/service_test.go`:
- Around line 35-39: The block in newRecognizerTestEnv duplicates construction
of transactions.ResolverDependencies already produced by resolverDeps(); replace
the inline construction in newRecognizerTestEnv with a call to resolverDeps()
(or call resolverDeps() and merge any additional test-only overrides) so both
places use the same source of truth; update newRecognizerTestEnv to consume the
resolverDeps() result rather than re-creating transactions.ResolverDependencies.
In `@openmeter/ledger/transactions/collection.go`:
- Around line 147-170: collectFromAttributableCustomerAccrued currently assumes
dependencies exist; add the same nil checks used in listCustomerFBOSources at
the start of collectFromAttributableCustomerAccrued to defend against nil deps.
Validate deps.AccountService, deps.AccountCatalog (and deps.BalanceQuerier if
the function later queries balances) and return an error like "missing
AccountCatalog in resolver dependencies" (or "missing BalanceQuerier in resolver
dependencies") so callers get consistent, descriptive failures before calling
GetCustomerAccounts or ListSubAccounts.
🪄 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: 03224b12-a43b-4201-a42f-20d2cf756a09
📒 Files selected for processing (44)
app/common/billing.goapp/common/charges.goapp/common/customerbalance.goapp/common/ledger.gocmd/billing-worker/wire_gen.gocmd/jobs/internal/wire_gen.gocmd/jobs/ledger/backfillaccounts/backfillaccounts.gocmd/server/wire_gen.goopenmeter/ledger/account.goopenmeter/ledger/account/account.goopenmeter/ledger/account/account_business.goopenmeter/ledger/account/account_customer.goopenmeter/ledger/account/service.goopenmeter/ledger/account/service/service.goopenmeter/ledger/account/subaccount.goopenmeter/ledger/accounts.goopenmeter/ledger/balance.goopenmeter/ledger/chargeadapter/creditpurchase.goopenmeter/ledger/chargeadapter/creditpurchase_test.goopenmeter/ledger/chargeadapter/flatfee_test.goopenmeter/ledger/chargeadapter/helpers.goopenmeter/ledger/chargeadapter/usagebased_test.goopenmeter/ledger/customerbalance/facade_test.goopenmeter/ledger/customerbalance/service.goopenmeter/ledger/customerbalance/testenv_test.goopenmeter/ledger/customerbalance/transactions.goopenmeter/ledger/customerbalance/transactions_test.goopenmeter/ledger/historical/balance.goopenmeter/ledger/historical/ledger.goopenmeter/ledger/ledger_fx_test.goopenmeter/ledger/ledger_test.goopenmeter/ledger/noop/noop.goopenmeter/ledger/primitives.goopenmeter/ledger/query.goopenmeter/ledger/recognizer/service.goopenmeter/ledger/recognizer/service_test.goopenmeter/ledger/resolvers/account.goopenmeter/ledger/testutils/deps.goopenmeter/ledger/testutils/integration.goopenmeter/ledger/transactions/collection.goopenmeter/ledger/transactions/resolve.goopenmeter/ledger/transactions/testenv_test.gotest/credits/creditgrant_test.gotest/credits/sanity_test.go
💤 Files with no reviewable changes (3)
- openmeter/ledger/accounts.go
- openmeter/ledger/customerbalance/transactions_test.go
- openmeter/ledger/query.go
Overview
Refactors ledger package boundaries around stronger root-level public abstractions.
ledger.Account/ledger.SubAccountto identity + routing primitivesledger.BalanceQuerierAccountCatalog,AccountLocker, and balance queryingledger/accountto implement catalog + locking behind root interfacesledger/historicalto depend on root interfaces instead of concrete account servicesNotes for Reviewer
Summary by CodeRabbit