Documentation
¶
Overview ¶
Package purchase handles the purchase workflow including approvals and execution.
Index ¶
- Constants
- Variables
- func BuildScheduledNoticeData(dashboardURL string, execution *config.PurchaseExecution, ...) email.NotificationData
- func CheckStepCommitmentCap(plan *config.PurchasePlan, recs []config.RecommendationRecord) error
- func ErrCategoryMessage(category string) string
- func IsCommittedPartialRun(row *config.PurchaseExecution, err error) bool
- func IsDefiniteAWSRefusal(recs []config.RecommendationRecord, stored string) bool
- func IsOrphanedPlanStep(exec *config.PurchaseExecution) bool
- func IsRedshiftExecution(exec *config.PurchaseExecution) bool
- func NeverSubmitted(exec *config.PurchaseExecution) bool
- func OrphanExecutionError(execution *config.PurchaseExecution) error
- func ParseReapAfterFromEnv() time.Duration
- func PrefetchLadderVisibility(ctx context.Context, store interface{ ... }, ...) prefetchedVisibility
- func RedriveRefusalReason(exec *config.PurchaseExecution) string
- func RedshiftRetryPermanentRefusal(exec *config.PurchaseExecution, sinceStamp *time.Duration) string
- func RedshiftRetryWait(exec *config.PurchaseExecution, sinceUpdate time.Duration) time.Duration
- func ResolveOpsHint(failureReason string) string
- func RetryRefusalReason(exec *config.PurchaseExecution) string
- func SanitizeStoredError(s string) string
- func SendLadderNotice(ctx context.Context, n ScheduledNotifier, globalCfg *config.GlobalConfig, ...) error
- func SendScheduledNotice(ctx context.Context, n ScheduledNotifier, globalCfg *config.GlobalConfig, ...) error
- func ServerNoteMessage(err error) (string, bool)
- func SingleCloudAccountIDFromRecs(recs []config.RecommendationRecord) (*string, error)
- func StepCapApplies(plan *config.PurchasePlan) bool
- func SummarizeFailure(err error) (category, message string)
- func SummarizeProviderError(err error) (category, message string)
- func ValidateApprovalToken(execution *config.PurchaseExecution, token string) error
- type AttemptJournal
- type ClaimedRowCheck
- type CommitmentVisibility
- type FinalizeResult
- type FireResult
- type LadderBuildInput
- type LadderFireDeps
- type LadderFireResult
- type LadderFireStore
- type LadderInstrumentBuilder
- type LadderInstrumentRegistry
- type LadderNoticeFacts
- type LadderRIDescriberFactory
- type LadderRIPricerFactory
- type LadderReconcileDeps
- type LadderReconcileResult
- type LadderReconcileRunStore
- type LadderReconcileStore
- type LadderSPDescriberFactory
- type LadderUnresolved
- type Manager
- func (m *Manager) ApproveAndExecute(ctx context.Context, executionID, actor string, transitionedBy *string, ...) (*config.PurchaseExecution, string, error)
- func (m *Manager) ApproveExecution(ctx context.Context, executionID, token, actor string, check ClaimedRowCheck) (*config.PurchaseExecution, string, error)
- func (m *Manager) AttachResolvedRecommendations(ctx context.Context, exec *config.PurchaseExecution, ...) (bool, error)
- func (m *Manager) CancelExecution(ctx context.Context, executionID, token, actor string) error
- func (m *Manager) DirectExecute(ctx context.Context, executionID, actor string, transitionedBy *string, ...) (*config.PurchaseExecution, string, error)
- func (m *Manager) FinalizeInFlightRevocations(ctx context.Context) (*FinalizeResult, error)
- func (m *Manager) FireScheduledDelayedPurchases(ctx context.Context) (*FireResult, error)
- func (m *Manager) LadderRIDescriber(ctx context.Context, cloudAccountID, region string) (RIDescriber, error)
- func (m *Manager) LadderRIPricer(ctx context.Context, cloudAccountID, region string) (RIOfferingPricer, error)
- func (m *Manager) LadderSPDescriber(ctx context.Context, cloudAccountID, region string) (SPDescriber, error)
- func (m *Manager) ProcessScheduledPurchases(ctx context.Context) (*ProcessResult, error)
- func (m *Manager) ReapStuckExecutions(ctx context.Context, reapAfter time.Duration) (*ReapResult, error)
- func (m *Manager) RecoverStrandedApprovals(ctx context.Context) (int, error)
- func (m *Manager) RunPlannedPurchaseNow(ctx context.Context, executionID, actor string, transitionedBy *string, ...) (*config.PurchaseExecution, string, error)
- func (m *Manager) SendUpcomingPurchaseNotifications(ctx context.Context) (*NotificationResult, error)
- func (m *Manager) SetRecommendationSource(src planstep.Source)
- type ManagerConfig
- type NotificationResult
- type ProcessResult
- type RIDescriber
- type RIOfferingPricer
- type RIUnit
- type ReapResult
- type SPDescriber
- type STSClient
- type ScheduledNotifier
Constants ¶
const ( ErrCategoryAccessDenied = "access_denied" ErrCategoryLimit = "limit_reached" ErrCategoryUnknown = "unknown" )
Closed set of purchase failure categories shown to users in place of the provider's own error text, which carries ARNs, account IDs and request IDs.
const DefaultMaxDueRowAge = 24 * time.Hour
DefaultMaxDueRowAge is how long after its due time the fire and process sweeps may still buy a row when ManagerConfig.MaxDueRowAge is unset. It matches config.LadderFireGrace, the same limit the ladder already applies to its own scheduled tranches.
const DefaultReapAfter = 10 * time.Minute
DefaultReapAfter is the default age at which a running execution is considered stuck (approved rows use approvedReapAfter). The issue (#678) calls for "configurable via env var, default 10m" — the threshold is intentionally conservative: the happy-path executor completes in <60s; the longest legitimately-slow paths (multi-account fan-out, provider rate-limit backoff) settle in <3min. 10 minutes leaves multiple multiples of headroom so the reaper never fights a real executor.
const LadderFiredStaleAfter = 6 * time.Hour
LadderFiredStaleAfter is how long a fired tranche may stay unresolved before the reconciler logs an alert for it. It never changes the tranche: an unresolved fired tranche keeps netting, so the ladder cannot over-buy.
const PlanGoneRefusal = "" /* 129-byte string literal not displayed */
PlanGoneRefusal is the text recorded on, and returned for, a plan step whose plan is gone.
const PurchaseFailedLogMarker = "purchase_execution_failed"
PurchaseFailedLogMarker is the stable token logged once for every execution row that ends "failed" or "partially_completed" (issue #714). The per-cloud monitoring modules (terraform/modules/monitoring/{aws,gcp,azure}) turn it into a log-based metric and alert on any occurrence, so the token is a contract with Terraform: rename it only together with those filters (TestMonitoringLogMarkersMatchGo guards the pairing).
Variables ¶
var ( ErrInvalidApprovalToken = errors.New("invalid approval token") ErrApprovalTokenExpired = errors.New("approval token has expired") )
ErrInvalidApprovalToken and ErrApprovalTokenExpired let the HTTP layer map a bad email-link token to a 4xx instead of a 500.
var ErrClaimedRowRefused = errors.New("purchase refused after claim: the claimed execution no longer passes the authorization checks")
ErrClaimedRowRefused marks a run refused by the caller's ClaimedRowCheck after the claim was won and before any provider call (issue #415). The row ends "failed" with no_submission stamped; the check's own error is wrapped alongside it so callers can still map it (for example to a 403).
var ErrDueRowTooOld = errors.New("scheduled purchase skipped: it was due too long ago")
ErrDueRowTooOld marks a row the fire or process sweep refused because it was due more than the due-row age cap ago (issue #712). The first tick after a sweep is enabled (the fire sweep by default since #712, the process sweep on opt-in) can find a long backlog of overdue rows whose recommendations and prices are stale; buying them all at once is the outcome this cap prevents. The row ends failed with no_submission set, so it can be retried deliberately from History.
var ErrFourEyesDenied = errors.New("approval declined")
ErrFourEyesDenied wraps every refusal by the 4-eyes approval policy, as opposed to a failure to evaluate it (config or store errors).
var ErrNoExecutionID = errors.New("purchase: scheduled notice needs an execution ID")
ErrNoExecutionID is returned by SendScheduledNotice for an execution without an ID.
var ErrNoScheduledNotifier = errors.New("purchase: no scheduled notifier configured")
ErrNoScheduledNotifier is returned by SendScheduledNotice when no notifier is configured.
var ErrPlanStepNoRecommendations = errors.New("plan step has no recommendations attached, so it cannot buy anything")
ErrPlanStepNoRecommendations marks a plan-step execution that carries no recommendations. Nothing attaches recommendations to a plan step yet (platform#609), so such a step can only "succeed" by buying nothing, which would complete it and advance the ramp. It is refused instead. The text is user-facing, so it names no internal issue (tracked in platform#631); rows stored before that carry a "(platform#631: ...)" suffix, which errnotes.go still recognizes.
var ErrRecOutsideBoundGroups = fmt.Errorf("%w: recommendation is outside every bound group", ErrStepCommitmentCap)
ErrRecOutsideBoundGroups marks a bound plan step (issue #1746) holding a recommendation that no group bound. It wraps ErrStepCommitmentCap, so every cap site refuses it the same way.
var ErrStaleAzurePricing = errors.New("stale Azure recommendation pricing; refresh recommendations and submit a new purchase")
var ErrStepCommitmentCap = errors.New("plan step refused by commitment cap")
ErrStepCommitmentCap marks a plan step refused by the per-plan spend cap.
Functions ¶
func BuildScheduledNoticeData ¶
func BuildScheduledNoticeData(dashboardURL string, execution *config.PurchaseExecution, globalCfg *config.GlobalConfig, actor string) email.NotificationData
BuildScheduledNoticeData constructs the email.NotificationData from the execution and global config.
func CheckStepCommitmentCap ¶
func CheckStepCommitmentCap(plan *config.PurchasePlan, recs []config.RecommendationRecord) error
CheckStepCommitmentCap refuses a plan step's recommendations unless the plan carries a cap and the step's TOTAL commitment (upfront + monthly * term * 12, see RecommendationRecord.TotalCommitment) fits under it. It fails closed:
- a nil plan, a plan without MaxStepCommitment (nil or <= 0), or a non-finite cap refuses everything;
- a recommendation with a zero, negative or non-finite total commitment is refused (Azure monthly commitments have upfront 0, so upfront alone would pass anything);
- a recommendation whose CommitmentCurrency is not provably USD, other or empty (unknown), is refused: the cap is USD and nothing converts;
- no recommendations is not a step that can buy, so it is not this check's concern and returns nil (the no-recommendations refusal owns it).
It only ever refuses; nothing here buys.
func ErrCategoryMessage ¶
ErrCategoryMessage returns the fixed user message for a category.
func IsCommittedPartialRun ¶
func IsCommittedPartialRun(row *config.PurchaseExecution, err error) bool
IsCommittedPartialRun reports whether an execute call that returned row and err ended partially_completed with that status saved: some commitments were bought, so the run is revocable and its executed email must go out like a completed run's (issue #532). An audit loss is excluded: the stored row is still "running", whatever the returned row says.
func IsDefiniteAWSRefusal ¶
func IsDefiniteAWSRefusal(recs []config.RecommendationRecord, stored string) bool
IsDefiniteAWSRefusal reports whether a stored error proves nothing was bought: every rec is AWS and every "; "-separated segment is an AWS 4xx with a listed pre-send code from a single-attempt purchase call. Azure, GCP, 5xx, a missing code or a server note anywhere means the outcome is not proven, so the answer is false.
func IsOrphanedPlanStep ¶
func IsOrphanedPlanStep(exec *config.PurchaseExecution) bool
IsOrphanedPlanStep reports a plan step whose plan is gone (#1048). purchase_executions.plan_id is ON DELETE SET NULL, so a deleted plan leaves its rows plan-less with nothing naming the plan. The one stored marker that survives is step_number: plan creation and the step sweep always write the 1-based step (>= 1, migration 000098), while a direct-execute, retry of one, or ladder row has no step and stores 0 (see persistRetryExecution: "for ad-hoc executions PlanID is "" and StepNumber is 0"). The DB default of 1 never applies because the store writes the field explicitly. Only stored fields are read: the approve paths stamp ExecutedByUserID and PreApprovalSkipReason on the claimed row in memory before the executor runs, so those prove nothing. A retry successor copies PlanID and StepNumber, so it stays refused too.
Legacy risk: an ad-hoc row stored with step_number >= 1 before the store wrote the field explicitly would be refused, and a step-0 orphan from before migration 000098 is not recognized.
func IsRedshiftExecution ¶
func IsRedshiftExecution(exec *config.PurchaseExecution) bool
IsRedshiftExecution reports whether exec has a selected Redshift recommendation.
func NeverSubmitted ¶
func NeverSubmitted(exec *config.PurchaseExecution) bool
NeverSubmitted reports a first-attempt row proven to have sent nothing.
func OrphanExecutionError ¶
func OrphanExecutionError(execution *config.PurchaseExecution) error
OrphanExecutionError returns a descriptive error when the execution has no resolvable CloudAccountID and the provider is explicitly non-AWS (issue #609). AWS executions with a nil CloudAccountID are passed through because the ambient-host-account fallback from PR #607/#604 handles them. Empty provider is treated as AWS (legacy rows pre-dating multi-cloud support).
An execution is NOT considered orphan if any individual recommendation carries its own non-nil CloudAccountID — multi-rec fan-out executions can have a nil execution-level field while individual recs still name the target account.
Exported so the HTTP layer (internal/api) can call the same guard without duplicating the predicate. Extracted from ApproveExecution to keep that function below the gocyclo threshold — same pattern as loadCancelableExecution.
func ParseReapAfterFromEnv ¶
ParseReapAfterFromEnv reads PURCHASE_APPROVED_REAP_AFTER from the environment and parses it via time.ParseDuration. Falls back to DefaultReapAfter on either an absent env var, a parse failure, or a non-positive duration (0s / negative) — each variant logs a WARN so ops can spot a typo without the reaper silently running at the default. Never panics: a misconfigured env var must not crash the Lambda's other scheduled tasks.
Non-positive values are explicitly rejected: time.ParseDuration accepts "0s" and "-5m" as valid, but feeding them into ListStuckExecutions would either match every row (0s) or invert the SELECT into "updated_at < NOW() + |d|" (negative) and reap fresh executions. The store has its own guard (defense-in-depth) but rejecting here keeps the misconfig visible in the WARN log rather than as a confusing store error.
func PrefetchLadderVisibility ¶
func PrefetchLadderVisibility(ctx context.Context, store interface { GetExecutionByID(ctx context.Context, id string) (*config.PurchaseExecution, error) }, spFactory LadderSPDescriberFactory, riFactory LadderRIDescriberFactory, fired []config.LadderTrancheDB) prefetchedVisibility
PrefetchLadderVisibility resolves, outside any transaction, whether the commitments of each fired tranche's completed execution are visible. It makes no provider call when nothing is fired or no execution has completed. Any lookup or API error is recorded against the affected executions and logged; nothing is ever reported visible on an error.
func RedriveRefusalReason ¶
func RedriveRefusalReason(exec *config.PurchaseExecution) string
RedriveRefusalReason returns a short operator-facing reason why exec must not be re-driven, or "" when every recommendation on it carries a provider-side guarantee that a second attempt collapses onto the first.
This is the single source of truth for re-drive safety. Both the reaper's automatic in-place re-drive (via allRecsSafeToRedrive) and the user-facing Retry endpoint (Handler.checkRetryEligibilityGates in internal/api) gate on it, so a provider/service that is unsafe for one is unsafe for the other. Before issue #1668 only the reaper consulted it, and clicking Retry on a landed Azure savings-plans row bought a second savings plan, which cannot be canceled.
Safe providers / services (issue #639):
- AWS RDS, ElastiCache, MemoryDB, OpenSearch and Savings Plans: a deterministic reservation ID or ClientToken collapses a repeat onto the first attempt (#636/#638).
- AWS Redshift: the Retry gate (checkRedshiftRetryGate) and the dispatch gate (stampRedshiftDispatch) reuse the first attempt's request time, so go's dedupe adopts a node already bought; both refuse when that cannot be proven.
- Azure reservations (compute, relational-db, cache, nosql, memorydb, search, data-warehouse): DoIdempotentPurchaseTwoStep performs a tag-based lookup before purchasing (#729 / #721).
- GCP compute (CUDs): server-side RequestId + deterministic name from the token (#654).
NOT safe:
- AWS EC2 (slugs ec2, compute): the purchase API takes no client token, so a lost response may have bought the commitment and a second attempt would buy another (MON-02). The provider sends the call once and reports "purchase outcome unknown".
- Azure savings-plans: the pinned client names the order alias after the idempotency token when one is set (a timestamp name only on the empty-token CLI path), but no test or provider doc here confirms that a repeat PUT of the same alias collapses onto the first order, and there is no tag-based lookup. Until that is verified, a re-drive is treated as able to buy a duplicate savings plan. The refusal covers exactly the slugs that dispatch to the Azure savings-plans client (pinned by TestRedriveGuardReachMatchesDispatchReach).
- Any provider this function does not recognize, rather than assuming a guard exists.
Empty provider ("") is treated as AWS (pre-multi-cloud legacy rows).
It answers exactly one question: could re-driving these recommendations buy something twice. An execution with no recommendations buys nothing, so it has no duplicate risk and gets no refusal here. Callers that need "there is nothing worth re-driving" must say so themselves, as allRecsSafeToRedrive does above.
The reason is rendered verbatim to the operator, so it explains the refusal in product terms rather than naming internals.
func RedshiftRetryPermanentRefusal ¶
func RedshiftRetryPermanentRefusal(exec *config.PurchaseExecution, sinceStamp *time.Duration) string
RedshiftRetryPermanentRefusal returns the reason a failed Redshift execution can never be retried, or "". sinceStamp is the age of its first dispatch on the database clock, nil when the row has no stamp.
func RedshiftRetryWait ¶
RedshiftRetryWait returns how much longer a Retry must wait for sinceUpdate (age of the row's last write on the database clock) to reach the settle time.
func ResolveOpsHint ¶
ResolveOpsHint returns a non-empty hint when the failure reason matches a known-persistent pattern, else empty. Match is case- insensitive substring contains so backend wording variations don't silently slip through ("ses sandbox" / "SES sandbox" / "SES Sandbox" all hit).
func RetryRefusalReason ¶
func RetryRefusalReason(exec *config.PurchaseExecution) string
RetryRefusalReason is RedriveRefusalReason for the user-facing Retry of a failed row. A row proven to have sent nothing (no_submission at attempt 0) cannot have bought anything, so the no-duplicate-guard refusals do not apply.
func SanitizeStoredError ¶
SanitizeStoredError turns a stored error string into text safe to show: it passes through only when every item is an allowlisted server note, and otherwise the whole remainder becomes one category message. The partial-run prefix is kept.
func SendLadderNotice ¶
func SendLadderNotice(ctx context.Context, n ScheduledNotifier, globalCfg *config.GlobalConfig, dashboardURL string, exec *config.PurchaseExecution, facts LadderNoticeFacts) error
SendLadderNotice sends the scheduled notice of an automatic ladder purchase. The ladder variant is selected by facts, never by inspecting the execution, so SendScheduledNotice and its callers are unchanged.
func SendScheduledNotice ¶
func SendScheduledNotice(ctx context.Context, n ScheduledNotifier, globalCfg *config.GlobalConfig, dashboardURL string, exec *config.PurchaseExecution, actor string) error
SendScheduledNotice builds and sends the scheduled-purchase notice, returning the send error wrapped so callers can log or act on it.
func ServerNoteMessage ¶
ServerNoteMessage returns fixed server text for a known server-authored refusal so live responses can show it. A sentinel yields only its own text, never the wrapped chain; any other error must be allowlisted notes.
func SingleCloudAccountIDFromRecs ¶
func SingleCloudAccountIDFromRecs(recs []config.RecommendationRecord) (*string, error)
SingleCloudAccountIDFromRecs returns the cloud_account_id shared by every SELECTED recommendation, nil when no selected recommendation carries one (the ambient single-account deployment), and errAmbiguousAccountScope when the selected recs span more than one account or mix attributed and unattributed entries (#1902). Only selected recs count: they are the recs the money moves for (processPurchaseRecommendations buys selectedIndices). Exported so the API boundary (validateExecutePurchaseRecommendations) applies the identical rule before an execution row exists.
func StepCapApplies ¶
func StepCapApplies(plan *config.PurchasePlan) bool
StepCapApplies reports whether CheckStepCommitmentCap must run for plan: auto-purchase plans, plans with a cap, and bound plans, whose recommendations must map to a group whether or not any cap is set. The attach and email approval sites share it so they cannot drift.
func SummarizeFailure ¶
SummarizeFailure is SummarizeProviderError for errors that may also be a known server-authored refusal: those keep their own readable text, since the category message would hide what to fix.
func SummarizeProviderError ¶
SummarizeProviderError classifies a live error by its type or explicit code fields and returns its category and fixed message.
func ValidateApprovalToken ¶
func ValidateApprovalToken(execution *config.PurchaseExecution, token string) error
ValidateApprovalToken checks that the execution carries a non-empty token, that the supplied token matches the stored one using constant-time comparison (Finding #4 -- prevents timing attacks), and that the token has not expired (issue #397). Legacy rows with a nil ApprovalTokenExpiresAt pass the TTL check for backward compatibility. Extracted from ApproveExecution to keep that function under the gocyclo threshold. Exported so the HTTP layer's delayed-approval branch (which never calls ApproveExecution) validates the token the same way (issue #586).
execution.ApprovalToken is the SHA-256 hex digest stored at rest (issue #103), never the raw secret; config.ApprovalTokenMatches hashes the supplied token and compares digests in constant time.
Types ¶
type AttemptJournal ¶
type AttemptJournal interface {
common.AttemptJournal
common.ClaimReader
common.PurchaseClaimer
}
AttemptJournal is the journal the manager hands to providers. It must also read claims (go#700) and take the durable purchase claim (go#745), so a wrapper that hides ClaimedByOthers or the claim methods fails to compile instead of silently disabling the cross-lineage exclusion or the cross-process claim the Azure reservation flow finds by type assertion.
type ClaimedRowCheck ¶
type ClaimedRowCheck func(ctx context.Context, claimed *config.PurchaseExecution) error
ClaimedRowCheck re-runs a caller's authorization checks (permission Constraints such as MaxPurchaseAmount) against the row the claim CAS returned, which is exactly the row executeAndFinalize buys. A caller's earlier check ran on a snapshot read before the CAS, so a repricing or a recommendation attach landing in between would otherwise be bought unchecked (issue #415). A nil check skips the re-check; only callers with no pre-CAS Constraints check (the token approve) pass nil.
type CommitmentVisibility ¶
type CommitmentVisibility interface {
CommitmentVisible(ctx context.Context, tranche config.LadderTrancheDB, executionID string) (bool, error)
}
CommitmentVisibility reports whether the commitment bought by a completed execution already shows up in the provider's layer listing. The production adapter lands with the executor; an error or false keeps the tranche fired.
type FinalizeResult ¶
type FinalizeResult struct {
// Found is the number of unrevoked purchase_history rows with a recorded
// Return (return_posted_at) that the sweep saw.
Found int
// Finalized is the number of rows successfully stamped by MarkPurchaseRevoked.
Finalized int
// Errored is the number of rows the MarkPurchaseRevoked call failed for.
Errored int
// Released is the number of rows whose revocation_in_flight flag was
// cleared because no Return was recorded within
// staleRevocationInFlightAfter (issue #1523). They are not revoked.
Released int
}
FinalizeResult summarizes one sweep of FinalizeInFlightRevocations. Returned for the scheduled-task handler to log and surface in CloudWatch.
type FireResult ¶
type FireResult struct {
// Found is the number of status=scheduled rows whose scheduled_execution_at
// is in the past (SELECT pre-CAS).
Found int `json:"found"`
// Fired is the number of rows successfully transitioned from "scheduled" to
// "approved" and then through executeAndFinalize. Fired <= Found.
Fired int `json:"fired"`
// RaceLost is the number of rows where the scheduled->approved CAS was
// rejected by a concurrent operation (e.g. the user clicked Revoke between
// the SELECT and the CAS). This is normal and not an error.
RaceLost int `json:"race_lost"`
// Errored is the number of rows where the fire attempt failed for a reason
// other than a CAS race (DB error, provider error). Worth alerting on.
Errored int `json:"errored"`
// Stale is the number of claimed rows refused, unbought: because they were
// due more than the due-row age cap ago (ErrDueRowTooOld, issue #712), or by
// the plan's step cap re-check (ErrStepCommitmentCap, or a failure to read
// the plan; #1933), which a cap lowered since the approval fails. They end
// failed with no_submission and are not counted in Errored.
Stale int `json:"stale"`
// Deferred is the number of due rows left untouched (still scheduled)
// because less than purchaseRunBudget remained on the context deadline.
// The next sweep picks them up (issue #1582).
Deferred int `json:"deferred"`
}
FireResult carries the aggregate outcome of a single FireScheduledDelayedPurchases sweep. Callers log these counts and return them to the Lambda scheduler so they appear in CloudWatch Logs.
type LadderBuildInput ¶
type LadderBuildInput struct {
CloudAccountID string // cloud_accounts.id, not the 12-digit number.
Region string // deployment region.
// RIUnits is the live per-reservation price of each stored RI shape, looked
// up before the claim (the claim does no I/O). Missing means fail closed.
RIUnits map[string]RIUnit
// StoredRecs is read before the claim for the EC2 Instance SP and RI
// builders, which take identity and split weights from it, never amounts.
StoredRecs []config.RecommendationRecord
Tranche config.LadderTrancheDB // read-only; Build never mutates it.
}
LadderBuildInput is everything a builder may read. Evidence fields for later instruments are added here, so builder signatures never change.
type LadderFireDeps ¶
type LadderFireDeps struct {
Store LadderFireStore
Notifier ScheduledNotifier
Registry *LadderInstrumentRegistry
RIPricer LadderRIPricerFactory // nil leaves RI tranches unresolved.
Now func() time.Time
OwnAccountID string // external id of the AWS account the process runs in.
Region string
DashboardURL string
}
LadderFireDeps is everything one ladder fire sweep needs. Notifier is nil when no real sender is configured; the sweep then refuses to claim, because an execution nobody was told about must not exist.
type LadderFireResult ¶
type LadderFireResult struct {
Configs, Skipped, Due, Unresolved, Claimed, Trimmed, Errored int
// Announced counts executions stamped after a send; the rest of a claim is
// NoticeFailed (send error), NoticeDeferred (no time left) or StampFailed.
Announced, NoticeFailed, NoticeDeferred, StampFailed, SettleFailed int
}
LadderFireResult counts what one sweep did. Skipped counts configs a gate refused, Errored configs whose reads or claim failed; Due, Unresolved, Claimed and Trimmed sum over the configs that reached the resolve step.
func RunLadderFire ¶
func RunLadderFire(ctx context.Context, deps LadderFireDeps) (LadderFireResult, error)
RunLadderFire claims every due, resolvable ladder tranche into a scheduled execution, config by config. It is not registered as a scheduled task and buys nothing by itself: a claimed execution is only fireable once the notice step stamps it, and the fire sweep's recheck refuses it until then. The caller must treat a claimed but unannounced execution as a lost notice: it nets against the ceiling for a day, then the recheck refuses it and the reconciler disables the config (a re-enable, never a spend).
Every refusal creates nothing and logs its reason. The global switches are re-read per config, so a switch flipped mid-sweep stops the remaining configs. A config that errors is counted and the sweep goes on; the sweep returns an error when any config errored, so the scheduler records a failed run. Due tranches that cannot be resolved are never claimed, and if none of a config's due tranches resolves the claim is skipped with an ERROR, because the overdue sweep would otherwise cancel them as expired a day later. The due read is capped, so rows behind unresolvable heads can starve; the WARN on a full read says so.
type LadderFireStore ¶
type LadderFireStore interface {
GetGlobalConfig(ctx context.Context) (*config.GlobalConfig, error)
GetLadderConfigs(ctx context.Context) ([]config.LadderConfigDB, error)
GetCloudAccount(ctx context.Context, id string) (*config.CloudAccount, error)
ListStoredRecommendations(ctx context.Context, filter config.RecommendationFilter) ([]config.RecommendationRecord, error)
GetLadderSweepCeiling(ctx context.Context, configID string) (*int64, error)
ListDueLadderTranches(ctx context.Context, configID string, asOf time.Time, limit int, layers []ladder.LayerType) ([]config.LadderDueRow, error)
ClaimDueLadderTranches(ctx context.Context, configID string, asOf time.Time, limit int, filter config.LadderClaimFilter,
create func(ctx context.Context, tx pgx.Tx, tranche config.LadderTrancheDB) (string, error)) ([]config.LadderTrancheDB, error)
SavePurchaseExecutionTx(ctx context.Context, tx pgx.Tx, execution *config.PurchaseExecution) error
SaveExecutionIfStatus(ctx context.Context, execution *config.PurchaseExecution, expected []string) error
WithTx(ctx context.Context, fn func(tx pgx.Tx) error) error
LockLadderTrancheChainTx(ctx context.Context, tx pgx.Tx, trancheID string) ([]config.LadderChainNode, error)
CancelScheduledExecutionAtomic(ctx context.Context, tx pgx.Tx, executionID string, cancelledBy *string) (canceled bool, currentStatus string, err error)
TransitionLadderTrancheTx(ctx context.Context, tx pgx.Tx, id string, from, to ladder.TrancheStatus, reason string) (bool, error)
}
LadderFireStore is the slice of the Postgres store the ladder fire sweep uses.
type LadderInstrumentBuilder ¶
type LadderInstrumentBuilder func(in LadderBuildInput) ([]config.RecommendationRecord, error)
LadderInstrumentBuilder turns one claimed tranche into the records to buy. The sum of the returned hourly commitments never exceeds the tranche amount.
type LadderInstrumentRegistry ¶
type LadderInstrumentRegistry struct {
// contains filtered or unexported fields
}
LadderInstrumentRegistry maps a ladder layer to its builder. It is built by its constructor only, so a layer is buildable exactly when it is listed.
func NewLadderInstrumentRegistry ¶
func NewLadderInstrumentRegistry() *LadderInstrumentRegistry
NewLadderInstrumentRegistry returns the registry of buildable layers.
func (*LadderInstrumentRegistry) Build ¶
func (r *LadderInstrumentRegistry) Build(in LadderBuildInput) ([]config.RecommendationRecord, error)
Build maps the tranche to purchase records, failing closed: any error means nothing is bought and the tranche stays scheduled.
func (*LadderInstrumentRegistry) Layers ¶
func (r *LadderInstrumentRegistry) Layers() []ladder.LayerType
Layers lists the buildable layers in a stable order, for the claim allowlist.
type LadderNoticeFacts ¶
type LadderNoticeFacts struct {
AccountLabel string
TrancheID string
HourlyCommitment float64
TermYears int
}
LadderNoticeFacts are what an automatic ladder purchase's notice states beyond the execution itself.
type LadderRIDescriberFactory ¶
type LadderRIDescriberFactory func(ctx context.Context, cloudAccountID, region string) (RIDescriber, error)
LadderRIDescriberFactory returns a describer authenticated for one cloud account and region (the EC2 client's region scopes the lookup).
type LadderRIPricerFactory ¶
type LadderRIPricerFactory func(ctx context.Context, cloudAccountID, region string) (RIOfferingPricer, error)
LadderRIPricerFactory returns a pricer for one cloud account and region.
type LadderReconcileDeps ¶
type LadderReconcileDeps struct {
Store LadderReconcileRunStore
SP LadderSPDescriberFactory
RI LadderRIDescriberFactory
Now func() time.Time
}
LadderReconcileDeps is what one scheduled reconcile run needs.
type LadderReconcileResult ¶
type LadderReconcileResult struct {
Checked, Completed, Failed, Unresolved, Stale, LostRace, Errored int
Deferred, ConfigsDisabled int
}
LadderReconcileResult counts what one sweep did. Deferred counts tranches left fired because their config row was busy; the next sweep retries them. ConfigsDisabled counts configs a failed tranche switched off (decision D5).
func ReconcileLadderTranches ¶
func ReconcileLadderTranches(ctx context.Context, store LadderReconcileStore, vis CommitmentVisibility, now time.Time) (LadderReconcileResult, error)
ReconcileLadderTranches moves fired tranches to completed or failed from the state of their executions. Each tranche is decided inside one transaction that holds the tranche row and the retry-chain tail row, so a concurrent Retry cannot link a successor between the decision and the write. Tranches it cannot prove stay fired and keep netting; those older than LadderFiredStaleAfter are logged as errors. A tranche whose reconcile errors is counted in Errored and logged, and the sweep goes on; after the last tranche the run returns a summary error so the task shows as failed. All fired tranches are visited, page by page. The ladder_reconcile task runs it.
func RunLadderReconcile ¶
func RunLadderReconcile(ctx context.Context, d LadderReconcileDeps) (LadderReconcileResult, error)
RunLadderReconcile is the entry point the ladder_reconcile scheduled task runs: prefetch visibility, then ReconcileLadderTranches against the map. With no fired tranche it touches no provider API.
type LadderReconcileRunStore ¶
type LadderReconcileRunStore interface {
LadderReconcileStore
GetExecutionByID(ctx context.Context, id string) (*config.PurchaseExecution, error)
}
LadderReconcileRunStore is what RunLadderReconcile needs from the store.
type LadderReconcileStore ¶
type LadderReconcileStore interface {
ListFiredLadderTranches(ctx context.Context, after *config.LadderFiredCursor, limit int) ([]config.LadderTrancheDB, error)
WithTx(ctx context.Context, fn func(tx pgx.Tx) error) error
LockLadderTrancheChainTx(ctx context.Context, tx pgx.Tx, trancheID string) ([]config.LadderChainNode, error)
TransitionLadderTrancheTx(ctx context.Context, tx pgx.Tx, id string, from, to ladder.TrancheStatus, reason string) (bool, error)
GetGlobalConfigTx(ctx context.Context, tx pgx.Tx) (*config.GlobalConfig, error)
DisableLadderConfigTx(ctx context.Context, tx pgx.Tx, configID string) (bool, error)
CountLadderRunTrancheStatuses(ctx context.Context, runID string) (map[ladder.TrancheStatus]int, error)
TransitionLadderRunStatus(ctx context.Context, id string, fromStatuses []ladder.RunStatus, toStatus ladder.RunStatus) (*config.LadderRunDB, error)
}
LadderReconcileStore is the slice of the Postgres store the reconciler uses.
type LadderSPDescriberFactory ¶
type LadderSPDescriberFactory func(ctx context.Context, cloudAccountID, region string) (SPDescriber, error)
LadderSPDescriberFactory returns a describer authenticated for one cloud account and region.
type LadderUnresolved ¶
LadderUnresolved is a due tranche the sweep will not claim, with the reason.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager handles purchase workflow.
func NewManager ¶
func NewManager(cfg ManagerConfig) *Manager
NewManager creates a new purchase manager.
func (*Manager) ApproveAndExecute ¶
func (m *Manager) ApproveAndExecute(ctx context.Context, executionID, actor string, transitionedBy *string, check ClaimedRowCheck) (*config.PurchaseExecution, string, error)
ApproveAndExecute atomically flips a pending/notified execution to "approved" (stamping ApprovedBy) and then runs the purchase synchronously. Callers MUST have already authorized the actor — this method does no RBAC or token validation; it is shared between:
- ApproveExecution (token path: token validated by the caller and pinned inside the CAS; it calls transitionApproveAndExecute directly)
- approvePurchaseViaSession (session path: RBAC validated by the caller)
- directExecutePurchase (execute_mode="direct": RBAC validated by the caller)
Concurrency: TransitionExecutionStatus uses an atomic UPDATE WHERE status IN ('pending','notified'). Two callers racing to approve the same row will see exactly one win — the loser receives a clear "cannot transition" error. Cross-execution concurrency is unaffected: each approval drives its own executeAndFinalize, which already fans out per-account in parallel via executeMultiAccount.
The returned row carries the approval's final status, also on an execution error; it is nil when the run never started. check runs against the claimed row before any provider call; see ClaimedRowCheck.
func (*Manager) ApproveExecution ¶
func (m *Manager) ApproveExecution(ctx context.Context, executionID, token, actor string, check ClaimedRowCheck) (*config.PurchaseExecution, string, error)
ApproveExecution is the token-authenticated approve entry point used by the legacy email-link flow. After validating the approval token it hands off to the ApproveAndExecute funnel (transitionApproveAndExecute), which performs the atomic status transition with the token pinned inside it, runs the AWS purchase synchronously, and mints the fresh revocation token returned here.
actor carries the email of the operator who triggered the approval (the session-authed click on the HTTP path) so it can be stamped onto ApprovedBy. Empty actor is recorded as NULL — the column is nullable TEXT and we don't want to claim "approved by nobody".
check is the caller's ClaimedRowCheck, run against the claimed row before any provider call (issue #415); the token path passes nil.
Returns the same row and token as ApproveAndExecute (issue #532): the row carries the run's final status, also on an execution error, and is nil when the run never started (bad token, orphan, 4-eyes denial, lost claim), so the caller can tell a refusal from a provider failure after the claim. The raw revocation token minted on success is a return value rather than something the caller re-fetches from the DB (see transitionApproveAndExecute). It is empty on failure, and best-effort empty if the mint itself failed after an otherwise-successful approve. A partially_completed run returns its token together with its error, so a non-empty token with an error means part of the purchase committed and is revocable.
func (*Manager) AttachResolvedRecommendations ¶
func (m *Manager) AttachResolvedRecommendations(ctx context.Context, exec *config.PurchaseExecution, recs []config.RecommendationRecord) (bool, error)
AttachResolvedRecommendations persists the recommendations a plan step resolved onto its still-empty pending/notified execution, together with the suppressions that stop Opportunities (and the next step's resolution) from offering the same recs again. Both writes happen in one transaction: a crash leaves the row empty with no suppressions, or populated with them.
Returns false (and writes nothing) when another resolver attached first or the row left pending/notified; the caller re-reads the row instead of overwriting it. On success exec is updated in place.
func (*Manager) CancelExecution ¶
CancelExecution cancels a pending execution. actor carries the email of the session-authenticated user who clicked cancel; verified by the caller (HTTP path: authorizeApprovalAction) before reaching here. Same empty-actor rationale as ApproveExecution.
Concurrency: CancelExecutionAtomicTokenPinned uses a conditional UPDATE WHERE status IN ('pending','notified') so a concurrent approve that wins the race causes zero rows to be affected and the caller receives a clean error with the current status rather than silently overwriting the approved row. The same UPDATE also requires the stored token hash to still match token and be unexpired: loadCancelableExecution validated it against a snapshot, and a re-notification that rotated the token since must not let the old one cancel (issue #1190). That refusal returns an error wrapping config.ErrApprovalTokenChanged.
func (*Manager) DirectExecute ¶
func (m *Manager) DirectExecute(ctx context.Context, executionID, actor string, transitionedBy *string, check ClaimedRowCheck) (*config.PurchaseExecution, string, error)
DirectExecute is ApproveAndExecute for a session with the direct-execute permission: the same 4-eyes-gated, CAS-guarded funnel, but it stamps the executed_* audit fields once the CAS has won, so a refused or lost direct execute leaves no executed_at on a row that never ran.
func (*Manager) FinalizeInFlightRevocations ¶
func (m *Manager) FinalizeInFlightRevocations(ctx context.Context) (*FinalizeResult, error)
FinalizeInFlightRevocations sweeps unrevoked purchase_history rows whose Azure Return was recorded as accepted (return_posted_at) and retries MarkPurchaseRevoked for each. These rows represent cases where the Azure Return API call succeeded but the subsequent DB write failed — the finalize_revocations scheduled tick ensures the audit record is eventually consistent without requiring the user to retry (which would be rejected by Azure as "already returned").
A row that is only flagged (revocation_in_flight) with no recorded Return is never marked revoked (issue #1523): its request may have died before the Return was posted, so the purchase may still be active and billed. Once it has been flagged for staleRevocationInFlightAfter, the sweep clears the flag instead, so the user can revoke it again, and logs it for an operator. A failure to release is logged, does not stop the finalize pass, and is returned with the result.
The sweep uses a fixed timestamp of time.Now() at the START of the sweep so all rows finalized in one pass share the same revokedAt wall-clock value, which makes log correlation easier.
Per-row error handling: rows that fail MarkPurchaseRevoked after retries are logged and counted in FinalizeResult.Errored but do not abort the sweep — the sweep continues to the next row so a single stuck row does not block finalization of all in-flight rows.
Cancellation: the backoff between retries honors ctx. When ctx is done the row being retried is counted as Errored, the counts so far are logged, and the sweep returns them with an error wrapping ctx.Err(), so a Lambda near its deadline stops instead of sleeping past it (issue #243).
func (*Manager) FireScheduledDelayedPurchases ¶
func (m *Manager) FireScheduledDelayedPurchases(ctx context.Context) (*FireResult, error)
FireScheduledDelayedPurchases runs a sweep that fires all purchase_executions with status="scheduled" and scheduled_execution_at <= NOW(). For each row:
- Atomically transition scheduled -> approved via TransitionExecutionStatus (CAS; skips the row if the revoke handler won the race and flipped it to canceled first).
- Keep the ApprovedBy stored when the purchase was approved (the claim is transitioned_by NULL) and guard the claim with an audit save.
- Run executeAndFinalize to call the cloud SDK and flip the row to completed/failed.
A claimed row whose scheduled_execution_at is more than the due-row age cap in the past is failed unbought instead (issue #712), so the first tick after the sweep is scheduled cannot fire a backlog of stale delayed purchases.
Safety: idempotent across duplicate invocations (the CAS guard prevents double-firing). Per-row error isolation: a failure on row N never blocks rows N+1..K. Counts are aggregated in FireResult for the caller to log.
func (*Manager) LadderRIDescriber ¶
func (m *Manager) LadderRIDescriber(ctx context.Context, cloudAccountID, region string) (RIDescriber, error)
LadderRIDescriber is the production RI factory, built like LadderSPDescriber.
func (*Manager) LadderRIPricer ¶
func (m *Manager) LadderRIPricer(ctx context.Context, cloudAccountID, region string) (RIOfferingPricer, error)
LadderRIPricer is the production LadderRIPricerFactory: an EC2 client authenticated for the cloud account with the same per-account credential resolution the purchase itself uses. The only call it makes through the pricer is DescribeReservedInstancesOfferings (read-only); nothing is bought. Any failure returns an error and no pricer, so the sweep leaves the RI tranches unresolved.
func (*Manager) LadderSPDescriber ¶
func (m *Manager) LadderSPDescriber(ctx context.Context, cloudAccountID, region string) (SPDescriber, error)
LadderSPDescriber is the production factory: the same per-account credential resolution the purchase itself used.
func (*Manager) ProcessScheduledPurchases ¶
func (m *Manager) ProcessScheduledPurchases(ctx context.Context) (*ProcessResult, error)
ProcessScheduledPurchases checks for and executes scheduled purchases.
func (*Manager) ReapStuckExecutions ¶
func (m *Manager) ReapStuckExecutions(ctx context.Context, reapAfter time.Duration) (*ReapResult, error)
ReapStuckExecutions runs one sweep that finds purchase_executions stuck in running longer than reapAfter, or in approved longer than approvedReapAfter(reapAfter), and atomically transitions them to "failed" via the existing TransitionExecutionStatus CAS. Each successful transition also persists a canonical error message so the History UI (issue #621) can show why the row was reaped and the operator knows it's safe to retry.
Approved rows get the later threshold so the process sweep's RecoverStrandedApprovals can re-drive them first (issue #894); the reaper only fails the ones recovery never picked up, e.g. on deployments that do not schedule the process sweep.
Safety properties:
- Local-status-only: the reaper never touches provider commitments. If the real executor did get a commitment created on the provider before dying, the row is still flipped to failed locally — the operator's retry hits the idempotency path (#636/#638/#652) which surfaces a duplicate-reservation error and short-circuits cleanly.
- CAS-protected: if the real executor wakes up and finishes between the SELECT and the CAS, TransitionExecutionStatus returns an error ("cannot transition from completed/failed"); we log at INFO and move on. The real executor wins the race.
- Per-row error-isolation: a failure on row N never blocks rows N+1..K. Counts are aggregated in ReapResult for the caller to log.
func (*Manager) RecoverStrandedApprovals ¶
RecoverStrandedApprovals finds executions stuck in the "approved" status past staleApprovedThreshold and either re-drives them idempotently (executions where every rec is safe to re-drive and the row has a durable ExecutionID) or drives them into a terminal "failed" state (rows with unsafe recs or without a stable ExecutionID).
Idempotent re-drive path (issue #639): all AWS, Azure reservations, and GCP compute service clients derive or look up a deterministic idempotency key from DeriveIdempotencyToken(idempotencyLineageKey(exec), i). This is an IN-PLACE re-drive — the same row, so the lineage key is unchanged — which reproduces the same token, so the cloud provider dedupes the second call and no double-purchase occurs. (The retry/fan-out double-buy hole #1012 closes is about NEW rows minting a fresh ExecutionID; that does not apply here.) The row transitions directly to "completed" (or "failed"/"partially_completed" on a genuine error), bypassing the manual Retry step required by the old safe-fail path. See allRecsSafeToRedrive for which provider/service combinations are eligible.
Safe-fail path: Azure savings-plans recs are excluded because a repeat order-alias PUT is not confirmed to be deduplicated (see RedriveRefusalReason). Executions without a stable ExecutionID (legacy rows) also fall through because idempotencyLineageKey(exec) falls back to "" for them and DeriveIdempotencyToken("", i) would produce the same token set for every such row. These fall through to the original behavior: the row is atomically transitioned to "failed" so it surfaces in History and can be Retry-ed by an operator after confirming the cloud-side state.
The transition in the safe-fail path is atomic: TransitionExecutionStatus only flips rows still in "approved", so if the original run finally completes between the stale SELECT and this UPDATE, the transition is a no-op and the genuine "completed" status is preserved.
func (*Manager) RunPlannedPurchaseNow ¶
func (m *Manager) RunPlannedPurchaseNow(ctx context.Context, executionID, actor string, transitionedBy *string, check ClaimedRowCheck) (*config.PurchaseExecution, string, error)
RunPlannedPurchaseNow lets an operator force a scheduled purchase (pending or paused) to execute immediately instead of waiting for its scheduled date, going through the exact same 4-eyes gate and synchronous executeAndFinalize funnel ApproveAndExecute uses (issue #218). The previous runPlannedPurchase implementation only flipped the row's status to "running" and returned success: no executor consumes "running" rows (the scheduler picks up pending/notified, the reaper only cleans up a stuck "running" row after 10 minutes), so nothing ever bought the purchase and the row later reads "failed" out from under the operator who was told it ran.
Sharing transitionApproveAndExecute's CAS with ApproveAndExecute and claimAndExecuteWithin is also what makes this idempotent: a second "Run now" click, or the scheduler racing the same pending row, loses the atomic UPDATE ... WHERE status IN (...) and gets a clean "cannot transition" error rather than executing the purchase a second time.
The returned row carries the run-now audit stamp and its final status, also on an execution error; it is nil when the run never started. check runs against the claimed row before any provider call; see ClaimedRowCheck.
func (*Manager) SendUpcomingPurchaseNotifications ¶
func (m *Manager) SendUpcomingPurchaseNotifications(ctx context.Context) (*NotificationResult, error)
SendUpcomingPurchaseNotifications sends notifications for upcoming automated purchases.
func (*Manager) SetRecommendationSource ¶
SetRecommendationSource wires the strict recommendation read the plan-step attach resolves through. Late-bound because the scheduler is built after the manager and imports this package.
type ManagerConfig ¶
type ManagerConfig struct {
ProviderFactory provider.FactoryInterface
AmbientAWSCreds aws.CredentialsProvider
STSClient STSClient
AssumeRoleSTS credentials.STSClient
CredentialStore credentials.CredentialStore
OIDCSigner oidc.Signer
// AttemptJournal records each purchase attempt durably (go#107). Nil keeps
// the provider's own window dedupe.
AttemptJournal AttemptJournal
EmailSender email.SenderInterface
ConfigStore config.StoreInterface
// BastionSTSFactory builds the STS client a bastion-mode account's target
// role is assumed with, signed with the bastion account's credentials.
// Without it bastion accounts fail to resolve (issue #263).
BastionSTSFactory credentials.STSClientFactory
DashboardURL string
OIDCIssuerURL string
NotificationDaysBefore int
// MaxDueRowAge caps how long after its due time the fire and process
// sweeps may still buy a row (issue #712); an older row is failed
// unbought instead. Zero means DefaultMaxDueRowAge.
MaxDueRowAge time.Duration
}
ManagerConfig holds configuration for the purchase manager.
type NotificationResult ¶
type NotificationResult struct {
Notified int `json:"notified"`
}
NotificationResult holds the result of sending notifications.
type ProcessResult ¶
type ProcessResult struct {
Errors []string `json:"errors,omitempty"`
Processed int `json:"processed"`
Executed int `json:"executed"`
Failed int `json:"failed"`
Recovered int `json:"recovered,omitempty"`
// Stale counts the Failed rows refused because they were due more than
// the due-row age cap ago (ErrDueRowTooOld, issue #712). Each one is
// also in Failed and Errors.
Stale int `json:"stale,omitempty"`
}
ProcessResult holds the result of processing scheduled purchases.
type RIDescriber ¶
type RIDescriber interface {
DescribeReservedInstances(ctx context.Context, in *ec2.DescribeReservedInstancesInput, optFns ...func(*ec2.Options)) (*ec2.DescribeReservedInstancesOutput, error)
}
RIDescriber is the one EC2 call the RI visibility prefetch needs. *ec2.Client satisfies it.
type RIOfferingPricer ¶
type RIOfferingPricer interface {
GetOfferingDetailsForClass(ctx context.Context, rec common.Recommendation, offeringClass string) (*common.OfferingDetails, error)
}
RIOfferingPricer is the one read-only EC2 call the RI builder needs. The go library's EC2 client satisfies it.
type RIUnit ¶
RIUnit is the live price of ONE reservation of an instance shape, looked up before the claim. Err is set when the lookup or its validation failed.
type ReapResult ¶
type ReapResult struct {
// Found is the number of rows the SELECT returned (i.e. stuck rows the
// sweep saw — pre-CAS).
Found int `json:"found"`
// Reaped is the number of rows that successfully transitioned to
// "failed" via the atomic CAS. Reaped <= Found; the gap is rows the
// real executor finished between the SELECT and the CAS (CAS race
// rejected the reap — correct behavior, not an error).
Reaped int `json:"reaped"`
// RaceLost is the number of rows where the CAS rejected the reap
// because the row's status changed between the SELECT and the
// transition (the real executor woke up and beat us). Logged at
// INFO; not surfaced as an error.
RaceLost int `json:"race_lost"`
// Errored is the number of rows where the persistence step failed
// (CAS itself errored or the canonical-error follow-up save failed).
// These are real ops issues worth surfacing.
Errored int `json:"errored"`
}
ReapResult summarizes one sweep of ReapStuckExecutions. Returned for the scheduled-task handler to log + surface in CloudWatch / metrics.
type SPDescriber ¶
type SPDescriber interface {
DescribeSavingsPlans(ctx context.Context, in *sdksp.DescribeSavingsPlansInput, optFns ...func(*sdksp.Options)) (*sdksp.DescribeSavingsPlansOutput, error)
}
SPDescriber is the one Savings Plans API call the visibility prefetch needs. *savingsplans.Client satisfies it.
type STSClient ¶
type STSClient interface {
GetCallerIdentity(ctx context.Context, params *sts.GetCallerIdentityInput, optFns ...func(*sts.Options)) (*sts.GetCallerIdentityOutput, error)
}
STSClient interface for AWS STS operations.
type ScheduledNotifier ¶
type ScheduledNotifier interface {
SendPurchaseScheduledNotification(ctx context.Context, data email.NotificationData) error
}
ScheduledNotifier sends the scheduled-purchase notice.
Source Files
¶
- account_scope.go
- approvals.go
- approvals_cancel.go
- approvals_foureyes.go
- attach_recommendations.go
- azure_pricing.go
- claim.go
- due_age_cap.go
- elasticache_duplicate_pool.go
- elasticache_recent_check.go
- errnotes.go
- errsummary.go
- execution.go
- execution_account.go
- execution_recs.go
- execution_scope.go
- execution_servicemap.go
- execution_single.go
- failure_notify.go
- fan_out_shape.go
- finalize_revocations.go
- gcp_recent_check.go
- history_adoption.go
- ladder_execution_recheck.go
- ladder_fire.go
- ladder_fire_exec.go
- ladder_fire_gate.go
- ladder_fire_notice.go
- ladder_fire_resolve.go
- ladder_fire_settle.go
- ladder_instrument.go
- ladder_instrument_convert.go
- ladder_instrument_ec2sp.go
- ladder_instrument_family.go
- ladder_instrument_ri.go
- ladder_instrument_ri_price.go
- ladder_reconcile.go
- ladder_reconcile_d5.go
- ladder_ri_pricer.go
- ladder_run_rollup.go
- ladder_visibility.go
- ladder_visibility_ri.go
- late_accounts.go
- manager.go
- manager_redrive.go
- manager_scheduler.go
- manager_terminal.go
- notifications.go
- ops_hint.go
- orphaned_plan_step.go
- partition_guard.go
- plan_step_attach.go
- plan_step_attach_candidates.go
- plan_step_expired_fail.go
- plan_step_managed.go
- plan_step_readopt.go
- reaper.go
- recover_reaped.go
- redshift_lineage.go
- redshift_retry.go
- refusal_tally.go
- retry_unsent.go
- scheduled_fire.go
- scheduled_fire_cap.go
- scheduled_notice.go
- step_cap.go
- stranded_redrive.go