usage

package
v0.12.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 30, 2026 License: MIT Imports: 28 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Provider cost rates + per-customer margin (ADR-079). COST — what the OPERATOR pays their LLM providers — is a separate ledger from PRICE (what the customer is billed); nothing here touches invoices or rating. The per-event COGS stamp itself lives in store.Ingest (single funnel); this file is the operator surface: rate CRUD + the margin report.

Index

Constants

View Source
const (
	BillingStatusAfterClose          = "after_close"
	BillingStatusNoPrice             = "no_price"
	BillingStatusNotOnPlan           = "not_on_plan"
	BillingStatusOutsideSubscription = "outside_subscription"
)

The billing_status values (UsageEvent.BillingStatus).

View Source
const (
	BatchIngested     = "ingested"
	BatchDeduplicated = "deduplicated"
)

The results of one batch event.

View Source
const HeldListCustomers = 200

HeldListCustomers caps how many external customer ids GET /v1/usage-events/held lists. Every group of a listed id is returned, so a listed id's row count is complete; HeldSummary's totals count all ids.

View Source
const MaxDimensionKeys = 16

MaxDimensionKeys caps the size of the JSONB dimensions map on each usage event. Dimensions decide which plan price takes the event (a price takes an event whose dimensions include all of its dimension_match); bounding the per-event JSONB size protects the GIN index from pathological tenants and matches the cap on a price's dimension_match (domain.MaxDimensionKeys, 16 labels).

Variables

View Source
var ErrHoldUnavailable = errors.New("usage: held store not wired")

ErrHoldUnavailable is returned by HoldCall when the service has no held store wired. Callers treat it like any store failure.

Functions

func BillingModes

func BillingModes(meters []domain.Meter) map[string]string

BillingModes is, for each meter, the aggregation billing uses for its events: the meter's own, which every price of the meter bills under (ADR-130 §2). An empty or unknown aggregation reads as sum.

func CallInputKey

func CallInputKey(key string) (string, bool)

CallInputKey is the key of the call's input row for a cache-write row's key, and false for any other key. It follows the key layout LiteLLM's mapper writes, <call id>:<role> (pinned by a test there); ReleaseHeld uses it to find a held cache-write row's input row.

func CheckNoNUL added in v0.11.0

func CheckNoNUL(field, value string) error

CheckNoNUL returns errs.Invalid naming field when value, that field of an event, holds a NUL character (nulMessage), and nil otherwise.

func ParseDimensionsParam

func ParseDimensionsParam(raw string) (map[string]any, error)

ParseDimensionsParam parses the `dimensions` query value ("k=v,k2=v2") the same way the list and aggregate endpoints do. Exported for the CSV export, which takes the same filter.

func WithPeriodCache

func WithPeriodCache(ctx context.Context) context.Context

WithPeriodCache returns ctx carrying a cache for the open-period reads of the ingest calls made with it. A door that ingests many rows one call at a time (the LiteLLM callback) uses it for its request.

Types

type APIEvent

type APIEvent struct {
	ExternalCustomerID string           `json:"external_customer_id"`
	EventName          string           `json:"event_name"`
	Quantity           json.RawMessage  `json:"quantity,omitempty"`
	Dimensions         map[string]any   `json:"dimensions,omitempty"`
	IdempotencyKey     string           `json:"idempotency_key,omitempty"`
	Timestamp          *json.RawMessage `json:"timestamp,omitempty"`
	Properties         json.RawMessage  `json:"properties,omitempty"`
}

APIEvent is the public API input — developers send external identifiers.

Quantity is kept raw so parseQuantity can answer every bad value with a 422 naming the field (a decode error would be a 400 for the whole body, and a whole batch). The response side serializes it as a decimal string.

Properties is not a field. It was the old name of Dimensions, removed before 0.9.0, and is decoded only so an event that still sends it with a key is refused: stored without its dimensions it would be priced by the wrong rule, silently. A null or empty properties is taken as absent.

type Aggregate

type Aggregate struct {
	TotalEvents     int             `json:"total_events"`
	TotalUnits      decimal.Decimal `json:"total_units"`
	ActiveMeters    int             `json:"active_meters"`
	ActiveCustomers int             `json:"active_customers"`
	ByMeter         []MeterTotal    `json:"by_meter"`
}

Aggregate is the response shape of GET /v1/usage-events/aggregate. It powers the stat cards + "Usage by Meter" breakdown on the dashboard's /usage page so they reflect server-side filtered totals rather than reductions over the current page of events.

TotalUnits is decimal-string-encoded (NUMERIC(38,12) per ADR-005) so fractional GPU-hours and partial tokens round-trip without loss. It adds quantities across meters, whatever their units and modes, so it is kept for API compatibility only; the dashboard shows ByMeter[].Value instead.

func (*Aggregate) ApplyMeterModes

func (a *Aggregate) ApplyMeterModes(modes map[string]string)

ApplyMeterModes fills Aggregation and Value on every row (and its daily series) from the meter's aggregation mode. modes maps meter id to mode.

type AggregationMemo

type AggregationMemo struct {
	// contains filtered or unexported fields
}

AggregationMemo remembers AggregateClaims results for the length of one request, so two readers that need the same (customer, meter, claims, window) run the scan once.

It exists for the public cost dashboard: the page shows this period's usage (CustomerUsageService) and an estimated remaining credit (billing.Engine.LiveCreditBalance), and both aggregate the same meter over the same period. That scan is the expensive part of the request (it reads every usage event of the period), and without the memo the dashboard would pay for it twice. The two readers live in different packages and call the store through different interfaces, so the shared result rides on ctx rather than being passed between them.

The readers' windows differ for a second subscription on a different cycle, and each then runs its own scan.

Never put one on a ctx that outlives a request: a memoized result does not see usage that arrives later.

func WithAggregationMemo

func WithAggregationMemo(ctx context.Context) (context.Context, *AggregationMemo)

WithAggregationMemo returns ctx carrying a memo, and the memo. A memo already on ctx is kept and returned, so a caller further out (a test counting scans) observes the same one.

func (*AggregationMemo) Hits

func (m *AggregationMemo) Hits() int

Hits is how many aggregations were answered from the memo.

func (*AggregationMemo) Queries

func (m *AggregationMemo) Queries() int

Queries is how many aggregations reached the database.

type AuditEmitter

type AuditEmitter interface {
	LogInTx(ctx context.Context, tx *sql.Tx, e audit.Entry) error
}

AuditEmitter is the narrow in-tx audit seam (ADR-090). Provider-cost rate CRUD has no service layer — the handler is the layer that knows intent, so it builds the audit.Entry and the store threads the closure onto its own transaction: rate write and audit row commit or roll back together.

type BatchEventResult

type BatchEventResult struct {
	Status        string `json:"status"`
	BillingStatus string `json:"billing_status,omitempty"`
}

BatchEventResult is what a batch did with one event: wrote it ("ingested") or found it already stored under its key ("deduplicated"). BillingStatus is set only on a row the batch wrote, when it has one: a deduplicated row was answered when it was first written.

type BatchResponse

type BatchResponse struct {
	Ingested     int `json:"ingested"`
	Deduplicated int `json:"deduplicated"`
	Total        int `json:"total"`
	UnbilledCounts
	Results []BatchEventResult `json:"results"`
}

BatchResponse is the batch 201. The counts by billing_status count written rows answered with each status (open_period.go); results holds each event's result at its index in the request.

type BatchResult

type BatchResult struct {
	// Inserted counts rows newly written.
	Inserted int
	// Deduplicated counts rows already stored under the same key.
	Deduplicated int
	// Results is each event's result, in request order.
	Results []BatchEventResult
	// Unbilled counts the written rows by billing_status (open_period.go).
	Unbilled UnbilledCounts
}

BatchResult is what one batch wrote.

type CallEvent

type CallEvent struct {
	Quantity       decimal.Decimal
	Dimensions     map[string]any
	IdempotencyKey string
	// Timestamp nil means the instant ctx carries (the request's), as for
	// Ingest.
	Timestamp *time.Time
	// ObservedCostMicros is the provider's own cost for this row (ADR-079
	// D4); nil falls to the rate table.
	ObservedCostMicros *int64
}

CallEvent is one usage row of a call. The customer and meter are the call's.

type CallInput

type CallInput struct {
	CustomerID string
	MeterID    string
	// Events is the call as the current mapper records it.
	Events []CallEvent
	// Legacy is the same call as the mapper before the cache-write split
	// recorded it, nil when the two agree. LegacyKey is the key both carry
	// with different quantities (the call's input key): if a row is already
	// stored under it with Legacy's quantity, the call was first recorded
	// the old way and is written as Legacy, so its cache writes, already
	// inside that input row, are not billed a second time.
	Legacy    []CallEvent
	LegacyKey string
}

CallInput is one call whose customer and meter exist.

type CallResult

type CallResult struct {
	// Inserted counts rows newly written (or newly held).
	Inserted int
	// Deduplicated counts rows already stored, already held, or held and
	// then discarded.
	Deduplicated int
	// Legacy is true when the call was written the pre-split way.
	Legacy bool
	// Written lists, for IngestCallResolvingHeld, the indices of the rows it
	// newly wrote to usage_events, into the mapping it wrote (the events,
	// or the legacy events when Legacy is true). IngestCall counts the
	// unbilled rows from it.
	Written []int
	// Unbilled counts, for IngestCall, the rows written by billing_status
	// (open_period.go).
	Unbilled UnbilledCounts
}

CallResult reports what writing one call did.

type Class

type Class int

Class is where one usage row falls against a customer's open periods. Higher wins when subscriptions disagree: a subscription that bills the row, or still may, wins, then one that prices its meter, then one that held its time.

const (
	// Outside: no active subscription billed the row's time. Before a
	// subscription started, after its end, or in another subscription's time
	// for the meter.
	Outside Class = iota
	// NotOnPlan: an open period of a subscription holds the row's time, but
	// no plan it was on then prices the meter.
	NotOnPlan
	// AfterClose: a subscription already invoiced the row's time (a period
	// since its billing started, before the current one), and no future
	// invoice counts it. Whatever plan it is on now: a price added now would
	// not bill the row.
	AfterClose
	// NoPrice: the time falls in an open period whose plan prices the meter
	// at its pin, but no price of the plan takes the row's labels.
	NoPrice
	// Later: not checked. The row's time is at or after the current
	// period's end, and the subscription goes on: a period not invoiced yet
	// holds it, but its plans and prices are not known yet.
	Later
	// InOpen: an open period's invoice counts it.
	InOpen
)

func (Class) BillingStatus

func (c Class) BillingStatus() string

BillingStatus is the billing_status a written row of class c answers with: "" when Hardcount found no reason no invoice bills the row (InOpen), and when it was not checked (Later).

type CostDashboardAssembler

type CostDashboardAssembler struct {
	// contains filtered or unexported fields
}

CostDashboardAssembler builds the sanitized projection served by GET /v1/public/cost-dashboard/{token}. Two responsibilities:

  • resolve the public token to a customer (via the customer store)
  • compose the usage view (via CustomerUsageService) and sanitize it into the public envelope

Lives in the usage package because the heavy lifting is the usage math; the customer-package handler imports it via the narrow CostDashboardService interface (returns `any` to keep the customer package free of usage-domain types).

func NewCostDashboardAssembler

func NewCostDashboardAssembler(customers CustomerTokenLookup, usageSvc *CustomerUsageService, subs SubscriptionLister, credits CostDashboardCreditReader) *CostDashboardAssembler

NewCostDashboardAssembler wires the public-projection assembler. All four deps are required, and so is SetLiveBalanceReader before serving.

func (*CostDashboardAssembler) GetByToken

func (a *CostDashboardAssembler) GetByToken(ctx context.Context, token string) (any, error)

GetByToken resolves the token, composes the usage view, sanitizes, and returns the public projection. Returns errs.ErrNotFound when the token doesn't match a customer — the handler surfaces this as 401 (anti-enumeration).

Empty-state contract: when the customer has no active subscription (no_subscription branch), the response carries empty subscriptions, usage and totals, the customer's credits, and `billing_period.source = "no_subscription"` instead of a 5xx, so the embed widget can render a clean empty state that still shows the balance.

func (*CostDashboardAssembler) SetLiveBalanceReader

func (a *CostDashboardAssembler) SetLiveBalanceReader(r CostDashboardLiveBalance)

SetLiveBalanceReader wires the live credit figure. A setter because the billing engine is built after this assembler at boot.

type CostDashboardCreditReader

type CostDashboardCreditReader interface {
	CreditSummary(ctx context.Context, tenantID, customerID string) ([]CostDashboardCredits, error)
}

CostDashboardCreditReader is the narrow surface the assembler uses to read a customer's credit position. The credit service implements it through an adapter in internal/api, so this package does not import the credit domain. CreditSummary returns one entry per currency the customer holds credit in (ADR-129), with Currency, BalanceCents and the commit/promotional split set.

type CostDashboardCredits

type CostDashboardCredits struct {
	Currency                  string `json:"currency"`
	BalanceCents              int64  `json:"balance_cents"`
	CommitRemainingCents      int64  `json:"commit_remaining_cents"`
	PromotionalRemainingCents int64  `json:"promotional_remaining_cents"`
	UnbilledUsageCents        int64  `json:"unbilled_usage_cents"`
	EstimatedRemainingCents   int64  `json:"estimated_remaining_cents"`
}

CostDashboardCredits is the customer's credit position in one currency (issue #86, ADR-129). Amounts in two currencies are never added together.

BalanceCents is the ledger balance: credit is drawn down when an invoice is issued, so it does not move during a billing period. EstimatedRemainingCents is the figure a "live balance" widget wants: the balance minus UnbilledUsageCents, never below zero.

UnbilledUsageCents is NOT projected_total_cents: the projection sums every currency, and unbilled usage is one currency's. The three live fields come from CostDashboardLiveBalance (issue #1019), so the block adds up on its own: estimated = max(balance - unbilled, 0).

type CostDashboardLiveBalance

type CostDashboardLiveBalance interface {
	LiveCreditBalance(ctx context.Context, tenantID, customerID string) (domain.CreditLiveBalance, error)
}

CostDashboardLiveBalance computes the customer's live credit figure. It is the same function the secret-key read GET /v1/credits/balance/{id}/live serves (billing.Engine.LiveCreditBalance), so the public page and the API never show different numbers for one customer.

type CostDashboardMeter

type CostDashboardMeter struct {
	EventName        string               `json:"event_name"`
	MeterName        string               `json:"meter_name"`
	Unit             string               `json:"unit"`
	Currency         string               `json:"currency"`
	TotalQuantity    string               `json:"total_quantity"`
	TotalAmountCents int64                `json:"total_amount_cents"`
	Prices           []CostDashboardPrice `json:"prices"`
}

type CostDashboardPeriod

type CostDashboardPeriod struct {
	Start  time.Time `json:"start"`
	End    time.Time `json:"end"`
	Source string    `json:"source"` // "subscription" | "no_subscription"
}

type CostDashboardPrice

type CostDashboardPrice struct {
	DimensionMatch    map[string]string `json:"dimension_match,omitempty"`
	Quantity          string            `json:"quantity"`
	AmountCents       int64             `json:"amount_cents"`
	UnitAmountDecimal *string           `json:"unit_amount_decimal,omitempty"`
}

CostDashboardPrice is the usage one price took this period. A catch-all price has no dimension_match.

type CostDashboardProjection

type CostDashboardProjection struct {
	CustomerID          string                      `json:"customer_id"`
	TenantID            string                      `json:"tenant_id"`
	BillingPeriod       CostDashboardPeriod         `json:"billing_period"`
	Subscriptions       []CostDashboardSubscription `json:"subscriptions"`
	Usage               []CostDashboardMeter        `json:"usage"`
	Totals              []CostDashboardTotal        `json:"totals"`
	ProjectedTotalCents int64                       `json:"projected_total_cents"`
	// Credits is the credit position, one entry per currency (ADR-129),
	// ordered by currency.
	Credits []CostDashboardCredits `json:"credits"`
	// Livemode marks whether this dashboard reflects real-money usage; the
	// embed shows a "Test mode" banner when false. Shipped in the JSON
	// contract pre-outreach so partner UIs never face a mid-pilot schema
	// addition (ADR-032 consumer-ready JSON).
	Livemode bool `json:"livemode"`
}

CostDashboardProjection is the wire shape returned from GET /v1/public/cost-dashboard/{token}. Slice fields default to non- nil so the wire emits "[]" not "null" — embed widgets iterate without null guards.

What's deliberately ABSENT (sanitization contract):

  • email, display_name, external_id, metadata (customer PII)
  • billing_profile (legal name, address, tax_id)
  • warnings (operator-facing tech messages from CustomerUsageService)
  • plan_id and price_id (internal identifiers; plan_name is enough for display)

What's PRESENT:

  • customer_id + tenant_id (caller already has the token, so these are not secrets)
  • billing_period { start, end, source }
  • subscriptions (id + plan_name + currency + period only)
  • usage[] (meter + per-price breakdown, by the events each price takes)
  • totals[] (per-currency rollup)
  • projected_total_cents (sum across currencies — Stripe-style single-number summary the widget surfaces as the headline)
  • credits (balance, remaining prepaid commit and promotional credit, usage not yet billed, and an estimate of what is left after it)

type CostDashboardSubscription

type CostDashboardSubscription struct {
	ID                 string    `json:"id"`
	PlanName           string    `json:"plan_name"`
	Currency           string    `json:"currency"`
	CurrentPeriodStart time.Time `json:"current_period_start"`
	CurrentPeriodEnd   time.Time `json:"current_period_end"`
}

type CostDashboardTotal

type CostDashboardTotal struct {
	Currency    string `json:"currency"`
	AmountCents int64  `json:"amount_cents"`
}

type CustomerCostByModel

type CustomerCostByModel struct {
	Model      string
	CostMicros int64
	Events     int64
}

CustomerCostByModel aggregates the stamped COGS for one customer's window: per-model cost plus the honesty counters (ADR-079 D7 — 'unresolved' = token events that carried costable dims but matched no rate: the actionable signal; 'not_applicable' events are excluded so they can't drown it).

type CustomerLookup

type CustomerLookup interface {
	Get(ctx context.Context, tenantID, id string) (domain.Customer, error)
}

CustomerLookup is the narrow surface CustomerUsageService needs from customer.Store. Returns errs.ErrNotFound for cross-tenant IDs (RLS hides the row); the handler propagates that as 404 customer_not_found.

type CustomerResolver

type CustomerResolver interface {
	GetByExternalID(ctx context.Context, tenantID, externalID string) (domain.Customer, error)
}

CustomerResolver looks up a customer by external ID.

type CustomerTokenLookup

type CustomerTokenLookup interface {
	GetByCostDashboardToken(ctx context.Context, token string) (domain.Customer, error)
}

CustomerTokenLookup is the narrow surface the assembler uses to resolve the cost-dashboard token to a customer. RLS-bypass implementation lives in customer.PostgresStore.GetByCostDashboardToken (the token IS the credential — no tenant context yet).

type CustomerUsageBucket

type CustomerUsageBucket struct {
	BucketStart time.Time                  `json:"bucket_start"`
	PerMeter    map[string]decimal.Decimal `json:"per_meter"`
}

CustomerUsageBucket is one UTC-day cell of the time-series. PerMeter is keyed by meter_id with the day's total quantity (decimal so the NUMERIC(38,12) storage precision round-trips). Days with no events are still included with PerMeter empty / zeroed so the chart renders continuous time without client-side gap-filling.

type CustomerUsageHandler

type CustomerUsageHandler struct {
	// contains filtered or unexported fields
}

CustomerUsageHandler exposes GET /v1/customers/{id}/usage. Kept distinct from the existing usage.Handler (which owns /v1/usage-events ingest+list) because this surface composes across customer/subscription/pricing — the dependency set is materially different.

func NewCustomerUsageHandler

func NewCustomerUsageHandler(svc *CustomerUsageService) *CustomerUsageHandler

NewCustomerUsageHandler wires a handler around a CustomerUsageService.

func (*CustomerUsageHandler) CustomerUsageRoutes

func (h *CustomerUsageHandler) CustomerUsageRoutes() chi.Router

CustomerUsageRoutes returns the sub-router, mounted at /v1/customers/{id}/usage; the customer ID is read from chi.URLParam(r, "id").

type CustomerUsageMeter

type CustomerUsageMeter struct {
	MeterID          string               `json:"meter_id"`
	EventName        string               `json:"event_name"`
	MeterName        string               `json:"meter_name"`
	Unit             string               `json:"unit"`
	Currency         string               `json:"currency"`
	TotalQuantity    decimal.Decimal      `json:"total_quantity"`
	TotalAmountCents int64                `json:"total_amount_cents"`
	Prices           []CustomerUsagePrice `json:"prices"`
}

CustomerUsageMeter is one meter the customer's plans price, with its rolled-up usage and cost over the queried window. Prices carries one row per price that took usage, with its plan: two plans can price one meter differently (ADR-130 §10).

type CustomerUsagePeriod

type CustomerUsagePeriod struct {
	From time.Time
	To   time.Time
}

CustomerUsagePeriod is the input window. Both From and To zero → default to the customer's current billing cycle. Partial bounds (one zero, one non-zero) are rejected with a 422 by resolvePeriod.

type CustomerUsagePeriodOut

type CustomerUsagePeriodOut struct {
	From   time.Time `json:"from"`
	To     time.Time `json:"to"`
	Source string    `json:"source"`
}

CustomerUsagePeriodOut tells the client which window the response covers and whether the server inferred it from the current cycle or honored an explicit ?from=&to=.

type CustomerUsagePrice

type CustomerUsagePrice struct {
	PriceID        string            `json:"price_id,omitempty"`
	PlanID         string            `json:"plan_id"`
	DimensionMatch map[string]string `json:"dimension_match,omitempty"`
	Quantity       decimal.Decimal   `json:"quantity"`
	AmountCents    int64             `json:"amount_cents"`
	// UnitAmountDecimal is the per-unit price to display (decimal cents): the
	// configured rate for per_unit, else the effective amount÷qty — the SAME
	// value the invoice line shows (ADR-054, via
	// domain.DisplayUnitAmountDecimalFor).
	UnitAmountDecimal *string `json:"unit_amount_decimal,omitempty"`
	// NoPrice marks the usage no price of the plan took: billing bills
	// nothing for it. Surfaced as a row so a mislabeled dimension value (the
	// most likely integration error on a matrix-priced meter) is visible to
	// the operator. Excluded from the meter's totals (they mirror the
	// invoice) and from the public cost dashboard.
	NoPrice bool `json:"no_price,omitempty"`
}

CustomerUsagePrice is the usage one plan price took over the window, and what it bills. DimensionMatch is the events the price takes; a catch-all price has none.

type CustomerUsageResult

type CustomerUsageResult struct {
	CustomerID    string                      `json:"customer_id"`
	Period        CustomerUsagePeriodOut      `json:"period"`
	Subscriptions []CustomerUsageSubscription `json:"subscriptions"`
	Meters        []CustomerUsageMeter        `json:"meters"`
	Totals        []CustomerUsageTotal        `json:"totals"`
	Warnings      []string                    `json:"warnings"`
	// Buckets is the daily-grain time series powering the customer-usage
	// chart. One entry per UTC day in [period.from, period.to), missing
	// days zero-filled so chart consumers don't have to gap-fill. With no
	// explicit window, a meter's quantities are read over its own
	// subscription's current period, the window its totals cover. Each
	// bucket carries per-meter quantities — the frontend stacks them or
	// flattens depending on the meter cardinality. Bucket quantities are raw
	// SUM(quantity) per meter and include usage no price matched, so they
	// need not add up to Meters[] totals: those use each meter's
	// aggregation (max, last, …) and leave the no_price row out.
	Buckets []CustomerUsageBucket `json:"buckets"`
}

CustomerUsageResult is the response shape for GET /v1/customers/{id}/usage. Snake-case JSON keys, struct-tag enforced. Slices default to non-nil so the wire emits "[]" not "null" — clients can iterate without null guards.

type CustomerUsageService

type CustomerUsageService struct {
	// contains filtered or unexported fields
}

CustomerUsageService composes the per-domain reads behind GET /v1/customers/{id}/usage: customer existence, subscription set, period resolution, the rater's buckets, totals and warnings.

func NewCustomerUsageService

func NewCustomerUsageService(
	usageSvc *Service,
	customers CustomerLookup,
	subscriptions SubscriptionLister,
	pricing PricingReader,
) *CustomerUsageService

NewCustomerUsageService wires the read-side composition. Every collaborator is required, the rater through SetRater.

func (*CustomerUsageService) Get

func (s *CustomerUsageService) Get(ctx context.Context, tenantID, customerID string, period CustomerUsagePeriod) (CustomerUsageResult, error)

Get composes the customer-usage view (ADR-130 §10). Order:

  1. Customer existence (RLS makes cross-tenant IDs return ErrNotFound).
  2. Active subscriptions for the customer. A canceled one is not part of what the customer uses now; its events are under /v1/usage-events.
  3. Period resolution (current cycle from primary sub, or explicit ?from=&to= validated for partial bounds, ordering, 1-year cap).
  4. Each subscription through billing's rater: with no window, its own current period as its close would bill it now (windows, floors); with an explicit window, an estimate at its current-period prices.
  5. With no window, the period becomes the earliest start to the latest end of the rated subscriptions' current periods, and each meter's daily buckets are read over its own subscription's period, so the chart shows the usage the totals rated.
  6. Per-currency totals roll-up, warnings collection, subscription summary.

func (*CustomerUsageService) SetRater

func (s *CustomerUsageService) SetRater(r UsageRater)

SetRater wires the billing rater. The engine is built after this service, so it is set after construction.

type CustomerUsageSubscription

type CustomerUsageSubscription struct {
	ID                 string    `json:"id"`
	PlanID             string    `json:"plan_id"`
	PlanName           string    `json:"plan_name"`
	Currency           string    `json:"currency"`
	CurrentPeriodStart time.Time `json:"current_period_start"`
	CurrentPeriodEnd   time.Time `json:"current_period_end"`
}

CustomerUsageSubscription summarises one of the customer's subscriptions that overlapped the queried window. Plan info is denormalised so the dashboard renders "Plan: AI API Pro · cycle Apr 1 → May 1" without a follow-up call.

type CustomerUsageTotal

type CustomerUsageTotal struct {
	Currency    string `json:"currency"`
	AmountCents int64  `json:"amount_cents"`
}

CustomerUsageTotal is one currency's roll-up across all meters. We always emit a list (one entry per distinct currency) even when there's only one currency — consistent shape lets clients read totals[0] without branching, and lines up with /v1/* "always lists" convention.

type DailyBucketRow

type DailyBucketRow struct {
	BucketStart time.Time
	MeterID     string
	Quantity    decimal.Decimal
}

DailyBucketRow is one (bucket_start, meter) cell from the bucket aggregation. Storage-shape only; the service composes these into the gap-filled DailyBucket presentation type before serving.

type DailyValue

type DailyValue struct {
	Date  string          `json:"date"` // YYYY-MM-DD in the request's tz
	Value decimal.Decimal `json:"value"`
	// contains filtered or unexported fields
}

DailyValue is one calendar day of a meter's usage under the meter's mode (sum, count, per-customer peak or latest reading, added across customers). Days without events are absent.

type DiscardHeldRequest

type DiscardHeldRequest struct {
	ExternalCustomerID string `json:"external_customer_id"`
	// EventName limits the discard to one meter. Empty discards every held
	// row for the external id.
	EventName string `json:"event_name"`
}

type ExportFilter

type ExportFilter struct {
	CustomerID string
	MeterID    string
	Dimensions map[string]any
}

ExportFilter narrows the usage export to what the Usage page shows: one customer, one meter, and events whose dimensions contain every pair (`properties @>`, the same match List uses). Empty fields do not filter.

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

func NewHandler

func NewHandler(svc *Service, customers CustomerResolver, meters MeterResolver) *Handler

func (*Handler) Backfill

func (h *Handler) Backfill(w http.ResponseWriter, r *http.Request)

Backfill is exported so the router mounts it on its own route, outside the usage-events sub-router; its permission (usage:write) is in the API's route table.

func (*Handler) Routes

func (h *Handler) Routes() chi.Router

Routes serves /v1/usage-events. Each route's permission is in the API's route table: sending events (single and batch) needs only usage:ingest, the one permission an ingest key holds (ADR-133).

func (*Handler) SetHeldDeps

func (h *Handler) SetHeldDeps(customers CustomerLookup)

SetHeldDeps wires what the held-usage routes read besides the usage store: a customer by id, to check a release target. Wired in wire.go with the customer store. Which released rows an invoice counts is read by the service (Service.Release).

func (*Handler) SetMeterLister

func (h *Handler) SetMeterLister(l MeterLister)

SetMeterLister wires the meter list the aggregate endpoint reads modes from. Unwired, every by_meter value is the plain sum with an empty aggregation.

type HeldCall

type HeldCall struct {
	Events    []domain.HeldUsageEvent
	Legacy    []domain.HeldUsageEvent
	LegacyKey string
}

HeldCall is StoreCall for HoldCall.

type HeldStore

type HeldStore interface {
	// ListHeldSummary groups the rows still held, for the most recent
	// HeldListCustomers external customer ids, with totals over all of them.
	ListHeldSummary(ctx context.Context, tenantID string) (HeldSummary, error)
	// HeldFor returns the distinct event names and the row count still held
	// for one external customer id.
	HeldFor(ctx context.Context, tenantID, externalCustomerID string) (eventNames []string, rows int, err error)
	// ReleaseHeld moves held rows into usage_events in one transaction.
	ReleaseHeld(ctx context.Context, tenantID string, in ReleaseHeldInput, emit func(tx *sql.Tx, res ReleaseHeldResult) error) (ReleaseHeldResult, error)
	// DiscardHeld marks held rows discarded (kept, never ingested).
	DiscardHeld(ctx context.Context, tenantID, externalCustomerID, eventName string, emit func(tx *sql.Tx, n int) error) (int, error)
	// IngestCallResolvingHeld is the live LiteLLM ingest. It writes every
	// event of one LiteLLM call in one transaction: a key held and then
	// discarded is not written, a key still held is written and its held
	// row marked released, and the pre-split replay guard applies.
	IngestCallResolvingHeld(ctx context.Context, tenantID string, call StoreCall) (CallResult, error)
	// HoldCall holds every event of one LiteLLM call in one transaction,
	// with the same replay guard.
	HoldCall(ctx context.Context, tenantID string, call HeldCall) (CallResult, error)
}

HeldStore keeps usage rows that could not be ingested yet because their customer or meter did not exist (#1044, ADR-122). PostgresStore implements it; NewService picks it up from the Store it is given.

type HeldSummary

type HeldSummary struct {
	Groups []HeldUsageGroup
	// TotalCustomers counts the distinct external customer ids with rows
	// still held, listed or not.
	TotalCustomers int
	// TotalRows counts every row still held, listed or not.
	TotalRows int
}

HeldSummary is the held list plus totals over every row still held, so the dashboard can say when the list is cut.

type HeldUsageGroup

type HeldUsageGroup struct {
	ExternalCustomerID string                 `json:"external_customer_id"`
	EventName          string                 `json:"event_name"`
	Reason             domain.HeldUsageReason `json:"reason"`
	Rows               int                    `json:"rows"`
	TotalQuantity      decimal.Decimal        `json:"total_quantity"`
	FirstEventAt       time.Time              `json:"first_event_at"`
	LastEventAt        time.Time              `json:"last_event_at"`
	LastReceivedAt     time.Time              `json:"last_received_at"`
	// CustomerID is the customer whose external_id now matches, or ""
	// when none does yet. Filled by the handler, not the store.
	CustomerID string `json:"customer_id"`
	// MeterExists says whether a meter with EventName exists now. Filled by
	// the handler, not the store.
	MeterExists bool `json:"meter_exists"`
}

HeldUsageGroup is one line of GET /v1/usage-events/held: the rows still held for one (external customer id, event name, reason).

type HoldCallInput

type HoldCallInput struct {
	Source             string
	ExternalCustomerID string
	EventName          string
	Reason             domain.HeldUsageReason
	Events             []CallEvent
	Legacy             []CallEvent
	LegacyKey          string
}

HoldCallInput is one call whose customer or meter does not exist yet.

type HoldInput

type HoldInput struct {
	Source             string
	ExternalCustomerID string
	EventName          string
	Quantity           decimal.Decimal
	Dimensions         map[string]any
	IdempotencyKey     string
	// EventAt is the row's own time. Nil means the time Hardcount received it.
	EventAt            *time.Time
	ObservedCostMicros *int64
	Reason             domain.HeldUsageReason
}

HoldInput is one usage row the caller could not ingest.

type IngestInput

type IngestInput struct {
	CustomerID     string          `json:"customer_id"`
	MeterID        string          `json:"meter_id"`
	Quantity       decimal.Decimal `json:"quantity,omitempty"`
	Dimensions     map[string]any  `json:"dimensions,omitempty"`
	IdempotencyKey string          `json:"idempotency_key,omitempty"`
	Timestamp      *time.Time      `json:"timestamp,omitempty"`
	// ObservedCostMicros is the provider's OWN reported cost for this one
	// event, in micro-dollars — the ADR-079 D4 fast-follow. When set it wins
	// over rate-table inference and stamps provider_cost_source='observed';
	// when nil the table path is unchanged.
	//
	// The caller must have already applied D4's rule, because this layer
	// cannot re-derive it: only a PER-HALF figure may arrive here
	// (input_cost onto the input event, output_cost onto the output event).
	// A whole-call figure must never reach this field — it would be stamped
	// onto each half and multi-count COGS, which is exactly why phase 1
	// stamped nothing at all.
	ObservedCostMicros *int64 `json:"observed_cost_micros,omitempty"`
}

IngestInput is the internal service input — uses resolved internal IDs only. The handler is responsible for resolving external identifiers before calling this.

type ListFilter

type ListFilter struct {
	TenantID   string
	CustomerID string
	MeterID    string
	From       *time.Time
	To         *time.Time
	// Dimensions filters events whose properties JSONB CONTAINS every
	// pair (`properties @> $1` — multi-key containment is AND; served by
	// the GIN index from migration 0062). Values are typed: the handler
	// parses "cached=true" / "attempt=2" as JSON literals and everything
	// else as strings, matching how ingest stored them. Pre-2026-07-05
	// the dashboard SENT this param and the server silently dropped it —
	// unfiltered data rendered as filtered.
	Dimensions map[string]any
	Limit      int
	Offset     int
	// DayLoc is read by Aggregate only: the per-meter daily series buckets
	// events by calendar day in this location. nil means UTC.
	DayLoc *time.Location
}

type MarginAssembler

type MarginAssembler struct {
	// contains filtered or unexported fields
}

MarginAssembler joins stamped COGS with rated usage revenue.

func NewMarginAssembler

func NewMarginAssembler(store *PostgresStore, usageSvc *CustomerUsageService) *MarginAssembler

NewMarginAssembler requires the customer usage service: the report rates its usage through it.

func (*MarginAssembler) Get

func (a *MarginAssembler) Get(ctx context.Context, tenantID, customerID string, from, to time.Time) (MarginReport, error)

type MarginModelRow

type MarginModelRow struct {
	Model string `json:"model"`
	// CostCents is the stamped provider cost in cents, exactly the stored
	// micro-dollars ÷ 10^4 (ADR-130 §3).
	CostCents    decimal.Decimal `json:"cost_cents"`
	RevenueCents int64           `json:"revenue_cents,omitempty"`
	Attributed   bool            `json:"attributed"`
	// MarginBps is this model's margin, by the same formula as the
	// report's headline (marginBps). Omitted whenever the headline is
	// (currency, unresolved cost) and also when the row has no attributed
	// revenue or no stamped cost of its own: either way it is a margin
	// nobody measured.
	MarginBps *int64 `json:"margin_bps,omitempty"`
	// contains filtered or unexported fields
}

MarginModelRow is one per-model line of the margin report. RevenueCents and MarginBps are set ONLY when the model's revenue is honestly attributable (the winning price names `model` in its dimension_match); otherwise Attributed=false and only cost renders — never a heuristic allocation (ADR-079 D6).

type MarginReport

type MarginReport struct {
	CustomerID string    `json:"customer_id"`
	From       time.Time `json:"from"`
	To         time.Time `json:"to"`
	// Headline (always correct): total rated usage revenue vs total
	// stamped provider cost for the window. Rated USAGE revenue — base
	// fees, credits, and taxes are not in this number (it is a usage
	// unit-economics view, not GAAP margin; the UI copy says so).
	RevenueCents int64 `json:"revenue_cents"`
	// RevenueCurrency is the currency of RevenueCents: the currency of the
	// price rules that rated it (ADR-100 keeps a customer's prices in one
	// currency). Empty when the window's revenue spans more than one
	// currency, or when the customer has no priced meter.
	RevenueCurrency string `json:"revenue_currency,omitempty"`
	// CostCents is the window's stamped provider cost in cents, exactly the
	// stored micro-dollars ÷ 10^4 (ADR-130 §3).
	CostCents decimal.Decimal `json:"cost_cents"`
	// CostCurrency is the currency of CostCents. Always USD: provider cost
	// rates are USD only, and LiteLLM reports its cost in dollars.
	CostCurrency string `json:"cost_currency"`
	// MarginBps = (revenue − cost) / revenue in basis points; omitted
	// when revenue is 0, when revenue is not in CostCurrency (a margin
	// across two currencies would be a made-up number), when no event
	// in the window carries a provider cost (CostedEvents == 0), and when
	// some event's cost is unknown (UnresolvedEvents > 0). Without a cost
	// the formula reads 100%; with part of the cost missing it reads too
	// high. Either way it is a margin nobody measured.
	MarginBps *int64 `json:"margin_bps,omitempty"`
	// CostedEvents counts the window's events that carry a stamped provider
	// cost (zero cost included). Zero means the cost side is unknown, not
	// free.
	CostedEvents int64 `json:"costed_events"`
	// CostRatesConfigured is whether the tenant has any provider cost rate
	// at all. False with CostedEvents == 0 means "set up Provider costs";
	// true means the rates exist but none matched this usage.
	CostRatesConfigured      bool             `json:"cost_rates_configured"`
	ByModel                  []MarginModelRow `json:"by_model"`
	UnattributedRevenueCents int64            `json:"unattributed_revenue_cents"`
	UnresolvedEvents         int64            `json:"unresolved_events"`
	// contains filtered or unexported fields
}

type MeterLister

type MeterLister interface {
	ListMeters(ctx context.Context, tenantID string) ([]domain.Meter, error)
}

MeterLister lists the tenant's meters. The aggregate endpoint reads each meter's aggregation from them (see BillingModes) so a Maximum meter reports its peak, not a sum of readings. Wired in wire.go (pricing.Service).

type MeterResolver

type MeterResolver interface {
	GetMeterByEventName(ctx context.Context, tenantID, eventName string) (domain.Meter, error)
}

MeterResolver looks up a meter by the event_name its events send.

type MeterTotal

type MeterTotal struct {
	MeterID string          `json:"meter_id"`
	Total   decimal.Decimal `json:"total"`
	// Aggregation is the meter's mode used for Value ("" when unknown;
	// Value then equals Total).
	Aggregation string          `json:"aggregation"`
	Value       decimal.Decimal `json:"value"`
	Events      int             `json:"events"`
	Customers   int             `json:"customers"`
	// Peak is the highest single reported quantity.
	Peak  decimal.Decimal `json:"peak"`
	Daily []DailyValue    `json:"daily"`
	// contains filtered or unexported fields
}

MeterTotal is the per-meter row in Aggregate.ByMeter — one entry per distinct meter_id matching the filter, sorted by Total DESC.

Total is the plain sum of reported quantities. Value is the meter's usage under its own aggregation (Service.Aggregate fills it from the meter's mode), because a sum is the wrong number for a Maximum or a Latest-value meter: three Storage readings of 140, 210 and 120 GB are a 210 GB peak, not 470 GB.

  • sum: Value = sum of quantities
  • count: Value = number of events
  • max: Value = each customer's highest reading in the window, added across customers
  • last: Value = each customer's latest reading in the window, added across customers

Billing applies max and last per billing period; the window here is the caller's filter, which the dashboard labels.

type OpenPeriod

type OpenPeriod struct {
	// Start and End are the current billing period [Start, End).
	Start, End time.Time
	// Floor is where the close began to bill the subscription's usage: the
	// start of its first period, at midnight of its first day (ADR-012), not
	// the instant it started. Nil when unknown: nothing before Start is then
	// after_close.
	Floor *time.Time
	// Ends is where the subscription's scheduled cancel takes effect
	// (Subscription.CancelEffectiveAt): End, when the subscription is
	// scheduled to cancel at the end of the period. No invoice bills its
	// usage from it on. Nil when no cancel is scheduled.
	Ends *time.Time
	// Plans holds, by plan id, each plan's prices at its pin of the period.
	Plans map[string]PriceSet
	// Stretches are the period's plan stretches, the ones the close bills
	// by: a plan changed away from in the period keeps its stretch.
	Stretches []Stretch
	// Windows holds, by meter id, the windows over which the close bills
	// the meter's usage. Stretches never overlap, so neither do a meter's
	// windows. A window starts no earlier than another subscription's
	// coverage end of the meter.
	Windows map[string][]Window
}

OpenPeriod is what classify needs from one active subscription. Build it with OpenPeriodOf.

func OpenPeriodOf

func OpenPeriodOf(sub domain.Subscription, stretches []Stretch, windows map[string][]Window, atPin map[string]PriceSet, billedFrom *time.Time) (OpenPeriod, bool)

OpenPeriodOf builds sub's OpenPeriod. stretches and windows are its current period's plan stretches and usage windows (the close's). atPin holds, by plan id, the prices of each plan of the period at its pin of the period (the period start, or where the subscription first joined the plan in it). A plan missing from it prices nothing. billedFrom is where the close began to bill sub (billing.PeriodPlan.BilledFrom). ok is false when sub is not active or has no current period.

type OpenPeriodReader

type OpenPeriodReader interface {
	// OpenPeriods returns the OpenPeriod of every active subscription of the
	// customer, with each plan's prices at its pins.
	OpenPeriods(ctx context.Context, tenantID, customerID string) ([]OpenPeriod, error)
}

OpenPeriodReader reads what ingest and the held-usage release classify against. Implemented in internal/api from the subscription store and the pricing store.

type PostgresStore

type PostgresStore struct {
	// contains filtered or unexported fields
}

func NewPostgresStore

func NewPostgresStore(db *postgres.DB) *PostgresStore

func (*PostgresStore) Aggregate

func (s *PostgresStore) Aggregate(ctx context.Context, filter ListFilter) (Aggregate, error)

Aggregate returns the totals + per-meter breakdown that powers the /usage page. It honours the same filter as List (customer / meter / from / to / dimensions) but ignores limit/offset — the whole point is to surface filtered totals, not page slices.

SQL strategy: one row-of-totals query, then one per-meter query and one per-(day, meter) query. The per-meter queries first roll up per customer (sum, count, peak, latest reading) so the service can pick the value that matches each meter's aggregation mode: a Maximum meter is the sum of each customer's peak, never the sum of every reading. All three run inside the same tenant tx so RLS scopes them identically. SUM is decimal-precision (NUMERIC(38,12)).

func (*PostgresStore) AggregateClaims

func (s *PostgresStore) AggregateClaims(
	ctx context.Context,
	tenantID, customerID, meterID, aggregation string,
	claims []domain.UsageClaim,
	from, to time.Time,
) ([]domain.ClaimedUsage, error)

AggregateClaims rolls a customer's events of one meter in [from, to) into one quantity per claim, under the meter's aggregation (ADR-130 §2). Each event belongs to the first claim in the list whose match its dimensions contain (JSONB containment, `properties @> match`), so no event is counted twice; an event no claim takes is the unclaimed bucket (PriceID ""). The caller lists the claims in claim order (domain.ClaimOrder: the most labels first), so the claim is the caller's and every caller claims the same way.

The aggregation is the meter's, one of sum, count, max and last. last is the latest event by (timestamp DESC, id DESC), the order every read of a last meter uses (AggregateForBillingPeriodByAgg, Aggregate): two events at one instant are a tie the id breaks, so every path bills the same one.

A bucket's quantity is the aggregation over that bucket's events alone, so a max or last meter with several claims bills each claim's own peak or latest value.

func (*PostgresStore) AggregateDailyBuckets

func (s *PostgresStore) AggregateDailyBuckets(ctx context.Context, tenantID, customerID string, meterIDs []string, from, to time.Time) ([]DailyBucketRow, error)

AggregateDailyBuckets — see Store interface for contract. UTC-day granularity matches every reference platform (Datadog, OpenAI, AWS Cost Explorer); finer grain (hour) lives in a future bucket-grain param when an operator needs it. NULL meter_ids → empty result with no DB roundtrip. The result is unsorted; the service fills gaps and sorts by (bucket_start, meter_id) before serving.

func (*PostgresStore) AggregateForBillingPeriod

func (s *PostgresStore) AggregateForBillingPeriod(ctx context.Context, tenantID, customerID string, meterIDs []string, from, to time.Time) (map[string]decimal.Decimal, error)

func (*PostgresStore) AggregateForBillingPeriodByAgg

func (s *PostgresStore) AggregateForBillingPeriodByAgg(ctx context.Context, tenantID, customerID string, meters map[string]string, from, to time.Time) (map[string]decimal.Decimal, error)

func (*PostgresStore) CustomerProviderCost

func (s *PostgresStore) CustomerProviderCost(ctx context.Context, tenantID, customerID string, from, to time.Time) (byModel []CustomerCostByModel, unresolvedEvents int64, err error)

func (*PostgresStore) DeleteProviderCostRate

func (s *PostgresStore) DeleteProviderCostRate(ctx context.Context, tenantID, id string) error

DeleteProviderCostRate removes a rate row. Stamped events keep their snapshot (documented — deletion never rewrites history).

func (*PostgresStore) DeleteProviderCostRateAudited

func (s *PostgresStore) DeleteProviderCostRateAudited(
	ctx context.Context, tenantID, id string,
	emit func(tx *sql.Tx, deleted domain.ProviderCostRate) error,
) error

DeleteProviderCostRateAudited is DeleteProviderCostRate with an in-tx audit emission hook (ADR-090 shared fate). Two properties matter here:

  • emit runs ONLY on a row that actually vanished. DELETE … RETURNING yields a row iff exactly one was removed; a miss is sql.ErrNoRows → errs.ErrNotFound with no emission, so deleting a nonexistent rate can never fabricate a "deleted" record.
  • emit receives the DELETED row, read inside the tx. The row is gone afterwards, so the audit entry is the only surviving description of what the operator removed — an id alone would be unresolvable forever.

func (*PostgresStore) DiscardHeld

func (s *PostgresStore) DiscardHeld(ctx context.Context, tenantID, externalCustomerID, eventName string, emit func(tx *sql.Tx, n int) error) (int, error)

DiscardHeld marks the held rows for one external customer id (and one event name, when given) discarded. The rows are kept as a record; they are never ingested.

func (*PostgresStore) GetByIdempotencyKey

func (s *PostgresStore) GetByIdempotencyKey(ctx context.Context, tenantID, key string) (domain.UsageEvent, error)

GetByIdempotencyKey fetches the event a replayed key originally wrote. Backs replay-as-success on the public ingest door: instead of a bare 409, the handler returns the original row (Stripe idempotency shape). Livemode scoping rides the RLS session like every other reader.

func (*PostgresStore) HasProviderCostRates

func (s *PostgresStore) HasProviderCostRates(ctx context.Context, tenantID string) (bool, error)

HasProviderCostRates reports whether the tenant has any provider cost rate in the current mode (RLS-scoped). The margin report uses it to tell "no rates set up" apart from "rates exist but none matched".

func (*PostgresStore) HeldFor

func (s *PostgresStore) HeldFor(ctx context.Context, tenantID, externalCustomerID string) ([]string, int, error)

HeldFor returns the event names and row count still held for one external customer id.

func (*PostgresStore) HoldCall

func (s *PostgresStore) HoldCall(ctx context.Context, tenantID string, call HeldCall) (CallResult, error)

HoldCall holds one LiteLLM call — every event the mapper made from it — in ONE transaction, ON CONFLICT DO NOTHING per key, so a resend of a call already held is counted as deduplicated. It applies IngestCallResolvingHeld's replay guard, with the claim on the held table: the call's input key is looked up in usage_events (a customer deleted and recreated under the same external id), and otherwise the split :input is held first. That insert waits for an uncommitted hold of the same key, and on conflict the held row's quantity (any status) decides. A stored pre-split input quantity holds the call as call.Legacy, so the held list shows no write rows for it.

Held write rows can still meet a pre-split :input: this release holds the call split, then a copy of the previous release writes the old :input once the customer exists (a rolling deploy, a rollback, a replay it serves). Billing is guarded where the write rows would be written: ReleaseHeld and IngestCallResolvingHeld read the stored :input and bill no write row on top of it. Only a release run by the previous release's code would; the CHANGELOG says not to release held LiteLLM usage while copies of the previous release serve.

HoldCall takes no row locks (its inserts wait only on an uncommitted insert of the same key, and every hold of a call inserts :input first), so unlike IngestCallResolvingHeld it cannot deadlock and is not retried.

func (*PostgresStore) Ingest

func (s *PostgresStore) Ingest(ctx context.Context, tenantID string, event domain.UsageEvent) (domain.UsageEvent, error)

func (*PostgresStore) IngestAudited

func (s *PostgresStore) IngestAudited(ctx context.Context, tenantID string, event domain.UsageEvent, emit func(tx *sql.Tx, out domain.UsageEvent) error) (domain.UsageEvent, error)

IngestAudited is Ingest with a hook, emit, run on the ingest's transaction after the insert, only when the row was written. An emit error rolls the write back.

Only BACKFILL passes a hook, which writes an audit row (ADR-090): live ingest (POST /v1/usage-events, /batch, the LiteLLM spend callback) is machine metering at up to ~1000/s, usage_events IS the record, and a row per event would double the write volume of the hottest path for no forensic gain. An operator inserting BACKDATED usage is changing what a customer will be billed for a period that may already have closed — an operator action on the money path, not machine telemetry. Sharing the ingest tx means a backfilled event that cannot be recorded is not ingested at all.

func (*PostgresStore) IngestBatch

func (s *PostgresStore) IngestBatch(ctx context.Context, tenantID string, events []domain.UsageEvent) (inserted []int, deduped int, err error)

IngestBatch writes every event in ONE transaction — all-or-nothing. Pre-fix, BatchIngest looped one tx per event: a mid-batch abort (client timeout, connection drop, crash) left a COMMITTED PREFIX, and the standard client response — retry the whole batch — re-ingested that prefix. Atomic batches rule out the committed prefix. They do not make a retry safe by themselves: a batch that committed and lost its response is written again unless its events carry keys, which is why the HTTP door requires one on every event (#980).

Keyed duplicates (replay of a fully-committed batch, or the same key twice within one batch) are counted in deduped, not errors — matching the LiteLLM door's replay contract. inserted lists the indices of the events written, so the caller can tell which rows this batch wrote.

func (*PostgresStore) IngestCallResolvingHeld

func (s *PostgresStore) IngestCallResolvingHeld(ctx context.Context, tenantID string, call StoreCall) (CallResult, error)

IngestCallResolvingHeld writes one LiteLLM call — every event the mapper made from it — in ONE transaction, so a crash or a store failure leaves all of the call or none of it, and a LiteLLM resend finds the call whole.

Each key follows the held rules (#1044, ADR-122), read under the held row's lock (lockHeldKeys), the lock ReleaseHeld's and DiscardHeld's UPDATEs take, so whichever runs second sees the first one's status:

  • held and then discarded: not written (counted as deduplicated). The operator decided these rows are never billed, and a LiteLLM resend after the customer exists must not undo that.
  • still held: written (or found already written) and the held row marked released, so a later discard cannot mark a row discarded whose usage is already in usage_events.
  • already in usage_events: deduplicated.

The replay guard (when call.Legacy is set): the call's input key may already be stored by the mapper before the cache-write split, whose input quantity includes the writes. Writing the split mapping on top would add the write rows on new keys while :input dedups: the writes billed twice. So the input key decides, from the row already stored under it:

  • a usage_events row decides whenever there is one: it is what bills. With a held row for the key, that row's lock (taken above) is the one every LiteLLM writer of the key takes first — this release, the previous one's per-event ingest, ReleaseHeld's claim — so a plain read now sees any such write that committed.
  • with a held row and no usage_events row, the held row's quantity decides (any status: a discarded row is never written).
  • with neither, the split :input is INSERTed first. That insert is the claim: ON CONFLICT on the (tenant_id, livemode, idempotency_key) UNIQUE waits for an uncommitted insert of the same key — such as a copy of the previous release writing the old :input during a rolling deploy — and then sees it. A SELECT-then-INSERT would not see the uncommitted row and would double-bill. On conflict the stored row's quantity decides.

A deciding quantity equal to the pre-split input quantity means the call was first recorded the old way: it is written as call.Legacy (no write rows, the old input quantity and cost), so every key of it dedups or releases its held row, and any held write row of the call is marked released with no event: its tokens are already billed inside :input. Any other quantity, or none, means the split mapping.

A deadlock (another transaction locking the call's held rows in another order, such as ReleaseHeld's claim) aborts the transaction; it is run once more before the error reaches the caller.

func (*PostgresStore) List

func (s *PostgresStore) List(ctx context.Context, filter ListFilter) ([]domain.UsageEvent, int, error)

List pages usage events ordered by (timestamp DESC, id DESC) with LIMIT/OFFSET, and counts every event the filter matches.

id as the tiebreaker keeps ordering deterministic when many events share a microsecond — common for batched ingestion.

func (*PostgresStore) ListHeldSummary

func (s *PostgresStore) ListHeldSummary(ctx context.Context, tenantID string) (HeldSummary, error)

ListHeldSummary returns one group per (external customer id, event name, reason) over the rows still held, newest arrival first.

func (*PostgresStore) ListProviderCostRates

func (s *PostgresStore) ListProviderCostRates(ctx context.Context, tenantID string) ([]domain.ProviderCostRate, error)

ListProviderCostRates returns the tenant's current rates (mode-scoped via RLS), ordered for the dashboard table.

func (*PostgresStore) ReleaseHeld

func (s *PostgresStore) ReleaseHeld(ctx context.Context, tenantID string, in ReleaseHeldInput, emit func(tx *sql.Tx, res ReleaseHeldResult) error) (ReleaseHeldResult, error)

ReleaseHeld ingests held rows for one external customer id in ONE transaction:

  1. Claim: UPDATE ... SET status='released' WHERE status='held' ... RETURNING. Row locks make a concurrent release wait, then re-check status='held' and skip what this one claimed: disjoint sets.
  2. Insert each claimed row through ingestOneTx, the same INSERT every ingest path uses, under its ORIGINAL idempotency key and event time, with origin 'backfill'. ON CONFLICT there means usage_events already has the key (LiteLLM resent the call after the customer existed): the held row is still marked released, with no event id, and nothing is billed twice. A LiteLLM cache-write row is treated the same way when usage_events already bills its call the pre-split way, writes inside :input (writesBilledInInput).
  3. Record the written event id on the held row, run emit (the service reads the meters' buckets and writes the audit row on tx), commit. A failure anywhere rolls all of it back: the rows stay held.

func (*PostgresStore) StreamForExport

func (s *PostgresStore) StreamForExport(ctx context.Context, tenantID string, from, to time.Time, fn func(domain.UsageEvent) error) error

StreamForExport walks EVERY usage event in the [from,to] window in ONE snapshot transaction. See customer.PostgresStore.StreamForExport for the general reason (issue #475); usage is the case that made it urgent. This table is the hottest write path in the product, and the export is given a five-minute timeout PRECISELY because it streams a lot of rows — which is exactly the window in which concurrent ingest is guaranteed. Under the old LIMIT/OFFSET-per-transaction paging, every event ingested mid-export shifted the newest-first window and duplicated the row on a page boundary. A duplicated usage row in a finance CSV reads as usage that did not happen.

The SELECT carries `origin`, which List's does not — so the `origin` column in usage-events.csv was always empty, and an operator could not tell an operator BACKFILL from a metered API event in the artifact they reconcile with. The export's columns are its own contract.

func (*PostgresStore) StreamForExportFiltered

func (s *PostgresStore) StreamForExportFiltered(ctx context.Context, tenantID string, from, to time.Time, f ExportFilter, fn func(domain.UsageEvent) error) error

StreamForExportFiltered is StreamForExport with the Usage page's filters, so "Export CSV" downloads exactly the rows the page lists.

func (*PostgresStore) UpsertProviderCostRate

func (s *PostgresStore) UpsertProviderCostRate(ctx context.Context, tenantID string, r domain.ProviderCostRate) (domain.ProviderCostRate, error)

UpsertProviderCostRate creates or edits-in-place the rate for a key (current-rate semantics, ADR-079 D1: the per-event stamp is the history; editing a rate only affects FUTURE events).

func (*PostgresStore) UpsertProviderCostRateAudited

func (s *PostgresStore) UpsertProviderCostRateAudited(
	ctx context.Context, tenantID string, r domain.ProviderCostRate,
	emit func(tx *sql.Tx, out domain.ProviderCostRate) error,
) (domain.ProviderCostRate, error)

UpsertProviderCostRateAudited is UpsertProviderCostRate with an in-tx audit emission hook: the rate write and its audit row commit or roll back together (ADR-090 shared fate). The store owns the transaction and exposes it to the closure; the caller (the handler — this surface has no service) owns row content. emit sees the PERSISTED rate, so the audit row carries the store-assigned id and the values as they actually landed. nil emit = unaudited upsert (unit-test / non-request callers).

The emission is unconditional on success by construction: an INSERT … ON CONFLICT DO UPDATE … RETURNING that scans a row always wrote one (a same-values re-PUT still bumps updated_at — a real mutation), so there is no zero-row arm to fabricate evidence for.

type PriceSet

type PriceSet struct {
	// Ahead: the pin had not passed when the prices were read, so a price
	// saved later can still be in force at it. No flag is drawn from such a
	// set.
	Ahead bool
	// ByMeter holds, by meter id, the dimension_match of each price of the
	// meter. A meter missing from it is not priced by the plan.
	ByMeter map[string][]map[string]string
}

PriceSet is a plan's prices at one pin as ingest matches them.

type PricingReader

type PricingReader interface {
	GetPlan(ctx context.Context, tenantID, id string) (domain.Plan, error)
	GetMeter(ctx context.Context, tenantID, id string) (domain.Meter, error)
}

PricingReader reads the plans and meters the response names.

type ProviderCostHandler

type ProviderCostHandler struct {
	// contains filtered or unexported fields
}

ProviderCostHandler is the operator surface: rate CRUD + margin report. Operator-auth only — COGS never renders on customer-facing pages.

func NewProviderCostHandler

func NewProviderCostHandler(store *PostgresStore, margin *MarginAssembler) *ProviderCostHandler

NewProviderCostHandler requires the margin assembler, which serves the margin report.

func (*ProviderCostHandler) Margin

Margin serves GET /v1/customers/{id}/margin?from&to (operator auth; mounted from the router next to the other customer subresources).

func (*ProviderCostHandler) Routes

func (h *ProviderCostHandler) Routes() chi.Router

func (*ProviderCostHandler) SetAuditLogger

func (h *ProviderCostHandler) SetAuditLogger(a AuditEmitter)

SetAuditLogger wires in-tx audit emission for the rate mutations (ADR-090). There is no provider-cost service, so the handler builds the entry — it is the layer that knows the operator's intent — and hands it to the store's …Audited variants, which run it on the write's own transaction. A nil emitter skips emission (keeps handler unit tests fake-friendly); the composition root's audit.MustWired check is what makes a forgotten wiring line fail loudly at boot instead of silently un-auditing the routes.

type ProviderCostRequest

type ProviderCostRequest struct {
	Provider      string          `json:"provider"`
	Model         string          `json:"model"`
	TokenType     string          `json:"token_type"`
	UnitCostCents json.RawMessage `json:"unit_cost_cents"`
	Currency      string          `json:"currency"`
}

ProviderCostRequest is the PUT /v1/provider-costs body, decoded strictly: an unknown field is a 422 naming it. unit_cost_cents is kept raw so every bad value is a 422 naming it (domain.ParseDecimal), not a 400 for the whole body.

type ReleaseHeldInput

type ReleaseHeldInput struct {
	ExternalCustomerID string
	// CustomerID is the customer the rows are ingested for.
	CustomerID string
	// MeterIDs maps event name to meter id. Rows whose event name is absent
	// stay held.
	MeterIDs map[string]string
	// NotAfter is the customer's current time. Rows stamped after it stay
	// held: ingesting them would put usage in the customer's future.
	NotAfter time.Time
	// Limit caps the rows claimed by one call.
	Limit int
}

ReleaseHeldInput selects the held rows to release and where they go.

type ReleaseHeldRequest

type ReleaseHeldRequest struct {
	ExternalCustomerID string `json:"external_customer_id"`
	// CustomerID releases into a customer whose external_id differs (the
	// LiteLLM `user` value had a typo). Empty means the customer whose
	// external_id equals ExternalCustomerID.
	CustomerID string `json:"customer_id"`
}

type ReleaseHeldResult

type ReleaseHeldResult struct {
	Rows []ReleasedRow
	// StillHeld counts rows for the external customer id that are still
	// held after this release and that this release could not take: a meter
	// that does not exist, or a time after the customer's current time.
	StillHeld int
	// MoreToRelease counts rows still held that this release could have
	// taken but did not, because it stopped at Limit. Another release takes
	// them.
	MoreToRelease int
}

ReleaseHeldResult reports what one release did.

type ReleaseInput

type ReleaseInput struct {
	ExternalCustomerID string
	CustomerID         string
	// MeterIDs maps event name to meter id for every meter that exists.
	MeterIDs map[string]string
}

ReleaseInput names the held rows to release and the customer they go to.

type ReleaseResult

type ReleaseResult struct {
	CustomerID string `json:"customer_id"`
	// Released counts rows newly written to usage_events.
	Released int `json:"released"`
	// Deduplicated counts rows usage_events already had under the same key
	// (LiteLLM resent the call after the customer existed), and LiteLLM
	// cache-write rows whose call usage_events already bills with the writes
	// inside its input row. Marked released, not written again.
	Deduplicated int `json:"deduplicated"`
	// StillHeld counts rows for this external id left held that a release
	// cannot take yet: their meter does not exist, or their time is after
	// the customer's current time.
	StillHeld int `json:"still_held"`
	// MoreToRelease counts rows left held only because one release takes at
	// most 5,000 rows. Release again to take them.
	MoreToRelease int `json:"more_to_release"`
	// InOpenPeriod counts released rows whose time falls in an active
	// subscription's current billing period and that a price of the plan the
	// subscription was on then takes. Rows Hardcount does not check count here
	// too: a row after the period end, released before that period's invoice
	// is built (the grace), when the subscription goes on.
	InOpenPeriod int `json:"in_open_period"`
	// NoPrice counts released rows whose time falls in a billing period not
	// invoiced yet, whose meter the plan that bills that time prices, but no
	// price of that plan takes their labels (dimension_match).
	NoPrice int `json:"no_price"`
	// NotOnPlan counts released rows whose time falls in a subscription's
	// billing period not invoiced yet, but whose meter the subscription's
	// plan does not price.
	NotOnPlan int `json:"not_on_plan"`
	// OutsideOpenPeriod counts released rows outside every subscription's
	// time (before it started, after it ends or after its scheduled cancel,
	// or in another, ended subscription's time), and rows in a period whose
	// invoice is already built. Bill them with a one-off invoice if they
	// should be charged.
	// Hardcount never moves usage onto a later invoice (ADR-120).
	OutsideOpenPeriod int `json:"outside_open_period"`
}

ReleaseResult is the response of POST /v1/usage-events/held/release. Its counts are what Hardcount found when the release wrote the rows, as for an ingest's billing_status (open_period.go): not a promise. The invoice is the final answer.

type ReleasedRow

type ReleasedRow struct {
	HeldID     string         `json:"-"`
	EventID    string         `json:"-"`
	EventName  string         `json:"-"`
	EventAt    time.Time      `json:"-"`
	Dimensions map[string]any `json:"-"`
	// Deduplicated: usage_events already had the row; it was not written.
	Deduplicated bool `json:"-"`
}

ReleasedRow is one held row the release wrote, or found already written.

type ReleasedUsage

type ReleasedUsage struct {
	At      time.Time
	MeterID string
	// Labels are the row's dimensions, which decide the price that takes it.
	Labels map[string]any
}

ReleasedUsage is one released row, for countReleased.

type Service

type Service struct {
	// contains filtered or unexported fields
}

func NewService

func NewService(store Store) *Service

func (*Service) Aggregate

func (s *Service) Aggregate(ctx context.Context, filter ListFilter, modes map[string]string) (Aggregate, error)

Aggregate returns server-side totals + per-meter breakdown matching the filter. Used by GET /v1/usage-events/aggregate so the /usage dashboard's stat cards reflect filtered totals rather than a reduce over the current page of paginated events. Limit/Offset on the filter are intentionally ignored — the whole point is the unbounded total.

modes maps meter id to the meter's aggregation (sum, count, max, last); each by_meter row's Value follows it. A meter missing from modes keeps Value = Total (plain sum) and an empty Aggregation, so the caller can tell the value was not mode-aware.

func (*Service) AggregateClaims

func (s *Service) AggregateClaims(
	ctx context.Context,
	tenantID, customerID, meterID, aggregation string,
	claims []domain.UsageClaim,
	from, to time.Time,
) ([]domain.ClaimedUsage, error)

AggregateClaims rolls one customer's events of one meter in [from, to) into one quantity per claim, under the meter's aggregation (see the Store contract). An unknown aggregation is refused, never read as a sum: a meter's events must not bill under an aggregation the meter does not have.

func (*Service) AggregateDailyBuckets

func (s *Service) AggregateDailyBuckets(ctx context.Context, tenantID, customerID string, meterIDs []string, from, to time.Time) ([]DailyBucketRow, error)

AggregateDailyBuckets delegates to the store. Exposed on the Service so CustomerUsageService can fetch chart data without holding the Store directly. See Store interface for contract.

func (*Service) AggregateForBillingPeriod

func (s *Service) AggregateForBillingPeriod(ctx context.Context, tenantID, customerID string, meterIDs []string, from, to time.Time) (map[string]decimal.Decimal, error)

func (*Service) Backfill

func (s *Service) Backfill(ctx context.Context, tenantID string, input IngestInput) (domain.UsageEvent, error)

Backfill ingests a historical usage event. Requires a non-nil timestamp strictly in the past; rejects missing / future / equal-to-now values so operators can't accidentally double-post a live event through the audit path. The row is tagged origin='backfill'.

Billing semantics: backfilled events count toward any period whose [start, end) contains the event's timestamp, but only until that period's invoice is built (INVOICE_GRACE_PERIOD after its end, ADR-120). A built invoice keeps the quantities it copied into its line items, and nothing re-aggregates a closed period, so a backfill into one is stored but not billed, the same outcome as a late live event (see KNOWN BEHAVIOR in prepare), and its 201 says so (billing_status "after_close"). The operator bills it with a one-off invoice.

func (*Service) BatchIngest

func (s *Service) BatchIngest(ctx context.Context, tenantID string, events []IngestInput) (BatchResult, []error)

BatchIngest validates every event, then writes them ALL in one store transaction — all-or-nothing. Pre-fix each event committed in its own tx: a mid-batch abort (client timeout, dropped connection) left a committed prefix, and the standard retry-the-batch response re-ingested that prefix. Now either the whole batch lands or none of it does. A retry of a batch that did commit is deduped only by the events' keys, which the HTTP door requires (#980).

Validation failures are collected for EVERY failing index (a bare "quantity too large" across a 500-event batch was undebuggable) and abort before any write. The events share the instant ctx carries, the request's; with none, each event's build reads the clock. Idempotency replays count as deduplicated — success, not failure — matching the LiteLLM door. A failed open-period read aborts before any write too, and a failed meter read or a failed write rolls the batch back; each comes back as storeUnavailable, 503 at the door.

func (*Service) Discard

func (s *Service) Discard(ctx context.Context, tenantID, externalCustomerID, eventName string) (int, error)

Discard marks the held rows for one external customer id (and one meter key, when given) discarded. They stay in the table as a record and are never ingested.

func (*Service) GetByIdempotencyKey

func (s *Service) GetByIdempotencyKey(ctx context.Context, tenantID, key string) (domain.UsageEvent, error)

GetByIdempotencyKey fetches the event a replayed key originally wrote — backs the public door's replay-as-success response (200 + original row + Idempotent-Replayed header instead of a bare 409).

func (*Service) HeldFor

func (s *Service) HeldFor(ctx context.Context, tenantID, externalCustomerID string) ([]string, int, error)

HeldFor returns the event names and row count still held for one external customer id.

func (*Service) HoldCall

func (s *Service) HoldCall(ctx context.Context, tenantID string, in HoldCallInput) (CallResult, error)

HoldCall holds one call's events in one transaction, each with heldEvent's checks. A key already held is counted as deduplicated. A row with no timestamp is held at the call's time: the request's, as the rows a call ingests are stamped.

func (*Service) Ingest

func (s *Service) Ingest(ctx context.Context, tenantID string, input IngestInput) (domain.UsageEvent, error)

func (*Service) IngestCall

func (s *Service) IngestCall(ctx context.Context, tenantID string, in CallInput) (CallResult, error)

IngestCall writes one call's events in one transaction. Each event gets Ingest's checks and timestamp rules; a key held and then discarded is not written, and a key still held is written and its held row released (see PostgresStore.IngestCallResolvingHeld). The customer's open periods are read before the write, and the rows the store newly wrote, in the mapping it wrote, are classified on its transaction after the inserts (open_period.go); only they are counted by billing_status.

func (*Service) List

func (s *Service) List(ctx context.Context, filter ListFilter) ([]domain.UsageEvent, int, error)

func (*Service) ListHeld

func (s *Service) ListHeld(ctx context.Context, tenantID string) (HeldSummary, error)

ListHeld returns the rows still held, grouped, with totals.

func (*Service) Release

func (s *Service) Release(ctx context.Context, tenantID string, in ReleaseInput) (ReleaseResult, error)

Release ingests the held rows for one external customer id into the given customer, at most once per idempotency key (see PostgresStore.ReleaseHeld). Rows stamped after the request's instant stay held. The result says which released rows an invoice counts, by the rule ingest flags with (classify, open_period.go).

func (*Service) SetAuditLogger

func (s *Service) SetAuditLogger(a AuditEmitter)

SetAuditLogger wires in-tx audit emission for BACKFILL. Live ingest stays unaudited by design (machine metering; usage_events is the record) — but an operator inserting BACKDATED usage is changing what a customer gets billed for a period that may already have closed, so that action is recorded.

func (*Service) SetClock added in v0.10.0

func (s *Service) SetClock(c clock.Clock)

SetClock sets the service's clock: the server's clock, the one the billing engine bills by. A read through it returns the instant ctx carries, which on a request is the request's; with none, each read reads the clock.

func (*Service) SetOpenPeriodReader

func (s *Service) SetOpenPeriodReader(r OpenPeriodReader)

SetOpenPeriodReader wires the open-period reads that answer an event with its billing_status (open_period.go). Optional: unwired, nothing is flagged (narrow tests).

type Store

type Store interface {
	Ingest(ctx context.Context, tenantID string, event domain.UsageEvent) (domain.UsageEvent, error)
	// IngestAudited runs emit, when not nil, on the ingest's own transaction
	// after the insert, only when the row was written; an emit error rolls
	// the write back. A BACKFILL writes its audit row there (ADR-090; see
	// PostgresStore.IngestAudited).
	IngestAudited(ctx context.Context, tenantID string, event domain.UsageEvent, emit func(tx *sql.Tx, out domain.UsageEvent) error) (domain.UsageEvent, error)
	// IngestBatch writes every event in ONE transaction — all-or-nothing,
	// so a client retry after a mid-batch abort never re-ingests a
	// committed prefix. Idempotency replays are counted in deduped, not
	// errors. Returns the indices of the events it inserted, the number
	// deduplicated, and the error.
	IngestBatch(ctx context.Context, tenantID string, events []domain.UsageEvent) ([]int, int, error)
	// GetByIdempotencyKey returns the event a replayed key originally
	// wrote (errs.ErrNotFound when absent). Backs replay-as-success on
	// the public ingest door.
	GetByIdempotencyKey(ctx context.Context, tenantID, key string) (domain.UsageEvent, error)
	List(ctx context.Context, filter ListFilter) ([]domain.UsageEvent, int, error)
	Aggregate(ctx context.Context, filter ListFilter) (Aggregate, error)
	AggregateForBillingPeriod(ctx context.Context, tenantID, customerID string, meterIDs []string, from, to time.Time) (map[string]decimal.Decimal, error)
	AggregateForBillingPeriodByAgg(ctx context.Context, tenantID, customerID string, meters map[string]string, from, to time.Time) (map[string]decimal.Decimal, error)

	// AggregateClaims rolls a customer's events of one meter in
	// [from, to) into one quantity per claim, under the meter's
	// aggregation: sum, count, max or last (the latest event by timestamp,
	// then id). Each event belongs to the first claim, in the order given,
	// whose match its dimensions contain; an event no claim takes is
	// returned as the unclaimed entry (PriceID "").
	AggregateClaims(ctx context.Context, tenantID, customerID, meterID, aggregation string, claims []domain.UsageClaim, from, to time.Time) ([]domain.ClaimedUsage, error)

	// AggregateDailyBuckets returns events bucketed to UTC-day granularity
	// over [from, to) for the given customer × meter set. One row per
	// (bucket_start, meter_id) — the service fills missing buckets with
	// zero so chart consumers get continuous time. Sums to the same
	// per-meter total as AggregateForBillingPeriod over the same window;
	// powers the daily-bar-chart on the customer-usage view (matches
	// Datadog / OpenAI / AWS Cost Explorer's primary visual primitive).
	AggregateDailyBuckets(ctx context.Context, tenantID, customerID string, meterIDs []string, from, to time.Time) ([]DailyBucketRow, error)
}

type StoreCall

type StoreCall struct {
	Events    []domain.UsageEvent
	Legacy    []domain.UsageEvent
	LegacyKey string
}

StoreCall is one LiteLLM call for IngestCallResolvingHeld: Events is how the current mapper records it, Legacy (with LegacyKey) how the mapper before the cache-write split did. See CallInput.

type Stretch

type Stretch struct {
	PlanID   string
	From, To time.Time
}

Stretch is one stretch [From, To) of a current period during which the subscription was on PlanID (the close's plan stretches).

type SubscriptionLister

type SubscriptionLister interface {
	ListLiveByCustomer(ctx context.Context, tenantID, customerID string) ([]domain.Subscription, error)
}

SubscriptionLister returns every active subscription of a customer, oldest first. A page of all of them would lose an active one behind newer canceled ones.

type UnbilledCounts

type UnbilledCounts struct {
	AfterClose          int `json:"after_close"`
	NoPrice             int `json:"no_price"`
	NotOnPlan           int `json:"not_on_plan"`
	OutsideSubscription int `json:"outside_subscription"`
}

UnbilledCounts counts written rows by billing_status: the batch and LiteLLM answers carry them.

func (*UnbilledCounts) Add

func (u *UnbilledCounts) Add(status string)

Add counts one row answered with status ("" counts nothing).

func (UnbilledCounts) Plus

Plus is u and o counted together.

type UsageRater

type UsageRater interface {
	// RateCurrentPeriod is the subscription's current period as its close
	// would bill it now.
	RateCurrentPeriod(ctx context.Context, sub domain.Subscription) (domain.RatedSubscription, error)
	// RateWindow is an estimate over [from, to), each window priced at the
	// pin it has in the subscription's current period.
	RateWindow(ctx context.Context, sub domain.Subscription, from, to time.Time) (domain.RatedSubscription, error)
}

UsageRater prices a subscription's usage the way billing does (ADR-130 §10). Implemented by *billing.Engine, wired in wire.go: the rater lives in billing, so the customer page prices usage the way the invoice does.

type Window

type Window struct {
	PlanID   string
	From, To time.Time
}

Window is one window [From, To) of a current period over which the close bills a meter's usage by PlanID's prices (billing.PeriodPlan.UsageWindows).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL