cloudspend

package
v1.5.8 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Overview

Package cloudspend reads provider-side spend, forecasts and budgets behind one neutral shape. Providers publish lagged numbers, so every report carries its data age and an estimated flag, and amounts of different currencies are never added together.

Index

Constants

View Source
const (
	ReasonAccountInterval = "account_interval"
	ReasonUserHourly      = "user_hourly"
)

Refusal reasons.

View Source
const (
	SourceUsageAPI     = "usage_api"
	SourceCostExplorer = "cost_explorer"
	SourceBudgetAPI    = "budget_api"
	SourceBalance      = "balance"
	SourceEstimate     = "estimate"
)

Report sources.

View Source
const (
	StateOK           = "ok"
	StateTagNotActive = "tag_not_active"
	StateDisabled     = "disabled"
)

Report states. Anything but StateOK means the numbers are absent on purpose.

View Source
const (
	ForecastProvider = "provider"
	ForecastLinear   = "linear"
)

Forecast sources.

View Source
const ProjectTagKey = "levelrail:project"

ProjectTagKey is the cost allocation tag Levelrail puts on what it creates.

Variables

View Source
var ErrUnsupported = errors.New("cloudspend: not supported by this provider")

ErrUnsupported is returned when a provider cannot answer a call.

Functions

func ErrorCode

func ErrorCode(err error) string

ErrorCode maps an error to the short code stored on a report.

func LinearForecast

func LinearForecast(mtd float64, start, now, end time.Time) float64

LinearForecast projects month-to-date spend to the end of the period.

func Register

func Register(p Provider, f Factory)

Register adds a provider. Each provider file calls it from init.

Types

type AWSReader

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

AWSReader reads Cost Explorer, Budgets and the Pricing API.

func NewAWSReader

func NewAWSReader(caller awsCaller, accountID string, cfg func() Config) *AWSReader

NewAWSReader wraps a caller; exported for fakes in other packages' tests.

func (*AWSReader) Budgets

func (r *AWSReader) Budgets(ctx context.Context, _ SpendQuery) ([]ProviderBudget, error)

Budgets reads DescribeBudgets, which is read only, cheap and not gated.

func (*AWSReader) EstimatePrice

func (r *AWSReader) EstimatePrice(ctx context.Context, q PriceQuery) (PriceEstimate, error)

EstimatePrice returns the lowest positive hourly on-demand price that matches the query, so the caller can show a cost before creating anything.

func (*AWSReader) Forecast

func (r *AWSReader) Forecast(ctx context.Context, q SpendQuery) (SpendForecast, error)

Forecast adds the provider's forecast for the rest of the month to the month-to-date figure, and falls back to a linear projection when AWS has too little history to forecast.

func (*AWSReader) Provider

func (r *AWSReader) Provider() Provider

Provider implements Reader.

func (*AWSReader) Spend

func (r *AWSReader) Spend(ctx context.Context, q SpendQuery) (SpendReport, error)

Spend reads month to date grouped by the project tag and by service in one daily request. It is off unless the Cost Explorer setting is on.

type Cache

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

Cache serves reports from memory, runs one fetch at a time per key and rate limits forced refreshes. A failed fetch keeps the last good report.

func NewCache

func NewCache(cfg func() Config) *Cache

NewCache builds a cache that reads its limits live from cfg.

func (*Cache) Get

func (c *Cache) Get(ctx context.Context, k Key, fetch Fetch) (SpendReport, error)

Get returns a fresh entry, or a stale one while one background fetch runs, or waits for the first fetch when nothing is cached.

func (*Cache) Refresh

func (c *Cache) Refresh(ctx context.Context, k Key, user string, fetch Fetch) (SpendReport, Decision, error)

Refresh is a forced refresh. It obeys the per-account interval and the per-user hourly limit; a denial returns the cached report, if any.

type Config

type Config struct {
	Enabled               bool
	CacheTTL              time.Duration
	RefreshMinInterval    time.Duration
	RefreshPerUserPerHour int
	StaleAfter            time.Duration
	// AWSCostExplorer gates every paid Cost Explorer call; false by default.
	AWSCostExplorer bool
	// MaxPages bounds pagination on every provider; below 1 reads one page.
	MaxPages    int
	HTTPTimeout time.Duration
	// Now is a test seam.
	Now func() time.Time
}

Config holds the live runtime settings. Keys, all under cloud.spend.:

enabled, cache_ttl_minutes, refresh_min_interval_minutes,
refresh_per_user_per_hour, stale_after_hours, aws_cost_explorer,
max_pages, http_timeout_seconds.

The runtimesettings owner maps them onto this struct. A zero value means no caching or no limit, never a hidden default.

type Credentials

type Credentials map[string]string

Credentials are the sealed account fields a factory needs, by key name (see each provider file).

type Decision

type Decision struct {
	Allowed    bool
	Reason     string
	RetryAfter time.Duration
}

Decision is the outcome of a forced refresh. The API turns a denial into 429 with Retry-After set to RetryAfter.

type DigitalOceanReader

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

DigitalOceanReader reads GET /customers/my/balance.

func NewDigitalOceanReader

func NewDigitalOceanReader(token, base string, cfg func() Config) *DigitalOceanReader

NewDigitalOceanReader builds a reader; base is overridable for fakes.

func (*DigitalOceanReader) Budgets

Budgets returns none: DigitalOcean has no budget API.

func (*DigitalOceanReader) Forecast

Forecast is linear from month to date, since the balance has no projection.

func (*DigitalOceanReader) Provider

func (r *DigitalOceanReader) Provider() Provider

Provider implements Reader.

func (*DigitalOceanReader) Spend

Spend reports month-to-date usage in USD, the only currency DigitalOcean bills.

type Factory

type Factory func(creds Credentials, cfg func() Config) (Reader, error)

Factory builds a reader from account credentials and live settings.

type Fetch

type Fetch func(ctx context.Context) (SpendReport, error)

Fetch loads a fresh report from the provider.

type HetznerReader

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

HetznerReader estimates spend from servers and the price list.

func NewHetznerReader

func NewHetznerReader(token, base string, cfg func() Config) *HetznerReader

NewHetznerReader builds a reader; base is overridable for fakes.

func (*HetznerReader) Budgets

Budgets returns none: Hetzner has no budget API.

func (*HetznerReader) Forecast

func (r *HetznerReader) Forecast(ctx context.Context, q SpendQuery) (SpendForecast, error)

Forecast is linear from the estimate.

func (*HetznerReader) Provider

func (r *HetznerReader) Provider() Provider

Provider implements Reader.

func (*HetznerReader) Spend

Spend estimates month to date from creation time and list prices. The currency is EUR, the price list's gross currency.

type Key

type Key struct {
	AccountID string
	Scope     string
}

Key identifies one cached report. Rate limits use AccountID alone so a caller cannot dodge them by varying Scope.

type Line

type Line struct {
	Name     string  `json:"name"`
	Amount   float64 `json:"amount"`
	Currency string  `json:"currency"`
	// ProviderID links a per-resource line back to an instance.
	ProviderID string `json:"provider_id,omitempty"`
}

Line is one amount in its own currency.

type OracleReader

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

OracleReader reads the Usage API and the Budgets API with a signed key.

func NewOracleReader

func NewOracleReader(signer ocisign.Signer, tenant, usageBase, budgetBase string, cfg func() Config) *OracleReader

NewOracleReader builds a reader with explicit bases; tests pass a plain HTTP fake and a signer with AllowInsecure set.

func (*OracleReader) Budgets

func (r *OracleReader) Budgets(ctx context.Context, _ SpendQuery) ([]ProviderBudget, error)

Budgets lists active budgets in the tenancy. The Budgets API documents no currency field, so an empty one is filled from the usage currency.

func (*OracleReader) Forecast

func (r *OracleReader) Forecast(ctx context.Context, q SpendQuery) (SpendForecast, error)

Forecast asks the Usage API for a BASIC forecast over the whole month and sums what it returns, falling back to linear when it returns nothing.

func (*OracleReader) Provider

func (r *OracleReader) Provider() Provider

Provider implements Reader.

func (*OracleReader) Spend

Spend reads cost by service, and by resource when asked. Daily granularity needs midnight UTC bounds, and the data lags real use by hours.

type PriceEstimate

type PriceEstimate struct {
	Hourly    float64 `json:"hourly"`
	Monthly   float64 `json:"monthly"`
	Currency  string  `json:"currency"`
	Estimated bool    `json:"estimated"`
}

PriceEstimate is a pre-create cost estimate, always flagged estimated.

type PriceQuery

type PriceQuery struct {
	ServiceCode string
	Region      string
	Filters     map[string]string
	// HoursPerMonth turns an hourly rate into a monthly estimate.
	HoursPerMonth float64
}

PriceQuery asks the Pricing API for an on-demand price. Filters are exact attribute matches, so any service and attribute set works.

type Provider

type Provider string

Provider names a spend source.

const (
	ProviderAWS          Provider = "aws"
	ProviderOracle       Provider = "oracle"
	ProviderDigitalOcean Provider = "digitalocean"
	ProviderHetzner      Provider = "hetzner"
)

Registered providers.

func Providers

func Providers() []Provider

Providers lists the registered provider names, sorted.

type ProviderBudget

type ProviderBudget struct {
	ID              string     `json:"id"`
	Name            string     `json:"name"`
	Amount          float64    `json:"amount"`
	Currency        string     `json:"currency"`
	ActualSpend     float64    `json:"actual_spend"`
	ForecastedSpend float64    `json:"forecasted_spend"`
	Period          string     `json:"period"`
	DataAsOf        *time.Time `json:"data_as_of,omitempty"`
}

ProviderBudget is a budget defined on the provider side, read only.

type ProviderError

type ProviderError struct {
	Status int
	Code   string
}

ProviderError carries only a status and a short code, so a provider body never reaches a client.

func (*ProviderError) Error

func (e *ProviderError) Error() string

type Reader

type Reader interface {
	Provider() Provider
	Spend(ctx context.Context, q SpendQuery) (SpendReport, error)
	Forecast(ctx context.Context, q SpendQuery) (SpendForecast, error)
	Budgets(ctx context.Context, q SpendQuery) ([]ProviderBudget, error)
}

Reader reads spend for one account of one provider.

func New

func New(p Provider, creds Credentials, cfg func() Config) (Reader, error)

New builds the reader for a provider, or ErrUnsupported.

type SpendForecast

type SpendForecast struct {
	AccountID string     `json:"account_id"`
	Provider  Provider   `json:"provider"`
	Currency  string     `json:"currency"`
	Amount    float64    `json:"amount"`
	Source    string     `json:"source"`
	PeriodEnd time.Time  `json:"period_end"`
	Estimated bool       `json:"estimated"`
	DataAsOf  *time.Time `json:"data_as_of,omitempty"`
}

SpendForecast is the projected month-end total in one currency.

type SpendQuery

type SpendQuery struct {
	AccountID  string
	Start, End time.Time
	// ByResource asks for per-resource lines where the provider has them.
	ByResource bool
	// Region is only used by providers whose endpoints are regional.
	Region string
}

SpendQuery selects what to read. Zero Start and End mean month to date.

type SpendReport

type SpendReport struct {
	AccountID   string    `json:"account_id"`
	Provider    Provider  `json:"provider"`
	PeriodStart time.Time `json:"period_start"`
	PeriodEnd   time.Time `json:"period_end"`
	State       string    `json:"state"`
	// FixHint says what to change when State is not ok.
	FixHint string `json:"fix_hint,omitempty"`
	// Totals has one entry per currency, never a cross-currency sum.
	Totals     []Total    `json:"totals"`
	ByService  []Line     `json:"by_service"`
	ByProject  []Line     `json:"by_project"`
	ByResource []Line     `json:"by_resource"`
	Source     string     `json:"source"`
	Estimated  bool       `json:"estimated"`
	DataAsOf   *time.Time `json:"data_as_of,omitempty"`
	FetchedAt  time.Time  `json:"fetched_at"`
	Stale      bool       `json:"stale"`
	// ErrorCode is a short code from the last failed refresh, never a provider body.
	ErrorCode string `json:"error_code,omitempty"`
}

SpendReport is the neutral month-to-date view of one account.

type Total

type Total struct {
	Currency string  `json:"currency"`
	Amount   float64 `json:"amount"`
}

Total is the sum of one currency.

func TotalsByCurrency

func TotalsByCurrency(lines []Line) []Total

TotalsByCurrency sums lines per currency and keeps currencies apart.

Jump to

Keyboard shortcuts

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