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
- Variables
- func ErrorCode(err error) string
- func LinearForecast(mtd float64, start, now, end time.Time) float64
- func Register(p Provider, f Factory)
- type AWSReader
- func (r *AWSReader) Budgets(ctx context.Context, _ SpendQuery) ([]ProviderBudget, error)
- func (r *AWSReader) EstimatePrice(ctx context.Context, q PriceQuery) (PriceEstimate, error)
- func (r *AWSReader) Forecast(ctx context.Context, q SpendQuery) (SpendForecast, error)
- func (r *AWSReader) Provider() Provider
- func (r *AWSReader) Spend(ctx context.Context, q SpendQuery) (SpendReport, error)
- type Cache
- type Config
- type Credentials
- type Decision
- type DigitalOceanReader
- func (r *DigitalOceanReader) Budgets(context.Context, SpendQuery) ([]ProviderBudget, error)
- func (r *DigitalOceanReader) Forecast(ctx context.Context, q SpendQuery) (SpendForecast, error)
- func (r *DigitalOceanReader) Provider() Provider
- func (r *DigitalOceanReader) Spend(ctx context.Context, q SpendQuery) (SpendReport, error)
- type Factory
- type Fetch
- type HetznerReader
- func (r *HetznerReader) Budgets(context.Context, SpendQuery) ([]ProviderBudget, error)
- func (r *HetznerReader) Forecast(ctx context.Context, q SpendQuery) (SpendForecast, error)
- func (r *HetznerReader) Provider() Provider
- func (r *HetznerReader) Spend(ctx context.Context, q SpendQuery) (SpendReport, error)
- type Key
- type Line
- type OracleReader
- func (r *OracleReader) Budgets(ctx context.Context, _ SpendQuery) ([]ProviderBudget, error)
- func (r *OracleReader) Forecast(ctx context.Context, q SpendQuery) (SpendForecast, error)
- func (r *OracleReader) Provider() Provider
- func (r *OracleReader) Spend(ctx context.Context, q SpendQuery) (SpendReport, error)
- type PriceEstimate
- type PriceQuery
- type Provider
- type ProviderBudget
- type ProviderError
- type Reader
- type SpendForecast
- type SpendQuery
- type SpendReport
- type Total
Constants ¶
const ( ReasonAccountInterval = "account_interval" ReasonUserHourly = "user_hourly" )
Refusal reasons.
const ( SourceUsageAPI = "usage_api" SourceCostExplorer = "cost_explorer" SourceBudgetAPI = "budget_api" SourceBalance = "balance" SourceEstimate = "estimate" )
Report sources.
const ( StateOK = "ok" StateTagNotActive = "tag_not_active" StateDisabled = "disabled" )
Report states. Anything but StateOK means the numbers are absent on purpose.
const ( ForecastProvider = "provider" ForecastLinear = "linear" )
Forecast sources.
const ProjectTagKey = "levelrail:project"
ProjectTagKey is the cost allocation tag Levelrail puts on what it creates.
Variables ¶
var ErrUnsupported = errors.New("cloudspend: not supported by this provider")
ErrUnsupported is returned when a provider cannot answer a call.
Functions ¶
func LinearForecast ¶
LinearForecast projects month-to-date spend to the end of the period.
Types ¶
type AWSReader ¶
type AWSReader struct {
// contains filtered or unexported fields
}
AWSReader reads Cost Explorer, Budgets and the Pricing API.
func NewAWSReader ¶
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) 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.
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 ¶
Credentials are the sealed account fields a factory needs, by key name (see each provider file).
type Decision ¶
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 ¶
func (r *DigitalOceanReader) Budgets(context.Context, SpendQuery) ([]ProviderBudget, error)
Budgets returns none: DigitalOcean has no budget API.
func (*DigitalOceanReader) Forecast ¶
func (r *DigitalOceanReader) Forecast(ctx context.Context, q SpendQuery) (SpendForecast, error)
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 ¶
func (r *DigitalOceanReader) Spend(ctx context.Context, q SpendQuery) (SpendReport, error)
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 ¶
func (r *HetznerReader) Budgets(context.Context, SpendQuery) ([]ProviderBudget, error)
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 ¶
func (r *HetznerReader) Spend(ctx context.Context, q SpendQuery) (SpendReport, error)
Spend estimates month to date from creation time and list prices. The currency is EUR, the price list's gross currency.
type Key ¶
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 ¶
func (r *OracleReader) Spend(ctx context.Context, q SpendQuery) (SpendReport, error)
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.
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 ¶
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.
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.