common

package
v0.0.0-...-519451a Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2026 License: OSL-3.0 Imports: 23 Imported by: 5 modules, 24 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package common — JSON codec helpers for the polymorphic ServiceDetails interface so per-rec details survive the round-trip through purchase_executions.recommendations (JSONB) without dropping the service-specific fields that drive offering lookup.

Background: before issue #453 the only Details data preserved across the dashboard → DB → executePurchase boundary was a single "engine" string on RecommendationRecord. EC2 platform / tenancy / scope, RDS AZ-config, SP plan-type / hourly-commitment all vanished, so the cloud service client's findOfferingID either fell back to "Linux/UNIX"-style defaults (silently mis-purchasing Windows recs as Linux) or returned "invalid service details for <Service>" outright. We now persist the full ServiceDetails payload as a raw JSON blob on the record, and reconstruct the matching typed pointer here at execute time using the rec's Service string as the discriminator.

All helpers live in pkg/common so the typed dispatch sits next to the type definitions (ComputeDetails / DatabaseDetails / …). internal/config (where RecommendationRecord lives) is deliberately kept free of pkg/common imports so the dependency graph stays a strict DAG.

Pointer invariant: this codec always reconstructs *DatabaseDetails / *CacheDetails, and every other producer (AWS, Azure, the CSV loader) constructs them as pointers too, so Recommendation.Details never holds a bare DatabaseDetails / CacheDetails value anywhere in the codebase. Consumers that type-switch on Details only need the pointer case for these two types. ComputeDetails is the one remaining exception: the Azure compute client (providers/azure/services/compute) and the GCP compute-engine client (providers/gcp/services/computeengine) both still construct it as a value, so consumers that handle ComputeDetails must keep accepting both forms. Dropping the value case would silently blank every Azure VM and GCP compute row instead of failing to compile.

Package common provides cloud-agnostic types and interfaces for multi-cloud cost optimization

Index

Constants

View Source
const (
	DropMinPoolSize           = "--min-pool-size"
	DropExtendedSupport       = "--include-extended-support"
	DropCoverageSizedToZero   = "--coverage-sized-to-zero"
	DropTargetAlreadyMet      = "target-already-met"
	DropTargetSizedToZero     = "target-sized-to-zero"
	DropTargetInputInvalid    = "target-input-invalid"
	DropTargetCoverageUnknown = "target-coverage-unknown"
	DropFamilyAlreadyAtTarget = "family-nu-already-at-target"
	DropFamilyNoNUSignal      = "family-nu-no-nu-signal"
	DropFamilySizedToZero     = "family-nu-sized-to-zero"
	DropDuplicateDedup        = "duplicate-dedup"
	DropMaxInstances          = "--max-instances"
	DropMinCountAfterCap      = "--min-count-after-cap"
)

Drop reason keys used by all filter and sizing stages. Using typed constants avoids typos at call sites and lets tests assert on the exact key.

View Source
const (
	ScopeRegional = "regional"
	ScopeZonal    = "zonal"
)

Canonical tokens returned by NormalizeScopeName.

View Source
const (
	DefaultClaimTTL           = 120 * time.Second
	DefaultClaimRenewInterval = DefaultClaimTTL / 3
	DefaultClaimSettleWindow  = 10 * time.Minute
)

Default lease numbers (go#745 plan Q3). The settle window must exceed the lease TTL plus the client-side request bound plus the provider's listing propagation delay.

View Source
const (
	PurchaseSourceCLI = "cudly-cli"
	PurchaseSourceWeb = "cudly-web"
	PurchaseSourceMCP = "cudly-mcp"
)

Source values for PurchaseOptions.Source. Kept lowercase so they can be used directly as GCP label values (GCP labels must be lowercase) and match AWS tag / Azure reservation tag conventions.

View Source
const ArcheraEnrollmentWindowDays = 7

ArcheraEnrollmentWindowDays is how long after a purchase a buyer has to enroll that commitment in Archera's coverage.

View Source
const ArcheraNonGatingDisclosure = "This is entirely optional. CUDly's purchase and management features " +
	"work fully without Archera."

ArcheraNonGatingDisclosure states that the offer is optional and that CUDly is fully functional without it. Disclosure 1 of 2.

View Source
const ArcheraPitch = "Want to push your coverage to 100% without the risk that a future capacity decrease " +
	"leaves you paying for commitments you no longer use? You can buy underutilization insurance for " +
	"Reserved Instances and Savings Plans from Archera."

ArcheraPitch is the offer itself: what the coverage does and why a buyer who just committed spend might want it.

View Source
const ArcheraSignupURL = "https://www.archera.ai/cudly"

ArcheraSignupURL is the Archera signup link carrying CUDly attribution. Shared with the CLI and kept identical to the frontend's ARCHERA_SIGNUP_URL (frontend/src/archera.ts).

NOTE: internal/email/templates.go currently sends a DIFFERENT link (https://archera.ai/signup?mode=cudly). That divergence predates this constant and is deliberately left alone here rather than silently normalized, because the two may be distinct attribution paths on Archera's side; reconciling them is a partnership question, not a refactor.

View Source
const ArcheraSponsorshipDisclosure = "For full disclosure, Archera sponsors CUDly's Open Source development " +
	"from a fraction of their insurance premiums."

ArcheraSponsorshipDisclosure states the financial relationship behind the recommendation. Disclosure 2 of 2.

View Source
const HoursPerMonth = HoursPerYear / 12

HoursPerMonth is the average month length (HoursPerYear / 12 = 730) used to convert hourly rates into monthly ones.

View Source
const HoursPerYear = 8760.0

HoursPerYear is the 365-day year length (24 * 365) used to convert a reservation term in years into billable hours.

View Source
const IdempotencyTagKey = "cudly-idempotency-token"

IdempotencyTagKey is the tag key under which the deterministic per-rec idempotency token (see DeriveIdempotencyToken) is stamped on commitments that the cloud API cannot dedupe natively. EC2 Reserved Instances have no ClientToken on PurchaseReservedInstancesOffering, so the EC2 client checks for an already-tagged RI before purchasing and tags the freshly-bought RI with this key afterwards, making a re-driven purchase idempotent (issue #636).

View Source
const PurchaseTagKey = "purchase-automation"

PurchaseTagKey is the tag/label key every CUDly-purchased commitment carries so customers and CUDly itself can attribute commitments back to the tool.

Variables

View Source
var (
	// ErrClaimHeld is returned by AcquireClaim when another holder's lease is
	// live. Nothing was changed.
	ErrClaimHeld = errors.New("purchase claim held by another holder")
	// ErrClaimSettlePending is returned by AcquireClaim when the lease on a
	// sending claim has expired but the settle window since the holder's last
	// renewal has not elapsed. The earlier holder's purchase may still commit,
	// so it also wraps ErrOutcomeUnknown (go#745 plan Q4: fail loud, buy nothing).
	ErrClaimSettlePending = fmt.Errorf("purchase claim settle window has not elapsed: %w", ErrOutcomeUnknown)
	// ErrClaimLost is returned by RenewClaim, AdvanceClaim and ReleaseClaim when
	// the row is no longer this holder and generation.
	ErrClaimLost = errors.New("purchase claim lost")
)
View Source
var ErrCommitmentPurchaseNotSupported = errors.New("commitment purchase not supported for this service")

ErrCommitmentPurchaseNotSupported is returned by ServiceClient.PurchaseCommitment implementations for services that have no programmatic committed-use / commitment purchase API. Their recommendations are advisory only: callers must surface them for human action rather than auto-purchasing. Returning this sentinel (instead of silently provisioning a billable resource) guarantees a "purchase" never creates infrastructure. Callers can detect it with errors.Is(err, ErrCommitmentPurchaseNotSupported).

View Source
var ErrCurrencyNotAccepted = errors.New("currency not accepted")

ErrCurrencyNotAccepted marks an operation refused because the billing currency is missing or differs from the currency the caller asked for, as distinct from an API failure. On its own it means the refusal came before anything was purchased or exchanged. A refusal on a retry that follows a purchase attempt which may have committed (Azure reservations, attempt 2 or later) also carries ErrOutcomeUnknown: then the earlier purchase may exist, so keep the money counted and reconcile. Check ErrOutcomeUnknown before treating it as "nothing was bought". Detect it with errors.Is(err, ErrCurrencyNotAccepted).

View Source
var ErrInvalidIdempotencyToken = errors.New("common: invalid idempotency token")

ErrInvalidIdempotencyToken is returned by OrderIDFromToken when a non-empty token cannot be turned into a reservation order GUID.

View Source
var ErrMuteSecretMissing = errors.New("common: NOTIFICATION_MUTE_SECRET is required")

ErrMuteSecretMissing is returned by ResolveMuteSecret when NOTIFICATION_MUTE_SECRET is unset. Falling back to a well-known key in any environment would make unsubscribe tokens forgeable for any (email, scope) tuple, so callers must fail closed.

View Source
var ErrOutcomeUnknown = errors.New("purchase outcome unknown")

ErrOutcomeUnknown marks a purchase whose request may have reached the cloud provider but whose result is not known: the commitment may already exist. Services whose purchase API has no idempotency token or caller-chosen ID (AWS EC2, Redshift) must not be re-sent automatically after such an error; reconcile against the provider first (see provider.PurchaseReconciler). Detect it with errors.Is(err, ErrOutcomeUnknown). Consumers such as the platform persist errors as strings, so the text "purchase outcome unknown" is effectively a contract until the platform persists a typed flag (platform #778).

View Source
var ErrRefusedBeforePurchase = errors.New("refused before purchase")

ErrRefusedBeforePurchase wraps an error from a check that refused the purchase before the purchase request was built or sent. It says nothing about why: the cause may be an offering upfront above the approved amount (or one that cannot be compared with it), a count bound, a service-ownership rule, or a duplicate-purchase guard, and retrying or asking for approval may not help. Some producers wrap only the sentinel and carry the cause in the message, so callers cannot rely on unwrapping to tell the causes apart. Its presence is sufficient to know that this call sent no purchase request, but its absence proves nothing: other refusals do not carry it. It describes only the call that returned it and says nothing about earlier calls with the same idempotency token. A wrapper that combines several purchase calls must not propagate it unless none of them sent a request. Detect it with errors.Is(err, ErrRefusedBeforePurchase).

View Source
var ErrUntypedServiceDetails = errors.New("service details payload for a service with no typed details")

jsonNullBytes is the JSON encoding of nil. Cached so the null-payload check below doesn't allocate on every call (this is the read-back step of every purchase, so it's worth avoiding the string conversion that would otherwise happen on the same path). ErrUntypedServiceDetails is returned (wrapped) by DecodeServiceDetailsFor when a payload exists for a service with no typed details. Read paths over persisted rows can match it with errors.Is to surface or skip the row; purchase paths should treat it as a hard failure.

Functions

func BreakEven

func BreakEven(rec Recommendation) (months float64, known bool)

BreakEven returns the number of months until the upfront payment of rec is recovered by its recurring discount, and whether that is known.

  • A positive rec.BreakEvenMonths set by a provider wins.
  • No upfront (CommitmentCost == 0): (0, true). There is nothing to recover. Exception: a zero upfront on a payment option that carries an upfront (see UpfrontPriceUnknown) is a missing price, not a known zero: (0, false).
  • Otherwise upfront / gross monthly savings, where gross monthly savings is EstimatedSavings plus the upfront amortized over the term. EstimatedSavings is the net monthly figure (already after the amortized upfront), so using it alone would overstate the break-even and push all-upfront commitments past their own term.
  • Net savings so low that gross monthly savings is not positive: (+Inf, true). The commitment never pays back its upfront.
  • Negative or non-finite money fields, or a term that is not 1yr/3yr: (0, false). Unknown is not 0 and is never reported as a break-even.

The result is invariant under ScaleRecommendationCosts: upfront and savings scale together.

func BuildReservationName

func BuildReservationName(f ReservationNameFields, fallbackPrefix string) string

BuildReservationName composes a rich, parseable identifier for an AWS reservation purchase. The format mirrors the Azure DisplayName format from #686 so cross-cloud parsers can share logic:

{svc}-{region}-{sku}-{count}x-{term}-{paymt}-{ts}-{rand}

e.g. "opensearch-us-east-1-r6gd-large-search-3x-1yr-allup-20260521T002019-a1b2c3d4" (which then gets truncated to fit the 60-char cap — see below).

The result is always sanitized via SanitizeReservationID for AWS reservation-name allowlists ([a-zA-Z0-9-], so underscores in SKU names become '-') and never longer than awsReservationNameMaxLen (60). If the composed string would exceed 60, optional fields are progressively dropped: timestamp first, then payment-option. The random suffix is NEVER dropped (it keeps otherwise-identical purchases from colliding); if the required segments plus suffix still overflow, the SKU is truncated. The service code, region, SKU, count, and term are NEVER dropped — those are the high-signal segments operators rely on to identify the reservation in the AWS console.

fallbackPrefix is the prefix passed to SanitizeReservationID for the unreachable empty-output fallback (e.g. "rds-reserved-"); it preserves the prior call-site behavior at every service when the builder ever emits an unsanitisable input.

func CheckAuditLogWritable

func CheckAuditLogWritable(path string) error

CheckAuditLogWritable verifies the audit file is readable and writable and its immediate namespace parents can be opened and synced for durability.

func DeploymentFromDetails

func DeploymentFromDetails(details ServiceDetails) string

DeploymentFromDetails extracts the RDS deployment option (AZConfig) from recommendation details. Returns "" for non-database service types.

The `d == nil` check after the type assertion is not redundant with the `details == nil` check above it: the first only catches an untyped nil, so an interface holding a typed nil pointer reaches the assertion, satisfies it, and would panic on the field read. Same guard as EngineFromDetails.

func DeriveIdempotencyToken

func DeriveIdempotencyToken(executionID string, recIndex int) string

DeriveIdempotencyToken returns a deterministic token for a single purchase recommendation, derived from the owning execution's ID and the recommendation's index within that execution. The same (executionID, recIndex) pair always yields the same token, so a re-driven purchase of a stranded execution (issue #636) reuses the identical token: AWS Savings Plans dedupe on it natively via CreateSavingsPlanInput.ClientToken, and the EC2 RI client uses it as a dedupe tag (IdempotencyTagKey). The output is a 64-char hex SHA-256 digest, which fits the AWS ClientToken 64-character limit exactly.

Unlike GenerateApprovalToken this is intentionally NOT random: idempotency requires the token be reproducible from durable inputs (execution_id + index), which both survive a strand-and-re-drive. It is not a credential, so the lack of unpredictability is by design.

func DeriveMuteToken

func DeriveMuteToken(key []byte, email, scope string) string

DeriveMuteToken returns a 32-byte HMAC-SHA256 token (hex-encoded) that signs the (email, scope) tuple. The token is embedded in the List-Unsubscribe URL; the handler re-derives it from the query params and compares in constant time, so a forged URL cannot mute a different address.

key must be resolved by the caller via ResolveMuteSecret, which applies a fail-closed policy in every environment. An empty key is a configuration error and yields the empty string so the caller emits no usable token (and a later VerifyMuteToken comparison against it fails), rather than silently signing with a well-known fallback.

func EC2NormalizationFactor

func EC2NormalizationFactor(size string) float64

EC2NormalizationFactor returns the AWS normalization factor of an EC2 instance size such as "xlarge" (8). It returns 0 when the size is not recognized, including "metal".

func EC2SizeFlexibleFamily

func EC2SizeFlexibleFamily(family string) bool

EC2SizeFlexibleFamily reports whether a regional Linux/Unix default-tenancy reservation of the instance family (the part of the type before the dot, such as "m5" or "u7i-6tb") can be size-flexible. It is case-insensitive and false for the families AWS excludes.

func EngineFilterKey

func EngineFilterKey(details ServiceDetails) (key string, normalize func(string) string)

EngineFilterKey returns the value the --include-engines/--exclude-engines filters compare against, and the normalizer to apply to each filter entry. Databases and caches use their engine; compute (EC2) uses its platform, which the CSV and table label "Engine". EngineFromDetails is deliberately left alone: it feeds the dedupe key and Matches, and existing EC2 commitments carry no engine to match a platform against. An empty key means the recommendation has no engine or platform.

func EngineFromDetails

func EngineFromDetails(details ServiceDetails) string

EngineFromDetails extracts and normalizes the engine name from recommendation details. Returns an empty string for non-database/cache service types. DatabaseDetails/CacheDetails are always pointers (every producer constructs them that way; see service_details_codec.go's package doc for the invariant). The nil-pointer guards are not dead code: the `details == nil` check above only catches an untyped nil, so a typed nil reaches the switch and would panic on the field read.

func GenerateApprovalToken

func GenerateApprovalToken() (string, error)

GenerateApprovalToken returns a 32-byte cryptographically secure random token, hex-encoded (64 chars). Used for purchase + RI exchange + plan approval flows where the token is the only credential in a one-click email link.

Why not uuid.New().String()? UUID v4 is 122 bits of entropy in a known format (8-4-4-4-12 hex with version + variant nibbles fixed). 32 random bytes provide a full 256 bits of unpredictability and a uniform output space, making token guessing computationally hopeless.

func IdempotencyGUID

func IdempotencyGUID(token string) string

IdempotencyGUID formats an idempotency token as a deterministic canonical GUID (8-4-4-4-12 lowercase hex) for use as an Azure reservationOrderID (issue #641). The Azure Reservations API path is reservationOrders/{guid} and a PUT is idempotent on a stable order ID, so deriving the GUID from the token makes a re-drive re-PUT the same order rather than create a second reservation.

It uses the first 32 hex characters (128 bits) of the token, which is itself a SHA-256 hex digest, so the GUID is deterministic and collision-free at any realistic purchase volume. Returns "" when token is shorter than 32 hex chars (e.g. empty) so callers keep their prior non-idempotent ID behavior.

func IdempotentReservationID

func IdempotentReservationID(prefix, token string) string

IdempotentReservationID derives a deterministic, AWS-safe reservation ID from an idempotency token (issue #641). The same token always yields the same ID, so a re-driven purchase reuses the identical customer-supplied reservation ID and AWS rejects the duplicate server-side (RDS/ElastiCache/MemoryDB each return a *AlreadyExists* fault). Returns "" when token is empty so the caller keeps its prior non-idempotent (timestamp-based) ID behavior for call sites that supply no token (e.g. the CLI path).

prefix should be a short, lowercase, hyphen-terminated service tag (e.g. "rds-id-") so the reservation is identifiable in the console; the token is hex so the result needs no further sanitisation beyond SanitizeReservationID's invariants.

func IsSavingsPlan

func IsSavingsPlan(s ServiceType) bool

IsSavingsPlan reports whether s is a canonical Savings Plans service slug: the umbrella sentinel (ServiceSavingsPlansAll) or one of the four per-plan-type constants. Legacy spellings are deliberately rejected so existing callers keep their behavior; pass them through NormalizeSavingsPlansServiceType first.

func MarshalServiceDetails

func MarshalServiceDetails(details ServiceDetails) (json.RawMessage, error)

MarshalServiceDetails encodes a ServiceDetails value into a raw JSON payload suitable for the RecommendationRecord.Details JSONB column. Returns (nil, nil) when details is nil so the column stays NULL / absent rather than persisting a literal JSON "null".

func MaskToken

func MaskToken(token string) string

MaskToken returns a log-safe representation of an idempotency/approval token: the first 8 characters followed by an ellipsis, never the full value. This keeps just enough of the prefix to correlate log lines for a single purchase while avoiding emitting the whole caller-supplied token into persistent logs (a stable per-execution identifier that should not leak verbatim). An empty token yields "(none)". A token of 8 chars or fewer is fully redacted to "(redacted)" rather than echoed: an 8-char prefix of an 8-char input is the whole value, so for short inputs (e.g. a short secret a future caller might pass) nothing of the token is emitted.

func NormalizeDeploymentName

func NormalizeDeploymentName(deployment string) string

NormalizeDeploymentName canonicalises an RDS deployment-option string (e.g. Cost Explorer's "Multi-AZ" or the parser's "multi-az") to a single lowercase, no-separator form. Mirrors providers/aws/recommendations/coverage.go's normaliseDeployment, which lives in the root module and can't be imported here (pkg is a separate Go module); keep the two in sync by hand if the vocabulary changes.

An empty input stays "" rather than becoming a synthetic bucket, so non-RDS commitments/recommendations (which never populate a deployment) collapse onto the same key instead of colliding with a real single-az/multi-az bucket.

func NormalizeEngineName

func NormalizeEngineName(engine string) string

NormalizeEngineName normalizes database engine names to a consistent format. Returns lowercase of the input as a fallback when the engine is not recognized.

func NormalizePlatformName

func NormalizePlatformName(platform string) string

NormalizePlatformName normalizes an EC2 platform for filter comparison.

func NormalizeScopeName

func NormalizeScopeName(scope string) string

NormalizeScopeName normalizes an EC2 reservation scope to ScopeRegional or ScopeZonal. Unrecognized input returns "" (unknown, a wildcard). Mirrors parseEC2Scope in providers/aws/services/ec2/client.go ("Region", "Availability Zone", and the hyphenated legacy spelling), which pkg cannot import.

func NormalizeSource

func NormalizeSource(s string) (string, error)

NormalizeSource lowercases s and returns it when it matches an allowed source. Returns an error on anything else so cloud tags cannot be polluted with arbitrary caller-supplied strings (which would be impossible to retroactively remove from committed resources).

func NormalizeTenancyName

func NormalizeTenancyName(tenancy string) string

NormalizeTenancyName normalizes an EC2 tenancy for comparison. "shared" is the operator spelling of the API value "default"; "dedicated" and "host" stay distinct. Unrecognized input returns "" (unknown, a wildcard). Mirrors the accepted inputs of parseEC2Tenancy in providers/aws/services/ec2/client.go, which pkg cannot import.

func OrderIDFromToken

func OrderIDFromToken(token, fallback string) (string, error)

OrderIDFromToken returns the Azure reservationOrderID to PUT for a purchase: the deterministic GUID derived from token when one is valid (issue #641), or fallback when token is empty.

A non-empty token that IdempotencyGUID cannot format (shorter than 32 chars, or non-hex in its first 32) returns an error wrapping ErrInvalidIdempotencyToken instead of the fallback: silently falling back would make a re-drive create a second reservation. The error masks the token with MaskToken.

func PositiveIntFromEnv

func PositiveIntFromEnv(name string, def int) int

PositiveIntFromEnv returns the positive integer held in the env var name, or def when it is unset, not an integer, or not positive.

func RDSFamily

func RDSFamily(instanceType string) string

RDSFamily returns the family prefix of an RDS instance type, e.g. "db.r7g.2xlarge" gives "db.r7g". It returns "" when the type has no size suffix.

func RDSInstanceNU

func RDSInstanceNU(instanceType string) float64

RDSInstanceNU returns the normalized units of an RDS instance type such as "db.r7g.2xlarge" (16). It returns 0 when the size is not recognized.

func RDSSizeFlexibleEngine

func RDSSizeFlexibleEngine(engine string) bool

RDSSizeFlexibleEngine reports whether reservations of an engine are size-flexible. It is an allowlist: MySQL, MariaDB, PostgreSQL and Aurora. Oracle is exact-class: BYOL is flexible but License Included is not, and recommendations normalize Oracle without the license, so a flexible key for a commitment would never match its recommendation and would let a duplicate through. Oracle stays exact until both paths carry the license model (#342). SQL Server, Db2 (the AWS doc lists it both as flexible and as not) and unknown engines are exact-class too, so a reservation is never credited to a size it may not cover.

func ResolveMuteSecret

func ResolveMuteSecret() ([]byte, error)

ResolveMuteSecret returns the HMAC key for notification mute tokens, applying a fail-closed policy in every environment. Local development and tests must provide an explicit test-only value rather than sharing a predictable key.

func RunPurchaseClaimerConformance

func RunPurchaseClaimerConformance(t *testing.T, newClaimer func(t *testing.T) (c PurchaseClaimer, advance func(time.Duration)))

RunPurchaseClaimerConformance checks the PurchaseClaimer rules (go#745) against any implementation, so a durable store can be held to the in-memory reference. newClaimer returns a fresh store and a function that advances the store's own clock; a store with database time implements it by scaling or sleeping.

func SanitizeReservationID

func SanitizeReservationID(id, fallbackPrefix string) string

SanitizeReservationID returns an identifier safe for AWS reservation/reserved-instance ID or name fields: only ASCII letters, digits, and hyphens; no leading/trailing hyphen; no consecutive hyphens. Dots are replaced with hyphens. If the result would be empty, returns fallbackPrefix plus a Unix timestamp.

func SavingsPct

func SavingsPct(onDemandTotal, committedTotal float64) float64

SavingsPct returns the percentage a committed total saves against the on-demand total. It returns 0 when onDemandTotal is not positive, so a missing baseline never produces NaN or Inf.

func ShouldIncludeService

func ShouldIncludeService(params RecommendationParams, service ServiceType) bool

ShouldIncludeService reports whether service is selected by params: every service when params.Service is empty, otherwise only the requested one.

func UpfrontPriceUnknown

func UpfrontPriceUnknown(rec Recommendation) bool

UpfrontPriceUnknown reports whether rec's zero CommitmentCost is a missing price rather than a known zero upfront: the payment option says an upfront is charged (all, partial or Azure "upfront"), but the provider gave no figure. Azure Advisor "upfront" variants and AWS recommendations with a nil UpfrontCost have this shape. No-upfront, monthly and empty or unrecognized payment options keep a zero as a known zero upfront.

func VerifyMuteToken

func VerifyMuteToken(key []byte, email, scope, token string) bool

VerifyMuteToken returns true when token equals the HMAC for (email, scope) under key. Comparison is constant-time to prevent timing attacks. A non-empty token never matches when key is empty, so a missing secret fails closed.

func WriteAuditRecord

func WriteAuditRecord(record AuditRecord, path string) error

WriteAuditRecord marshals record to a single JSON line and appends it to path. Returns an error if RunID is empty or if any I/O step fails.

Types

type Account

type Account struct {
	Provider    ProviderType `json:"provider"`
	ID          string       `json:"id"`
	Name        string       `json:"name"`
	DisplayName string       `json:"display_name"`
	IsDefault   bool         `json:"is_default"`
}

Account represents a cloud account/subscription/project.

type AttemptJournal

type AttemptJournal interface {
	// PriorAttempts returns the records of every execution for the token,
	// including the caller's own; none is not an error.
	PriorAttempts(ctx context.Context, token string) ([]AttemptRecord, error)
	RecordAttempt(ctx context.Context, rec AttemptRecord) error
}

AttemptJournal is a durable record of purchase attempts per idempotency token (go#107). It is a record, not a lock.

RecordAttempt is committed before it returns. Allowed transitions: none to sending or purchased; sending to purchased or outcome_unknown; outcome_unknown to purchased; purchased to purchased only with the same ReservationID. Everything else is an error, including an identical sending or outcome_unknown repeat. OfferingID is write-once. Any error from either method means the state is not durably known. Implementations should call AttemptRecord.Validate before storing.

Caller contract: a caller that re-dispatches a token whose earlier attempt may have been sent must first wait long enough for the provider's listing to show a commitment that attempt bought.

type AttemptRecord

type AttemptRecord struct {
	IdempotencyToken string
	ExecutionID      string
	State            AttemptState
	// ReservationID is the provider-side commitment ID; set only when State is
	// AttemptPurchased.
	ReservationID string
	// OfferingID is the offering the attempt was sent under; write-once.
	OfferingID string
}

AttemptRecord is one durable entry of an AttemptJournal.

func (AttemptRecord) Validate

func (r AttemptRecord) Validate() error

Validate reports whether the record is well formed. Error text never includes the full idempotency token.

type AttemptState

type AttemptState string

AttemptState is the lifecycle state of one purchase attempt. A caller's storage CHECK constraint must use exactly these strings.

const (
	AttemptSending        AttemptState = "sending"
	AttemptPurchased      AttemptState = "purchased"
	AttemptOutcomeUnknown AttemptState = "outcome_unknown"
)

type AuditRecord

type AuditRecord struct {
	Timestamp time.Time `json:"timestamp"`

	// RecurringMonthlyCost is the recurring charge in USD per month (the part
	// paid every month after any upfront payment), copied from
	// Recommendation.RecurringMonthlyCost. nil (omitted) means the provider did
	// not report it, which is not the same as a known 0 (all-upfront).
	RecurringMonthlyCost *float64 `json:"recurring_monthly_cost,omitempty"`

	RunID           string         `json:"run_id"`
	Provider        ProviderType   `json:"provider"`
	AccountID       string         `json:"account_id"`
	AccountName     string         `json:"account_name"`
	CredentialScope string         `json:"credential_scope,omitempty"` // Routing identifier, not a verified account ID.
	Region          string         `json:"region"`
	Service         string         `json:"service"`
	ResourceType    string         `json:"resource_type"`
	CommitmentType  CommitmentType `json:"commitment_type"`
	CommitmentID    string         `json:"commitment_id"`
	Status          string         `json:"status"`
	ErrorMessage    string         `json:"error_message"`

	// Source identifies the CUDly surface (cudly-cli / cudly-web) that
	// triggered the purchase. Mirrors the value stamped on the commitment
	// itself via purchase-automation tag/label.
	Source string `json:"source,omitempty"`

	RawRecommendation json.RawMessage `json:"raw_recommendation,omitempty"`
	Term              int             `json:"term_months"`
	Count             int             `json:"count"`
	EstimatedCost     float64         `json:"estimated_cost"` // Upfront payment (Recommendation.CommitmentCost); 0 for no-upfront commitments.
	EstimatedSavings  float64         `json:"estimated_savings"`
	DryRun            bool            `json:"dry_run"`
}

AuditRecord is one line in the JSON-lines audit log. Status values: "success", "error", "skipped" (dry-run), "skipped_covered" (idempotency).

func NewAuditRecord

func NewAuditRecord(runID string, rec Recommendation, result PurchaseResult, status string, dryRun bool, source string) AuditRecord

NewAuditRecord constructs an AuditRecord from a Recommendation and a PurchaseResult. status must be one of: "success", "error", "skipped" (dry-run), "skipped_covered" (idempotency). source is the CUDly surface that triggered the run — copied into the JSONL so CLI audit logs can be reconciled against the DB's purchase_history.source column.

type CacheDetails

type CacheDetails struct {
	Engine   string `json:"engine"` // redis, memcached
	NodeType string `json:"node_type"`
	Shards   int    `json:"shards,omitempty"`
}

CacheDetails represents cache-specific details (ElastiCache, Azure Cache, Memorystore).

func (CacheDetails) GetDetailDescription

func (d CacheDetails) GetDetailDescription() string

func (CacheDetails) GetServiceType

func (d CacheDetails) GetServiceType() ServiceType

type Claim

type Claim struct {
	Token      string
	Holder     string
	Phase      ClaimPhase
	OrderID    string
	Generation int64
}

Claim is the handle AcquireClaim returns. Holder and Generation identify the lease (Generation is the fencing token); Phase is the row's phase at acquisition and OrderID is set only when Phase is ClaimCompleted.

type ClaimOutcome

type ClaimOutcome struct {
	OrderID string
}

ClaimOutcome tells ReleaseClaim how the claim ended. OrderID non-empty means an order exists: the row becomes completed. Empty means nothing was bought by the holder: the row is deleted, but only if the store still has it in phase claimed. A sending row is left to expire whatever the holder saw.

type ClaimPhase

type ClaimPhase string

ClaimPhase is what a purchase claim protects at a given moment (go#745). A caller's storage CHECK constraint must use exactly these strings.

const (
	// ClaimClaimed: the holder owns the token and no purchase request has been
	// sent. No money moved.
	ClaimClaimed ClaimPhase = "claimed"
	// ClaimSending: set immediately before the purchase request. From here the
	// provider may hold an order even if the holder dies.
	ClaimSending ClaimPhase = "sending"
	// ClaimCompleted: an order exists and its ID is recorded. Terminal.
	ClaimCompleted ClaimPhase = "completed"
)

type ClaimReader

type ClaimReader interface {
	ClaimedByOthers(ctx context.Context, token string, ids []string) ([]string, error)
}

ClaimReader is an optional interface an AttemptJournal may also implement (go#700). A provider client finds it by type assertion on PurchaseOptions.AttemptJournal; a journal without it behaves as before.

ClaimedByOthers returns the subset of ids that some attempt under a token other than token has recorded as purchased. An id that only the given token recorded is not returned, and an empty result excludes nothing. Any error means the claims are not known.

type ClaimRow

type ClaimRow struct {
	ExpiresAt  time.Time
	RenewedAt  time.Time
	Holder     string
	Phase      ClaimPhase
	OrderID    string
	Generation int64
	Exists     bool
}

ClaimRow is a read-only copy of one MemoryPurchaseClaimer row.

type Commitment

type Commitment struct {
	StartDate      time.Time       `json:"start_date"`
	EndDate        time.Time       `json:"end_date"`
	Provider       ProviderType    `json:"provider"`
	Account        string          `json:"account"`
	CommitmentID   string          `json:"commitment_id"`
	CommitmentType CommitmentType  `json:"commitment_type"`
	Service        ServiceType     `json:"service"`
	Region         string          `json:"region"`
	ResourceType   string          `json:"resource_type"`
	Engine         string          `json:"engine,omitempty"`     // Database engine for RDS/ElastiCache (e.g., "mysql", "aurora-postgresql")
	Deployment     string          `json:"deployment,omitempty"` // RDS Multi-AZ vs Single-AZ, Azure SQL zone redundancy; empty otherwise
	State          CommitmentState `json:"state"`

	// EC2 reserved-instance dimensions. Empty means unknown or a wildcard.
	// Filled by the EC2 commitment listing from the reserved instance's
	// product description, tenancy, scope and availability zone.
	Platform         string `json:"platform,omitempty"`
	Tenancy          string `json:"tenancy,omitempty"`
	Scope            string `json:"scope,omitempty"`
	AvailabilityZone string `json:"availability_zone,omitempty"`

	// CostCurrency is the ISO 4217 code Cost is denominated in, when the
	// provider reports one; empty means not reported.
	CostCurrency string `json:"cost_currency,omitempty"`

	Count int     `json:"count"`
	Cost  float64 `json:"cost"`
	// CostKnown reports whether Cost holds a price the provider reported. The zero
	// value means unknown, so a Cost of 0 on a commitment that did not set
	// CostKnown must not be read as free. Set it true only where the amount was
	// read from the provider (a real 0 included).
	CostKnown bool `json:"cost_known"`

	// StartDateIsDay marks StartDate as a UTC calendar date. The zero value
	// means StartDate is a precise timestamp; true means the real instant
	// lies in [StartDate, StartDate+24h).
	StartDateIsDay bool `json:"start_date_is_day,omitempty"`
}

Commitment represents an existing commitment (RI/SP/CUD/etc).

Deployment is set for AWS RDS and Azure SQL Database and stays empty for services without a deployment dimension (EC2, ElastiCache, etc). When populated, it carries the same vocabulary as DatabaseDetails.AZConfig on Recommendation ("single-az" / "multi-az" on AWS, "zoneRedundant" / "none" on Azure) so pool-key matching can collapse both sides via normaliseDeployment in the recommendations package. Without this field, RDS expiry adjustments would silently miss because Recommendation lookup keys are deployment-aware while commitment keys defaulted to empty.

type CommitmentState

type CommitmentState string

CommitmentState is the provider-neutral lifecycle state of a Commitment. Providers map their native states onto these values; a native state with no mapping passes through verbatim, and duplicate detection counts it as owned (fail closed).

const (
	CommitmentStateActive         CommitmentState = "active"
	CommitmentStatePaymentPending CommitmentState = "payment-pending"
	CommitmentStateQueued         CommitmentState = "queued"
)

Owned states: the commitment covers, or will cover, usage, so duplicate detection counts it. They match the AWS RI and Savings Plans state enums; queued is a scheduled future purchase and must count, or it gets bought a second time.

const (
	CommitmentStateRetired       CommitmentState = "retired"
	CommitmentStatePendingReturn CommitmentState = "pending-return"
	CommitmentStateExpired       CommitmentState = "expired"
	CommitmentStateCanceled      CommitmentState = "canceled"
	CommitmentStateFailed        CommitmentState = "failed"
)

Ended states: the commitment no longer covers usage, or is being returned, so duplicate detection ignores it.

type CommitmentType

type CommitmentType string

CommitmentType represents different commitment types across clouds.

const (
	CommitmentReservedInstance CommitmentType = "reserved-instance" // AWS RI, Azure RI
	CommitmentSavingsPlan      CommitmentType = "savings-plan"      // AWS Savings Plans
	CommitmentCUD              CommitmentType = "committed-use"     // GCP CUD
	CommitmentReservedCapacity CommitmentType = "reserved-capacity" // Azure/GCP storage
)

func (CommitmentType) String

func (c CommitmentType) String() string

String returns the string representation of the commitment type.

type ComputeDetails

type ComputeDetails struct {
	InstanceType      string  `json:"instance_type"`
	Platform          string  `json:"platform"`                    // linux, windows
	Tenancy           string  `json:"tenancy"`                     // default, dedicated, host
	Scope             string  `json:"scope"`                       // regional, zonal
	AvailabilityZone  string  `json:"availability_zone,omitempty"` // required for zonal EC2 scope, empty for regional
	GCPCommitmentType string  `json:"gcp_commitment_type,omitempty"`
	VCPU              int     `json:"vcpu,omitempty"`      // 0 = unknown
	MemoryGB          float64 `json:"memory_gb,omitempty"` // 0 = unknown
}

ComputeDetails represents compute-specific details (EC2, VM, Compute Engine).

VCPU + MemoryGB are populated by per-provider catalog lookups when available (Azure: armcompute.ResourceSKU.Capabilities; AWS: ec2:DescribeInstanceTypes; GCP: machine-type catalog). They are optional — converters that don't yet wire a catalog leave them at the zero value, and the JSON tag uses omitempty so unknown values don't pollute the API payload.

func (ComputeDetails) GetDetailDescription

func (d ComputeDetails) GetDetailDescription() string

GetDetailDescription returns a short human description of the compute recommendation. The base form is "<platform>/<tenancy>"; when both VCPU and MemoryGB are populated (>0) the size is appended as " (<vcpu> vCPU / <memory> GB)" to give the UI a one-line summary without forcing the caller to inspect the struct.

func (ComputeDetails) GetServiceType

func (d ComputeDetails) GetServiceType() ServiceType

type CrossAttribution

type CrossAttribution struct {
	Service ServiceType `json:"service"`
	Count   int         `json:"count"`
}

CrossAttribution is the count of one other service's resources whose underlying compute a resource-based Compute Engine CUD also discounts.

type DataWarehouseDetails

type DataWarehouseDetails struct {
	NodeType      string `json:"node_type"`
	ClusterType   string `json:"cluster_type,omitempty"` // single-node, multi-node
	NumberOfNodes int    `json:"number_of_nodes"`
}

DataWarehouseDetails represents data warehouse-specific details (Redshift, Synapse, BigQuery).

func (DataWarehouseDetails) GetDetailDescription

func (d DataWarehouseDetails) GetDetailDescription() string

func (DataWarehouseDetails) GetServiceType

func (d DataWarehouseDetails) GetServiceType() ServiceType

type DatabaseDetails

type DatabaseDetails struct {
	Engine        string `json:"engine"` // mysql, postgres, sqlserver, etc.
	EngineVersion string `json:"engine_version,omitempty"`
	AZConfig      string `json:"az_config"` // single-az, multi-az
	InstanceClass string `json:"instance_class"`
	Deployment    string `json:"deployment,omitempty"` // Azure: single, pool
}

DatabaseDetails represents database-specific details (RDS, Azure SQL, Cloud SQL).

func (DatabaseDetails) GetDetailDescription

func (d DatabaseDetails) GetDetailDescription() string

func (DatabaseDetails) GetServiceType

func (d DatabaseDetails) GetServiceType() ServiceType

type DropSummary

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

DropSummary accumulates the count of recommendations dropped per reason across the full fetch-filter-size pipeline. It is not safe for concurrent use from multiple goroutines; the main pipeline is sequential per service and region so no synchronization is needed.

func NewDropSummary

func NewDropSummary() *DropSummary

NewDropSummary returns a zero-valued DropSummary ready to record drops.

func (*DropSummary) Add

func (d *DropSummary) Add(reason string, n int)

Add increments the drop count for the given reason by n. Safe to call on a zero-value DropSummary (e.g. var d DropSummary); the underlying map is lazily initialized on first use. A zero n is a no-op and does not create a key for the reason. A negative n is a programming error and panics: it would subtract from the tally and silently understate the run's totals.

func (*DropSummary) FormatOneLine

func (d *DropSummary) FormatOneLine() string

FormatOneLine returns a compact single-line summary such as:

Dropped 14 recs: --min-pool-size=8, target-already-met=4, duplicate-dedup=2

Returns an empty string when no drops have been recorded.

func (*DropSummary) IsEmpty

func (d *DropSummary) IsEmpty() bool

IsEmpty reports whether no drops have been recorded.

func (*DropSummary) Total

func (d *DropSummary) Total() int

Total returns the sum of all drops recorded.

type ExchangeOrigin

type ExchangeOrigin string

ExchangeOrigin identifies the task that created an RI exchange record so that pending-cancellation can be scoped by origin (standalone vs ladder) through a typed value rather than a bare bool. It lives in pkg/common because both pkg/exchange (the caller) and internal/config (the store implementation) need it, and pkg/common carries no heavy provider-SDK dependencies.

const (
	// ExchangeOriginStandalone is the standalone ri_exchange_reshape scheduled
	// task. Its pending records have ladder_run_id IS NULL in the database.
	ExchangeOriginStandalone ExchangeOrigin = "standalone-ri-exchange"
	// ExchangeOriginLadder is the cudly-ladder engine (ladder run reshape
	// phase). Its pending records have ladder_run_id IS NOT NULL.
	ExchangeOriginLadder ExchangeOrigin = "cudly-ladder"
)

func (ExchangeOrigin) String

func (o ExchangeOrigin) String() string

String returns the string representation of the exchange origin.

func (ExchangeOrigin) Validate

func (o ExchangeOrigin) Validate() error

Validate returns an error when the origin is not a known value. Callers on the money path (pending cancellation) must fail loud on an unexpected origin rather than silently defaulting to the wrong partition.

type MemoryPurchaseClaimer

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

MemoryPurchaseClaimer is an in-process PurchaseClaimer. It is the reference for the interface's rules and the store used by tests; it is not durable and does not make anything exclusive across processes. now is the store's clock, the only time source (callers pass durations, never instants).

func NewMemoryPurchaseClaimer

func NewMemoryPurchaseClaimer(now func() time.Time) *MemoryPurchaseClaimer

NewMemoryPurchaseClaimer returns an empty store reading time from now.

func (*MemoryPurchaseClaimer) AcquireClaim

func (m *MemoryPurchaseClaimer) AcquireClaim(_ context.Context, token, holder string, ttl, settle time.Duration) (Claim, error)

func (*MemoryPurchaseClaimer) AdvanceClaim

func (m *MemoryPurchaseClaimer) AdvanceClaim(_ context.Context, claim Claim, phase ClaimPhase) error

func (*MemoryPurchaseClaimer) ReleaseClaim

func (m *MemoryPurchaseClaimer) ReleaseClaim(_ context.Context, claim Claim, outcome ClaimOutcome) error

func (*MemoryPurchaseClaimer) RenewClaim

func (m *MemoryPurchaseClaimer) RenewClaim(_ context.Context, claim Claim, ttl time.Duration) error

func (*MemoryPurchaseClaimer) Row

func (m *MemoryPurchaseClaimer) Row(token string) ClaimRow

Row returns a copy of the token's row; Exists is false when none.

type MuteNotifScope

type MuteNotifScope string

MuteNotifScope is the set of valid notification scopes for per-recipient muting (issue #297). Each scope corresponds to one category of outbound email; a mute row suppresses only that category for its holder.

const (
	// ScopePurchaseApprovals suppresses purchase-approval-request emails.
	ScopePurchaseApprovals MuteNotifScope = "purchase_approvals"
	// ScopeRIExchangeApprovals suppresses RI-exchange pending-approval emails.
	ScopeRIExchangeApprovals MuteNotifScope = "ri_exchange_approvals"
)

type NoSQLDetails

type NoSQLDetails struct {
	Engine          string `json:"engine"`
	APIType         string `json:"api_type,omitempty"`
	ThroughputUnits int    `json:"throughput_units,omitempty"`
}

NoSQLDetails represents NoSQL-specific details (Cosmos DB, DynamoDB, Firestore). Engine is the provider-level family ("cosmos", "dynamodb", "firestore"); APIType is the cosmos-specific sub-API (sql, mongodb, cassandra, gremlin, table) and stays empty for non-cosmos engines. ThroughputUnits is the reserved-throughput unit (RU/s for cosmos). Zero-value fields indicate the source payload didn't supply the data (e.g. SKU string lacks a throughput tier or API-type hint) — do NOT treat zero as "definitely zero", only as "unknown".

func (NoSQLDetails) GetDetailDescription

func (d NoSQLDetails) GetDetailDescription() string

func (NoSQLDetails) GetServiceType

func (d NoSQLDetails) GetServiceType() ServiceType

type OfferingDetails

type OfferingDetails struct {
	OfferingID          string  `json:"offering_id"`
	ResourceType        string  `json:"resource_type"`
	Term                string  `json:"term"`
	PaymentOption       string  `json:"payment_option"`
	Currency            string  `json:"currency"`
	UpfrontCost         float64 `json:"upfront_cost"`
	RecurringCost       float64 `json:"recurring_cost"`
	TotalCost           float64 `json:"total_cost"`
	EffectiveHourlyRate float64 `json:"effective_hourly_rate"`
}

OfferingDetails represents cloud provider offering details.

All amounts are per ONE reservation or commitment unit, in Currency; callers multiply by the purchase count. AWS providers fill every field: RecurringCost is per HOUR, TotalCost is UpfrontCost plus RecurringCost times the term's hours, and EffectiveHourlyRate is TotalCost divided by those hours. Other providers may use a different RecurringCost period (GCP Compute Engine reports it per month), so compare offerings on TotalCost, which does not depend on the recurring period.

type PaymentOption

type PaymentOption string

PaymentOption is the payment structure of a purchase action.

const (
	PaymentAllUpfront     PaymentOption = "all-upfront"
	PaymentPartialUpfront PaymentOption = "partial-upfront"
	PaymentNoUpfront      PaymentOption = "no-upfront"
)

func ParsePaymentOption

func ParsePaymentOption(s string) (PaymentOption, error)

ParsePaymentOption converts s into a PaymentOption, returning a descriptive error when s is not a recognized value.

func (PaymentOption) Validate

func (p PaymentOption) Validate() error

Validate returns an error when p is not a recognized PaymentOption.

type ProviderType

type ProviderType string

ProviderType identifies the cloud provider.

const (
	ProviderAWS   ProviderType = "aws"
	ProviderAzure ProviderType = "azure"
	ProviderGCP   ProviderType = "gcp"
)

func (ProviderType) String

func (p ProviderType) String() string

String returns the string representation of the provider type.

type PurchaseClaimer

type PurchaseClaimer interface {
	AcquireClaim(ctx context.Context, token, holder string, ttl, settle time.Duration) (Claim, error)
	RenewClaim(ctx context.Context, claim Claim, ttl time.Duration) error
	AdvanceClaim(ctx context.Context, claim Claim, phase ClaimPhase) error
	ReleaseClaim(ctx context.Context, claim Claim, outcome ClaimOutcome) error
}

PurchaseClaimer is an optional interface an AttemptJournal may also implement (go#745). A provider client finds it by type assertion on PurchaseOptions.AttemptJournal; a journal without it behaves as before. It makes a purchase exclusive per idempotency token ACROSS processes, which the AttemptJournal record alone does not.

Every duration is relative and every instant is computed by the store, never by the caller, so replica clock skew cannot change a lease.

AcquireClaim, as one atomic step:

  • no row: insert with generation 1, phase claimed, expiry now+ttl.
  • phase completed: change nothing; return a Claim with Phase completed and the recorded OrderID, and no error.
  • live lease: change nothing; return an error wrapping ErrClaimHeld.
  • expired claimed row: take over, generation+1, phase claimed.
  • expired sending row: if the last renewal plus settle has not elapsed, change nothing and return an error wrapping ErrClaimSettlePending; otherwise take over, generation+1, KEEP phase sending, so a later peer cannot skip the settle window.

RenewClaim extends the lease and records the renewal time. AdvanceClaim moves claimed to sending (sending to sending is a no-op); no other phase is accepted. ReleaseClaim ends the claim per ClaimOutcome. Renew, Advance and Release return an error wrapping ErrClaimLost when the row is no longer (Holder, Generation). Any other error means the state is not durably known.

type PurchaseOptions

type PurchaseOptions struct {
	// RequestedAt is the first-dispatch time of this purchase lineage, stable
	// across re-drives of the same IdempotencyToken. Providers use it to bound
	// idempotency lookups for services that have no client token (Redshift
	// reserved nodes). A zero value means unknown; a provider that requires it
	// must refuse the purchase rather than guess.
	RequestedAt time.Time

	Source string

	// ReservationID, when set, is used as the provider-side commitment
	// identifier (e.g. RDS ReservedDBInstanceId) so purchased commitments
	// carry a descriptive, account/engine/region-aware name instead of a
	// generic auto-generated one. Providers sanitize it to their ID rules.
	ReservationID string

	// IdempotencyToken, when non-empty, is a deterministic token (see
	// DeriveIdempotencyToken) that makes commitment creation idempotent across
	// re-drives of the same execution (issue #636). Savings Plans pass it as
	// the native CreateSavingsPlan ClientToken; EC2 RIs (which have no native
	// token) check for an existing RI tagged with it before purchasing and tag
	// the new RI with it afterwards. Empty means no idempotency guard (the CLI
	// purchase path, which has no owning execution, leaves it empty and keeps
	// its prior non-idempotent behavior).
	IdempotencyToken string

	// ExecutionID, when non-empty, is the purchase_executions row UUID that
	// owns this purchase attempt. Carried so the purchase-execution flow can
	// emit log lines tagged with the execution ID for correlation with the
	// CloudWatch / DB execution row (issue #667). The CLI purchase path has
	// no owning execution and leaves it empty.
	ExecutionID string

	// AttemptJournal, when non-nil, durably records purchase attempts per
	// IdempotencyToken (go#107). Nil means no journal (today's behavior).
	// Only Redshift reads it, honored by providers/aws from the follow-up
	// change onward; other providers ignore it. Used only with a non-empty
	// IdempotencyToken; see AttemptJournal for the caller contract.
	// A journal that also implements the optional ClaimReader lets Redshift
	// skip nodes another purchase recorded, from the follow-up change to
	// providers/aws onward (go#700).
	AttemptJournal AttemptJournal

	// OfferingClass is the EC2 Reserved Instance offering class for this
	// purchase: "convertible" (exchangeable) or "standard" (locked, ~5%
	// cheaper). Empty means the caller has not set one; the EC2 client
	// defaults to "convertible" to preserve pre-694 behavior.
	// Only meaningful for EC2 RI purchases; ignored by other providers.
	OfferingClass string
}

PurchaseOptions carries per-execution metadata threaded through ServiceClient.PurchaseCommitment. Source is the CUDly surface that triggered the purchase (CLI vs web); every provider stamps it onto the commitment it creates (as a tag, label, or — where the cloud API permits nothing else — encoded in the commitment description).

type PurchaseResult

type PurchaseResult struct {
	Timestamp time.Time `json:"timestamp"`
	Error     error     `json:"error,omitempty"`

	// Cost is the total upfront charge for the whole purchase (unit price x count).
	// Nil means unknown; a non-nil zero means no upfront charge. On an adopted
	// re-drive (ExistingCommitment) the original purchase's charge is not known:
	// the AWS RI services (EC2, RDS, ElastiCache, MemoryDB, OpenSearch, Redshift)
	// return nil. GCP Compute Engine reports 0 today and returns nil after a
	// follow-up change for #211. Azure reports 0 for a monthly billing plan and
	// nil for an upfront one, as on a fresh purchase.
	Cost *float64 `json:"cost"`

	CommitmentID string `json:"commitment_id,omitempty"`

	// OfferingClass is, on an adopted re-drive, the offering class AWS reports
	// for the existing commitment; empty otherwise. The EC2 provider sets it in
	// a follow-up change for #211.
	OfferingClass string `json:"offering_class,omitempty"`

	Recommendation Recommendation `json:"recommendation"`
	Success        bool           `json:"success"`
	DryRun         bool           `json:"dry_run"`

	// ExistingCommitment is true when the provider adopted a commitment that
	// already existed for the same idempotency token (a re-drive of an earlier
	// attempt) instead of creating a new one. Success stays true and
	// CommitmentID names the adopted commitment. See Cost for its value on
	// adoption. False on a fresh purchase.
	ExistingCommitment bool `json:"existing_commitment,omitempty"`

	// IdempotencyTagMissing is true when the purchase succeeded but the
	// post-purchase write of its idempotency-token tag failed (EC2, which has
	// no client token). A re-drive with the same token cannot find this
	// commitment and would buy again, so the caller must not repeat the call.
	// Success stays true. False on every other path.
	IdempotencyTagMissing bool `json:"idempotency_tag_missing,omitempty"`
}

PurchaseResult represents the outcome of a commitment purchase.

type RIUtilization

type RIUtilization struct {
	ReservedInstanceID string `json:"reserved_instance_id"`

	// SKUName is the Azure reservation SKU (e.g. "Standard_D2s_v3"). It is
	// empty for AWS RIs because Cost Explorer does not return the instance
	// type on the utilization response. Consumers that need it for Azure
	// can populate downstream display from this field; AWS consumers can
	// join on ReservedInstanceID via the EC2 DescribeReservedInstances API.
	SKUName string `json:"sku_name,omitempty"`

	UtilizationPercent float64 `json:"utilization_percent"`
	PurchasedHours     float64 `json:"purchased_hours"`
	TotalActualHours   float64 `json:"total_actual_hours"`
	UnusedHours        float64 `json:"unused_hours"`
}

RIUtilization holds utilization data for a single Reserved Instance over a lookback period. The struct is defined here (rather than in a provider package) so both AWS and Azure can return the same type and callers can treat either provider's results uniformly without a cross-provider import.

AWS field mapping (Cost Explorer GetReservationUtilization):

ReservedInstanceID  <- dimension key (SUBSCRIPTION_ID group value)
PurchasedHours      <- UtilizationsByTime[].Groups[].Utilization.PurchasedHours
TotalActualHours    <- UtilizationsByTime[].Groups[].Utilization.TotalActualHours
UnusedHours         <- UtilizationsByTime[].Groups[].Utilization.UnusedHours
UtilizationPercent  <- derived: (TotalActualHours / PurchasedHours) * 100

Azure field mapping (Consumption ReservationsSummaries, monthly grain):

ReservedInstanceID  <- Properties.ReservationID
PurchasedHours      <- Properties.ReservedHours  (sum across periods)
TotalActualHours    <- Properties.UsedHours       (sum across periods)
UnusedHours         <- PurchasedHours - TotalActualHours
UtilizationPercent  <- derived: (TotalActualHours / PurchasedHours) * 100
SKUName             <- Properties.SKUName (Azure-only; empty string for AWS)

type Recommendation

type Recommendation struct {
	// Metadata
	Timestamp time.Time `json:"timestamp,omitempty" csv:"Timestamp"`

	// Service-specific details (polymorphic)
	Details ServiceDetails `json:"details,omitempty" csv:"-"`

	// RecurringMonthlyCost is the recurring monthly charge for this commitment
	// (i.e. the part the user pays every month after any upfront payment).
	// nil means the provider API did not return a monthly breakdown — the
	// frontend renders nil as "—" rather than "$0" to avoid misleading users.
	// Populated by cloud parsers when the API exposes it; left nil otherwise.
	RecurringMonthlyCost *float64 `json:"recurring_monthly_cost,omitempty" csv:"RecurringMonthlyCost"`

	// ExistingCoveragePercentExact preserves expiry arithmetic until in-process sizing.
	// Treat it as immutable; clear it when replacing coverage, even with the same percentage.
	// Serialization drops this state and its exact-arithmetic guarantee.
	ExistingCoveragePercentExact *big.Rat `json:"-" csv:"-"`

	// Provider identification
	Provider    ProviderType `json:"provider" csv:"Provider"`
	Account     string       `json:"account" csv:"Account"`
	AccountName string       `json:"account_name" csv:"AccountName"`

	// Service identification
	Service ServiceType `json:"service" csv:"Service"`
	Region  string      `json:"region" csv:"Region"`

	// Resource details
	ResourceType string `json:"resource_type" csv:"ResourceType"` // Instance type, node type, VM size, etc.

	// Commitment details
	CommitmentType CommitmentType `json:"commitment_type" csv:"CommitmentType"` // RI, SP, CUD, etc.
	Term           Term           `json:"term" csv:"Term"`                      // 1yr, 3yr
	PaymentOption  PaymentOption  `json:"payment_option" csv:"PaymentOption"`   // all-upfront, partial, no-upfront, monthly

	// CommitmentCurrency covers CommitmentCost and RecurringMonthlyCost, not savings or baseline.
	// Empty means unknown; presence requires source-proven amounts and currency for every required payment leg.
	CommitmentCurrency string `json:"commitment_currency,omitempty" csv:"CommitmentCurrency"`

	// Metadata
	SourceRecommendation string `json:"source_recommendation,omitempty" csv:"SourceRecommendation"`

	// RawRecommendation holds the original cloud API response bytes for audit/debugging.
	// omitempty ensures nil is absent from JSON (not written as null).
	RawRecommendation json.RawMessage `json:"raw_recommendation,omitempty" csv:"-"`

	// UsageHistory is an ordered slice of daily coverage/utilization
	// percentages (0-100) for the last N days of the lookback window
	// (oldest-to-newest). Populated by cloud collectors that can source the
	// signal from the provider API; nil when not yet wired or when the
	// provider returned no data (frontend renders "—" in that case).
	// Not written to CSV (no column heading — enrichment-only field).
	UsageHistory []float64 `json:"usage_history,omitempty" csv:"-"`

	// CrossAttributions lists the other services whose compute this commitment
	// also covers; Count is instances for Cloud SQL and Memorystore. Empty when none.
	CrossAttributions []CrossAttribution `json:"cross_attributions,omitempty" csv:"-"`

	// Resource details
	Count int `json:"count" csv:"Count"`

	// Cost information. OnDemandCost, EstimatedSavings and SavingsPercentage are
	// USD: providers skip a recommendation whose source reports an explicit
	// non-USD currency; an AWS Cost Explorer detail with no CurrencyCode is
	// accepted as is. CommitmentCurrency covers only the commitment legs.
	//
	// Zero is the default for all four cost fields: a zero is either a known
	// zero (for example a no-upfront CommitmentCost or a 0% saving) or a figure
	// the provider did not return, and the fields alone cannot tell them apart.
	// Priced (below) marks OnDemandCost and EstimatedSavings only; CommitmentCost
	// and SavingsPercentage have no marker. No pointer was adopted because it
	// would break every caller and the JSON/CSV output.
	OnDemandCost      float64 `json:"on_demand_cost" csv:"OnDemandCost"`
	CommitmentCost    float64 `json:"commitment_cost" csv:"CommitmentCost"`
	EstimatedSavings  float64 `json:"estimated_savings" csv:"EstimatedSavings"`
	SavingsPercentage float64 `json:"savings_percentage" csv:"SavingsPercentage"`

	// Break-even in months (populated by cloud parsers where available; used by scorer filter)
	BreakEvenMonths float64 `json:"break_even_months,omitempty" csv:"BreakEvenMonths"`

	// Utilization signals — populated by cloud parsers when the API exposes them.
	// Used by --target-coverage sizing (see cmd/helpers.go: ApplyTargetCoverage).
	// AverageInstancesUsedPerHour is RI-only (zero for SPs and other commitment types).
	// RecommendedUtilization is "what AWS projects for the full recommendation"
	// (%). ProjectedUtilization / ProjectedCoverage are populated by the sizing
	// step after we pick our own quantity.
	// RecommendedCount is AWS's pre-sizing count (mirrors Count before
	// ApplyCoverage / ApplyTargetCoverage mutates Count); zero for SPs since
	// the SP commitment is dollar-denominated rather than count-denominated.
	// ExistingCoveragePct is the share of demand already covered by existing
	// commitments in the same pool (from CE GetReservationCoverage /
	// GetSavingsPlansCoverage). Only meaningful when ExistingCoverageKnown is
	// true; zero with Known=false means CE returned nothing for this pool (or
	// the fetch step wasn't run), and RI target-coverage sizing drops such
	// recs. See cmd/helpers.go.
	AverageInstancesUsedPerHour float64 `json:"average_instances_used_per_hour,omitempty" csv:"AverageInstancesUsedPerHour"`
	RecommendedUtilization      float64 `json:"recommended_utilization,omitempty" csv:"RecommendedUtilization"`
	RecommendedCount            int     `json:"recommended_count,omitempty" csv:"RecommendedCount"`
	ExistingCoveragePct         float64 `json:"existing_coverage_pct,omitempty" csv:"ExistingCoveragePct"`

	ProjectedUtilization float64 `json:"projected_utilization,omitempty" csv:"ProjectedUtilization"`
	ProjectedCoverage    float64 `json:"projected_coverage,omitempty" csv:"ProjectedCoverage"`

	// ExistingCoverageKnown distinguishes "CE returned a value for this
	// pool" (Known=true, Pct possibly 0.0 meaning the pool has running
	// instances but no RI coverage yet) from "CE has no data for this
	// pool" (Known=false, Pct=0.0 by default). Set by
	// ApplyCoverageMapToRecommendations whenever a pool lookup hits, and
	// by family-NU sizing when a family-level existing% lands on the rec.
	// CSV writers use this to render "n/a" for unknown vs "0.0" for
	// genuine zero-coverage pools. RI --target-coverage sizing drops recs
	// with Known=false and positive average demand (target-coverage-unknown).
	ExistingCoverageKnown bool `json:"existing_coverage_known,omitempty" csv:"-"`

	// Priced is true only when the parser got OnDemandCost and EstimatedSavings
	// from the provider source, so a reported 0 is distinguishable from an
	// absent figure (go#326). False means unknown, not zero; parsers that have
	// not been audited leave it unset.
	Priced bool `json:"priced,omitempty" csv:"-"`
}

Recommendation represents a commitment purchase recommendation across any cloud provider.

func ResizeCount

func ResizeCount(rec Recommendation, newCount int) (Recommendation, error)

ResizeCount returns rec sized to newCount with every money field scaled by newCount/rec.Count (see ScaleRecommendationCosts for what scales). Use it wherever a filter shrinks a recommendation's count, so Count and cost cannot drift apart.

It fails loud rather than inventing a per-unit cost: rec.Count must be positive, and newCount must be in [1, rec.Count]. Growing a count is the sizing paths' job (they derive the target from demand) and dropping to zero is the caller's drop decision, so neither is accepted here.

func ScaleRecommendationCosts

func ScaleRecommendationCosts(rec Recommendation, ratio float64) Recommendation

ScaleRecommendationCosts multiplies every extensive (whole-row) money field of rec by ratio and returns the result. Used by sizing paths (ApplyCoverage, ApplyTargetCoverage, ApplyInstanceLimit, family-NU) to keep Count and cost in sync when a recommendation is sized down (or up) from AWS's proposal. Without this helper the same scaling pattern was duplicated at every sizing site, and #1830 was a sizing site that forgot it entirely.

Extensive MONEY fields scale here; intensive ones deliberately do not. SavingsPercentage and BreakEvenMonths are ratios of two figures that scale together, so they are invariant. RecommendedCount is a frozen record of the provider's pre-sizing proposal. AverageInstancesUsedPerHour and UsageHistory describe observed demand, which does not change with what we choose to buy.

Two count-linear NON-money fields are deliberately out of scope here and are the caller's problem: ProjectedCoverage / ProjectedUtilization (recomputed from the chosen quantity by the target-coverage callers, which is why scaling them here would be wrong) and DataWarehouseDetails.NumberOfNodes (a Redshift count mirror set at parse time). Neither is re-derived by ApplyInstanceLimit, so a capped run can still report a projection sized for the pre-cap count. Tracked by #1845; purchases read Count, not these.

Pointer and pointed-to state is copied rather than mutated: callers hold the pre-sizing slice (the reporter diffs against it), so writing through a shared pointer would corrupt their copy.

  • RecurringMonthlyCost is allocated as a new pointer when present. A nil stays nil: nil means "the provider returned no monthly breakdown" and renders as "—", which is not the same claim as $0.
  • SavingsPlanDetails.HourlyCommitment is the SP's own money quantity (an SP commitment is dollar-denominated, not count-denominated), so it scales with the rest. Details is replaced with a scaled copy. A rec whose Details is any other type is left alone.

func (*Recommendation) UnmarshalJSON

func (r *Recommendation) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes details into the typed pointer for the recommendation's service (DecodeServiceDetailsFor), so a Recommendation, and a PurchaseResult carrying one, round-trips through JSON. encoding/json cannot decode an object into the ServiceDetails interface on its own. As with encoding/json, absent details leave Details unchanged and null sets it nil.

type RecommendationParams

type RecommendationParams struct {
	Service        ServiceType
	Region         string
	LookbackPeriod string // 7d, 30d, 60d
	Term           string // 1yr, 3yr
	PaymentOption  string

	// SPAccountScope selects the Cost Explorer account scope for Savings Plans
	// recommendations: "linked" or "payer" (case-insensitive). Empty means
	// linked. Payer scope only applies to a management account.
	SPAccountScope string

	// RIAccountScope selects the Cost Explorer account scope for Reserved
	// Instance recommendations, with the same values as SPAccountScope:
	// "linked" or "payer" (case-insensitive). Empty means linked.
	RIAccountScope string

	AccountFilter  []string
	IncludeRegions []string
	ExcludeRegions []string

	// Savings Plans specific filters
	IncludeSPTypes []string // Compute, EC2Instance, SageMaker, Database
	ExcludeSPTypes []string

	// ExperimentalGCPPlanTerm (GCP Compute Engine only, ignored elsewhere)
	// takes the CUD term from the recommendation's root Commitment plan
	// instead of Term. EXPERIMENTAL: the payload shape is unverified against a
	// live Recommender. Default false keeps Term, defaulting to "1yr".
	ExperimentalGCPPlanTerm bool
}

RecommendationParams represents parameters for fetching recommendations.

type ReconcileRequest

type ReconcileRequest struct {
	// AttemptEndedAt is when that attempt returned ErrOutcomeUnknown. Required: it closes the match window.
	AttemptEndedAt time.Time
	// Options are the PurchaseOptions of the attempt that returned ErrOutcomeUnknown. RequestedAt (the
	// lineage's first dispatch) is required; IdempotencyToken and OfferingClass are used when set.
	Options        PurchaseOptions
	Recommendation Recommendation
}

ReconcileRequest describes a purchase attempt that returned ErrOutcomeUnknown.

type ReconcileResult

type ReconcileResult struct {
	Verdict      ReconcileVerdict
	CommitmentID string   // set only with ReconcileFound
	Reason       string   // Unknown only: why, one fixed phrase per branch
	Criteria     []string // fields that matched, e.g. "instance-type", "count", "start-window"
	CandidateIDs []string // Unknown only: commitments that kept the answer open (operator checks these)
	Tagged       bool     // Found carried the request's idempotency token tag (EC2 only)
}

ReconcileResult is the read-only answer to "did that purchase land?".

func (ReconcileResult) IsFound

func (r ReconcileResult) IsFound() bool

IsFound is true only for a Found verdict that names a commitment.

type ReconcileVerdict

type ReconcileVerdict string

ReconcileVerdict is the outcome of ReconcilePurchase. There is deliberately no NotFound value: a lookup can never prove a purchase did not happen (describe lag, clock drift, modified or split commitments), so "nothing found" is Unknown. The zero value is not Found.

const (
	ReconcileUnknown ReconcileVerdict = "unknown"
	ReconcileFound   ReconcileVerdict = "found"
)

type Region

type Region struct {
	Provider    ProviderType `json:"provider"`
	ID          string       `json:"id"`
	Name        string       `json:"name"`
	DisplayName string       `json:"display_name"`
}

Region represents a cloud region/location.

type ReservationNameFields

type ReservationNameFields struct {
	// Now is the timestamp baseline. Must be non-zero for production calls.
	// Tests inject a fixed value for determinism.
	Now time.Time

	// Service is the short identifier for the AWS service, e.g. "rds",
	// "cache", "memdb", "opensearch", "redshift". Set per-call by the
	// service client; the builder treats it as opaque and sanitizes it.
	Service string

	// Region is the AWS region string (e.g. "us-east-1", "eu-west-1").
	Region string

	// ResourceType is the AWS instance/node type (e.g. "db.t4g.medium",
	// "m5.large"). Dots are converted to hyphens by SanitizeReservationID.
	ResourceType string

	// Term is the commitment term, normalized to "1yr" / "3yr" by upstream
	// recommendation parsers. The builder collapses it to "1yr"/"3yr" when
	// possible, and sanitizes otherwise.
	Term string

	// Payment is the payment-option string from the recommendation
	// ("all-upfront", "no-upfront", "partial-upfront"). The builder
	// normalizes to a short form ("allup", "noup", "partup") so the
	// segment stays under 8 chars.
	Payment string

	// Count is the reservation quantity. Always rendered as "{N}x".
	Count int
	// contains filtered or unexported fields
}

ReservationNameFields carries the inputs needed by BuildReservationName.

Now and randSource are exposed so tests can pin time and randomness for deterministic assertions. Production callers leave randSource nil (the builder then uses crypto/rand) and pass time.Now().

func (ReservationNameFields) WithRandSource

func (f ReservationNameFields) WithRandSource(b []byte) ReservationNameFields

WithRandSource returns a copy of f with the given bytes used as the random suffix source (test hook). Production code does not call this.

type SavingsPlanDetails

type SavingsPlanDetails struct {
	PlanType string `json:"plan_type"` // Compute, EC2Instance, SageMaker

	// Currency is the ISO 4217 code HourlyCommitment is denominated in. Azure
	// requires it to match the billing account currency and fails closed when
	// it is empty or malformed; empty is never treated as USD.
	Currency string `json:"currency,omitempty"`

	// Deprecated: never populated; it once held the savings percentage, which is
	// Recommendation.SavingsPercentage. Kept so stored rows still decode.
	Coverage string `json:"coverage,omitempty"`

	// InstanceFamily is the EC2 instance family recommended by Cost Explorer
	// (e.g. "m5"). Only populated for EC2Instance Savings Plans; empty for
	// Compute, SageMaker and Database plans which are family-agnostic. Used at
	// purchase time to add an instanceFamily filter to DescribeSavingsPlansOfferings
	// so the offering resolves to the correct family rather than the
	// lexicographically-smallest across all families in the region.
	InstanceFamily string `json:"instance_family,omitempty"`

	// Region is the AWS region recommended by Cost Explorer for this EC2Instance
	// Savings Plan (e.g. "us-east-1"). Only populated for EC2Instance plans;
	// Compute, SageMaker and Database plans are global and carry no region.
	// Used at purchase time as the region filter for DescribeSavingsPlansOfferings
	// instead of the client's configured region, which may differ.
	Region string `json:"region,omitempty"`

	// OfferingID is the exact Savings Plans offering ID returned by Cost Explorer
	// in SavingsPlansDetails.OfferingId. When non-empty the purchase path uses it
	// directly and skips DescribeSavingsPlansOfferings entirely, which is the
	// safest possible resolution. Only populated when CE provides it.
	OfferingID string `json:"offering_id,omitempty"`

	HourlyCommitment float64 `json:"hourly_commitment"`
}

SavingsPlanDetails represents AWS Savings Plans specific details.

func (SavingsPlanDetails) GetDetailDescription

func (d SavingsPlanDetails) GetDetailDescription() string

func (SavingsPlanDetails) GetServiceType

func (d SavingsPlanDetails) GetServiceType() ServiceType

type SearchDetails

type SearchDetails struct {
	InstanceType    string `json:"instance_type"`
	MasterNodeType  string `json:"master_node_type,omitempty"`
	MasterNodeCount int    `json:"master_node_count,omitempty"`
}

SearchDetails represents search-specific details (OpenSearch, Azure Search).

func (SearchDetails) GetDetailDescription

func (d SearchDetails) GetDetailDescription() string

func (SearchDetails) GetServiceType

func (d SearchDetails) GetServiceType() ServiceType

type ServiceDetails

type ServiceDetails interface {
	GetServiceType() ServiceType
	GetDetailDescription() string
}

ServiceDetails is an interface for service-specific details.

func DecodeServiceDetailsFor

func DecodeServiceDetailsFor(service string, raw json.RawMessage) (ServiceDetails, error)

DecodeServiceDetailsFor reconstructs a typed *Details pointer from a raw JSON payload, dispatched by the service string from RecommendationRecord. Service accepts the same strings persisted by the scheduler's converter (e.g. "ec2", "rds", "elasticache", "opensearch", "redshift", "memorydb", "savingsplans", "savings-plans-compute" and the dash-free spellings — see internal/purchase/execution.go: mapServiceType / mapSavingsPlansSlug).

Behavior:

  • raw is empty AND service maps to a known *Details type → returns a zero-valued typed pointer (the legacy / pre-#453 fallback). The downstream service client's type-assertion succeeds; the EC2 client rejects empty Platform / Tenancy / Scope rather than defaulting them.
  • raw is empty or JSON null AND service maps to no *Details type → returns (nil, nil) so callers fall through to their existing nil-details paths.
  • raw is non-empty → unmarshals into the typed pointer for the service. Unmarshal errors surface as errors (don't fall back silently — that's how #453's mis-purchases hid for a release).
  • raw is non-empty AND service maps to no *Details type (including an unknown or misspelled slug) → returns an error naming the service. Silently dropping the payload would hand the purchase path nil details and let it proceed on defaults (issue #123, A09-018).

type ServiceType

type ServiceType string

ServiceType identifies the service type across clouds.

const (
	// Compute.
	ServiceCompute ServiceType = "compute" // EC2, VM, Compute Engine

	// Database.
	ServiceRelationalDB ServiceType = "relational-db" // RDS, Azure SQL, Cloud SQL
	ServiceNoSQL        ServiceType = "nosql"         // DynamoDB, CosmosDB, Firestore

	// Cache.
	ServiceCache ServiceType = "cache" // ElastiCache, Azure Cache, Memorystore

	// Search.
	ServiceSearch ServiceType = "search" // OpenSearch, Azure Search

	// Data Warehouse.
	ServiceDataWarehouse ServiceType = "data-warehouse" // Redshift, Synapse, BigQuery

	// Storage.
	ServiceStorage ServiceType = "storage" // S3, Blob Storage, Cloud Storage

	// Savings/Commitments
	//
	// ServiceSavingsPlansAll is the umbrella sentinel for all AWS Savings Plans.
	// Its string value "savingsplans" (no hyphen) matches the frontend identifier
	// and the value persisted in service_configs.service / purchase_history.service
	// so that direct comparisons work without a normaliser. See issue #85 for the
	// rationale (frontend chosen as canonical to avoid a SQL data migration).
	//
	// This is NOT a per-plan-type slug. The four granular forms are:
	//   ServiceSavingsPlansCompute, ServiceSavingsPlansEC2Instance,
	//   ServiceSavingsPlansSageMaker, ServiceSavingsPlansDatabase.
	// Use SavingsPlansPlanTypes() to iterate over them in canonical order.
	//
	// Code that needs to recognize pre-#85 persisted "savings-plans" rows
	// (e.g. purchase_executions JSONB blobs) goes through the mapper in
	// internal/purchase/execution.go.
	ServiceSavingsPlansAll ServiceType = "savingsplans" // umbrella sentinel for "any SP"

	// Per-plan-type Savings Plans slugs. Each maps 1:1 to an AWS
	// types.SupportedSavingsPlansType so users can configure term/payment
	// defaults independently per plan type. These were introduced after the
	// umbrella was normalised; the dash-form slugs intentionally differ from
	// the umbrella's "savingsplans" so a generic-vs-specific comparison is
	// unambiguous (use IsSavingsPlan to recognize the family).
	ServiceSavingsPlansCompute     ServiceType = "savings-plans-compute"     // ComputeSp: EC2, Fargate, Lambda
	ServiceSavingsPlansEC2Instance ServiceType = "savings-plans-ec2instance" // Ec2InstanceSp: specific EC2 families
	ServiceSavingsPlansSageMaker   ServiceType = "savings-plans-sagemaker"   // SagemakerSp
	ServiceSavingsPlansDatabase    ServiceType = "savings-plans-database"    // DatabaseSp: RDS
	ServiceCommitments             ServiceType = "commitments"               // Generic commitments

	// Other.
	ServiceOther ServiceType = "other" // Catch-all for unclassified services

	// Legacy AWS service types (for backward compatibility).
	ServiceEC2         ServiceType = "ec2"
	ServiceRDS         ServiceType = "rds"
	ServiceElastiCache ServiceType = "elasticache"
	ServiceOpenSearch  ServiceType = "opensearch"
	// ServiceElasticsearch is a typed alias of ServiceOpenSearch — a future
	// const declared with the same string value but different intent will
	// now produce a compile error rather than silently equal.
	ServiceElasticsearch             = ServiceOpenSearch
	ServiceRedshift      ServiceType = "redshift"
	ServiceMemoryDB      ServiceType = "memorydb"
)

func NormalizeSavingsPlansServiceType

func NormalizeSavingsPlansServiceType(s ServiceType) (ServiceType, bool)

NormalizeSavingsPlansServiceType maps s to its canonical Savings Plans slug. Canonical slugs return themselves; known legacy spellings return the canonical slug they stand for. Anything else, including non-Savings-Plans services and differently cased input, returns ("", false) so callers fail loudly instead of defaulting.

func SavingsPlansPlanTypes

func SavingsPlansPlanTypes() []ServiceType

SavingsPlansPlanTypes returns the four per-plan-type SP slugs in canonical iteration order (Compute -> EC2Instance -> SageMaker -> Database). Use this for any fan-out over "all SP plan types"; it makes the 4-way expansion visible at the call site instead of relying on the umbrella sentinel (ServiceSavingsPlansAll) to expand implicitly inside the rec collector.

func (ServiceType) String

func (s ServiceType) String() string

String returns the string representation of the service type.

type Term

type Term string

Term is the commitment duration of a purchase action.

const (
	Term1Year Term = "1yr"
	Term3Year Term = "3yr"
)

func ParseTerm

func ParseTerm(s string) (Term, error)

ParseTerm converts s into a Term, returning a descriptive error when s is not a recognized value.

func ParseTermSpelling

func ParseTermSpelling[S ~string](s S, accept TermSpelling) (Term, bool)

ParseTermSpelling maps s to a Term when s is one of the spellings selected by accept, and reports false otherwise.

func (Term) Months

func (t Term) Months() int

Months returns the term length in months, or 0 for an unrecognized Term.

func (Term) Validate

func (t Term) Validate() error

Validate returns an error when t is not a recognized Term.

func (Term) Years

func (t Term) Years() int

Years returns the term length in years, or 0 for an unrecognized Term.

type TermSpelling

type TermSpelling uint8

TermSpelling selects which spellings of a term a caller accepts. Each caller keeps its own accepted set; the spellings and their meaning live here so they cannot drift apart.

const (
	// SpellCanonical accepts "1yr" and "3yr".
	SpellCanonical TermSpelling = 1 << iota
	// SpellBareYears accepts "1" and "3".
	SpellBareYears
	// SpellShortYears accepts "1y" and "3y".
	SpellShortYears
	// SpellMonths accepts "12mo" and "36mo".
	SpellMonths
	// SpellEmptyIsOneYear maps the empty string to Term1Year.
	SpellEmptyIsOneYear
	// SpellBareMonths accepts "12" and "36".
	SpellBareMonths
	// SpellISO accepts the ISO-8601 durations "P1Y" and "P3Y". Matching is
	// case-sensitive unless SpellFold is also set.
	SpellISO
	// SpellFold trims surrounding whitespace and lower-cases before matching.
	SpellFold
)

Jump to

Keyboard shortcuts

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