Skip to content

feat: remove PrepareForCreate from line service - #3823

Merged
turip merged 2 commits into
mainfrom
refactor/remove-prepare-for-create-from-line-service
Jan 28, 2026
Merged

turip merged 2 commits into
mainfrom
refactor/remove-prepare-for-create-from-line-service

Conversation

@turip

@turip turip commented Jan 28, 2026 •

Copy link
Copy Markdown
Member

Overview

We are removing the PrepareForCreate from the line service as these defaulting/time truncating logic are related to the line entity itself.

The line service is to be made a pure calculation-only package.

Notes for reviewer

Summary by CodeRabbit

  • Refactor

    • Simplified invoice line processing by removing intermediate preparation steps and consolidating line normalization into a streamlined pipeline.
    • Converted per-line preparation to batched mapping and validation for invoice line creation.
  • New Features

    • Added per-line normalization and batch-mapping helpers to produce normalized invoice lines before creation.
  • Chores

    • Minor formatting tweak (whitespace).

✏️ Tip: You can customize this high-level summary in your review settings.

We are removing the PrepareForCreate from the line service as these
defaulting/time truncating logic are related to the line entity itself.

The line service is to be made a pure calculation-only package.
@turip
turip requested a review from a team as a code owner January 28, 2026 09:30
@coderabbitai

coderabbitai Bot commented Jan 28, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The PR removes per-line PrepareForCreate processing and instead adds per-line and batch normalization methods (WithNormalizedValues, MapWithErr) that the billing service uses to normalize and assign invoice lines directly, updating invoice creation and update flows accordingly.

Changes

Cohort / File(s) Summary
Line interface & implementations
openmeter/billing/service/lineservice/service.go, openmeter/billing/service/lineservice/usagebasedline.go, openmeter/billing/service/lineservice/usagebasedlineflat.go
Removed PrepareForCreate(context.Context) (Line, error) from the Line interface and its implementations; deletes prior per-line pre-create truncation/validation hooks.
Standard line normalization helpers
openmeter/billing/stdinvoiceline.go, openmeter/billing/stdinvoice.go
Added StandardLine.WithNormalizedValues() and StandardInvoiceLines.MapWithErr() / WithNormalizedValues() to produce normalized copies of lines in batch.
Billing service flows (invoice & stdinvoiceline)
openmeter/billing/service/invoice.go, openmeter/billing/service/stdinvoiceline.go
Replaced per-line PrepareForCreate and inline conversion with batch mapping + normalization (WithNormalizedValues()), changed error contexts (e.g., "normalizing lines"/"mapping lines"), and adjusted line validation/creation pipeline to operate on normalized batches.
Minor formatting
openmeter/meter/mockadapter/meter.go
Inserted a blank line after appending meters in ListMeters (no logic change).

Sequence Diagram(s)

mermaid
sequenceDiagram
participant Client
participant BillingSvc as Billing Service
participant LineSvc as LineService/FeatureMeters
participant DB as Persistence
participant Events as EventPublisher

Client->>BillingSvc: CreateGatheringInvoice(request with lines)
BillingSvc->>BillingSvc: Map input lines -> set Namespace,Currency,ID,InvoiceID
BillingSvc->>BillingSvc: Call WithNormalizedValues() on batch
BillingSvc->>LineSvc: FromEntities(normalized lines, feature meters)
LineSvc->>LineSvc: ValidateForInvoice(normalized lines)
LineSvc->>DB: Create lines / persist invoice lines
DB-->>BillingSvc: Created lines / invoice state
BillingSvc->>BillingSvc: Update invoice with finalLines, calculate totals
BillingSvc->>Events: Publish InvoiceCreated/Updated
BillingSvc-->>Client: Return created gathering invoice

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

kind/refactor, release-note/breaking-change

Suggested reviewers

  • chrisgacsal
  • tothandras
  • GAlexIHU
🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 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: removing PrepareForCreate from the line service, which is the primary refactoring across multiple files.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor/remove-prepare-for-create-from-line-service

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.

@turip turip added release-note/misc Miscellaneous changes area/billing labels Jan 28, 2026

@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

🤖 Fix all issues with AI agents
In `@openmeter/billing/service/stdinvoiceline.go`:
- Around line 92-107: The error returned by slicesx.MapWithErr when building
linesToCreate is never checked and gets overwritten by the next call; after
calling slicesx.MapWithErr on input.Lines (creating linesToCreate and err) add
an immediate nil check (if err != nil) and return a wrapped error (e.g.,
fmt.Errorf("normalizing lines: %w", err)) before calling
s.lineService.FromEntities so any failure from WithNormalizedValues() on
billing.StandardLine is propagated.
🧹 Nitpick comments (2)
openmeter/billing/stdinvoiceline.go (1)

325-349: Nice addition for centralizing normalization logic!

The method looks solid overall. One thing to consider: there's no nil check before accessing out.UsageBased.Price at line 335. If UsageBased or Price is ever nil, this will panic.

I noticed the rest of the codebase (like DependsOnMeteredQuantity and ValidateUsageBased) follows the same pattern, so it seems like UsageBased being non-nil is an implicit invariant. Just wanted to flag this in case you'd like to add a defensive check here since this is new code:

🛡️ Optional defensive check
 func (i StandardLine) WithNormalizedValues() (*StandardLine, error) {
 	out := i.Clone()

 	out.Period = out.Period.Truncate(streaming.MinimumWindowSizeDuration)
 	out.InvoiceAt = out.InvoiceAt.Truncate(streaming.MinimumWindowSizeDuration)

+	if out.UsageBased == nil || out.UsageBased.Price == nil {
+		return out, nil
+	}
+
 	if out.UsageBased.Price.Type() == productcatalog.FlatPriceType {
openmeter/billing/service/stdinvoiceline.go (1)

60-68: Minor: Consider moving the empty check before resolveFeatureMeters.

The empty lines check at line 66 comes after resolveFeatureMeters at line 61. If input.Lines is empty, you're doing unnecessary work resolving feature meters. Could be a small optimization to check first:

♻️ Optional reorder
 	return transcationForInvoiceManipulation(ctx, s, input.Customer, func(ctx context.Context) (*billing.CreatePendingInvoiceLinesResult, error) {
+		if len(input.Lines) == 0 {
+			return nil, nil
+		}
+
 		featureMeters, err := s.resolveFeatureMeters(ctx, input.Lines)
 		if err != nil {
 			return nil, fmt.Errorf("resolving feature meters: %w", err)
 		}

-		if len(input.Lines) == 0 {
-			return nil, nil
-		}

@turip
turip enabled auto-merge (squash) January 28, 2026 09:45

@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

🤖 Fix all issues with AI agents
In `@openmeter/billing/service/stdinvoiceline.go`:
- Around line 61-62: CreatePendingInvoiceLines currently returns nil for empty
input.Lines, but the HTTP handler that calls CreatePendingInvoiceLines
dereferences the returned result (accessing res.IsInvoiceNew and res.Invoice)
without checking for nil, causing a potential panic. Fix by either making
CreatePendingInvoiceLines return a descriptive error for empty input or update
the HTTP handler that calls CreatePendingInvoiceLines to check if res == nil
before using res.IsInvoiceNew/res.Invoice and return an appropriate HTTP
response (e.g., 400 Bad Request or a clear error) when lines are empty;
reference CreatePendingInvoiceLines and the HTTP handler which reads
res.IsInvoiceNew and res.Invoice to locate the code to change.

Comment on lines +61 to +62
if len(input.Lines) == 0 {
return nil, nil

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.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Find and display the file to see the context around lines 61-62
fd -t f stdinvoiceline.go --exec cat -n {} \;

Repository: openmeterio/openmeter

Length of output: 36064


🏁 Script executed:

#!/bin/bash
# Search for all call sites of CreatePendingInvoiceLines
rg -n --type=go 'CreatePendingInvoiceLines' -C 3

Repository: openmeterio/openmeter

Length of output: 30598


🏁 Script executed:

#!/bin/bash
# Check the actual usage pattern at a few call sites
# Focus on openmeter code (not tests)

# invoiceupdate.go call
sed -n '155,170p' openmeter/billing/worker/subscriptionsync/service/invoiceupdate.go

# httpdriver call
sed -n '85,100p' openmeter/billing/httpdriver/invoiceline.go

Repository: openmeterio/openmeter

Length of output: 1008


Callers don't consistently handle nil result—HTTP handler needs nil check

The interface documents that CreatePendingInvoiceLines returns nil when input lines are empty, but the HTTP handler in openmeter/billing/httpdriver/invoiceline.go (lines 85–100) doesn't guard against this. It directly accesses res.IsInvoiceNew and res.Invoice after only checking the error, which will panic if the result is nil. Add a nil check before dereferencing the result, or return an error when the request contains empty lines.

🤖 Prompt for AI Agents
In `@openmeter/billing/service/stdinvoiceline.go` around lines 61 - 62,
CreatePendingInvoiceLines currently returns nil for empty input.Lines, but the
HTTP handler that calls CreatePendingInvoiceLines dereferences the returned
result (accessing res.IsInvoiceNew and res.Invoice) without checking for nil,
causing a potential panic. Fix by either making CreatePendingInvoiceLines return
a descriptive error for empty input or update the HTTP handler that calls
CreatePendingInvoiceLines to check if res == nil before using
res.IsInvoiceNew/res.Invoice and return an appropriate HTTP response (e.g., 400
Bad Request or a clear error) when lines are empty; reference
CreatePendingInvoiceLines and the HTTP handler which reads res.IsInvoiceNew and
res.Invoice to locate the code to change.

@turip
turip merged commit 6578ff0 into main Jan 28, 2026
27 checks passed
@turip
turip deleted the refactor/remove-prepare-for-create-from-line-service branch January 28, 2026 09:59
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