billing

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

Documentation

Overview

Package billing defines the boundary between core workflows and billing. Implementations are installed by the server before initialization or work.

Index

Constants

View Source
const BillingEnabledEnv = "SUPERPLANE_BILLING_ENABLED"

Variables

View Source
var (
	//revive:disable-next-line:error-strings
	ErrOrganizationSubscriptionLive = errors.New("Cancel the subscription in Billing before you delete the organization. You can delete it after the paid period ends.")
	//revive:disable-next-line:error-strings
	ErrOrganizationSubscriptionUnverified = errors.New("SuperPlane could not confirm with Polar that the subscription ended. Try again later.")
	//revive:disable-next-line:error-strings
	ErrOrganizationCheckoutPending      = errors.New("Finish the pending checkout or wait until it expires before you delete the organization.")
	ErrBillingPlanChanged               = errors.New("the billing record changed. Refresh and try again")
	ErrHostedCreditEmpty                = errors.New("hosted credit is empty")
	ErrFactoryHostedSpendBudgetNegative = errors.New("hosted spend limit cannot be negative")
	ErrFactoryHostedBudgetEmpty         = errors.New("this workspace has no remaining hosted credit")
	ErrHostedSubscriptionRequired       = errors.New("an active plan is required to run agents")
	ErrHostedPaymentPastDue             = fmt.Errorf("the renewal payment is past due: %w", ErrHostedSubscriptionRequired)
	ErrHostedSubscriptionPaused         = fmt.Errorf("the subscription is paused: %w", ErrHostedSubscriptionRequired)
	ErrPaymentMethodRequired            = errors.New("add a payment method in organization billing before usage")
)
View Source
var ErrImplementationMissing = errors.New("billing implementation is not installed")

Functions

func AssertHostedRunAllowed

func AssertHostedRunAllowed(tx *gorm.DB, organizationID uuid.UUID, factoryID *uuid.UUID) error

func AssertOrganizationPaymentMethod

func AssertOrganizationPaymentMethod(tx *gorm.DB, organizationID uuid.UUID) error

func AssertOrganizationPlanAllowsRuns

func AssertOrganizationPlanAllowsRuns(tx *gorm.DB, organizationID uuid.UUID) error

func Bind

func Bind(implementation Runtime) func()

Bind installs billing even when enforcement is disabled, because usage still needs pricing. The returned function restores the previous binding in tests.

func Enabled

func Enabled() bool

Enabled preserves the installation's existing billing switch.

func GetPastDueGraceDays

func GetPastDueGraceDays(tx *gorm.DB) (int, error)

func GrantWelcomeCredit

func GrantWelcomeCredit(tx *gorm.DB, organizationID, accountID uuid.UUID) error

func Initialize

func Initialize(tx *gorm.DB) error

func InitializeOrganization

func InitializeOrganization(tx *gorm.DB, organizationID uuid.UUID) error

func JoinLimit

func JoinLimit(tx *gorm.DB, organizationID uuid.UUID) (*int, error)

func MicrosToCents

func MicrosToCents(micros int64) int64

MicrosToCents formats a nonnegative ledger amount in whole cents.

func PrepareAdmission

func PrepareAdmission(ctx context.Context, organizationID uuid.UUID) error

func RemainingCreditMicros

func RemainingCreditMicros(tx *gorm.DB, organizationIDs []uuid.UUID) (map[uuid.UUID]int64, error)

func ResolveMarkupBPS

func ResolveMarkupBPS(tx *gorm.DB, organizationID uuid.UUID) (int, error)

func ResolveParallelTaskLimit

func ResolveParallelTaskLimit(tx *gorm.DB, organizationID uuid.UUID) (*int, error)

ResolveParallelTaskLimit returns nil when the effective plan has no runner limit.

func ResolveProductFeatures

func ResolveProductFeatures(tx *gorm.DB, organizationID uuid.UUID) (map[string]bool, error)

func SummarizeComputeUsage

func SummarizeComputeUsage(tx *gorm.DB, filter UsageReportFilter) (UsageTotals, []UsageByMachineType, error)

func SummarizeUsage

func SummarizeUsage(tx *gorm.DB, filter UsageReportFilter) (UsageTotals, []UsageByModel, error)

func UpdateFactoryHostedBudget

func UpdateFactoryHostedBudget(tx *gorm.DB, organizationID, factoryID uuid.UUID, budgetCents *int64) error

func UpdateInstallationSettings

func UpdateInstallationSettings(tx *gorm.DB, settings InstallationSettings) error

func UpdatePastDueGraceDays

func UpdatePastDueGraceDays(tx *gorm.DB, days int) error

func ValidateInvitationCapacity

func ValidateInvitationCapacity(tx *gorm.DB, organizationID uuid.UUID, alreadyPending bool, pendingLimit int) error

func ValidateMemberAdmission

func ValidateMemberAdmission(tx *gorm.DB, organizationID uuid.UUID) error

func ValidatePastDueGraceDays

func ValidatePastDueGraceDays(days int) error

func ValidateSpendingReportWindow

func ValidateSpendingReportWindow(since, until time.Time) error

Types

type CapacityAlert

type CapacityAlert interface{ Emit() }

CapacityAlert describes a transition staged in a caller-owned transaction. Only the owner of the outermost transaction emits it after a successful commit.

func RecheckSeatCapacity

func RecheckSeatCapacity(tx *gorm.DB, organizationID uuid.UUID, cause string) (CapacityAlert, error)

type CapacityAlerts

type CapacityAlerts []CapacityAlert

func (CapacityAlerts) Emit

func (alerts CapacityAlerts) Emit()

type ComputeUsage

type ComputeUsage struct {
	MachineType     string
	FleetID         string
	DurationSeconds int64
}

type CreditSummary

type CreditSummary struct {
	GrantMicros              int64
	SuperPlaneGrantMicros    int64
	PurchasedCreditMicros    int64
	BilledMicros             int64
	RemainingMicros          int64
	IncludedRemainingMicros  int64
	PurchasedRemainingMicros int64
	WelcomeRemainingMicros   int64
	AdminRemainingMicros     int64
	MarkupBPS                int
	Warning                  bool
	WelcomeCreditExpiresAt   *time.Time
}

func DescribeCredit

func DescribeCredit(tx *gorm.DB, organizationID uuid.UUID) (CreditSummary, error)

type DeletionGuard

type DeletionGuard interface {
	Validate(tx *gorm.DB, organizationID uuid.UUID) error
}

DeletionGuard verifies the prepared provider snapshot under the caller's organization lock. Provider requests must finish before the transaction.

func LocalDeletionGuard

func LocalDeletionGuard(tx *gorm.DB, organizationID uuid.UUID) (DeletionGuard, error)

func PrepareDeletion

func PrepareDeletion(ctx context.Context, organizationID uuid.UUID) (DeletionGuard, error)

type FactoryBudget

type FactoryBudget struct {
	BudgetCents     *int64
	BilledMicros    int64
	RemainingMicros int64
	Warning         bool
	Capped          bool
}

func DescribeFactoryBudget

func DescribeFactoryBudget(tx *gorm.DB, organizationID, factoryID uuid.UUID) (FactoryBudget, error)

type HTTPRegistrar

type HTTPRegistrar interface {
	RegisterPublic(*mux.Router)
	RegisterAdmin(*mux.Router)
}

HTTPRegistrar installs billing handlers on the existing routers. The caller owns authentication, authorization, and middleware on each router.

type InstallationSettings

type InstallationSettings struct {
	TrialCreditCents            int64
	MarkupBPS                   int
	WarningThresholdBPS         int
	CreditPurchaseFeeBPS        int
	CreditPurchaseFixedFeeCents int64
}

InstallationSettings contains the billing fields on shared installation settings. Provider configuration belongs to core.

func GetInstallationSettings

func GetInstallationSettings(tx *gorm.DB) (InstallationSettings, error)

type Provider

type Provider interface {
	PrepareDeletion(context.Context, uuid.UUID) (DeletionGuard, error)
	PrepareAdmission(context.Context, uuid.UUID) error
	ValidateMemberAdmission(*gorm.DB, uuid.UUID) error
	ValidateInvitationCapacity(*gorm.DB, uuid.UUID, bool, int) error
	RecheckSeatCapacity(*gorm.DB, uuid.UUID, string) (CapacityAlert, error)
	AssertOrganizationPaymentMethod(*gorm.DB, uuid.UUID) error
}

Provider verifies external billing state and stages capacity transitions.

type Rate

type Rate struct {
	Input      int64
	Output     int64
	CacheRead  int64
	CacheWrite int64
	Reasoning  int64
}

Rate contains cents per million tokens from a provider catalog.

func LookupRate

func LookupRate(provider, model string) (Rate, bool)

type Runtime

type Runtime interface {
	JoinLimit(*gorm.DB, uuid.UUID) (*int, error)
	ValidateSpendingReportWindow(time.Time, time.Time) error
	GetPastDueGraceDays(*gorm.DB) (int, error)
	UpdatePastDueGraceDays(*gorm.DB, int) error
	ValidatePastDueGraceDays(int) error
	Initialize(*gorm.DB) error
	InitializeOrganization(*gorm.DB, uuid.UUID) error
	GrantWelcomeCredit(*gorm.DB, uuid.UUID, uuid.UUID) error
	PrepareDeletion(context.Context, uuid.UUID) (DeletionGuard, error)
	LocalDeletionGuard(*gorm.DB, uuid.UUID) (DeletionGuard, error)
	PrepareAdmission(context.Context, uuid.UUID) error
	ValidateMemberAdmission(*gorm.DB, uuid.UUID) error
	ValidateInvitationCapacity(*gorm.DB, uuid.UUID, bool, int) error
	ResolveSeats(*gorm.DB, uuid.UUID) (*SeatUsage, error)
	RecheckSeatCapacity(*gorm.DB, uuid.UUID, string) (CapacityAlert, error)
	AssertOrganizationPaymentMethod(*gorm.DB, uuid.UUID) error
	AssertOrganizationPlanAllowsRuns(*gorm.DB, uuid.UUID) error
	AssertHostedRunAllowed(*gorm.DB, uuid.UUID, *uuid.UUID) error
	ResolveParallelTaskLimit(*gorm.DB, uuid.UUID) (*int, error)
	ResolveProductFeatures(*gorm.DB, uuid.UUID) (map[string]bool, error)
	ResolveMarkupBPS(*gorm.DB, uuid.UUID) (int, error)
	RemainingCreditMicros(*gorm.DB, []uuid.UUID) (map[uuid.UUID]int64, error)
	DescribeCredit(*gorm.DB, uuid.UUID) (CreditSummary, error)
	DescribeFactoryBudget(*gorm.DB, uuid.UUID, uuid.UUID) (FactoryBudget, error)
	UpdateFactoryHostedBudget(*gorm.DB, uuid.UUID, uuid.UUID, *int64) error
	PriceUsage(*gorm.DB, uuid.UUID, Usage) (UsagePrice, error)
	PriceCompute(ComputeUsage) (UsagePrice, error)
	LookupRate(string, string) (Rate, bool)
	GetInstallationSettings(*gorm.DB) (InstallationSettings, error)
	UpdateInstallationSettings(*gorm.DB, InstallationSettings) error
	SummarizeUsage(*gorm.DB, UsageReportFilter) (UsageTotals, []UsageByModel, error)
	SummarizeComputeUsage(*gorm.DB, UsageReportFilter) (UsageTotals, []UsageByMachineType, error)
	ListWorkOrderRunUsage(*gorm.DB, UsageReportFilter, int, int) ([]WorkOrderRunUsage, int64, error)
	ListAllWorkOrderRunUsage(*gorm.DB, UsageReportFilter) ([]WorkOrderRunUsage, error)
	SummarizeUsageByLocalDay(*gorm.DB, UsageReportFilter, []time.Time) ([]UsageSplit, error)
}

Runtime owns billing rules and persistence. Core owns its workflow transactions.

func Current

func Current() (Runtime, error)

func Require

func Require() Runtime

type SeatUsage

type SeatUsage struct {
	PendingInvitations int  `json:"pending_invitations"`
	Invitable          *int `json:"invitable"`
	PerSeat            bool `json:"per_seat"`
	Purchased          *int `json:"purchased"`
	Occupied           int  `json:"occupied"`
	Available          *int `json:"available"`
	PlanMaximum        *int `json:"plan_maximum"`
	Purchasable        *int `json:"purchasable"`
	RenewalQuantity    *int `json:"renewal_quantity"`
	MemberLimit        *int `json:"member_limit"`
	PaymentBlocked     bool `json:"payment_blocked"`
}

func ResolveSeats

func ResolveSeats(tx *gorm.DB, organizationID uuid.UUID) (*SeatUsage, error)

type Usage

type Usage struct {
	Provider         string
	Model            string
	FundingSource    string
	InputTokens      int64
	OutputTokens     int64
	CacheReadTokens  int64
	CacheWriteTokens int64
	ReasoningTokens  int64
	CostMicros       *int64
}

type UsageByMachineType

type UsageByMachineType struct {
	MachineType     string
	DurationSeconds int64
	CostMicros      int64
}

UsageByMachineType is one fleet machine-type bucket in a compute report.

func (UsageByMachineType) CostCents

func (r UsageByMachineType) CostCents() int64

type UsageByModel

type UsageByModel struct {
	Provider    string
	Model       string
	TotalTokens int64
	CostMicros  int64
}

UsageByModel is one model bucket in a spend report.

func (UsageByModel) CostCents

func (r UsageByModel) CostCents() int64

type UsagePrice

type UsagePrice struct {
	ProviderCostMicros int64
	CostMicros         int64
	PriceBookVersion   string
}

func PriceCompute

func PriceCompute(usage ComputeUsage) (UsagePrice, error)

func PriceUsage

func PriceUsage(tx *gorm.DB, organizationID uuid.UUID, usage Usage) (UsagePrice, error)

type UsageReportFilter

type UsageReportFilter struct {
	OrganizationID uuid.UUID
	FactoryID      *uuid.UUID
	WorkOrderID    *uuid.UUID
	UsageKind      string
	Since          time.Time
	Until          time.Time
	Provider       string
	Model          string
	MachineType    string
	TaskOwnerID    *uuid.UUID
	FundingSource  string
}

UsageReportFilter scopes ledger aggregates.

type UsageSplit

type UsageSplit struct {
	// Model is spend on model tokens.
	Model UsageTotals
	// Compute is spend on runner machine time.
	Compute UsageTotals
}

UsageSplit is the ledger of one subject, divided by what the spend paid for.

func SummarizeUsageByLocalDay

func SummarizeUsageByLocalDay(tx *gorm.DB, filter UsageReportFilter, dayBounds []time.Time) ([]UsageSplit, error)

func (UsageSplit) Total

func (s UsageSplit) Total() UsageTotals

Total is the whole ledger of the subject, both bands together.

type UsageTotals

type UsageTotals struct {
	TotalTokens     int64
	DurationSeconds int64
	CostMicros      int64
}

UsageTotals is a token, duration, and cost sum.

func (UsageTotals) Add

func (t UsageTotals) Add(other UsageTotals) UsageTotals

Add returns the field-wise sum of two ledger totals.

func (UsageTotals) CostCents

func (t UsageTotals) CostCents() int64

type WorkOrderRunUsage

type WorkOrderRunUsage struct {
	WorkOrderExecutionID uuid.UUID
	WorkOrderID          uuid.UUID
	WorkOrderNumber      int64
	Title                string
	LastOccurredAt       time.Time
	UserID               *uuid.UUID
	UserName             string
	UserEmail            string
	TotalTokens          int64
	DurationSeconds      int64
	CostMicros           int64
	HostedCostMicros     int64
	BYOKCostMicros       int64
	Models               []string
	BYOKModels           []string
	MachineTypes         []string
}

WorkOrderRunUsage is one task-run spend row grouped from the ledger.

func ListAllWorkOrderRunUsage

func ListAllWorkOrderRunUsage(tx *gorm.DB, filter UsageReportFilter) ([]WorkOrderRunUsage, error)

func ListWorkOrderRunUsage

func ListWorkOrderRunUsage(tx *gorm.DB, filter UsageReportFilter, limit, offset int) ([]WorkOrderRunUsage, int64, error)

func (WorkOrderRunUsage) BYOKCostCents

func (r WorkOrderRunUsage) BYOKCostCents() int64

func (WorkOrderRunUsage) ComputeCostMicros

func (r WorkOrderRunUsage) ComputeCostMicros() int64

func (WorkOrderRunUsage) CostCents

func (r WorkOrderRunUsage) CostCents() int64

func (WorkOrderRunUsage) HostedCostCents

func (r WorkOrderRunUsage) HostedCostCents() int64

func (WorkOrderRunUsage) TokenCostMicros

func (r WorkOrderRunUsage) TokenCostMicros() int64

Jump to

Keyboard shortcuts

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