{"modulePath":"github.com/LeanerCloud/cloud-commitments-platform","version":"v0.0.0-20261202160902-a99bcb5bfea3","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package commitmentopts\n\nPackage commitmentopts discovers which (term, payment) commitment tuples each AWS commitment-capable service actually sells, persists the result, and exposes it to the API layer so the frontend can hide impossible combinations instead of hardcoding them.\n\nThe package never blocks a save on missing data: if no probe has been persisted yet (or the probe failed), Service.Validate falls back to permissive-true and the frontend's hardcoded rules still gate the UI.\n\n## Variables\n\n```go\nvar ErrNoData = errors.New(\"commitment options unavailable\")\n```\nErrNoData signals \"we don't have cached commitment options and can't produce them right now\" (no AWS account connected, or a probe failed). Callers MUST NOT treat this as a hard error — the API handler maps it to \\`{\"status\":\"unavailable\"}\\` and Validate maps it to permissive-true.\n\n## Functions\n\n```go\nfunc ValidateCombo(opts Options, provider, service string, term int, payment string) bool\n```\nValidateCombo reports whether (provider, service, term, payment) is a legal combination according to opts, a snapshot returned by Get. It is pure: no database or network access, so it is safe to call inside a transaction.\n\nIt is permissive where opts has nothing to say: a provider with no combos, or a service the probe returned no combos for, is treated as valid.\n\n## Types\n\n```go\ntype AccountLister interface {\n\tListCloudAccounts(ctx context.Context, filter config.CloudAccountFilter) ([]config.CloudAccount, error)\n}\n```\nAccountLister is the narrow subset of config.StoreInterface that Service needs. Defining it here (rather than depending on the full interface) keeps tests small and avoids a circular import when the API layer wires up the real store.\n\n```go\ntype AzureCredentialFn func(ctx context.Context, account *config.CloudAccount) (azcore.TokenCredential, error)\n```\nAzureCredentialFn resolves the token credential for an Azure account.\n\n```go\ntype AzureCurrencyFn func(ctx context.Context, account *config.CloudAccount) (string, error)\n```\nAzureCurrencyFn returns the billing currency (3-letter ISO 4217 code) of an Azure account. It must fail rather than guess: Azure validates a purchase in the billing account's currency.\n\n```go\ntype AzureSPProber struct {\n\t// NewClient builds an AzureSPValidateAPI from a credential. Override\n\t// in tests to return a mock.\n\tNewClient func(cred azcore.TokenCredential) (AzureSPValidateAPI, error)\n}\n```\nAzureSPProber probes the Azure Billing Benefits ValidatePurchase endpoint for each candidate (term, payment) combination and returns those the API accepts as live Combos.\n\nDesign notes:\n\n  - Azure has no \"list offerings\" catalog endpoint comparable to AWS Describe\\*Offerings. ValidatePurchase is the closest live signal that a given (term, billingPlan) configuration is currently accepted.\n  - The probe validates against the caller's real subscription with the minimum non-zero hourly commitment; ValidatePurchase never creates a purchase, so no billing impact occurs.\n  - A 4xx answer (other than 401, 403, 404, 408 and 429) for a 5-year combo means Azure does not sell it: the combo is dropped and the probe continues, but a probe that ends with no accepted combo at all is an error. Any other error (a 4xx on a 1- or 3-year combo, auth, throttling, 5xx, network, canceled context) is a probe failure and is bubbled up so the Service can apply its all-or-nothing policy.\n\n```go\nfunc DefaultAzureProbers() []*AzureSPProber\n```\nDefaultAzureProbers returns one prober instance for the Azure Savings Plans service. The Service wires these up by default for Azure probe runs.\n\n```go\nfunc (p *AzureSPProber) ProbeAzure(ctx context.Context, cred azcore.TokenCredential, subscriptionID, currencyCode string) ([]Combo, error)\n```\nProbeAzure probes the Azure ValidatePurchase endpoint for each candidate (term, billingPlan) combo and returns Combos for those the API accepts.\n\nsubscriptionID is the Azure subscription the probe is scoped to; it must be a real one (an enabled Azure account's), never a placeholder, so an empty value fails closed before any client is built.\n\ncurrencyCode is the billing currency of the account the probe runs against (a 3-letter ISO 4217 code such as \"USD\" or \"EUR\"). Azure evaluates a ValidatePurchase request against the billing account's currency, so a probe sent in any other currency yields a verdict about a commitment the account could never buy. The caller must resolve the account's real currency; there is no USD default. An empty or malformed code fails closed before any client is built or any request is sent.\n\nThe method signature differs from the AWS Prober interface because Azure authentication uses azcore.TokenCredential rather than aws.Config. Callers use this method directly; Service.probeAndPersistAzure wires it up.\n\n```go\nfunc (p *AzureSPProber) Service() string\n```\nService returns \"savingsplans\".\n\n```go\ntype AzureSPValidateAPI interface {\n\tValidatePurchase(\n\t\tctx context.Context,\n\t\tbody armbillingbenefits.SavingsPlanPurchaseValidateRequest,\n\t\toptions *armbillingbenefits.RPClientValidatePurchaseOptions,\n\t) (armbillingbenefits.RPClientValidatePurchaseResponse, error)\n}\n```\nAzureSPValidateAPI is the minimal Azure Billing Benefits surface the probe needs. It matches the ValidatePurchase method on \\*armbillingbenefits.RPClient so tests can substitute a mock without importing the concrete SDK client.\n\nNOTE: providers/azure/services/savingsplans.RPValidateAPI defines the same one-method interface. The duplication is intentional: importing the provider package from internal/commitmentopts would create a circular dependency. The interface is tiny enough that duplicating it here is the cleanest option.\n\n```go\ntype BuildConfigFn func(ctx context.Context, account *config.CloudAccount) (aws.Config, error)\n```\nBuildConfigFn resolves an aws.Config for a given CloudAccount. The real wiring uses credentials.ResolveAWSCredentialProvider; tests substitute a stub that returns a zero aws.Config.\n\n```go\ntype Combo struct {\n\tProvider  string\n\tService   string\n\tPayment   string\n\tTermYears int\n}\n```\nCombo is one (provider, service, term, payment) tuple harvested from the reserved-offerings APIs. TermYears is 1 or 3; Payment is one of \"all-upfront\", \"partial-upfront\", \"no-upfront\". Other durations and legacy utilization-style payment options are dropped during normalization.\n\n```go\ntype EC2DescribeOfferings interface {\n\tDescribeReservedInstancesOfferings(ctx context.Context, params *ec2.DescribeReservedInstancesOfferingsInput, optFns ...func(*ec2.Options)) (*ec2.DescribeReservedInstancesOfferingsOutput, error)\n}\n```\nEC2DescribeOfferings is the minimal EC2 surface we use.\n\n```go\ntype EC2Prober struct {\n\tNewClient func(cfg aws.Config) EC2DescribeOfferings\n}\n```\nEC2Prober probes ec2:DescribeReservedInstancesOfferings.\n\n```go\nfunc (p *EC2Prober) Probe(ctx context.Context, cfg aws.Config) ([]Combo, error)\n```\nProbe returns the combos for t3.micro. IncludeMarketplace is explicitly false so we only see AWS-native (standard/convertible) offerings — the Marketplace resale market has arbitrary durations that would pollute normalization.\n\n```go\nfunc (p *EC2Prober) Service() string\n```\nService returns \"ec2\".\n\n```go\ntype ElastiCacheDescribeOfferings interface {\n\tDescribeReservedCacheNodesOfferings(ctx context.Context, params *elasticache.DescribeReservedCacheNodesOfferingsInput, optFns ...func(*elasticache.Options)) (*elasticache.DescribeReservedCacheNodesOfferingsOutput, error)\n}\n```\nElastiCacheDescribeOfferings is the minimal ElastiCache surface we use.\n\n```go\ntype ElastiCacheProber struct {\n\tNewClient func(cfg aws.Config) ElastiCacheDescribeOfferings\n}\n```\nElastiCacheProber probes elasticache:DescribeReservedCacheNodesOfferings.\n\n```go\nfunc (p *ElastiCacheProber) Probe(ctx context.Context, cfg aws.Config) ([]Combo, error)\n```\nProbe returns the combos for cache.t3.micro.\n\n```go\nfunc (p *ElastiCacheProber) Service() string\n```\nService returns \"elasticache\".\n\n```go\ntype MemoryDBDescribeOfferings interface {\n\tDescribeReservedNodesOfferings(ctx context.Context, params *memorydb.DescribeReservedNodesOfferingsInput, optFns ...func(*memorydb.Options)) (*memorydb.DescribeReservedNodesOfferingsOutput, error)\n}\n```\nMemoryDBDescribeOfferings is the minimal MemoryDB surface we use.\n\n```go\ntype MemoryDBProber struct {\n\tNewClient func(cfg aws.Config) MemoryDBDescribeOfferings\n}\n```\nMemoryDBProber probes memorydb:DescribeReservedNodesOfferings.\n\n```go\nfunc (p *MemoryDBProber) Probe(ctx context.Context, cfg aws.Config) ([]Combo, error)\n```\nProbe returns the combos for db.r6g.large.\n\n```go\nfunc (p *MemoryDBProber) Service() string\n```\nService returns \"memorydb\".\n\n```go\ntype OpenSearchDescribeOfferings interface {\n\tDescribeReservedInstanceOfferings(ctx context.Context, params *opensearch.DescribeReservedInstanceOfferingsInput, optFns ...func(*opensearch.Options)) (*opensearch.DescribeReservedInstanceOfferingsOutput, error)\n}\n```\nOpenSearchDescribeOfferings is the minimal OpenSearch surface we use. The OpenSearch API has no per-instance-type filter on this endpoint, so the probe filters client-side after fetching.\n\n```go\ntype OpenSearchProber struct {\n\tNewClient func(cfg aws.Config) OpenSearchDescribeOfferings\n}\n```\nOpenSearchProber probes opensearch:DescribeReservedInstanceOfferings.\n\n```go\nfunc (p *OpenSearchProber) Probe(ctx context.Context, cfg aws.Config) ([]Combo, error)\n```\nProbe returns the combos for t3.small.search.\n\n```go\nfunc (p *OpenSearchProber) Service() string\n```\nService returns \"opensearch\".\n\n```go\ntype Options map[string]map[string][]Combo\n```\nOptions groups valid combos by provider and service. Shape:\n\n\tOptions[\"aws\"][\"rds\"] = []Combo{...}\n\nOnly AWS is ever populated today — Azure and GCP stay hardcoded in the frontend because their commitment APIs don't have an equivalent probe.\n\n```go\ntype PostgresStore struct {\n\t// contains filtered or unexported fields\n}\n```\nPostgresStore is the Postgres-backed commitmentopts.Store implementation.\n\n```go\nfunc NewPostgresStore(db *database.Connection) *PostgresStore\n```\nNewPostgresStore returns a store backed by the given connection. The connection must already have the 000176 migration applied.\n\n```go\nfunc (s *PostgresStore) Get(ctx context.Context) (Options, bool, error)\n```\nGet returns the persisted combos grouped by provider and service, limited to providers that have a probe run row, plus a boolean that is true iff any run row exists. The combos map may be empty even when the boolean is true — that legitimately means \"we probed and nothing matched our normalizer\".\n\n```go\nfunc (s *PostgresStore) HasData(ctx context.Context, provider string) (bool, error)\n```\nHasData reports whether a probe run row exists for provider.\n\n```go\nfunc (s *PostgresStore) ProbedAt(ctx context.Context, provider string) (time.Time, bool, error)\n```\nProbedAt returns provider's probe run time; the bool is false without a row.\n\n```go\nfunc (s *PostgresStore) Replace(ctx context.Context, provider string, combos []Combo, sourceAccountID string) error\n```\nReplace overwrites provider's run row (new probed\\_at and source) and swaps its combos for the given ones in one transaction, so a reader never sees the provider with no combos and a failed write keeps the previous snapshot.\n\n```go\nfunc (s *PostgresStore) Save(ctx context.Context, provider string, combos []Combo, sourceAccountID string) error\n```\nSave persists provider's probe run row and every combo transactionally. If the provider's run row already exists (a second process raced us to persist), the first row's probed\\_at and source win, but this call's combos are still added next to the existing ones (ON CONFLICT DO NOTHING). Replace is the path that overwrites the row and swaps the combos. Other providers' rows and combos are never touched.\n\n```go\ntype Prober interface {\n\t// Service returns the canonical service name used as the Options key\n\t// and persisted in commitment_options_combos.service.\n\tService() string\n\n\t// Probe issues paginated Describe*Offerings calls against a canonical\n\t// small instance type, normalizes the results, and returns unique\n\t// Combos. Errors bubble up — the orchestrating Service treats ANY\n\t// probe failure as \"don't persist\" (all-or-nothing).\n\tProbe(ctx context.Context, cfg aws.Config) ([]Combo, error)\n}\n```\nProber probes a single AWS service's reserved-offerings API and returns every unique (term, payment) tuple it exposes. Implementations live in probe.go, one per service.\n\n```go\nfunc DefaultProbers() []Prober\n```\nDefaultProbers returns one prober instance per commitment-capable service. The Service wires these up by default; tests override via a custom slice.\n\n```go\ntype RDSDescribeOfferings interface {\n\tDescribeReservedDBInstancesOfferings(ctx context.Context, params *rds.DescribeReservedDBInstancesOfferingsInput, optFns ...func(*rds.Options)) (*rds.DescribeReservedDBInstancesOfferingsOutput, error)\n}\n```\nRDSDescribeOfferings is the minimal RDS surface the probe needs. It matches the method signature on the generated client so tests can substitute a mock without dragging in the full RDSAPI interface.\n\n```go\ntype RDSProber struct {\n\t// NewClient builds a client from the probe's aws.Config. Override in\n\t// tests to return a mock.\n\tNewClient func(cfg aws.Config) RDSDescribeOfferings\n}\n```\nRDSProber probes rds:DescribeReservedDBInstancesOfferings.\n\n```go\nfunc (p *RDSProber) Probe(ctx context.Context, cfg aws.Config) ([]Combo, error)\n```\nProbe returns the normalized (term, payment) combos RDS currently sells against db.t3.micro.\n\n```go\nfunc (p *RDSProber) Service() string\n```\nService returns \"rds\".\n\n```go\ntype RedshiftDescribeOfferings interface {\n\tDescribeReservedNodeOfferings(ctx context.Context, params *redshift.DescribeReservedNodeOfferingsInput, optFns ...func(*redshift.Options)) (*redshift.DescribeReservedNodeOfferingsOutput, error)\n}\n```\nRedshiftDescribeOfferings is the minimal Redshift surface we use. The API has no NodeType filter on DescribeReservedNodeOfferings so the probe filters client-side.\n\n```go\ntype RedshiftProber struct {\n\tNewClient func(cfg aws.Config) RedshiftDescribeOfferings\n}\n```\nRedshiftProber probes redshift:DescribeReservedNodeOfferings.\n\n```go\nfunc (p *RedshiftProber) Probe(ctx context.Context, cfg aws.Config) ([]Combo, error)\n```\nProbe returns the combos for dc2.large.\n\n```go\nfunc (p *RedshiftProber) Service() string\n```\nService returns \"redshift\".\n\n```go\ntype SavingsPlansDescribeOfferings interface {\n\tDescribeSavingsPlansOfferings(ctx context.Context, params *savingsplans.DescribeSavingsPlansOfferingsInput, optFns ...func(*savingsplans.Options)) (*savingsplans.DescribeSavingsPlansOfferingsOutput, error)\n}\n```\nSavingsPlansDescribeOfferings is the minimal Savings Plans surface the probe needs. It matches the relevant method on the generated client so tests can substitute a mock without dragging in the full SavingsPlansAPI interface.\n\n```go\ntype SavingsPlansProber struct {\n\t// NewClient builds a client from the probe's aws.Config. Override in\n\t// tests to return a mock.\n\tNewClient func(cfg aws.Config) SavingsPlansDescribeOfferings\n}\n```\nSavingsPlansProber probes savingsplans:DescribeSavingsPlansOfferings once per plan type (Compute, EC2Instance, SageMaker, Database) and emits per-product service keys. The probe runs all four plan types in sequence and returns all combos; Service.probeAndPersist fans them out concurrently alongside the RI probers. Any plan type that returns zero offerings for a given account is silently skipped — the frontend falls back to its hardcoded rules for that key.\n\n```go\nfunc (p *SavingsPlansProber) Probe(ctx context.Context, cfg aws.Config) ([]Combo, error)\n```\nProbe calls DescribeSavingsPlansOfferings for each of the four plan types and returns combos keyed with the per-product service slug. Empty results for a plan type are silently dropped so the caller never stores a zero-combo entry that would incorrectly suppress the fallback.\n\n```go\nfunc (p *SavingsPlansProber) Service() string\n```\nService returns \"savings-plans\" — a sentinel used only for error wrapping. Each plan type emits its own per-product service key via Probe; the umbrella name is never stored.\n\n```go\ntype Service struct {\n\t// contains filtered or unexported fields\n}\n```\nService orchestrates probe-and-cache of AWS commitment options.\n\nConcurrency model:\n\n  - Get is DB-first. The DB lookup is lock-free.\n  - On a cache miss, Get acquires mu, re-checks the DB under the lock (to absorb a concurrent writer), then probes. The lock is per- process ; the provider PK on commitment\\_options\\_probe\\_runs handles cross-process races.\n  - Probes run concurrently under errgroup. Any probe error aborts the whole attempt and NOTHING is persisted — we never want a partial snapshot to set the \"cache warm\" sentinel.\n\n```go\nfunc New(store Store, accounts AccountLister, buildConfig BuildConfigFn, probers []Prober) *Service\n```\nNew returns a Service wired to the given dependencies. Pass DefaultProbers() for the real probe set; tests inject stubs.\n\n```go\nfunc (s *Service) CachedOptions(ctx context.Context, provider string) (byService map[string][]Combo, ok bool, err error)\n```\nCachedOptions returns provider's stored combos grouped by service, reading the store only: it never lists accounts, resolves credentials or probes, so it is safe on a request path. ok is false when provider has no probe run row. Options are global to the deployment (the store has no tenant key).\n\n```go\nfunc (s *Service) FreshAzureOptions(ctx context.Context) (byService map[string][]Combo, ok bool, err error)\n```\nFreshAzureOptions returns the stored Azure combos by service only while the row is younger than azureOptionsTTL, reading the store alone. ok is false for an absent or stale row, and without WithAzure, so callers treat the provider as unprobed instead of gating on data that may have gone out of date.\n\n```go\nfunc (s *Service) Get(ctx context.Context) (Options, error)\n```\nGet returns cached Options if they exist, otherwise probes. On any failure (no AWS account connected, probe error) it returns ErrNoData without persisting; callers map that to the unavailable status.\n\n```go\nfunc (s *Service) RefreshAzure(ctx context.Context) error\n```\nRefreshAzure probes Azure and persists the azure probe run row unless a fresh one (younger than azureOptionsTTL) exists already; a stale row is replaced only by a successful probe. It is a no-op without WithAzure or without an enabled Azure account. It is deliberately not part of Get, so AWS requests never wait on Azure. The scheduler calls it, best effort, after a collection run.\n\nThe run is bounded by azureRefreshTimeout. A failure is remembered for azureFailureTTL and returned again, without any Azure call, until it expires; a failure caused by the caller canceling its own context is not. A failure persists nothing and never touches the AWS row.\n\n```go\nfunc (s *Service) Validate(ctx context.Context, provider, service string, term int, payment string) (bool, error)\n```\nValidate reports whether (provider, service, term, payment) is a legal combination according to the cached probe data.\n\nFallback behavior: if no probe data exists (the server has never successfully probed) Validate returns true so saves aren't blocked when we can't verify. The frontend's hardcoded rules are the user-facing gate; this check is belt-and-braces.\n\nValidate reads the store through its own pool connections and can probe AWS on a cold cache, so it must not run while the caller holds a pooled transaction. Such callers fetch the Options with Get first and check them with ValidateCombo inside the transaction.\n\n```go\nfunc (s *Service) WithAzure(credential AzureCredentialFn, currency AzureCurrencyFn, probers []*AzureSPProber) *Service\n```\nWithAzure enables the Azure probe. Call it once, before the Service is shared between goroutines. It only makes RefreshAzure available: Get never touches Azure.\n\n```go\ntype Store interface {\n\t// Get returns the cached Options of every provider with a probe run\n\t// row, and a boolean indicating whether any probe run row exists. The boolean is the authoritative \"cache warm\"\n\t// signal — an empty combos slice plus a present run row means \"we\n\t// probed, AWS returned nothing matching our normalizer\", and callers\n\t// should NOT re-probe.\n\tGet(ctx context.Context) (Options, bool, error)\n\n\t// Save writes provider's probe run row and combos atomically. If the\n\t// provider's run row already exists (concurrent writer won the race),\n\t// the row is kept rather than raising an error. Other providers' rows\n\t// and combos are left untouched.\n\tSave(ctx context.Context, provider string, combos []Combo, sourceAccountID string) error\n\n\t// HasData reports whether a probe run row exists for provider. Used as\n\t// the per-provider \"cache warm\" check before acquiring the prober lock.\n\tHasData(ctx context.Context, provider string) (bool, error)\n\n\t// ProbedAt returns when provider's probe run row was written, and false\n\t// when no row exists.\n\tProbedAt(ctx context.Context, provider string) (time.Time, bool, error)\n\n\t// Replace atomically swaps provider's probe run row and combos for the\n\t// given ones, stamping probed_at with the current time. Unlike Save it\n\t// overwrites an existing row. Other providers are left untouched.\n\tReplace(ctx context.Context, provider string, combos []Combo, sourceAccountID string) error\n}\n```\nStore persists probe results. Implementations must treat the combos table as idempotent (ON CONFLICT DO NOTHING) so concurrent writers don't trip each other.\n\n","path":"github.com/LeanerCloud/cloud-commitments-platform/internal/commitmentopts","name":"commitmentopts","synopsis":"Package commitmentopts discovers which (term, payment) commitment tuples each AWS commitment-capable service actually sells, persists the result, and exposes it to the API layer so the frontend can hide impossible combinations instead of hardcoding them.","isRedistributable":true}
