pricing

package
v0.3.11 Latest Latest
Warning

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

Go to latest
Published: Jul 25, 2026 License: MIT Imports: 51 Imported by: 0

Documentation

Overview

Package pricing — Alibaba Cloud BSS pricing backend.

Alibaba Cloud exposes pricing through the BSS OpenAPI GetPayAsYouGoPrice endpoint, a unified API that prices all pay-as-you-go products (ECS, RDS, Redis, SLB, etc.) via product-specific ModuleList parameters. This backend handles the single API call; each mapper (in internal/resources/alibaba_*.go) builds the appropriate ModuleList and parses the response.

Contract with Alibaba mappers:

  • req.Product = the BSS ProductCode (e.g. "ecs", "rds", "slb").
  • req.Region = the Alibaba Cloud region (e.g. "cn-hangzhou").
  • req.Params = neutral params map. The backend reads: "SubscriptionType": "PayAsYouGo" | "Subscription" (default: "PayAsYouGo") "ModuleList": []map[string]interface{} with keys ModuleCode, PriceType, Config

Package pricing — AWS pricing backend.

This file is the single place where AWS Price List (Pricing) SDK knowledge lives, mirroring the role handlers.go plays for Tencent Cloud. The Engine delegates any PriceRequest whose Provider is "aws" to this backend.

The AWS Price List API works very differently from Tencent's per-product InquiryPrice* methods: there is ONE GetProducts operation, parameterised by a ServiceCode (e.g. "AmazonEC2") plus a set of attribute Filters (instanceType, location, ...). It returns PriceList: a slice of JSON strings, each a full product price document. We hand that slice back to the Mapper (as a JSON array) which extracts the OnDemand price it needs.

Contract with AWS mappers (see the aws_*.go mappers in internal/resources):

  • req.Product = the AWS ServiceCode (required), e.g. "AmazonEC2".
  • req.Region = an AWS region (us-east-1, ...) — informational only; the mapper is responsible for translating it into a "location" filter value, because the Pricing API filters on the human-readable location name ("US East (N. Virginia)"), not the region code.
  • req.Params["Filters"] = []interface{} of map[string]interface{} each with "Field" and "Value" (both strings). All filters are matched with TERM_MATCH. ServiceCode is added automatically from req.Product.
  • req.Params["MaxResults"] = optional float64/int cap (default 100).

The backend returns the PriceList JSON-array bytes: `[ "<product-json>", ... ]`.

Package pricing wraps Tencent Cloud pricing APIs with a common request/response shape and a local cache.

Each per-type Mapper produces a PriceRequest with a Product/Action pair; the engine routes to the right SDK client, executes InquiryPriceXxx, caches the raw JSON response keyed by sha256(request) namespaced by site, and returns it.

Site selection: Tencent Cloud runs two independent sites (Chinese-mainland and International) chosen by the credential, not the region. The engine applies Config.Site via the SDK's RootDomain and isolates the cache per site so the two never share entries. See Config.Site and rootDomainForSite.

Package pricing — product handler registry.

This file is the single place where per-product SDK knowledge lives. To add support for a new Tencent Cloud product, register one productHandler here:

  1. Provide a newClient factory (wraps the product's SDK NewClient).
  2. Map each supported Action name to an invoker that builds the typed request, binds params, calls the SDK, and returns sdkResult(out, err).

The Engine's Query/invoke path is fully generic and never needs editing.

Package pricing — Huawei Cloud BSS pricing backend.

Huawei Cloud exposes pricing through the BSS ListOnDemandResourceRatings API, a unified endpoint that prices all pay-per-use (on-demand) resources by product spec, region, and usage factor. This backend handles the single API call; each mapper (in internal/resources/huawei_*.go) builds the appropriate product_infos payload and parses the response.

Contract with Huawei mappers:

  • req.Product = informational label (e.g. "ecs", "rds", "dcs").
  • req.Region = the Huawei Cloud region (e.g. "cn-north-4", "ap-singapore").
  • req.Params = the RateOnDemandReq body fields: "product_infos": []DemandProductInfo where each DemandProductInfo has: id, cloud_service_type, resource_type, resource_spec, region, usage_factor, usage_value, usage_measure_id, subscription_num. The project_id (a UUID, NOT the region) is injected by the backend from Config.HuaweiProjectID / HUAWEI_PROJECT_ID — mappers must NOT set it.

Site selection: Huawei Cloud runs two independent BSS sites with separate account systems — the International site (bss-intl.myhuaweicloud.com, SDK package bssintl/v2) and the Chinese-mainland site (bss.myhuaweicloud.com, SDK package bss/v2). A credential is registered on exactly ONE of them, so it is selected explicitly via Config.HuaweiSite, NOT derived from the region. The two SDK request/response types differ, so the cn client is wrapped in an adapter (cnHuaweiBSSAdapter) that implements the intl-shaped huaweiBSSAPI by JSON round-tripping the body; query() stays type-agnostic.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SupportedProducts

func SupportedProducts() []string

SupportedProducts returns the product keys currently registered, useful for diagnostics and tests. Order is not guaranteed.

Types

type Config

type Config struct {
	SecretID  string
	SecretKey string
	Region    string
	CachePath string // BoltDB file path; empty = no cache
	NoCache   bool   // when true, cache is disabled even if CachePath is set

	// Site selects which Tencent Cloud site the credential belongs to.
	//
	// Tencent Cloud runs two fully independent sites with separate account
	// systems: the Chinese-mainland site (api host <product>.tencentcloudapi.com)
	// and the International site (<product>.intl.tencentcloudapi.com). A given
	// SecretID/SecretKey pair is registered on exactly ONE of them, so the site
	// is NOT derivable from the region (both sites expose overlapping region
	// names such as ap-guangzhou / ap-singapore). It must be selected explicitly
	// to match the credential.
	//
	// Accepted values (case-insensitive, whitespace-trimmed):
	//   "" | "domestic" | "cn" | "china"          -> Chinese-mainland site (default)
	//   "intl" | "international" | "global"        -> International site
	// Any other non-empty value is treated as a literal root domain override
	// (e.g. a private-cloud gateway), passed through to the SDK unchanged.
	Site string

	// AWSSite selects the AWS partition for pricing.
	//   "" | "intl" | "global" | "international" -> AWS global (default; us-east-1)
	//   "domestic" | "cn" | "china"              -> AWS China partition (aws-cn; cn-north-1)
	// A China-mainland AWS account (operated by Sinnet/ChinaNet) is a separate
	// partition from global AWS; the SDK selects it automatically from the region.
	AWSSite string

	// AlibabaSite selects which Alibaba Cloud site the credential belongs to.
	//   "" | "domestic" | "cn" | "china"          -> Chinese-mainland site (default)
	//   "intl" | "international" | "global"        -> International site (bp.aliyuncs.com)
	AlibabaSite string

	// HuaweiSite selects which Huawei Cloud site the credential belongs to.
	//   "" | "intl" | "international" | "global"  -> International site (default; bss-intl)
	//   "domestic" | "cn" | "china"              -> Chinese-mainland site (bss)
	// Huawei Cloud Intl uses bss-intl.myhuaweicloud.com; the Chinese-mainland
	// site uses bss.myhuaweicloud.com. A credential is registered on ONE site.
	HuaweiSite string

	// AWS credentials for the AWS Price List backend. These are OPTIONAL and
	// entirely separate from the Tencent SecretID/SecretKey above. When left
	// empty, the AWS SDK's default credential chain is used (environment vars
	// AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY / AWS_SESSION_TOKEN, shared
	// config files, IAM role, ...). They are only consulted when an AWS
	// resource is actually priced, so a pure-Tencent run needs none of them.
	AWSAccessKeyID     string
	AWSSecretAccessKey string
	AWSSessionToken    string

	// Alibaba Cloud credentials for the BSS pricing backend. These are OPTIONAL
	// and only consulted when an Alibaba Cloud resource is priced. When left
	// empty, the environment vars ALIBABA_ACCESS_KEY_ID / ALIBABA_ACCESS_KEY_SECRET
	// are used.
	AlibabaAccessKeyID     string
	AlibabaAccessKeySecret string

	// Huawei Cloud credentials for the BSS pricing backend. These are OPTIONAL
	// and only consulted when a Huawei Cloud resource is priced. When left
	// empty, the environment vars HUAWEI_ACCESS_KEY_ID / HUAWEI_SECRET_ACCESS_KEY
	// are used.
	HuaweiAccessKeyID     string
	HuaweiSecretAccessKey string

	// HuaweiProjectID is the UUID project ID sent as RateOnDemandReq.ProjectId
	// for Huawei Cloud pricing. It is NOT the region. When empty, no project_id
	// is sent (the API then bills under the credential's default project). Read
	// from HUAWEI_PROJECT_ID env in the CLI.
	HuaweiProjectID string

	// AlibabaBSSEndpointRegion is the region used to build the BSS OpenAPI
	// endpoint (e.g. "cn-hangzhou"). It is NOT necessarily the region of the
	// resource being priced. When empty it defaults to "cn-hangzhou".
	AlibabaBSSEndpointRegion string

	// HuaweiBSSEndpointRegion is the region used to resolve the BSS endpoint
	// (e.g. "cn-north-4" or "ap-southeast-3"). It is NOT the resource region.
	// When empty it defaults to "cn-north-4".
	HuaweiBSSEndpointRegion string

	// Timeout bounds a single pricing round-trip (per attempt) so a stalled
	// InquiryPrice call cannot hang the whole cost run. It is applied to both
	// backends: for Tencent Cloud via the SDK profile's HttpProfile.ReqTimeout
	// (whole-second granularity), and for AWS via a context deadline. Zero or
	// negative means "use defaultRequestTimeout".
	Timeout time.Duration

	// MaxRetries is the number of ADDITIONAL attempts made after the first when
	// a request fails with a retryable error (rate limiting, request timeout,
	// transient network/5xx). Non-retryable errors (bad params, unknown SKU)
	// fail immediately. Zero means "use defaultMaxRetries"; a negative value
	// disables retries entirely.
	MaxRetries int

	// CacheTTL sets how long a successful pricing response stays in the on-disk
	// cache before being treated as stale. Zero means "use defaultTTL" (24h).
	// A shorter TTL keeps prices fresher at the cost of more API calls.
	CacheTTL time.Duration
}

type Engine

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

func NewEngine

func NewEngine(cfg Config) (*Engine, error)

func (*Engine) Close

func (e *Engine) Close() error

func (*Engine) Query

func (e *Engine) Query(req PriceRequest) ([]byte, error)

Query dispatches to the right SDK client and returns the raw response JSON. The per-type Mapper decodes it into typed CostComponents.

The request path is: on-disk cache -> in-flight de-duplication -> backend dispatch (with retry). The cache and dedup layers key off the same site-namespaced cache key so a healthy run touches each distinct SKU at most once, keeping us well under the InquiryPrice QPS limit.

type PriceRequest

type PriceRequest struct {
	Provider string
	Product  string
	Action   string
	Region   string
	Params   map[string]interface{}
}

PriceRequest is the neutral request submitted by a Mapper.

Provider: "" | "tencentcloud" (default) | "aws". Selects the pricing
          backend. Empty is treated as "tencentcloud" for backward
          compatibility, so all pre-existing mappers keep working unchanged.
Product:  Tencent: "cvm" | "cbs" | "clb" | "cdb" | "redis" | ...
          AWS: the Price List ServiceCode, e.g. "AmazonEC2" | "AmazonRDS" |
          "AmazonElastiCache" | "AWSELB" | "AmazonS3".
Action:   Tencent: "InquiryPriceRunInstances" | "DescribeDBPrice" | ...
          AWS: unused (the AWS backend prices via Filters in Params); may be
          left empty or set to a descriptive label.
Region:   Tencent: ap-guangzhou / ap-shanghai / ...
          AWS: us-east-1 / eu-west-1 / ... (used only to build a Location
          filter; the Pricing API endpoint itself is always us-east-1).
Params:   action-specific input. Tencent: JSON-marshaled into the SDK
          request. AWS: a neutral map the AWS backend turns into GetProducts
          filters (see aws_backend.go).

func (PriceRequest) CacheKey

func (r PriceRequest) CacheKey() (string, error)

Jump to

Keyboard shortcuts

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