Documentation
¶
Overview ¶
Package config provides configuration management functionality.
Package config provides configuration management for CUDly.
Package config provides configuration management using PostgreSQL.
Index ¶
- Constants
- Variables
- func AWSPartitionFromARN(arn string) string
- func AccountConfigKey(accountID, provider, service string) string
- func AmountBasisSchemaReady(ctx context.Context, q rowQuerier) (bool, error)
- func ApprovalTokenMatches(storedHash, rawSupplied string) bool
- func CanonicalSuppressionEngine(provider, service, engine string) string
- func CanonicalSuppressionService(provider, service string) string
- func DerivePlanProviders(plan *PurchasePlan) ([]string, error)
- func DerivePlanServices(plan *PurchasePlan) []string
- func EffectiveStepCap(plan, group *float64) float64
- func GetAllCategories() []string
- func GetDefaultValue(key string) any
- func HashApprovalToken(rawToken string) string
- func IsBoundServiceKey(key string) bool
- func IsUSDCommitmentCurrency(currency string) bool
- func IsValidRIExchangeMode(mode string) bool
- func LadderAmountFloat(amount *big.Rat) float64
- func LadderAmountFloor(amount *big.Rat) *big.Rat
- func LadderCapMicros(v float64) (int64, error)
- func LadderInFlightOnDemand(rows []LadderInFlightRow) (float64, error)
- func LadderSweepCeilingMicros(v float64) (int64, error)
- func LadderTrancheSettled(status ladder.TrancheStatus) bool
- func NormalizePaymentOption(provider, raw string) (string, bool)
- func PaymentCoercionChangesSchedule(raw, canonical string) bool
- func RecIdentityKey(rec *RecommendationRecord) (string, error)
- func RequireLadderCommitmentBasis(tr *LadderTrancheDB) error
- func ResolveAccountConfigsForRecs(ctx context.Context, store AccountConfigReader, recs []RecommendationRecord) (map[string]*ServiceConfig, error)
- func ResolveConfiguredCoverageForRecs(ctx context.Context, store AccountConfigReader, recs []RecommendationRecord) (map[string]float64, error)
- func RevocationWindowClosesAtFor(provider string, purchaseTime time.Time) *time.Time
- func SavingsNetOfUpfront(provider, service string) bool
- func ServiceEntryProvider(key, fieldProvider string) string
- func StepCapCents(v float64) (int64, error)
- func StoredRecommendationIdentity(provider string, commitment common.CommitmentType, region, resourceType string) (storedRegion, storedResourceType string)
- func StoredRecommendationService(provider string, service common.ServiceType) string
- func SuppressionEngineSpellings(provider, service, canonical string) []string
- func SuppressionServiceSpellings(provider, canonical string) []string
- func SuppressionTupleKey(accountID, provider, service, region, resourceType, engine string) string
- func ValidateRIExchangeUtilizationThreshold(name string, t float64) error
- func ValidateRampScheduleEnv(val string) error
- type AccountConfigReader
- type AccountNotice
- type AccountRegistration
- type AccountRegistrationFilter
- type AccountServiceOverride
- type AccountStore
- type AuditActor
- type AuditContext
- type AuditEvent
- type CloudAccount
- type CloudAccountFilter
- type ComputeIdentity
- type ConfigSetting
- type DoomedRoot
- type ExecutionScope
- type ExecutionSettleRequest
- type ExecutionSettlement
- type ExecutionStatusCounts
- type ExecutionSummaryGroup
- type ExecutionsByStatusesQuery
- type GlobalConfig
- type HistoryExecutionsPageQuery
- type HistoryPageKey
- type HistorySource
- type HistoryStore
- type HistorySummaryFilter
- type HistorySummaryGroups
- type LadderAmendment
- type LadderAmendmentResult
- type LadderAmendmentStore
- type LadderAmountBasis
- type LadderChainNode
- type LadderClaimFilter
- type LadderCloudCheck
- type LadderConfigDB
- type LadderDueRow
- type LadderExecutionGate
- type LadderFiredCursor
- type LadderInFlightRow
- type LadderPlanBuilder
- type LadderResolveFailed
- type LadderResolveResult
- type LadderRunDB
- type LadderStore
- type LadderTimelineAction
- type LadderTimelineCursor
- type LadderTimelineEvent
- type LadderTimelinePage
- type LadderTimelineRun
- type LadderTimelineRunPage
- type LadderTimelineStore
- type LadderTrancheCounts
- type LadderTrancheDB
- type MarketplaceListingAttempt
- type MarketplaceListingClaim
- type MarketplaceListingProceedsTotal
- type MarketplaceListingSettlement
- type MarketplaceStore
- type PartialProviderSweep
- type PaymentSchedule
- type PlanGroupTarget
- type PlanNameTakenError
- type PlanRampBaseline
- type PlanRampQuantity
- type PlanScheduleCommand
- type PlanScheduleOutcome
- type PlanScheduleReceipt
- type PlanStore
- type PlanWriteGate
- type PlannedStep
- type PostgresStore
- func (s *PostgresStore) AcquireClaim(ctx context.Context, token, holder string, ttl, settle time.Duration) (common.Claim, error)
- func (s *PostgresStore) AdvanceClaim(ctx context.Context, claim common.Claim, phase common.ClaimPhase) error
- func (s *PostgresStore) AmendLadderTranche(ctx context.Context, id, accountID, provider, actor string, ...) (*LadderAmendmentResult, error)
- func (s *PostgresStore) ApplyPlanScheduleCommand(ctx context.Context, cmd PlanScheduleCommand) (*PlanScheduleOutcome, error)
- func (s *PostgresStore) ApproveAccountRegistration(ctx context.Context, reg *AccountRegistration, account *CloudAccount, ...) error
- func (s *PostgresStore) CancelAllPendingExchanges(ctx context.Context) (int64, error)
- func (s *PostgresStore) CancelExecutionAtomic(ctx context.Context, tx pgx.Tx, executionID string, cancelledBy *string) (canceled bool, currentStatus string, err error)
- func (s *PostgresStore) CancelExecutionAtomicTokenPinned(ctx context.Context, tx pgx.Tx, executionID string, cancelledBy *string, ...) (canceled bool, currentStatus string, err error)
- func (s *PostgresStore) CancelLadderRun(ctx context.Context, id string, fromStatuses []ladder.RunStatus, ...) (*LadderRunDB, error)
- func (s *PostgresStore) CancelPendingExchangesByOrigin(ctx context.Context, origin common.ExchangeOrigin) (int64, error)
- func (s *PostgresStore) CancelScheduledExecutionAtomic(ctx context.Context, tx pgx.Tx, executionID string, cancelledBy *string) (canceled bool, currentStatus string, err error)
- func (s *PostgresStore) CheckAZConfigMigration(ctx context.Context) error
- func (s *PostgresStore) ClaimCollectionInvocation(ctx context.Context, markerToken string) (token string, ok bool, err error)
- func (s *PostgresStore) ClaimDueLadderTranches(ctx context.Context, configID string, asOf time.Time, limit int, ...) ([]LadderTrancheDB, error)
- func (s *PostgresStore) ClaimMarketplaceListingSlot(ctx context.Context, purchaseID, clientToken string, priceSchedule []byte) (*MarketplaceListingClaim, error)
- func (s *PostgresStore) ClaimRIExchangeIdempotencyKey(ctx context.Context, key string, window time.Duration) (bool, error)
- func (s *PostgresStore) ClaimedByOthers(ctx context.Context, token string, ids []string) ([]string, error)
- func (s *PostgresStore) CleanupOldExecutions(ctx context.Context, retentionDays int) (int64, error)
- func (s *PostgresStore) ClearCollectionStarted(ctx context.Context, token string) error
- func (s *PostgresStore) ClearRegistrationCredentialPayload(ctx context.Context, registrationID string) error
- func (s *PostgresStore) ClearRevocationInFlight(ctx context.Context, purchaseID string) error
- func (s *PostgresStore) CompletePlanStep(ctx context.Context, planID string, stepNumber int) error
- func (s *PostgresStore) CompleteRIExchange(ctx context.Context, id, exchangeID string) error
- func (s *PostgresStore) CompleteRIExchangeWithPayment(ctx context.Context, id, exchangeID, acceptedPaymentDue string) error
- func (s *PostgresStore) CompleteTargetMetStepTx(ctx context.Context, tx pgx.Tx, planID string, stepNumber int, ...) error
- func (s *PostgresStore) CountExecutionsByPlanAndStatus(ctx context.Context, statuses []string, since time.Time) (map[string]ExecutionStatusCounts, error)
- func (s *PostgresStore) CountLadderRunTrancheStatuses(ctx context.Context, runID string) (map[ladder.TrancheStatus]int, error)
- func (s *PostgresStore) CountLiveExecutionsForAccount(ctx context.Context, accountID string) (int, error)
- func (s *PostgresStore) CountPendingExecutionsForAccount(ctx context.Context, accountID string) (int, error)
- func (s *PostgresStore) CreateAccountRegistration(ctx context.Context, reg *AccountRegistration) error
- func (s *PostgresStore) CreateCloudAccount(ctx context.Context, account *CloudAccount) error
- func (s *PostgresStore) CreatePurchasePlan(ctx context.Context, plan *PurchasePlan) error
- func (s *PostgresStore) CreatePurchasePlanWithAccounts(ctx context.Context, plan *PurchasePlan, accountIDs []string, ...) error
- func (s *PostgresStore) CreateSuppression(ctx context.Context, sup *PurchaseSuppression) error
- func (s *PostgresStore) CreateSuppressionTx(ctx context.Context, tx pgx.Tx, sup *PurchaseSuppression) error
- func (s *PostgresStore) DeleteAccountCredentials(ctx context.Context, accountID string) error
- func (s *PostgresStore) DeleteAccountRegistration(ctx context.Context, id string) error
- func (s *PostgresStore) DeleteAccountServiceOverride(ctx context.Context, accountID, provider, service string) error
- func (s *PostgresStore) DeleteAccountServiceOverrideAuditedTx(ctx context.Context, tx pgx.Tx, accountID, provider, service string, ...) error
- func (s *PostgresStore) DeleteCloudAccount(ctx context.Context, id string) error
- func (s *PostgresStore) DeletePurchasePlan(ctx context.Context, planID string) error
- func (s *PostgresStore) DeleteSuppressionsByExecution(ctx context.Context, executionID string) error
- func (s *PostgresStore) DeleteSuppressionsByExecutionTx(ctx context.Context, tx pgx.Tx, executionID string) error
- func (s *PostgresStore) DisableLadderConfigTx(ctx context.Context, tx pgx.Tx, configID string) (bool, error)
- func (s *PostgresStore) ExpireExecutionAtomic(ctx context.Context, tx pgx.Tx, executionID string, ...) (bool, error)
- func (s *PostgresStore) FailRIExchange(ctx context.Context, id, errorMsg string) error
- func (s *PostgresStore) FamilyRetryClaimedTx(ctx context.Context, tx pgx.Tx, family, planID, selfID string, selfIsRoot bool) (bool, error)
- func (s *PostgresStore) FinalizeRIExchangeDirectExecution(ctx context.Context, id string, outcome RIExchangeDirectOutcome) error
- func (s *PostgresStore) FindOpenRedshiftLineageConflictsTx(ctx context.Context, tx pgx.Tx, selfID, family string, tuples []RedshiftTuple, ...) ([]RedshiftLineageConflict, error)
- func (s *PostgresStore) FlipPurchaseRevocationInFlight(ctx context.Context, purchaseID string) error
- func (s *PostgresStore) GetAccountCredential(ctx context.Context, accountID, credentialType string) (string, error)
- func (s *PostgresStore) GetAccountRegistration(ctx context.Context, id string) (*AccountRegistration, error)
- func (s *PostgresStore) GetAccountRegistrationByToken(ctx context.Context, token string) (*AccountRegistration, error)
- func (s *PostgresStore) GetAccountServiceOverride(ctx context.Context, accountID, provider, service string) (*AccountServiceOverride, error)
- func (s *PostgresStore) GetActivePurchaseHistory(ctx context.Context, asOf time.Time, accountIDs []string, ...) ([]PurchaseHistoryRecord, error)
- func (s *PostgresStore) GetAllPurchaseHistory(ctx context.Context, limit int) ([]PurchaseHistoryRecord, error)
- func (s *PostgresStore) GetCloudAccount(ctx context.Context, id string) (*CloudAccount, error)
- func (s *PostgresStore) GetCloudAccountByExternalID(ctx context.Context, provider, externalID string) (*CloudAccount, error)
- func (s *PostgresStore) GetDoomedNextRoots(ctx context.Context, now time.Time) (map[string]DoomedRoot, error)
- func (s *PostgresStore) GetExecutionByID(ctx context.Context, executionID string) (*PurchaseExecution, error)
- func (s *PostgresStore) GetExecutionByPlanAndDate(ctx context.Context, planID string, scheduledDate time.Time) (*PurchaseExecution, error)
- func (s *PostgresStore) GetExecutionFanOutShape(ctx context.Context, lineageKey string) (string, error)
- func (s *PostgresStore) GetExecutionsByStatuses(ctx context.Context, statuses []string, limit int) ([]PurchaseExecution, error)
- func (s *PostgresStore) GetExecutionsByStatusesFiltered(ctx context.Context, q ExecutionsByStatusesQuery) ([]PurchaseExecution, error)
- func (s *PostgresStore) GetGlobalConfig(ctx context.Context) (*GlobalConfig, error)
- func (s *PostgresStore) GetGlobalConfigTx(ctx context.Context, tx pgx.Tx) (*GlobalConfig, error)
- func (s *PostgresStore) GetLadderConfig(ctx context.Context, cloudAccountID, provider string) (*LadderConfigDB, error)
- func (s *PostgresStore) GetLadderConfigs(ctx context.Context) ([]LadderConfigDB, error)
- func (s *PostgresStore) GetLadderExecutionGate(ctx context.Context, idempotencyKey string) (*LadderExecutionGate, error)
- func (s *PostgresStore) GetLadderRun(ctx context.Context, id string) (*LadderRunDB, error)
- func (s *PostgresStore) GetLadderSweepCeiling(ctx context.Context, configID string) (*int64, error)
- func (s *PostgresStore) GetMarketplaceListingAttempt(ctx context.Context, purchaseID string) (*MarketplaceListingAttempt, error)
- func (s *PostgresStore) GetMarketplaceListingProceedsTotals(ctx context.Context, purchaseIDs, accountIDs []string, ...) ([]MarketplaceListingProceedsTotal, error)
- func (s *PostgresStore) GetPendingExecutions(ctx context.Context) ([]PurchaseExecution, error)
- func (s *PostgresStore) GetPlanAccounts(ctx context.Context, planID string) ([]CloudAccount, error)
- func (s *PostgresStore) GetPlanRampBaselineTx(ctx context.Context, tx pgx.Tx, planID string) (PlanRampBaseline, error)
- func (s *PostgresStore) GetPlanScheduleReceiptTx(ctx context.Context, tx pgx.Tx, commandID string) (*PlanScheduleReceipt, error)
- func (s *PostgresStore) GetPlannedExecutions(ctx context.Context, statuses []string, limit int) ([]PurchaseExecution, error)
- func (s *PostgresStore) GetPurchaseHistory(ctx context.Context, accountID string, limit int) ([]PurchaseHistoryRecord, error)
- func (s *PostgresStore) GetPurchaseHistoryByPurchaseID(ctx context.Context, purchaseID string) (*PurchaseHistoryRecord, error)
- func (s *PostgresStore) GetPurchaseHistoryFiltered(ctx context.Context, filter PurchaseHistoryFilter) ([]PurchaseHistoryRecord, error)
- func (s *PostgresStore) GetPurchaseHistoryInFlight(ctx context.Context) ([]*PurchaseHistoryRecord, error)
- func (s *PostgresStore) GetPurchasePlan(ctx context.Context, planID string) (*PurchasePlan, error)
- func (s *PostgresStore) GetRIExchangeDailySpend(ctx context.Context, date time.Time) (string, error)
- func (s *PostgresStore) GetRIExchangeDirectExecution(ctx context.Context, id string) (*RIExchangeDirectRow, error)
- func (s *PostgresStore) GetRIExchangeHistory(ctx context.Context, since time.Time, limit int) ([]RIExchangeRecord, error)
- func (s *PostgresStore) GetRIExchangeHistoryForAccounts(ctx context.Context, since time.Time, limit int, accountIDs []string) ([]RIExchangeRecord, error)
- func (s *PostgresStore) GetRIExchangeRecord(ctx context.Context, id string) (*RIExchangeRecord, error)
- func (s *PostgresStore) GetRIExchangeRecordByToken(ctx context.Context, token string) (*RIExchangeRecord, error)
- func (s *PostgresStore) GetRIUtilizationCache(ctx context.Context, key RIUtilizationCacheKey) (*RIUtilizationCacheEntry, error)
- func (s *PostgresStore) GetRecommendationsFreshness(ctx context.Context) (*RecommendationsFreshness, error)
- func (s *PostgresStore) GetRedshiftRetryClock(ctx context.Context, executionID string) (RedshiftRetryClock, error)
- func (s *PostgresStore) GetScheduledExecutionsDue(ctx context.Context) ([]PurchaseExecution, error)
- func (s *PostgresStore) GetServiceConfig(ctx context.Context, provider, service string) (*ServiceConfig, error)
- func (s *PostgresStore) GetStaleApprovedExecutions(ctx context.Context, olderThan time.Duration) ([]PurchaseExecution, error)
- func (s *PostgresStore) GetStaleProcessingExchanges(ctx context.Context, olderThan time.Duration) ([]RIExchangeRecord, error)
- func (s *PostgresStore) GetStuckRampSteps(ctx context.Context) (map[string]RampStepBlock, error)
- func (s *PostgresStore) GetUserEmailByID(ctx context.Context, userID string) (string, error)
- func (s *PostgresStore) HasAccountCredentials(ctx context.Context, accountID string) (bool, error)
- func (s *PostgresStore) HistorySummaryAggregate(ctx context.Context, filter HistorySummaryFilter) (*HistorySummaryGroups, error)
- func (s *PostgresStore) InsertPlanScheduleReceiptTx(ctx context.Context, tx pgx.Tx, r *PlanScheduleReceipt) error
- func (s *PostgresStore) IsNotificationMuted(ctx context.Context, recipientEmail, scope string) (bool, error)
- func (s *PostgresStore) LadderTrancheScope(ctx context.Context, id string) (accountID, provider string, err error)
- func (s *PostgresStore) LatestLadderRunID(ctx context.Context, configID string) (string, error)
- func (s *PostgresStore) LatestLadderRunStartedAt(ctx context.Context, configID string) (*time.Time, error)
- func (s *PostgresStore) LinkRetryExecutionAtomic(ctx context.Context, tx pgx.Tx, executionID, retryExecutionID string) (linked bool, err error)
- func (s *PostgresStore) LinkUnsentRetryExecutionAtomic(ctx context.Context, tx pgx.Tx, executionID, retryExecutionID string) (linked bool, err error)
- func (s *PostgresStore) ListAccountRegistrations(ctx context.Context, filter AccountRegistrationFilter) ([]AccountRegistration, error)
- func (s *PostgresStore) ListAccountServiceOverrides(ctx context.Context, accountID string) ([]AccountServiceOverride, error)
- func (s *PostgresStore) ListActiveSuppressions(ctx context.Context) ([]PurchaseSuppression, error)
- func (s *PostgresStore) ListCloudAccounts(ctx context.Context, filter CloudAccountFilter) ([]CloudAccount, error)
- func (s *PostgresStore) ListDueLadderTranches(ctx context.Context, configID string, asOf time.Time, limit int, ...) ([]LadderDueRow, error)
- func (s *PostgresStore) ListExecutionsForPlanStepTx(ctx context.Context, tx pgx.Tx, planID string, stepNumber int) ([]PurchaseExecution, error)
- func (s *PostgresStore) ListFiredLadderTranches(ctx context.Context, after *LadderFiredCursor, limit int) ([]LadderTrancheDB, error)
- func (s *PostgresStore) ListHistoryExecutionsPage(ctx context.Context, q HistoryExecutionsPageQuery) ([]PurchaseExecution, error)
- func (s *PostgresStore) ListLadderTimeline(ctx context.Context, accountID, provider string, cursor *LadderTimelineCursor) (*LadderTimelinePage, error)
- func (s *PostgresStore) ListLadderTimelineRuns(ctx context.Context, accountID, provider string, cursor *LadderTimelineCursor) (*LadderTimelineRunPage, error)
- func (s *PostgresStore) ListMarketplaceListingsToPoll(ctx context.Context) ([]PurchaseHistoryRecord, error)
- func (s *PostgresStore) ListPendingExecutionIDsForAccount(ctx context.Context, accountID string) ([]string, error)
- func (s *PostgresStore) ListPlanCommittedTx(ctx context.Context, tx pgx.Tx, planID string) (map[string]PlanRampQuantity, error)
- func (s *PostgresStore) ListPlansWithAttachableEmptyRoot(ctx context.Context, now time.Time) (map[string]struct{}, error)
- func (s *PostgresStore) ListPlansWithReadoptableExpiredRoot(ctx context.Context, now time.Time, requireDifferentApprover bool) (map[string]struct{}, error)
- func (s *PostgresStore) ListPurchaseHistoryPage(ctx context.Context, filter PurchaseHistoryFilter, after *HistoryPageKey) ([]PurchaseHistoryPageRow, error)
- func (s *PostgresStore) ListPurchasePlans(ctx context.Context, filter PurchasePlanFilter) ([]PurchasePlan, error)
- func (s *PostgresStore) ListRIExchangeDirectHistory(ctx context.Context, f RIExchangeDirectHistoryFilter) ([]RIExchangeDirectHistoryRow, error)
- func (s *PostgresStore) ListRecentSubmitsTx(ctx context.Context, tx pgx.Tx, creatorID string, since time.Time) ([]PurchaseExecution, error)
- func (s *PostgresStore) ListServiceConfigs(ctx context.Context) ([]ServiceConfig, error)
- func (s *PostgresStore) ListStoredRecommendationTriples(ctx context.Context, scope RecommendationListScope) ([]RecommendationTriple, error)
- func (s *PostgresStore) ListStoredRecommendations(ctx context.Context, filter RecommendationFilter) ([]RecommendationRecord, error)
- func (s *PostgresStore) ListStoredRecommendationsChunk(ctx context.Context, filter RecommendationFilter, after *RecommendationScanKey, ...) (RecommendationChunk, error)
- func (s *PostgresStore) ListStuckExecutions(ctx context.Context, statuses []string, olderThan time.Duration) ([]PurchaseExecution, error)
- func (s *PostgresStore) ListUnresolvedRIExchangeDirectAccountRegions(ctx context.Context) ([]RIExchangeDirectAccountRegion, error)
- func (s *PostgresStore) ListUnresolvedRIExchangeDirectExecutions(ctx context.Context, f RIExchangeDirectListFilter) (*RIExchangeDirectListPage, error)
- func (s *PostgresStore) LockLadderTrancheChainTx(ctx context.Context, tx pgx.Tx, trancheID string) ([]LadderChainNode, error)
- func (s *PostgresStore) LockLadderTrancheForRetryTx(ctx context.Context, tx pgx.Tx, idempotencyKey string) (status ladder.TrancheStatus, found bool, err error)
- func (s *PostgresStore) LockPlanProvidersTx(ctx context.Context, tx pgx.Tx, providers []string) error
- func (s *PostgresStore) LockPurchasePlanTx(ctx context.Context, tx pgx.Tx, planID string) (*PurchasePlan, error)
- func (s *PostgresStore) LockRedshiftTuplesTx(ctx context.Context, tx pgx.Tx, tuples []RedshiftTuple) error
- func (s *PostgresStore) LockRetryFamilyTx(ctx context.Context, tx pgx.Tx, family string) error
- func (s *PostgresStore) MarkCollectionStarted(ctx context.Context) (token string, ok bool, err error)
- func (s *PostgresStore) MarkPurchaseRevoked(ctx context.Context, purchaseID string, revokedAt time.Time, ...) error
- func (s *PostgresStore) MarkRevocationReturnPosted(ctx context.Context, purchaseID string) error
- func (s *PostgresStore) NoteRIExchangeOutcomeUnknown(ctx context.Context, id, note string) error
- func (s *PostgresStore) OccupiedRampStepsInRangeTx(ctx context.Context, tx pgx.Tx, planID string, from, to int) ([]int, error)
- func (s *PostgresStore) PageStoredRecommendations(ctx context.Context, q RecommendationPageQuery) (RecommendationPage, error)
- func (s *PostgresStore) PinExecutionFanOutShape(ctx context.Context, lineageKey, shape string) (string, error)
- func (s *PostgresStore) PlanAndSaveLadderRun(ctx context.Context, configID string, asOf time.Time, build LadderPlanBuilder) (*LadderRunDB, error)
- func (s *PostgresStore) PredecessorProvenUnsent(ctx context.Context, executionID string) (bool, error)
- func (s *PostgresStore) PriorAttempts(ctx context.Context, token string) ([]common.AttemptRecord, error)
- func (s *PostgresStore) PruneStaleRecommendations(ctx context.Context, retentionDays int) (int64, error)
- func (s *PostgresStore) ReadoptExpiredRootTx(ctx context.Context, tx pgx.Tx, executionID string, ...) (*PurchaseExecution, error)
- func (s *PostgresStore) RecordAttempt(ctx context.Context, rec common.AttemptRecord) error
- func (s *PostgresStore) RecordMarketplaceListingActive(ctx context.Context, purchaseID, listingID string, listedAt time.Time) (bool, error)
- func (s *PostgresStore) RecoverReapedExecution(ctx context.Context, execution *PurchaseExecution) error
- func (s *PostgresStore) RecoverReapedExecutionTx(ctx context.Context, tx pgx.Tx, execution *PurchaseExecution) error
- func (s *PostgresStore) ReleaseClaim(ctx context.Context, claim common.Claim, outcome common.ClaimOutcome) error
- func (s *PostgresStore) ReleaseMarketplaceListingClaim(ctx context.Context, purchaseID, clientToken, priorState string, ...) error
- func (s *PostgresStore) ReleaseStaleRevocationsInFlight(ctx context.Context, after time.Duration) ([]string, error)
- func (s *PostgresStore) RenewClaim(ctx context.Context, claim common.Claim, ttl time.Duration) error
- func (s *PostgresStore) RescheduleAwaitingExecution(ctx context.Context, executionID string, scheduledDate time.Time) (bool, error)
- func (s *PostgresStore) ReserveApprovedRIExchange(ctx context.Context, id, dailyCapUSD, perExchangeCapUSD string) (string, error)
- func (s *PostgresStore) ReserveRIExchange(ctx context.Context, record *RIExchangeRecord, ...) (string, error)
- func (s *PostgresStore) ResolveLadderTrancheFailed(ctx context.Context, req LadderResolveFailed) (*LadderResolveResult, error)
- func (s *PostgresStore) ResolveManagedPlanRootTx(ctx context.Context, tx pgx.Tx, plan *PurchasePlan) (*PurchaseExecution, error)
- func (s *PostgresStore) ResolveMarketplaceListingAttempt(ctx context.Context, purchaseID string, seen MarketplaceListingAttempt, ...) (bool, error)
- func (s *PostgresStore) ResolveRIExchangeDirectExecution(ctx context.Context, req RIExchangeDirectResolve) (*RIExchangeDirectResolveResult, error)
- func (s *PostgresStore) ResolveStaleRIExchange(ctx context.Context, req RIExchangeResolve) (*RIExchangeResolveResult, error)
- func (s *PostgresStore) RotatePendingApprovalToken(ctx context.Context, executionID, tokenHash string, expiresAt time.Time) (bool, error)
- func (s *PostgresStore) SaveAccountCredential(ctx context.Context, accountID, credentialType, encryptedBlob string) error
- func (s *PostgresStore) SaveAccountServiceOverride(ctx context.Context, o *AccountServiceOverride) error
- func (s *PostgresStore) SaveAccountServiceOverrideAuditedTx(ctx context.Context, tx pgx.Tx, o *AccountServiceOverride, audit AuditContext) error
- func (s *PostgresStore) SaveConfigAuditEventTx(ctx context.Context, tx pgx.Tx, ev *AuditEvent) error
- func (s *PostgresStore) SaveExecutionIfStatus(ctx context.Context, execution *PurchaseExecution, expected []string) error
- func (s *PostgresStore) SaveExecutionIfStatusTx(ctx context.Context, tx pgx.Tx, execution *PurchaseExecution, ...) error
- func (s *PostgresStore) SaveGlobalConfig(ctx context.Context, config *GlobalConfig) error
- func (s *PostgresStore) SaveLadderRun(ctx context.Context, run *LadderRunDB) (*LadderRunDB, error)
- func (s *PostgresStore) SaveLadderRunWithTranches(ctx context.Context, run *LadderRunDB, tranches []LadderTrancheDB) (*LadderRunDB, error)
- func (s *PostgresStore) SaveLadderTranches(ctx context.Context, tranches []LadderTrancheDB) error
- func (s *PostgresStore) SavePurchaseExecution(ctx context.Context, execution *PurchaseExecution) error
- func (s *PostgresStore) SavePurchaseExecutionTx(ctx context.Context, tx pgx.Tx, execution *PurchaseExecution) error
- func (s *PostgresStore) SavePurchaseHistory(ctx context.Context, record *PurchaseHistoryRecord) error
- func (s *PostgresStore) SaveRIExchangeDirectExecution(ctx context.Context, record *RIExchangeDirectExecution) error
- func (s *PostgresStore) SaveRIExchangeRecord(ctx context.Context, record *RIExchangeRecord) error
- func (s *PostgresStore) SaveServiceConfig(ctx context.Context, config *ServiceConfig) error
- func (s *PostgresStore) ScheduleApprovedExecution(ctx context.Context, executionID string, fromStatuses []string, ...) (*PurchaseExecution, error)
- func (s *PostgresStore) ScheduleApprovedExecutionTokenPinned(ctx context.Context, executionID string, fromStatuses []string, ...) (*PurchaseExecution, error)
- func (s *PostgresStore) SetCancelledBy(ctx context.Context, executionID, cancelledBy string) error
- func (s *PostgresStore) SetExecutionRecommendationsIfEmptyTx(ctx context.Context, tx pgx.Tx, executionID string, ...) (bool, error)
- func (s *PostgresStore) SetLadderSweepCeiling(ctx context.Context, configID string, usdPerHr *float64) error
- func (s *PostgresStore) SetPlanAccounts(ctx context.Context, planID string, accountIDs []string) error
- func (s *PostgresStore) SetPlanAccountsGated(ctx context.Context, planID string, accountIDs []string, gate PlanWriteGate) error
- func (s *PostgresStore) SetPlanRampBaselineTx(ctx context.Context, tx pgx.Tx, planID string, baseline PlanRampBaseline) (bool, error)
- func (s *PostgresStore) SetRecommendationsCollectionError(ctx context.Context, errMsg string) error
- func (s *PostgresStore) SettleFailedExecution(ctx context.Context, req ExecutionSettleRequest) (*ExecutionSettlement, error)
- func (s *PostgresStore) SettleMarketplaceListing(ctx context.Context, st MarketplaceListingSettlement) (bool, error)
- func (s *PostgresStore) StampFirstDispatchTx(ctx context.Context, tx pgx.Tx, executionID string, horizon time.Duration) (StampResult, error)
- func (s *PostgresStore) StampOfferingClass(ctx context.Context, purchaseID, offeringClass string) error
- func (s *PostgresStore) StampPlanNotificationSent(ctx context.Context, planID string, at time.Time) error
- func (s *PostgresStore) StampRIExchangeApprovedBy(ctx context.Context, id, approverEmail string) error
- func (s *PostgresStore) TransitionExecutionStatus(ctx context.Context, executionID string, fromStatuses []string, ...) (*PurchaseExecution, error)
- func (s *PostgresStore) TransitionExecutionStatusPinned(ctx context.Context, executionID string, fromStatuses []string, ...) (*PurchaseExecution, error)
- func (s *PostgresStore) TransitionExecutionStatusPinnedTx(ctx context.Context, tx pgx.Tx, executionID string, fromStatuses []string, ...) (*PurchaseExecution, error)
- func (s *PostgresStore) TransitionExecutionStatusTokenPinned(ctx context.Context, executionID string, fromStatuses []string, ...) (*PurchaseExecution, error)
- func (s *PostgresStore) TransitionLadderRunStatus(ctx context.Context, id string, fromStatuses []ladder.RunStatus, ...) (*LadderRunDB, error)
- func (s *PostgresStore) TransitionLadderTranche(ctx context.Context, id string, from, to ladder.TrancheStatus, reason string) (bool, error)
- func (s *PostgresStore) TransitionLadderTrancheTx(ctx context.Context, tx pgx.Tx, id string, from, to ladder.TrancheStatus, ...) (bool, error)
- func (s *PostgresStore) TransitionRIExchangeStatus(ctx context.Context, id, fromStatus, toStatus string, actor *string) (*RIExchangeRecord, error)
- func (s *PostgresStore) TransitionRegistrationStatus(ctx context.Context, reg *AccountRegistration, fromStatus string, ...) error
- func (s *PostgresStore) UpdateAccountRegistration(ctx context.Context, reg *AccountRegistration) error
- func (s *PostgresStore) UpdateAccountServiceOverrideAtomic(ctx context.Context, accountID, provider, service string, audit AuditContext, ...) (*AccountServiceOverride, error)
- func (s *PostgresStore) UpdateCloudAccount(ctx context.Context, account *CloudAccount) error
- func (s *PostgresStore) UpdateGlobalConfigAtomic(ctx context.Context, apply func(*GlobalConfig) error) (*GlobalConfig, error)
- func (s *PostgresStore) UpdatePurchaseHistoryListing(ctx context.Context, purchaseID, listingID, listingState string) error
- func (s *PostgresStore) UpdatePurchasePlan(ctx context.Context, plan *PurchasePlan) error
- func (s *PostgresStore) UpdatePurchasePlanGated(ctx context.Context, plan *PurchasePlan, gate PlanWriteGate) error
- func (s *PostgresStore) UpdatePurchasePlanTx(ctx context.Context, tx pgx.Tx, plan *PurchasePlan) error
- func (s *PostgresStore) UpdateServiceConfigAtomic(ctx context.Context, provider, service string, ...) (*ServiceConfig, error)
- func (s *PostgresStore) UpsertLadderConfig(ctx context.Context, cfg *LadderConfigDB) (*LadderConfigDB, error)
- func (s *PostgresStore) UpsertNotificationMute(ctx context.Context, recipientEmail, scope, unmuteToken string) error
- func (s *PostgresStore) UpsertRIUtilizationCache(ctx context.Context, key RIUtilizationCacheKey, payload []byte, ...) error
- func (s *PostgresStore) UpsertRecommendations(ctx context.Context, collectedAt time.Time, recs []RecommendationRecord, ...) error
- func (s *PostgresStore) UpsertRecommendationsWithPartial(ctx context.Context, collectedAt time.Time, recs []RecommendationRecord, ...) error
- func (s *PostgresStore) WithTx(ctx context.Context, fn func(tx pgx.Tx) error) error
- type PurchaseAmountBasis
- type PurchaseExecution
- type PurchaseHistoryFilter
- type PurchaseHistoryPageRow
- type PurchaseHistoryRecord
- type PurchaseHistorySummaryGroup
- type PurchasePlan
- func (p *PurchasePlan) CheckBoundKeys() error
- func (p *PurchasePlan) CheckNoMultiStepSavingsPlans() error
- func (p *PurchasePlan) EnabledProviders() []string
- func (p *PurchasePlan) GraceDays(global *GlobalConfig) int
- func (p *PurchasePlan) RequireVetoWindow() error
- func (p *PurchasePlan) Validate() error
- func (p *PurchasePlan) ValidateDeescalation() error
- func (p *PurchasePlan) VetoWindowEnd(now time.Time) time.Time
- type PurchasePlanFilter
- type PurchaseSuppression
- type RIExchangeCloudCheck
- type RIExchangeDirectAccountRegion
- type RIExchangeDirectCursor
- type RIExchangeDirectExecution
- type RIExchangeDirectHistoryFilter
- type RIExchangeDirectHistoryRow
- type RIExchangeDirectHistoryStore
- type RIExchangeDirectListFilter
- type RIExchangeDirectListPage
- type RIExchangeDirectListStore
- type RIExchangeDirectOutcome
- type RIExchangeDirectResolve
- type RIExchangeDirectResolveResult
- type RIExchangeDirectResolveStore
- type RIExchangeDirectRow
- type RIExchangeRecord
- type RIExchangeResolve
- type RIExchangeResolveResult
- type RIExchangeResolveStore
- type RIExchangeStore
- type RIUtilizationCacheEntry
- type RIUtilizationCacheKey
- type RampAllocationMode
- type RampSchedule
- func (r *RampSchedule) CumulativePercent(step int) float64
- func (r *RampSchedule) FirstExecutionDate(now time.Time) *time.Time
- func (r *RampSchedule) GetCurrentCoverage(baseCoverage float64) float64
- func (r *RampSchedule) GetNextPurchaseDate() time.Time
- func (r *RampSchedule) IsComplete() bool
- func (r *RampSchedule) Validate() error
- func (r *RampSchedule) ValidateAllocationMode() error
- type RampStepBlock
- type RecommendationChunk
- type RecommendationFilter
- type RecommendationListScope
- type RecommendationOverrideRule
- type RecommendationPage
- type RecommendationPageQuery
- type RecommendationRecord
- func (r *RecommendationRecord) AmortizedUpfrontMonthly() float64
- func (r *RecommendationRecord) ComputeIdentity() (ComputeIdentity, error)
- func (r *RecommendationRecord) DetailsAZConfig() (string, error)
- func (r *RecommendationRecord) IdentityAZConfig() (string, error)
- func (r *RecommendationRecord) OnDemandBaseline() (float64, bool)
- func (r *RecommendationRecord) SuppressionVariant() (SuppressionVariant, error)
- func (r *RecommendationRecord) TotalCommitment() float64
- type RecommendationScanKey
- type RecommendationStore
- type RecommendationTriple
- type RecommendationsCollectionPartial
- type RecommendationsFreshness
- type RedshiftLineageConflict
- type RedshiftRetryClock
- type RedshiftTuple
- type ServiceConfig
- type StampResult
- type StoreInterface
- type StoredRecommendation
- type SuccessfulCollect
- type SuppressionVariant
Constants ¶
const ( AWSPartitionStandard = "aws" AWSPartitionChina = "aws-cn" AWSPartitionGovCloud = "aws-us-gov" )
AWS partition names as they appear in the second segment of an ARN.
const ( // DefaultListLimit is the default number of items returned in list operations. DefaultListLimit = 100 // MaxListLimit is the maximum number of items allowed in a single list request. MaxListLimit = 1000 // DefaultExecutionTTLDays is how long execution records are kept. DefaultExecutionTTLDays = 30 // DefaultStaleRecommendationRetentionDays is how long the cached // recommendations of a (provider, account) pair survive once that pair // stops collecting (a removed provider, a disabled account, credentials // that keep failing). Collection runs daily on every cloud (#1580), so // this is about 30 missed collections in a row: long enough to ride out // an outage or an expired credential nobody fixed for a few weeks, short // enough that a pair that is gone for good stops showing within a month. // PruneStaleRecommendations applies it after every collection (#120). DefaultStaleRecommendationRetentionDays = 30 // DefaultMaxRecommendationsInEmail is the max recommendations shown in email notifications. DefaultMaxRecommendationsInEmail = 10 // DefaultPasswordResetExpiry is how long password reset tokens are valid. DefaultPasswordResetExpiry = 1 * time.Hour )
Default configuration values.
const ( // MaxCoverage is the maximum allowed coverage percentage. MaxCoverage = 100 // MinCoverage is the minimum allowed coverage percentage. MinCoverage = 0 // MaxPlanNameLength is the maximum length for plan names. MaxPlanNameLength = 100 // MaxNotificationDaysBefore is the maximum days before purchase to send notification. MaxNotificationDaysBefore = 30 // MaxStepIntervalDays is the maximum interval between ramp steps. MaxStepIntervalDays = 365 // MaxTotalSteps is the maximum number of ramp steps. MaxTotalSteps = 100 // MaxServiceMinCount caps the per-service min-count recommendation // filter. Mirrors the CLI's MaxReasonableInstances ceiling so a typo // (e.g. a stray trailing zero) can't silently suppress every // recommendation. 0 disables the filter; values above this are rejected // at validation time. MaxServiceMinCount = 10000 )
Validation constants.
const ( // DefaultCoveragePercent is the default coverage percentage for new configs. DefaultCoveragePercent = 80 // DefaultNotifyDaysBefore is the default days before purchase to send notification. DefaultNotifyDaysBefore = 7 )
Default values for new configurations.
const ( // RampImmediate means all at once. RampImmediate = "immediate" // RampWeekly25Pct means 25% per week for 4 weeks. RampWeekly25Pct = "weekly-25pct" // #nosec G101 -- schedule constant; gosec misidentifies "pct" suffix as a credential pattern // RampMonthly10Pct means 10% per month for 10 months. RampMonthly10Pct = "monthly-10pct" // Weekly step interval in days. WeeklyStepIntervalDays = 7 // Monthly step interval in days. MonthlyStepIntervalDays = 30 )
Ramp schedule presets.
const ( // HoursPerDay is the number of hours in a day. HoursPerDay = 24 // MinHoursBetweenNotifications is the minimum hours between notification emails. MinHoursBetweenNotifications = 24 )
Time constants.
const ( // TokenByteLength is the length of generated tokens in bytes. TokenByteLength = 32 // MFATimeStep is the TOTP time step in seconds. MFATimeStep = 30 // MFADigits is the number of digits in MFA codes. MFADigits = 6 )
Token constants.
const ( AZConfigRecommendationsMigration = 158 AZConfigSuppressionsMigration = 159 )
The az_config expand migrations (issue #408). A later renumber is an edit of these two constants (plus the migration files).
const ( MinLadderHourlyCommit = 0.000001 MaxLadderHourlyCommitLimit = 1e12 )
MinLadderHourlyCommit and MaxLadderHourlyCommitLimit bound ladder_configs.max_hourly_commit_per_run. Below one micro-dollar the NUMERIC(20,6) column rounds to 0; the upper bound keeps the micro-dollar value inside int64 and far above any real hourly commitment.
const ( RIExchangeDirectStatusSubmitted = "submitted" RIExchangeDirectStatusCompleted = "completed" RIExchangeDirectStatusFailed = "failed" RIExchangeDirectStatusUnknown = "unknown" )
Statuses of an ri_exchange_direct_executions row (issue #82). A row is written as RIExchangeDirectStatusSubmitted before the provider call and moved exactly once to one of the three terminal statuses after it; see migration 000131 for what each one asserts about the money. On AWS, unknown means only that the accept response was lost (the library wrapped the error in common.ErrOutcomeUnknown); migration 000131's "timeout, 5xx, transport error" wording is stale for AWS.
const ( AuditOverrideUpsert = "account_service_override.upsert" AuditOverrideDelete = "account_service_override.delete" AuditOverrideImport = "account_service_override.import" )
Config audit event types.
const ( FanOutShapeSingle = "single" FanOutShapeMulti = "multi" )
Fan-out shapes of a purchase execution lineage (issue #97). The shape decides which key the per-rec provider idempotency tokens derive from: the lineage key itself on the single-account path, "<lineage key>:<account id>" per account on the fan-out path.
const ( LadderTerm = ladder.Term1Year LadderPayment = ladder.PaymentNoUpfront )
The only term and payment option automated ladder buys use (owner decision D6=A). Planning and the claim share them so a tranche is sized, stored and bought as one offering.
const ( RIExchangeDirectListDefaultLimit = 50 RIExchangeDirectListMaxLimit = 200 )
The list's page size: the default, and the most a caller may ask for.
const ( StatusCompleted = "completed" StatusPartiallyCompleted = "partially_completed" )
StatusCompleted / StatusPartiallyCompleted are the two terminal statuses that mean commitment was actually bought. A partially-completed row bought some of its recommendations and failed others (issue #642); it is a real purchase, which is why re-approving one would double-buy.
const ( ListingStateActive = "active" ListingStatePending = "pending" ListingStateCancelled = "cancelled" //nolint:misspell // AWS ListingStatus enum literal, not prose ListingStateClosed = "closed" )
AWS EC2 ReservedInstancesListing status values, mirroring the ec2types.ListingStatus enum. Stored verbatim in purchase_history.listing_state so the strings must match AWS exactly. ListingStatePending is additionally written by the marketplace-list handler as a transient claim that guards against concurrent listing creation (issue #292); the other three come straight from AWS.
const ( PartialReasonPermissionDenied = "permission_denied" PartialReasonThrottled = "throttled" PartialReasonTimeout = "timeout" PartialReasonCanceled = "canceled" PartialReasonNotFound = "not_found" PartialReasonOther = "other" // Advisor rows were kept because the Retail Prices catalog could not be // reached. Those rows may carry an outdated price and must not be // purchased until a good collection re-prices them. PartialReasonPricingUnavailable = "pricing_unavailable" // PartialReasonPricingHoldExpired counts accounts whose pricing hold hit // PricingHoldMaxAge and whose stale rows were evicted; it equals the length // of PartialProviderSweep.ExpiredHoldAccountIDs. PartialReasonPricingHoldExpired = "pricing_hold_expired" )
Reason categories for PartialProviderSweep.Reasons. The set is closed so the API never echoes provider error text.
const ( RIExchangeModeManual = "manual" RIExchangeModeAuto = "auto" )
RIExchangeModeManual and RIExchangeModeAuto are the only accepted ri_exchange_mode values.
const ( MinStepCommitment = 0.01 MaxStepCommitmentLimit = 1e15 )
MinStepCommitment and MaxStepCommitmentLimit bound max_step_commitment to what the NUMERIC(18,2) column stores: below one cent it rounds to 0 and violates CHECK > 0 (a 500), and 1e308 overflows it. NaN fails both comparisons.
const AccountNoticeUnsupportedPartition = "unsupported_partition"
AccountNoticeUnsupportedPartition is the AccountNotice code for an AWS account in a partition where CUDly cannot buy Savings Plans (issue #1194).
const ApprovalTokenTTL = 7 * 24 * time.Hour
ApprovalTokenTTL is the lifetime of a purchase approval token (issue #397). Tokens older than this are rejected by ApproveExecution and loadCancelableExecution. 7 days gives approvers a full business week to act without the window being infinite. Mirror the RI exchange model which uses a 6-hour TTL; purchase approvals are higher-stakes so a longer window is appropriate but must still be bounded.
const AzureRevocationWindowDays = 7
AzureRevocationWindowDays is the length of the Azure reservation free-cancel window: a reservation can be returned for a full refund within this many days of purchase (issue #290). It is the single source of truth for the window, referenced both at purchase-write time (to stamp PurchaseHistoryRecord.RevocationWindowClosesAt) and by the revoke endpoint's window check, so the two never drift.
const BoundKeySeparator = "#"
BoundKeySeparator joins a bound entry's "provider/service" key to its group id: "aws/ec2#<group_id>" (issue #1746).
const DefaultGracePeriodDays = 7
DefaultGracePeriodDays is the fallback window used when a provider has no entry in GlobalConfig.GracePeriodDays. A week gives cloud providers enough time to reflect a fresh commitment in their utilization metrics before we'd re-propose the same capacity.
const DefaultLadderBaselinePercentile = ladder.DefaultBaselinePercentile
DefaultLadderBaselinePercentile is the default usage percentile used to anchor the base commitment layer.
const DefaultLadderBufferFraction = ladder.DefaultBufferFraction
DefaultLadderBufferFraction is the default fraction of the base allocation reserved in short-term / convertible buffer commitments.
const DefaultLadderBufferUtilThreshold = ladder.DefaultBufferUtilizationThresholdPct
DefaultLadderBufferUtilThreshold is the default buffer-layer utilization % below which the engine emits a reshape recommendation.
const DefaultLadderLookbackDays = ladder.DefaultLookbackDays
DefaultLadderLookbackDays is the default historical window (days) used to compute the usage baseline.
const DefaultLadderMaxActionsPerRun = 10
DefaultLadderMaxActionsPerRun is the default cap on the number of PlannedActions the engine may execute per run.
const DefaultLadderTargetCoverage = ladder.DefaultTargetCoveragePct
DefaultLadderTargetCoverage is the default commitment coverage target (%). Aliases ladder.DefaultTargetCoveragePct so only one source of truth exists.
const DefaultPurchaseDelayHours = 48
DefaultPurchaseDelayHours is the default Gmail-style pre-fire delay. 48 hours gives most users a working-day window to spot and cancel an approval they didn't intend.
const DefaultRecommendationsCacheStaleHours = 24
DefaultRecommendationsCacheStaleHours is the default age (hours) after which the recommendations cache triggers a background refresh.
const DefaultRecommendationsLookbackDays = 7
DefaultRecommendationsLookbackDays is the default AWS Cost Explorer lookback window when no explicit value is configured.
const EmptyRootAttachSlackDays = 2
EmptyRootAttachSlackDays is how many days past the notice window a plan's empty root is already offered to the notification tick: a root dated D is visited from D-(N+slack) days, so one missed daily tick no longer strands it.
const LadderCeilingWindow = 24 * time.Hour
LadderCeilingWindow is the rolling window over which the claim sums the commitment already fired for a config against the sweep ceiling. It is not LadderFireGrace: the two are equal today but mean different things.
const LadderChainMaxDepth = 20
LadderChainMaxDepth caps how many executions the reconciler follows along a retry chain (head = the execution the tranche was claimed with). A longer chain is returned truncated, which the reconciler treats as unresolved.
const LadderFireGrace = 24 * time.Hour
LadderFireGrace is how late a scheduled ladder tranche may still be fired. It is the single definition behind both sides of the boundary: in-flight netting counts a scheduled tranche while it is still fireable, and the overdue sweep cancels it once it is not. Keeping both on ladderGraceCutoff guarantees every scheduled row is counted or canceled, never neither (neither would let the next run re-plan an amount the executor can still buy, and both would be bought) and never both.
const MarketplaceTerminalPollCutoffDays = 180
MarketplaceTerminalPollCutoffDays bounds how long a closed or canceled listing whose sale price was never determined is polled, counted from terminal_at (when it first became closed or canceled, migration 000179). Proceeds settle within the AWS Marketplace disbursement cycle (days to weeks), so 180 days is a deliberately conservative upper bound. Past it the listing keeps its terminal state and no proceeds, so totals count it as unsettled (issue #1586). Active and pending listings, and terminal rows with a NULL terminal_at, are always polled.
const MaxBoundIdentitiesPerGroup = 1000
MaxBoundIdentitiesPerGroup caps the recommendations one bound group may hold (issue #1746).
const MaxGracePeriodDays = 90
MaxGracePeriodDays is the ceiling enforced at read time as a safety net. The UI clamps input to [0, 30]; the DB isn't constrained, so a rogue write through psql shouldn't be able to suppress recs for years.
const MaxLadderActionsPerRun = 50
MaxLadderActionsPerRun is the ceiling enforced at validation time. A value above this is almost certainly a misconfiguration and should fail loud rather than fan out unbounded actions.
const MaxPurchaseDelayHours = 168
MaxPurchaseDelayHours is the ceiling for PurchaseDelayHours. One week is long enough for any reasonable review cycle; longer delays make the UX confusing and the scheduler overhead non-trivial.
const MaxRIExchangeUtilizationThreshold = 100.0
MaxRIExchangeUtilizationThreshold is the upper bound of ri_exchange_utilization_threshold, a percentage.
const MaxRecommendationsCacheStaleHours = 8760
MaxRecommendationsCacheStaleHours is the maximum configurable stale threshold: one year. Values above this are rejected at validation time.
const MaxRegistrationDescriptionLen = 2000
MaxRegistrationDescriptionLen caps a registration description at submit and in list results, so a row stored before the cap cannot bloat the list.
const PreApprovalSkipRampTargetMet = "ramp-target-met"
PreApprovalSkipRampTargetMet marks the completed no-op row a ramp step gets when its cumulative target is already held (platform#631). The advance gate (requireRampStepBought) is unchanged and still counts only completed or partially_completed rows as bought, so a failed zero-buy fan-out can never advance the ramp; only CompleteTargetMetStepTx writes this row, in the claim transaction, and the marker tells it apart from a purchase.
const PricingHoldMaxAge = 36 * time.Hour
PricingHoldMaxAge is how long an account's Azure rows stay held through a pricing outage before they are evicted. It is age based because manual and stale-cache refreshes also run collections, so a cycle count is not a time. On a daily schedule the hold is kept on the second run (about 24h) and the account is dropped on the third (about 48h).
const RIExchangeDirectResolveNoteMax = 1000
RIExchangeDirectResolveNoteMax bounds resolution_note, in bytes.
const RIExchangeDirectResolveSubmittedAfter = 10 * time.Minute
RIExchangeDirectResolveSubmittedAfter is how long a submitted AWS direct row must have existed before an operator may resolve it: the direct execute bounds its claim and provider call by one deadline taken before the row is saved (#1841), so no live process can still finalize it after this long. Measured on the database clock, like created_at.
const RIExchangeDirectResolveUnknownCheckAfter = time.Minute
RIExchangeDirectResolveUnknownCheckAfter is how long after an unknown row's completed_at the operator's AWS check must have been made, to allow for DescribeReservedInstances eventual consistency.
const RIExchangeResolveStaleAfter = 6 * time.Hour
RIExchangeResolveStaleAfter is how long a processing RI exchange must have been unchanged before an operator may resolve it. Every writer that can still settle a processing row (the approval request, the scheduled AUTO run) finishes within its own budget: 4m30s on the API path and the task timeout (15m default, TASK_TIMEOUT on Fargate) on the scheduled path. The margin keeps a late settlement from racing an operator's decision, and matches the ladder's fired-tranche threshold.
const ReadoptMaxExpiredAge = 30 * 24 * time.Hour
ReadoptMaxExpiredAge bounds how long after expiry an unapproved plan-step root may be re-armed. updated_at is the expiry time because nothing writes an expired row afterwards; a future writer that bumps it only widens the window.
const RevocationWindow = 24 * time.Hour
RevocationWindow is the time window after a purchase completes during which the buyer may request revocation (issue #291). 24 hours matches the AWS RI/SP support-case window advertised in the post-execution email. It is the single source of truth for both the fresh revocation token's expiry (minted in purchase.rotateApprovalToken) and the enforcement check in api.validateRevokeToken: the two MUST stay equal or a token could expire before the window closes and silently block a valid revoke.
const StatusCanceled = "canceled"
StatusCanceled is the canonical US-spelling status value new code writes.
const StatusExpired = "expired"
StatusExpired is written when an approval lapsed before anyone acted on it.
const StatusFailed = "failed"
StatusFailed is the terminal status written when an execution's purchase attempt errors out, and by the stuck-purchase reaper (internal/purchase/ reaper.go) for rows left in approved/running past its threshold.
const StatusRevocationRequested = "revocation_requested"
StatusRevocationRequested records that an operator asked for a completed purchase to be revoked. The cloud-side revocation happens outside this system (an AWS support case), and no code moves a row out of this status.
Variables ¶
var ( ErrLadderAmendNotFound = errors.New("ladder tranche not found") ErrLadderAmendConflict = errors.New("ladder tranche changed or is no longer editable") ErrLadderAmendInvalid = errors.New("ladder amendment exceeds the original run total, the current per-run cap or the config commitment ceiling") )
var ( ErrExecutionSettleNotFound = errors.New("execution not found") ErrExecutionSettleInvalid = errors.New("invalid execution settle request") ErrExecutionSettleConflict = errors.New("execution cannot be settled") // ErrExecutionSettleNotReady: the settlement migration is not applied yet. ErrExecutionSettleNotReady = errors.New("execution settlement is not available until the database migration is applied") )
Outcomes of an operator settle that the store distinguishes. The handler maps them to 404, 400 and 409.
var ( ErrLadderResolveNotFound = errors.New("ladder tranche not found") ErrLadderResolveInvalid = errors.New("invalid ladder resolve request") ErrLadderResolveConflict = errors.New("ladder tranche cannot be resolved") )
Outcomes of an operator resolve that the store distinguishes. The handler maps them to 404, 400 and 409.
var ( ErrRIExchangeResolveNotFound = errors.New("ri exchange not found") ErrRIExchangeResolveInvalid = errors.New("invalid ri exchange resolve request") ErrRIExchangeResolveConflict = errors.New("ri exchange cannot be resolved") )
Outcomes of an operator resolve of a stale processing RI exchange (#692) that the store distinguishes. The handler maps them to 404, 400 and 409.
var ( RampStepSucceededStatuses = []string{StatusCompleted, StatusPartiallyCompleted} RampStepSettledStatuses = []string{StatusCompleted, StatusPartiallyCompleted, StatusCanceled} RampStepStuckStatuses = []string{StatusFailed, StatusExpired} )
The three ramp-step status classes below drive the advance gate in CompletePlanStep and the stuck-ramp report GetStuckRampSteps (issue #1861). They are separate exported lists rather than one, because the gate asks two different questions of the same rows and the health report asks a third:
- RampStepSucceededStatuses answers "did this fan-out unit buy?". A step no unit bought must not advance the ramp at all.
- RampStepSettledStatuses answers "is this fan-out unit done holding the step open?". It is deliberately an ALLOWLIST: a status added to the schema later holds the step open until someone classifies it, which is the fail-closed direction on a money path.
- RampStepStuckStatuses answers "is this unit stuck rather than in flight?". Only these produce the plan-health ramp_blocked factor, so a retry still working its way through pending/running reads as recovery rather than as a frozen ramp.
Canceled counts as settled but neither succeeded nor stuck: to cancel a step's row is an operator deciding that unit will not buy, and that decision is what releases a ramp an unrecoverable account would otherwise freeze. Both spellings are listed for the duration of the expand-contract rename (migration 000089, contract in #1278), same as HealthScoredExecutionStatuses.
RampStepSucceededStatuses is the same predicate migration 000098 spells out inline as status IN ('completed','partially_completed') when it decides which rows a sibling has already bought for. The migration is frozen SQL and cannot import this, so the two are kept identical by hand: changing one without the other would make the backfill and the advance gate disagree about what "bought" means.
var DefaultSettings = []ConfigSetting{ { Key: "purchase_defaults.term", Value: 3, Type: "int", Category: "purchase_defaults", Description: "Default commitment term in years (1 or 3)", UpdatedAt: time.Time{}, }, { Key: "purchase_defaults.payment_option", Value: "no-upfront", Type: "string", Category: "purchase_defaults", Description: "Default payment option: no-upfront, partial-upfront, all-upfront", UpdatedAt: time.Time{}, }, { Key: "purchase_defaults.coverage", Value: 80.0, Type: "float", Category: "purchase_defaults", Description: "Default coverage percentage (0-100)", UpdatedAt: time.Time{}, }, { Key: "purchase_defaults.ramp_schedule", Value: "immediate", Type: "string", Category: "purchase_defaults", Description: "Default ramp schedule: immediate, weekly-25pct, monthly-10pct", UpdatedAt: time.Time{}, }, { Key: "notification.days_before", Value: 3, Type: "int", Category: "notification", Description: "Days before purchase to send notification", UpdatedAt: time.Time{}, }, { Key: "notification.email_enabled", Value: true, Type: "bool", Category: "notification", Description: "Enable email notifications for purchases", UpdatedAt: time.Time{}, }, { Key: "notification.approval_required", Value: true, Type: "bool", Category: "notification", Description: "Require approval before executing purchases", UpdatedAt: time.Time{}, }, { Key: "notification.email_from", Value: "noreply@cudly.io", Type: "string", Category: "notification", Description: "Email sender address for notifications", UpdatedAt: time.Time{}, }, { Key: "providers.aws_enabled", Value: true, Type: "bool", Category: "providers", Description: "Enable AWS provider for recommendations and purchases", UpdatedAt: time.Time{}, }, { Key: "providers.azure_enabled", Value: false, Type: "bool", Category: "providers", Description: "Enable Azure provider for recommendations and purchases", UpdatedAt: time.Time{}, }, { Key: "providers.gcp_enabled", Value: false, Type: "bool", Category: "providers", Description: "Enable GCP provider for recommendations and purchases", UpdatedAt: time.Time{}, }, { Key: "security.session_duration_hours", Value: 24, Type: "int", Category: "security", Description: "Session duration in hours before re-authentication required", UpdatedAt: time.Time{}, }, { Key: "security.lockout_attempts", Value: 5, Type: "int", Category: "security", Description: "Failed login attempts before account lockout", UpdatedAt: time.Time{}, }, { Key: "security.lockout_duration_minutes", Value: 15, Type: "int", Category: "security", Description: "Account lockout duration in minutes", UpdatedAt: time.Time{}, }, { Key: "security.password_min_length", Value: 12, Type: "int", Category: "security", Description: "Minimum password length requirement", UpdatedAt: time.Time{}, }, { Key: "security.password_require_special", Value: true, Type: "bool", Category: "security", Description: "Require special characters in passwords", UpdatedAt: time.Time{}, }, { Key: "security.password_require_number", Value: true, Type: "bool", Category: "security", Description: "Require numbers in passwords", UpdatedAt: time.Time{}, }, { Key: "security.password_require_uppercase", Value: true, Type: "bool", Category: "security", Description: "Require uppercase letters in passwords", UpdatedAt: time.Time{}, }, { Key: "scheduling.auto_collect", Value: false, Type: "bool", Category: "scheduling", Description: "Automatically collect recommendations on schedule", UpdatedAt: time.Time{}, }, { Key: "scheduling.collect_schedule", Value: "rate(1 day)", Type: "string", Category: "scheduling", Description: "Schedule for automatic recommendation collection (EventBridge format)", UpdatedAt: time.Time{}, }, { Key: "scheduling.auto_purchase", Value: false, Type: "bool", Category: "scheduling", Description: "Automatically execute approved purchase plans", UpdatedAt: time.Time{}, }, { Key: "scheduling.purchase_schedule", Value: "rate(1 day)", Type: "string", Category: "scheduling", Description: "Schedule for checking and executing purchase plans (EventBridge format)", UpdatedAt: time.Time{}, }, { Key: "aws.rds.min_utilization_percent", Value: 50.0, Type: "float", Category: "aws", Description: "Minimum RDS instance utilization for RI recommendations", UpdatedAt: time.Time{}, }, { Key: "aws.elasticache.min_utilization_percent", Value: 50.0, Type: "float", Category: "aws", Description: "Minimum ElastiCache node utilization for RI recommendations", UpdatedAt: time.Time{}, }, { Key: "aws.opensearch.min_utilization_percent", Value: 50.0, Type: "float", Category: "aws", Description: "Minimum OpenSearch instance utilization for RI recommendations", UpdatedAt: time.Time{}, }, { Key: "aws.ec2.include_convertible", Value: true, Type: "bool", Category: "aws", Description: "Include convertible EC2 Reserved Instances in recommendations", UpdatedAt: time.Time{}, }, { Key: "aws.savings_plans.compute_enabled", Value: true, Type: "bool", Category: "aws", Description: "Include Compute Savings Plans in recommendations", UpdatedAt: time.Time{}, }, { Key: "aws.savings_plans.ec2_enabled", Value: true, Type: "bool", Category: "aws", Description: "Include EC2 Instance Savings Plans in recommendations", UpdatedAt: time.Time{}, }, { Key: "aws.savings_plans.sagemaker_enabled", Value: true, Type: "bool", Category: "aws", Description: "Include SageMaker Savings Plans in recommendations", UpdatedAt: time.Time{}, }, { Key: "thresholds.min_monthly_savings", Value: 10.0, Type: "float", Category: "thresholds", Description: "Minimum monthly savings ($) to include recommendation", UpdatedAt: time.Time{}, }, { Key: "thresholds.min_savings_percentage", Value: 5.0, Type: "float", Category: "thresholds", Description: "Minimum savings percentage to include recommendation", UpdatedAt: time.Time{}, }, { Key: "thresholds.max_upfront_cost", Value: 0.0, Type: "float", Category: "thresholds", Description: "Maximum upfront cost ($) per purchase (0 = no limit)", UpdatedAt: time.Time{}, }, { Key: "retention.purchase_history_days", Value: 1095, Type: "int", Category: "retention", Description: "Days to retain purchase history (3 years default)", UpdatedAt: time.Time{}, }, { Key: "retention.recommendation_cache_hours", Value: 24, Type: "int", Category: "retention", Description: "Hours to cache recommendation data", UpdatedAt: time.Time{}, }, { Key: "ri_exchange.auto_exchange_enabled", Value: false, Type: "bool", Category: "ri_exchange", Description: "Master toggle for automated RI exchange", UpdatedAt: time.Time{}, }, { Key: "ri_exchange.mode", Value: "manual", Type: "string", Category: "ri_exchange", Description: "Exchange mode: manual (email approval) or auto (fully automated)", UpdatedAt: time.Time{}, }, { Key: "ri_exchange.utilization_threshold", Value: 95.0, Type: "float", Category: "ri_exchange", Description: "Utilization percentage below which an RI triggers exchange consideration", UpdatedAt: time.Time{}, }, { Key: "ri_exchange.max_payment_per_exchange_usd", Value: 0.0, Type: "float", Category: "ri_exchange", Description: "Maximum payment per single exchange in USD (0 = refuse any payment)", UpdatedAt: time.Time{}, }, { Key: "ri_exchange.max_payment_daily_usd", Value: 0.0, Type: "float", Category: "ri_exchange", Description: "Maximum total daily exchange spend in USD (0 = refuse any payment)", UpdatedAt: time.Time{}, }, { Key: "ri_exchange.lookback_days", Value: 30, Type: "int", Category: "ri_exchange", Description: "Days of utilization data to consider for exchange recommendations", UpdatedAt: time.Time{}, }, { Key: "api.rate_limit_requests_per_minute", Value: 100, Type: "int", Category: "api", Description: "Maximum API requests per minute per user", UpdatedAt: time.Time{}, }, { Key: "api.rate_limit_enabled", Value: true, Type: "bool", Category: "api", Description: "Enable API rate limiting", UpdatedAt: time.Time{}, }, { Key: "api.timeout_seconds", Value: 30, Type: "int", Category: "api", Description: "Default API request timeout in seconds", UpdatedAt: time.Time{}, }, }
DefaultSettings defines the default configuration values for CUDly. UpdatedAt is the zero time.Time{} for every entry: these are static compile-time defaults and have never been "updated" by a user.
var ErrAZConfigMigrationNotReady = fmt.Errorf("az_config migrations %06d and %06d are not applied", AZConfigRecommendationsMigration, AZConfigSuppressionsMigration)
ErrAZConfigMigrationNotReady means the recommendations and purchase_suppressions az_config migrations are not both applied. Apply them before running a release that reads or writes az_config.
var ErrAccountExternalIDHasHistory = errors.New("account external id is referenced by purchase history")
ErrAccountExternalIDHasHistory means UpdateCloudAccount would change an account's external_id while purchase_history or ri_exchange_history rows key on the old value, which would orphan them (issue #120). Permanent for the request: callers map it to 409.
var ErrApprovalTokenChanged = errors.New("approval token no longer matches the execution")
ErrApprovalTokenChanged is returned (wrapped) by TransitionExecutionStatusTokenPinned when the execution is still in an allowed status but its stored approval token no longer matches the one the caller supplied, or has expired: the token was rotated (re-notification) or lapsed after the caller validated it and before the transition (issue #590).
var ErrAuditLoss = errors.New("audit loss: execution persistence failed after purchase")
ErrAuditLoss is returned (wrapped) by executeAndFinalize when the purchase run itself completed but the subsequent SavePurchaseExecution call failed. The execution is already "running" (per the CAS in claimAndRedrive) but its final state was never persisted -- the row is stranded in "running" until the next recovery sweep. Callers that silence all drive errors (e.g. claimAndRedrive) must propagate this sentinel so the sweep surfaces the persistence failure rather than silently dropping the stranded row.
var ErrAzurePricingNotReady = errors.New("azure pricing migration not ready")
var ErrDuplicatePendingRegistration = errors.New("a pending registration already exists for this account")
ErrDuplicatePendingRegistration is returned by CreateAccountRegistration when a pending registration already exists for the same provider+external_id.
var ErrEditorReconciliationRequired = errors.New("plan is managed by the schedule editor")
ErrEditorReconciliationRequired means the plan is editor-managed and a legacy writer tried to change what only the schedule editor may. Permanent for the request: callers map it to 409; a background caller would skip, not retry.
var ErrEmptyPurchaseID = errors.New("purchase history record has no purchase id")
ErrEmptyPurchaseID is returned by SavePurchaseHistory for a record with no purchase_id. History is saved once per (provider, account_id, purchase_id), so an empty ID would be silently dropped after the first one (#774).
var ErrExecutionNotInExpectedStatus = errors.New("execution not in expected status")
ErrExecutionNotInExpectedStatus is returned by TransitionExecutionStatus when the target execution exists but its current status is not in the allowed `fromStatuses` set -- i.e. the atomic CAS rejected because some other writer transitioned the row first (e.g. the real executor finished between the reaper's SELECT and CAS). Callers can use errors.Is to distinguish this legitimate race-loss from a hard DB error.
var ErrExecutionRetryLinked = errors.New("execution already has a retry successor")
ErrExecutionRetryLinked is returned by RecoverReapedExecutionTx when the reaped row already has a retry successor linked. Overwriting it could mean two live purchases for one logical step, so the caller must fail loud and flag a possible double buy instead of recovering.
var ErrGroupTargetRefused = errors.New("group target edit refused")
ErrGroupTargetRefused marks a group target edit that is not allowed: an unbound plan, an unknown group, or a cap that would rise (issue #1057).
var ErrInvalidBoundGroup = errors.New("invalid bound plan group")
ErrInvalidBoundGroup marks a bound plan whose config groups conflict.
ErrLadderCeilingUnavailable: the sweep-ceiling migration is not applied yet.
var ErrLadderConfigBusy = errors.New("ladder config row is locked by another writer")
ErrLadderConfigBusy means another writer holds the ladder_configs row lock, so DisableLadderConfigTx did nothing and the caller must roll back and retry.
var ErrLadderLockTimeout = errors.New("ladder config lock timed out")
ErrLadderLockTimeout means the per-config ladder lock was not acquired within ladderLockTimeout (SQLSTATE 55P03). The operation did nothing; retry later.
var ErrLadderRunCancelActorRequired = errors.New("canceling a ladder run requires the actor's email")
ErrLadderRunCancelActorRequired is returned by CancelLadderRun when no actor is supplied, so a ladder run can never be canceled with a NULL canceled-by audit column.
var ErrLadderRunCancelViaTransition = errors.New("ladder run cancel must use CancelLadderRun so the actor is recorded")
ErrLadderRunCancelViaTransition is returned by TransitionLadderRunStatus for a transition to RunStatusCanceled: that path cannot stamp the canceled-by audit column, so cancels must go through CancelLadderRun (issue #542).
var ErrLadderTimelineRate = errors.New("ladder timeline row has an unreadable amount basis or commitment rate")
ErrLadderTimelineRate marks a stored amount basis or rate that cannot be converted; callers must not fall back to the native amount.
var ErrLadderTrancheNotFired = errors.New("ladder tranche is not fired")
ErrLadderTrancheNotFired means the tranche row is gone or no longer fired when the reconciler locked it: another writer won, nothing to do.
var ErrManagedPlanLiveExecutions = errors.New("managed plan still has active or unsettled purchases")
ErrManagedPlanLiveExecutions means deleting an editor-managed plan would detach an execution that may still hold or buy capacity.
var ErrMarketplaceListingEnded = errors.New("the marketplace listing is already recorded as ended")
ErrMarketplaceListingEnded is returned by UpdatePurchaseHistoryListing when the row already records the same listing as canceled or closed and the write would mark it live again. AWS never revives an ended listing, so such a write comes from a request that raced the cancel and lost.
var ErrMarketplaceTotalsScopeRequired = errors.New("marketplace listing proceeds totals require an account scope")
ErrMarketplaceTotalsScopeRequired is returned when proceeds totals are asked for without an account scope, so the read never covers every account.
var ErrMultiStepSavingsPlans = errors.New("multi-step ramps do not support Savings Plans: use a single-step (immediate) ramp or remove the Savings Plans service")
ErrMultiStepSavingsPlans marks an armed multi-step plan with an enabled Savings Plans service. Step 1 suppresses the whole SP recommendation for 7 days, so later steps find nothing and the ramp strands (platform#631, Q7). Read-only query for already-armed hits: runbooks/armed-multi-step-savings-plans-plans.md.
var ErrNoVetoWindow = errors.New("plan has no veto window")
ErrNoVetoWindow marks a plan whose notification window is empty: with NotificationDaysBefore < 1 the email goes out when the purchase is already due, so the human veto the notified status stands for has no time to happen.
var ErrNotFound = errors.New("not found")
ErrNotFound is returned when a requested config-store row does not exist.
var ErrPlanNameTaken = errors.New("a plan with this name already exists")
ErrPlanNameTaken is returned (as *PlanNameTakenError) by CreatePurchasePlanWithAccounts when a plan the caller can see already has the same name (issue #1734).
var ErrPlanNotPlannable = errors.New("plan step dates cannot be derived")
ErrPlanNotPlannable marks a plan whose step dates cannot be derived: it has already started, its dates are managed by hand, or its ramp is incomplete.
var ErrPlanProviderMismatch = errors.New("plan provider mismatch")
ErrPlanProviderMismatch is returned (wrapped) when an account attached to a plan belongs to a provider the plan's services do not use.
var ErrPlanScheduleCommandConflict = errors.New("plan schedule command id reused with a different request")
ErrPlanScheduleCommandConflict means a command id was already used with a different request (hash or plan). The caller must pick a new id.
var ErrPlanScheduleReceiptExists = errors.New("plan schedule command receipt already exists")
ErrPlanScheduleReceiptExists means a receipt with this command id is already stored. Receipts are immutable, so the caller replays instead of rewriting.
var ErrPlanScheduleRetryable = errors.New("plan schedule command is busy, retry")
ErrPlanScheduleRetryable means the command did not commit because of lock contention, a deadlock or a serialization failure. Nothing was written and the same command may be sent again.
var ErrPurchaseAlreadyRevoked = errors.New("purchase is already revoked")
ErrPurchaseAlreadyRevoked is returned (wrapped) by FlipPurchaseRevocationInFlight when the purchase_history row exists but is already revoked: a concurrent revoke finished first, so the caller must not start another provider return (issue #316).
var ErrPurchasePlanConflict = errors.New("purchase plan changed")
ErrPurchasePlanConflict means a plan changed after the caller read it.
var ErrRIExchangeDailyCapExceeded = errors.New("RI exchange daily cap exceeded")
ErrRIExchangeDailyCapExceeded marks a reservation refused because the initial quote does not fit the remaining daily or per-exchange headroom.
var ErrRIExchangeDirectExecutionNotSubmitted = errors.New("ri exchange direct execution is not awaiting an outcome")
ErrRIExchangeDirectExecutionNotSubmitted is returned by FinalizeRIExchangeDirectExecution when the row does not exist or has already been finalized. The first recorded outcome stands: an audit row is never rewritten.
var ErrRIExchangeDirectResolveNotReady = errors.New("resolving direct RI exchanges is not available until the database migration is applied")
ErrRIExchangeDirectResolveNotReady: the resolution migration is not applied yet.
var ErrRIExchangeExpired = errors.New("ri exchange has expired")
ErrRIExchangeExpired is returned (wrapped) by TransitionRIExchangeStatus when the record exists but its expires_at has passed, so the approval or rejection window is closed. The HTTP layer answers it with 410, like an expired purchase approval token (issue #587).
var ErrRIExchangeNotInExpectedStatus = errors.New("ri exchange status transition failed")
ErrRIExchangeNotInExpectedStatus is returned (wrapped) by TransitionRIExchangeStatus when the record exists and has not expired but its status is not the expected one: another writer, such as a concurrent approve or reject, transitioned it first. The HTTP layer answers it with 409.
var ErrRIExchangeReservationInvalid = errors.New("RI exchange reservation is invalid")
ErrRIExchangeReservationInvalid marks a reservation that can never succeed as stored: a malformed cap, quote or spend value, or a row that is not processing. Retrying cannot help, unlike a connection or lock failure.
var ErrRIExchangeSourceInFlight = errors.New("RI exchange source RI is held by an exchange in progress")
ErrRIExchangeSourceInFlight marks a reservation refused because another exchange still holds one of its source RIs in processing, so that exchange may already have happened at AWS (issue #1050).
var ErrRampLedgerUntrusted = errors.New("this ramp's purchase history from before the retention ledger cannot be verified, so it cannot size further steps")
var ErrRampStepAlreadyCounted = errors.New("ramp step already counted")
ErrRampStepAlreadyCounted is returned (wrapped) by CompletePlanStep when the plan has moved PAST the completing step. Unlike ErrRampStepCountedBySibling this is an anomaly worth an audit note on the execution row: the purchase bought commitment for a step the ramp counted earlier and will never count again, which is how a step_number stamped by pre-#1669 code (or during that deploy overlap) surfaces.
var ErrRampStepCountedBySibling = errors.New("ramp step already counted by a sibling execution")
ErrRampStepCountedBySibling is returned (wrapped) by CompletePlanStep when the plan is sitting exactly on the completing step: a sibling execution of the same step won the race to advance it, moments earlier. Routine on a multi-account step whose last two accounts finish together, and benign -- the step WAS counted, just not by this caller -- so it must not be stamped on the execution row. A note there would flip a cleanly-completed purchase into History's audit-gap rendering, which keys on a non-empty error.
var ErrRampStepIncomplete = errors.New("ramp step incomplete")
ErrRampStepIncomplete is returned (wrapped) by CompletePlanStep when the ramp step the completing execution belongs to has not been bought in full: another cloud account on that step is still outstanding, or nothing on the step bought at all. Counting it would report commitment the plan has not made (issue #1861). Transient by construction -- it clears when the outstanding account buys, when its row is canceled, or when the step is abandoned -- so callers must treat it as "not yet", not as a failure of the purchase that just completed.
The sentinel text stays generic because both cases wrap it and each supplies its own specifics; naming one of them here would mis-describe the other.
var ErrReadoptNotReady = errors.New("re-arming an expired plan step is not available until the database migration is applied")
ErrReadoptNotReady: the re-adoption migration is not applied yet.
var ErrReferenceTokenCollision = errors.New("registration reference token collision")
ErrReferenceTokenCollision is returned by CreateAccountRegistration when the generated reference_token is already taken. The caller should regenerate the token and retry; it says nothing about whether the account is registered.
var ErrRegistrationConflict = errors.New("registration status conflict: already processed")
ErrRegistrationConflict is returned when a registration status transition fails because another request already changed the status (concurrent modification).
var ErrRevocationInFlight = errors.New("purchase revocation is already in flight")
ErrRevocationInFlight is returned (wrapped) by FlipPurchaseRevocationInFlight when the purchase_history row is unrevoked but another request already holds the in-flight claim: that request is posting (or has posted) the provider return, so the caller must not post another one (issue #1518).
var HealthScoredExecutionStatuses = []string{ StatusFailed, StatusCanceled, }
HealthScoredExecutionStatuses are the execution statuses the plan health score counts (internal/api/plan_health.go). It lives here, in the package that owns both the status constants and the retention sweep, because two unrelated-looking pieces of code have to agree on it exactly:
- CountExecutionsByPlanAndStatus is asked for these statuses and windows them on updated_at.
- CleanupOldExecutions must not delete a row in one of these statuses while that window still covers it. Retaining on any other clock lets the sweep purge a row the score is still counting, which shows up as a plan's health score jumping overnight with no operator action.
Keeping one exported slice rather than a literal list on each side is what makes that agreement structural: adding a status to the score automatically extends the sweep's exclusion, so the two cannot drift.
var PresetRampSchedules = map[string]RampSchedule{
"immediate": {
Type: "immediate",
PercentPerStep: 100,
TotalSteps: 1,
},
"weekly-25pct": {
Type: "weekly",
PercentPerStep: 25,
StepIntervalDays: 7,
TotalSteps: 4,
},
"monthly-10pct": {
Type: "monthly",
PercentPerStep: 10,
StepIntervalDays: 30,
TotalSteps: 10,
},
}
PresetRampSchedules provides common ramp-up configurations.
var TerminalExecutionStatuses = []string{ StatusCompleted, StatusPartiallyCompleted, StatusFailed, StatusCanceled, StatusExpired, StatusRevocationRequested, }
TerminalExecutionStatuses are the execution statuses that no executor, scheduler or reaper will act on again. DeleteCloudAccount detaches rows in these statuses from the account being deleted (cloud_account_id = NULL, the same treatment purchase_history gets from its ON DELETE SET NULL FK) so the history survives the delete, and CountLiveExecutionsForAccount counts every other row as one that still needs the account (issue #265).
It is an ALLOWLIST on purpose: a status added to the schema later counts as live, and so blocks the delete, until someone classifies it here. Blocking a delete is recoverable; detaching an execution that will still run is not, because a row with no account falls back to plan fan-out or ambient credentials.
A failed row is listed even though it can be retried. A retry of a row detached here still carries the deleted account on its recommendations, so the executor refuses it before submission ("account not found") instead of buying elsewhere.
var ValidCollectionSchedules = []string{"", "hourly", "daily", "weekly"}
ValidCollectionSchedules lists all valid collection schedule values.
var ValidOfferingClasses = []string{"convertible", "standard"}
ValidOfferingClasses lists the accepted EC2 RI offering class values for GlobalConfig. The empty string is also accepted (maps to "convertible" at purchase time to preserve pre-694 behavior).
var ValidPaymentOptions = []string{"no-upfront", "partial-upfront", "all-upfront"}
ValidPaymentOptions lists the AWS-canonical payment options. Kept for backwards compatibility; prefer ValidPaymentOptionsByProvider for provider-aware validation.
var ValidPaymentOptionsByProvider = map[string][]string{
"aws": {"no-upfront", "partial-upfront", "all-upfront"},
"azure": {"upfront", "monthly"},
"gcp": {"monthly"},
}
ValidPaymentOptionsByProvider maps each provider to the payment option tokens it accepts. Each provider's set is the canonical set verified against the provider's service-client switch statements:
aws: {no-upfront, partial-upfront, all-upfront}: the three RI/SP billing tiers exposed by AWS APIs.
azure: {upfront, monthly}: verified against the 7 Azure service-client switches in providers/azure/services/{compute,cache,cosmosdb,database, search,synapse,managedredis}/client.go. (The savingsplans client mirrors AWS's three-tier set, but Azure savings-plan recs are not currently emitted; GetRecommendations returns []. The canonical set follows the only path that emits today.)
gcp: {monthly}: GCP CUDs are billed monthly across the commitment term; there is no upfront billing tier. See providers/gcp/services/computeengine/client.go:buildCommitmentRequests which takes only a Plan (TWELVE_MONTH/THIRTY_SIX_MONTH) and never reads PaymentOption.
Cross-provider tokens are rejected loudly by the validator. Legacy AWS-style tokens emitted by older code paths are canonicalized via NormalizePaymentOption at the rec-emission boundary BEFORE reaching this validator (see internal/scheduler/scheduler.go:convertRecommendations).
var ValidProviders = []string{"aws", "azure", "gcp"}
ValidProviders lists all supported cloud providers.
var ValidRampScheduleTypes = []string{"immediate", "weekly", "monthly", "custom"}
ValidRampScheduleTypes lists all supported ramp schedule types.
var ValidRecommendationsLookbackDays = []int{7, 30, 60}
ValidRecommendationsLookbackDays lists the AWS Cost Explorer LookbackPeriodInDays enum values. Other values are rejected.
Functions ¶
func AWSPartitionFromARN ¶
AWSPartitionFromARN returns the partition segment of an AWS ARN (arn:<partition>:<service>:...). It returns "" for inputs that are not ARNs or that name a partition other than aws, aws-cn and aws-us-gov.
func AccountConfigKey ¶
AccountConfigKey returns the map key used by ResolveAccountConfigsForRecs. Exposed so callers (scheduler filter, dashboard aggregator) can look up the resolved config for a given rec without re-implementing the format.
func AmountBasisSchemaReady ¶
AmountBasisSchemaReady reports whether purchase_history.amount_basis exists, for readers outside this package that run their own purchase_history SQL.
func ApprovalTokenMatches ¶
ApprovalTokenMatches reports whether rawSupplied is the token that hashes to storedHash, using a constant-time comparison of the two fixed-length hex digests (so neither the digest length nor a byte-by-byte early exit leaks timing information). Returns false whenever either side is empty -- an empty stored hash (no token set) must never be treated as satisfied by an empty supplied token.
func CanonicalSuppressionEngine ¶
CanonicalSuppressionEngine reads an engine "" as the engine the pinned library now emits, so a suppression and a rec match across the bumps that gave those recs an engine: go#702 for Azure cache ("redis", Advisor Redis recs had none) and go#735 for Azure relational-db ("sqlserver", every Azure SQL Database rec is SQL Server; issue #1950). Suppressions written before the bump keep engine "" in the table and are canonicalized on read. Other tuples are unchanged: an AWS RDS "" never matches "mysql".
func CanonicalSuppressionService ¶
CanonicalSuppressionService maps legacy AWS service slugs, and the dash-free spellings of the per-type Savings Plans slugs, to their canonical slug so a suppression and a rec match whichever spelling each was stored under (issues #1412, #1420, #1422). Other providers' services, including Azure and GCP "compute" and Azure "savingsplans", are returned unchanged. It lives in config, the lowest package both the scheduler and BuildSuppressions import; the pinned cloud-commitments-go common package has no such mapping.
func DerivePlanProviders ¶
func DerivePlanProviders(plan *PurchasePlan) ([]string, error)
DerivePlanProviders extracts the distinct set of providers a plan targets. Each service entry names its provider through its key, in the "provider/service" form buildServiceConfig writes or the legacy "provider:service" form migration 000040 wrote (internal/api findServiceKey accepts both). An entry whose key has neither form, such as a legacy alias kept under its original key, is identified by its own Provider field, the same field the legacy edit path (mergeRequestedServices) and plan step resolution go by.
An entry identified neither way is skipped: that can only narrow the set, so the check stays at least as strict. What it must never do is leave the set empty, because callers read an empty set as "no restriction" and would accept an account of any provider (issue #316). So when the plan has services but none of them identifies a provider, this returns an error. A nil plan, or a plan with no services, yields an empty set.
func DerivePlanServices ¶
func DerivePlanServices(plan *PurchasePlan) []string
DerivePlanServices extracts the distinct service names a plan targets from the "provider/service" and "provider:service" keys of plan.Services, sorted. A bound plan's "#<group_id>" suffix is not part of its service name.
func EffectiveStepCap ¶
EffectiveStepCap is min(group cap, plan cap) with a nil cap unbounded.
func GetAllCategories ¶
func GetAllCategories() []string
GetAllCategories returns a list of all configuration categories.
func GetDefaultValue ¶
GetDefaultValue returns the default value for a given key.
func HashApprovalToken ¶
HashApprovalToken returns the SHA-256 hex digest of a raw approval / revocation / rejection token, in the exact format persisted to the approval_token_hash column (purchase_executions, ri_exchange_history). Mirrors internal/auth's unexported hashSessionToken so every long-lived secret token in this codebase is hashed the same way before it touches storage (issue #103: the approval_token columns these replace held the raw, directly usable secret).
Empty input returns "" so "no token" continues to mean an empty/NULL column value rather than the hash of an empty string -- callers must not treat HashApprovalToken("") as a valid stored value.
func IsBoundServiceKey ¶
IsBoundServiceKey reports whether a services key names a bound group entry.
func IsUSDCommitmentCurrency ¶
IsUSDCommitmentCurrency is the one rule for "this CommitmentCurrency is USD": whitespace-trimmed and case-insensitive. Empty (unknown) is not USD.
func IsValidRIExchangeMode ¶
IsValidRIExchangeMode reports whether mode is exactly "manual" or "auto". The match is case-sensitive and does not trim, because the RI exchange consumer compares the literal values: "Auto", "" or " auto" are not equivalent to "auto" there.
func LadderAmountFloat ¶
LadderAmountFloat converts an exact planned tranche amount to the float64 a tranche row stores, flooring it to the column's six decimal places (see LadderAmountFloor). The go precision contract (pkg/ladder LadderCapability.PurchaseLayer, go#354) floors provider commitments and forbids callers rounding a *big.Rat up on the way to float64; nearest-float conversion can do exactly that just below a decimal boundary. Flooring at six decimals keeps a provider's five-decimal truncation identical to truncating the exact amount and keeps an amount below a provider minimum below it.
Below 1e9 USD/hr the floored value has at most 15 significant digits, so the result's shortest decimal form is the floored value itself and the store writes it without any further rounding. Above about 1e9 USD/hr the nearest float64 of the floored decimal can round it up by less than one float64 ulp, and nothing here refuses that; it is unreachable under the provider's 1e6 USD/hr cap.
func LadderAmountFloor ¶
LadderAmountFloor floors an exact planned tranche amount to the six decimal places ladder_tranches.amount_usd_hr stores, returning the exact floored decimal. A positive amount below 0.000001 floors to zero; callers must not persist that as a $0 tranche.
func LadderCapMicros ¶
LadderCapMicros returns the per-run hourly cap in exact micro-dollars. Caps with more than 6 decimals are rejected instead of rounded, so the stored and the compared value are identical (same approach as StepCapCents).
func LadderInFlightOnDemand ¶
func LadderInFlightOnDemand(rows []LadderInFlightRow) (float64, error)
LadderInFlightOnDemand is the rows' on-demand-equivalent total, summed exactly and rounded up to the next float only when the float is below it.
func LadderSweepCeilingMicros ¶
LadderSweepCeilingMicros is LadderCapMicros for the per-sweep ceiling; the error names max_hourly_commit_per_sweep.
func LadderTrancheSettled ¶
func LadderTrancheSettled(status ladder.TrancheStatus) bool
LadderTrancheSettled reports whether a tranche status can no longer lead to a purchase through its existing execution: anything but scheduled or fired. Unknown statuses count as settled, so Retry fails closed.
func NormalizePaymentOption ¶
NormalizePaymentOption maps a raw payment-option token onto the canonical token the given provider semantically models (see ValidPaymentOptionsByProvider). It exists so the recommendation-emission boundary (see internal/scheduler/scheduler.go:convertRecommendations) can defensively canonicalize any AWS-style token that a code path or a globally-default payment-option setting might stamp onto a non-AWS rec, before the rec is persisted and later validated against the provider-canonical set.
Returns (canonical, true) when raw is already canonical for the provider or has an unambiguous canonical mapping. Returns ("", false) for unknown providers and (raw, false) for tokens that have no canonical mapping on the given provider (e.g. an Azure/GCP-style "upfront" on AWS) — callers can use ok=false to surface the unmapped token at the next validator boundary. Per-provider mapping:
- AWS : passthrough (AWS already speaks the three-tier set).
- Azure: all-upfront → upfront, no-upfront → monthly, partial-upfront → monthly (no semantic equivalent — coerce to the no-upfront tier, CUDly's default billing schedule for Azure, rather than drop the rec; caller may log). Coercing to upfront here would silently bill an all-upfront schedule the caller never chose: the canonical token is persisted onto the execution and copied into common.Recommendation.PaymentOption (internal/purchase/execution.go), and the reservation-purchase billingPlan wiring being added in #1495/#1502 maps only upfront/monthly tokens and hard-errors on partial-upfront, so landing on monthly keeps the rec on the no-upfront schedule instead of an irreversible upfront charge — Azure does not allow changing a reservation's billing frequency after purchase.
- GCP : all-upfront → monthly, no-upfront → monthly, partial-upfront → monthly, upfront → monthly (GCP CUDs are inherently monthly-billed — every non-monthly token collapses to the one billing plan GCP actually models). The collapse from "upfront" to "monthly" is what makes the existing providers/gcp/services/computeengine/client.go:804 stamp safe: the scheduler.convertRecommendations boundary coerces it once before persistence so the rec carries the canonical token downstream.
The partial-upfront coercion is deliberate on both Azure and GCP: dropping the rec would be a silent data loss for the user, while coercing to the closest billing model the provider offers preserves the rec without changing the total the caller committed to. Microsoft documents that choice as cost-neutral: "The total cost of up-front and monthly reservations is the same and you don't pay any extra fees when you choose to pay monthly" (https://learn.microsoft.com/en-us/azure/cost-management-billing/reservations/prepare-buy-reservation). Caveat from the same page: monthly payments are NOT offered for SUSE Linux reservations, Red Hat plans, Azure Red Hat OpenShift licenses, or pre-purchase plans, so for those products the coerced token can make Azure reject the purchase. That is the intended failure mode — a loud purchase- time rejection is preferable to silently committing the caller to an upfront charge they never chose and cannot undo.
The caller is expected to log a warning when raw != canonical so an operator notices the upstream input bug.
The frontend mirrors this mapping in frontend/src/commitmentOptions.ts:normalizePaymentValue (it decides which option the plan/purchase dropdowns pre-select); the two must stay in lockstep.
Empty raw passes through as ("", true) — callers that distinguish "unset" from "invalid" can check the returned bool only when raw is non-empty.
func PaymentCoercionChangesSchedule ¶
PaymentCoercionChangesSchedule reports whether rewriting raw to canonical actually changes what the customer pays and when, as opposed to merely renaming the same schedule into the target provider's vocabulary.
Azure "all-upfront" -> "upfront" and Azure/GCP "no-upfront" -> "monthly" are renames: identical cash flow, different spelling. Azure "partial-upfront" -> "monthly" and GCP "upfront" -> "monthly" are real changes: the customer is billed on a schedule they did not ask for.
Only real changes are worth putting in front of a user (#1503). The fan-out purchase modal submits the AWS-style "all-upfront" for Azure buckets by construction (frontend/src/lib/purchase-compatibility.ts: paymentOptionsFor), so treating every rewrite as a change would fire a "billing schedule adjusted" warning on the ordinary Azure upfront purchase and train users to dismiss the one notice that matters.
func RecIdentityKey ¶
func RecIdentityKey(rec *RecommendationRecord) (string, error)
RecIdentityKey is the tuple a price is a function of: the same twelve components (the ninth is the zonal EC2 availability zone, "" for every other rec, issue #792; the tenth and eleventh are the EC2 platform and tenancy read from Details, "" when absent, issue #806; the twelfth is the database az_config read from Details, "" when absent, issue #408) behind RecommendationRecord.ID, with a nil and an empty CloudAccountID collapsed together (as purchaseConstraintSets and the store's account_key both do). Provider and payment are lowercased because validatePurchaseRecommendation canonicalises the request side.
func RequireLadderCommitmentBasis ¶
func RequireLadderCommitmentBasis(tr *LadderTrancheDB) error
RequireLadderCommitmentBasis refuses a tranche whose amount is not proven to be commitment dollars with a valid stored rate, so a caller never buys an on-demand-equivalent amount as the commitment.
func ResolveAccountConfigsForRecs ¶
func ResolveAccountConfigsForRecs( ctx context.Context, store AccountConfigReader, recs []RecommendationRecord, ) (map[string]*ServiceConfig, error)
ResolveAccountConfigsForRecs walks the recs once, collects the unique (cloud_account_id, provider, service) triples, and resolves each via ResolveServiceConfig(provider, service, global, override). Returns a map keyed by AccountConfigKey -> resolved *ServiceConfig.
A nil CloudAccountID uses an empty account key and resolves only global configuration. Triples with neither global configuration nor an account override are omitted from the map.
When a per-account override exists but no global ServiceConfig does, the override is applied against a synthesized default baseline (Enabled: true) so the operator's intent is honored even when a global row has not been created yet.
Errors from either lookup are returned alongside the partial map so the caller decides whether to fail the whole operation or pass through. The scheduler / dashboard read paths choose pass-through (over-show vs. under-show); the money path (ListRecommendationsStrict) fails. Suppression reads fail closed on every path, since they are a spend guard rather than a display filter (issue #111).
func ResolveConfiguredCoverageForRecs ¶
func ResolveConfiguredCoverageForRecs( ctx context.Context, store AccountConfigReader, recs []RecommendationRecord, ) (map[string]float64, error)
ResolveConfiguredCoverageForRecs returns the resolved coverage percentage per AccountConfigKey for the triples whose coverage was set by an operator: an override that carries a coverage (a configured 0 included) or a global ServiceConfig with a non-zero coverage. A global 0 and an override without a coverage over no global row are left out as unset.
func RevocationWindowClosesAtFor ¶
RevocationWindowClosesAtFor returns the timestamp at which the in-app revoke button should stop being offered for a purchase of the given provider made at purchaseTime, or nil when the provider has no in-app free-cancel window.
Only Azure has a direct-API free-cancel window in Phase 1. AWS EC2 RIs have a 24h window but no direct cancel API (revocation goes through an AWS Support case, out of Phase-1 scope), and GCP commitments have no free-cancel window at all, so both return nil and the History UI hides the button.
func SavingsNetOfUpfront ¶
SavingsNetOfUpfront reports whether Savings already has the amortized upfront deducted, so a payback period needs it added back. AWS reservations and Azure report it that way (Cost Explorer's own break-even only reproduces with it); Savings Plans and GCP are left as reported because their semantics are not established.
func ServiceEntryProvider ¶
ServiceEntryProvider returns the provider a services entry names: the key's prefix when the key has one, else the entry's Provider field, else "".
func StepCapCents ¶
StepCapCents returns the cap in whole cents, exactly. The column is NUMERIC(18,2) and Postgres rounds the decimal text pgx sends (the shortest representation of the float), so a cap with more than two decimals would be stored as a different value than the one compared (1.005 stores as 1.01). Such caps are rejected instead of rounded, which makes the stored and the compared value identical. The decimal text is parsed, not multiplied, because v*100 loses exactness near the 1e15 limit.
func StoredRecommendationIdentity ¶
func StoredRecommendationIdentity(provider string, commitment common.CommitmentType, region, resourceType string) (storedRegion, storedResourceType string)
StoredRecommendationIdentity returns the region and resource type the platform stores and keys a recommendation under. AWS Savings Plan recs are stored with both blank (ids, upsert key, suppressions and bound plan identities rely on it); family and region stay in the details JSON. A blank ResourceType is never filtered by the library duplicate check, so any future Savings Plan recfilter wiring must rebuild identity from details.
func StoredRecommendationService ¶
func StoredRecommendationService(provider string, service common.ServiceType) string
StoredRecommendationService is the service slug the platform stores and keys a provider recommendation under. go#702 relabelled Azure Redis recs from cache to memorydb; the platform's IDs, suppressions and per-account config key Azure Redis as cache, so it maps back here. AWS memorydb is a distinct service and is unchanged.
func SuppressionEngineSpellings ¶
SuppressionEngineSpellings returns every engine spelling a stored rec can carry that CanonicalSuppressionEngine maps to canonical.
func SuppressionServiceSpellings ¶
SuppressionServiceSpellings returns every service spelling a stored rec can carry that CanonicalSuppressionService maps to canonical for provider: canonical itself (when it maps to itself) and its legacy and dash-free aliases.
func SuppressionTupleKey ¶
SuppressionTupleKey joins a suppression 6-tuple into the string PageStoredRecommendations matches rows against. Two distinct tuples can only produce the same key when a value contains the separator; such a row is merely decided in Go instead of SQL, which is still exact.
func ValidateRIExchangeUtilizationThreshold ¶
ValidateRIExchangeUtilizationThreshold is the rule for a utilization threshold a caller writes: above 0 and at most MaxRIExchangeUtilizationThreshold. 0 is refused because the store replaces a stored 0 with its 95 default, so accepting it would silently apply a different threshold. Both write routes (PUT /api/ri-exchange/config and PUT /api/config) use it; name is the field as that route's caller knows it.
func ValidateRampScheduleEnv ¶
ValidateRampScheduleEnv validates a ramp-schedule value read from an environment variable (e.g. DEFAULT_RAMP_SCHEDULE). Empty string is always valid ("use the purchase manager's built-in default"). Non-empty values must be in ValidRampScheduleTypes. Called by the server startup boundary so misconfiguration is caught at boot time rather than silently propagated into purchases (issue #1026).
Types ¶
type AccountConfigReader ¶
type AccountConfigReader interface {
GetServiceConfig(ctx context.Context, provider, service string) (*ServiceConfig, error)
GetAccountServiceOverride(ctx context.Context, accountID, provider, service string) (*AccountServiceOverride, error)
}
AccountConfigReader is the minimal store surface needed by ResolveAccountConfigsForRecs. Both PostgresStore (production) and the scheduler's MockConfigStore (tests) already satisfy it via the broader StoreInterface — we narrow here so the helper can be unit-tested with a tiny ad-hoc fake.
type AccountNotice ¶
AccountNotice is a derived, non-persisted warning about a cloud account, returned with the account so the UI can show it.
func AWSPartitionNotices ¶
func AWSPartitionNotices(partition string) []AccountNotice
AWSPartitionNotices returns the notices for an AWS account in the given partition, or nil when the partition needs none.
type AccountRegistration ¶
type AccountRegistration struct {
UpdatedAt time.Time `json:"updated_at"`
CreatedAt time.Time `json:"created_at"`
CloudAccountID *string `json:"cloud_account_id,omitempty"`
ReviewedAt *time.Time `json:"reviewed_at,omitempty"`
ReviewedBy *string `json:"reviewed_by,omitempty"`
AzureClientID string `json:"azure_client_id,omitempty"`
GCPProjectID string `json:"gcp_project_id,omitempty"`
Description string `json:"description,omitempty"`
SourceProvider string `json:"source_provider,omitempty"`
AWSRoleARN string `json:"aws_role_arn,omitempty"`
AWSAuthMode string `json:"aws_auth_mode,omitempty"`
AWSExternalID string `json:"aws_external_id,omitempty"`
AzureSubscriptionID string `json:"azure_subscription_id,omitempty"`
AzureTenantID string `json:"azure_tenant_id,omitempty"`
ID string `json:"id"`
AzureAuthMode string `json:"azure_auth_mode,omitempty"`
ContactEmail string `json:"contact_email"`
GCPClientEmail string `json:"gcp_client_email,omitempty"`
GCPAuthMode string `json:"gcp_auth_mode,omitempty"`
GCPWIFAudience string `json:"gcp_wif_audience,omitempty"` // Full WIF provider resource; only set for federated path.
RegCredentialType string `json:"reg_credential_type,omitempty"`
RegCredentialPayload string `json:"-"` // never returned in API responses (encrypted at rest)
ReferenceToken string `json:"-"` // registrant's status credential; only submitRegistration returns it (#310)
RejectionReason string `json:"rejection_reason,omitempty"`
AccountName string `json:"account_name"`
ExternalID string `json:"external_id"`
Provider string `json:"provider"`
Status string `json:"status"` // pending, approved, rejected
HasCredentials bool `json:"has_credentials,omitempty"` // derived: true when reg_credential_type is set
}
AccountRegistration represents a self-service registration request from a target account owner. Submitted via POST /api/register during Terraform apply of the federation IaC, then approved or rejected by a CUDly admin.
type AccountRegistrationFilter ¶
type AccountRegistrationFilter struct {
Status *string
Provider *string
Search string
// Limit and Offset page the result; Limit 0 means MaxListLimit.
Limit int
Offset int
}
AccountRegistrationFilter for ListAccountRegistrations queries.
type AccountServiceOverride ¶
type AccountServiceOverride struct {
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
RampSchedule *string `json:"ramp_schedule,omitempty"`
Enabled *bool `json:"enabled,omitempty"`
Term *int `json:"term,omitempty"`
Payment *string `json:"payment,omitempty"`
Coverage *float64 `json:"coverage,omitempty"`
Provider string `json:"provider"`
ID string `json:"id"`
Service string `json:"service"`
AccountID string `json:"account_id"`
IncludeEngines []string `json:"include_engines,omitempty"`
ExcludeRegions []string `json:"exclude_regions,omitempty"`
IncludeTypes []string `json:"include_types,omitempty"`
ExcludeTypes []string `json:"exclude_types,omitempty"`
IncludeRegions []string `json:"include_regions,omitempty"`
ExcludeEngines []string `json:"exclude_engines,omitempty"`
}
AccountServiceOverride is a sparse per-account override on top of the global ServiceConfig. Nil pointer fields inherit the global value.
type AccountStore ¶
type AccountStore interface {
// Cloud accounts
CreateCloudAccount(ctx context.Context, account *CloudAccount) error
GetCloudAccount(ctx context.Context, id string) (*CloudAccount, error)
// GetCloudAccountByExternalID looks up a cloud account by its
// (provider, external_id) pair. Used by the scheduler's ambient
// collector path to tag rec rows with the registered host-account's
// UUID when the Lambda's STS identity matches a registered (but
// possibly disabled) account — so the approve-modal Account column
// shows the account name instead of `(ambient)`. Returns
// (nil, nil) when no row matches (the caller treats this as the
// genuine orphan case). The underlying
// `UNIQUE(provider, external_id)` constraint on cloud_accounts
// guarantees the lookup hits an index.
GetCloudAccountByExternalID(ctx context.Context, provider, externalID string) (*CloudAccount, error)
UpdateCloudAccount(ctx context.Context, account *CloudAccount) error
DeleteCloudAccount(ctx context.Context, id string) error
ListCloudAccounts(ctx context.Context, filter CloudAccountFilter) ([]CloudAccount, error)
// Account credentials (encrypted blobs; never returned via API)
SaveAccountCredential(ctx context.Context, accountID, credentialType, encryptedBlob string) error
// GetAccountCredential returns ErrNotFound when the account has no
// credential of credentialType.
GetAccountCredential(ctx context.Context, accountID, credentialType string) (string, error)
DeleteAccountCredentials(ctx context.Context, accountID string) error
HasAccountCredentials(ctx context.Context, accountID string) (bool, error)
// Account service overrides
GetAccountServiceOverride(ctx context.Context, accountID, provider, service string) (*AccountServiceOverride, error)
SaveAccountServiceOverride(ctx context.Context, override *AccountServiceOverride) error
DeleteAccountServiceOverride(ctx context.Context, accountID, provider, service string) error
// SaveAccountServiceOverrideAuditedTx upserts the override inside the
// caller's WithTx transaction and records the change (the stored row
// before and after) in config_audit_events, issue #1493. It serializes on
// the override's key, so a caller writing several overrides in one tx must
// write them in a consistent key order. A write that changes no setting
// records nothing. override is updated to the stored row.
SaveAccountServiceOverrideAuditedTx(ctx context.Context, tx pgx.Tx, override *AccountServiceOverride, audit AuditContext) error
// UpdateAccountServiceOverrideAtomic serializes a read-merge-write of one
// override under the same lock as SaveAccountServiceOverrideAuditedTx and
// audits the write. merge receives the stored row (nil when none) and
// returns the full row to write; its error aborts the write and is
// propagated unchanged. Returns the saved row.
UpdateAccountServiceOverrideAtomic(ctx context.Context, accountID, provider, service string, audit AuditContext, merge func(existing *AccountServiceOverride) (*AccountServiceOverride, error)) (*AccountServiceOverride, error)
// DeleteAccountServiceOverrideAuditedTx deletes the override inside the
// caller's transaction and records the deleted row in config_audit_events.
// Deleting a missing override records nothing.
DeleteAccountServiceOverrideAuditedTx(ctx context.Context, tx pgx.Tx, accountID, provider, service string, audit AuditContext) error
// SaveConfigAuditEventTx records a config_audit_events row inside the
// caller's transaction (the override import's own event). An empty ID is
// filled in.
SaveConfigAuditEventTx(ctx context.Context, tx pgx.Tx, event *AuditEvent) error
ListAccountServiceOverrides(ctx context.Context, accountID string) ([]AccountServiceOverride, error)
// Plan ↔ account association
SetPlanAccounts(ctx context.Context, planID string, accountIDs []string) error
// SetPlanAccountsGated is SetPlanAccounts with gate run under the plan's
// row lock, before the write (nil gate: plain set).
SetPlanAccountsGated(ctx context.Context, planID string, accountIDs []string, gate PlanWriteGate) error
GetPlanAccounts(ctx context.Context, planID string) ([]CloudAccount, error)
// Account registrations (self-service enrollment via federation IaC)
CreateAccountRegistration(ctx context.Context, reg *AccountRegistration) error
GetAccountRegistration(ctx context.Context, id string) (*AccountRegistration, error)
GetAccountRegistrationByToken(ctx context.Context, token string) (*AccountRegistration, error)
ListAccountRegistrations(ctx context.Context, filter AccountRegistrationFilter) ([]AccountRegistration, error)
UpdateAccountRegistration(ctx context.Context, reg *AccountRegistration) error
// TransitionRegistrationStatus atomically updates a registration's workflow fields.
// actor is the UUID of the reviewer (nil for system-initiated transitions).
TransitionRegistrationStatus(ctx context.Context, reg *AccountRegistration, fromStatus string, actor *string) error
// ClearRegistrationCredentialPayload removes the encrypted credential kept
// with a registration. A missing id is not an error.
ClearRegistrationCredentialPayload(ctx context.Context, registrationID string) error
// ApproveAccountRegistration atomically approves a pending registration,
// creates its cloud account and links them. Returns ErrRegistrationConflict
// when the registration is no longer pending; on any error nothing is saved.
ApproveAccountRegistration(ctx context.Context, reg *AccountRegistration, account *CloudAccount, actor *string) error
DeleteAccountRegistration(ctx context.Context, id string) error
}
AccountStore holds the cloud account, override and registration methods of StoreInterface; StoreInterface embeds it.
type AuditActor ¶
AuditActor is who made a change. Identity is never empty: the email, or the admin API key actor. UserID and APIKeyID are set only when they are real users/API key IDs.
type AuditContext ¶
type AuditContext struct {
ParentEventID *string
Details map[string]any
Actor AuditActor
}
AuditContext is passed with each audited override write: the actor, the import event the write belongs to (nil for a single PUT or DELETE) and optional event details (an import row's number).
type AuditEvent ¶
type AuditEvent struct {
CreatedAt time.Time
ParentEventID *string
AccountID *string
Provider *string
Service *string
Actor AuditActor
ID string
EventType string
Before json.RawMessage
After json.RawMessage
Details json.RawMessage
}
AuditEvent is one config_audit_events row. Before and After are the override settings as JSON (nil for none).
type CloudAccount ¶
type CloudAccount struct {
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
// Azure-specific
AzureTenantID string `json:"azure_tenant_id,omitempty"`
AzureSubscriptionID string `json:"azure_subscription_id,omitempty"`
AzureClientID string `json:"azure_client_id,omitempty"`
AzureAuthMode string `json:"azure_auth_mode,omitempty"`
CreatedBy string `json:"created_by,omitempty"`
Provider string `json:"provider"`
ExternalID string `json:"external_id"`
// AWS-specific
AWSAuthMode string `json:"aws_auth_mode,omitempty"`
AWSRoleARN string `json:"aws_role_arn,omitempty"`
AWSExternalID string `json:"aws_external_id,omitempty"`
AWSBastionID string `json:"aws_bastion_id,omitempty"`
AWSWebIdentityTokenFile string `json:"aws_web_identity_token_file,omitempty"`
Name string `json:"name"`
ContactEmail string `json:"contact_email,omitempty"`
ID string `json:"id"`
// GCPWIFAudience is the full Workload Identity Pool provider
// resource used as the STS audience when exchanging a CUDly
// KMS-signed JWT for a GCP access token. Only set for accounts
// using the secret-free workload_identity_federation path.
// Shape: //iam.googleapis.com/projects/<number>/locations/global/workloadIdentityPools/<pool>/providers/<provider>
GCPWIFAudience string `json:"gcp_wif_audience,omitempty"`
// GCP-specific
GCPProjectID string `json:"gcp_project_id,omitempty"`
GCPClientEmail string `json:"gcp_client_email,omitempty"`
GCPAuthMode string `json:"gcp_auth_mode,omitempty"`
Description string `json:"description,omitempty"`
BastionAccountName string `json:"bastion_account_name,omitempty"` // derived, not stored in DB
// Notices are warnings the API derives for the response, such as the
// aws-cn Savings Plans limitation (issue #1194). Derived, not stored in DB.
Notices []AccountNotice `json:"notices,omitempty"`
IsSelf bool `json:"is_self,omitempty"` // derived, not stored in DB
AWSIsOrgRoot bool `json:"aws_is_org_root,omitempty"` // AWS-specific
CredentialsConfigured bool `json:"credentials_configured"` // derived, not stored in DB
Enabled bool `json:"enabled"`
}
CloudAccount represents a single managed cloud account/subscription/project.
func (*CloudAccount) AWSPartition ¶
func (a *CloudAccount) AWSPartition() string
AWSPartition returns the AWS partition of the account, taken from its role ARN. It returns "" for non-AWS accounts and for AWS accounts with no role ARN (access_keys mode, or a self-account on ambient credentials), whose partition is not known without calling AWS.
type CloudAccountFilter ¶
type CloudAccountFilter struct {
Provider *string
Enabled *bool
BastionID *string // return accounts whose aws_bastion_id = *BastionID
Search string // substring match on name or external_id
}
CloudAccountFilter for ListCloudAccounts queries.
type ComputeIdentity ¶
ComputeIdentity is the EC2 platform and tenancy of a recommendation, the two Details fields that distinguish otherwise identical recommendations (issue #806). Values are VERBATIM: AWS platform is the raw Cost Explorer string ("Linux/UNIX"), so no trimming or case folding.
func (ComputeIdentity) IsZero ¶
func (c ComputeIdentity) IsZero() bool
IsZero reports whether neither field is known (non-compute recs, legacy rows without Details).
type ConfigSetting ¶
type ConfigSetting struct {
UpdatedAt time.Time `json:"updated_at"`
Value any `json:"value"`
Key string `json:"key"`
Type string `json:"type"` // int, float, bool, string, json
Category string `json:"category"`
Description string `json:"description"`
}
ConfigSetting represents a configuration setting for the defaults system.
func GetDefaultSetting ¶
func GetDefaultSetting(key string) *ConfigSetting
GetDefaultSetting returns the complete default setting for a given key.
func GetDefaultsByCategory ¶
func GetDefaultsByCategory(category string) []ConfigSetting
GetDefaultsByCategory returns all default settings for a given category.
type DoomedRoot ¶
type DoomedRoot struct {
StepNumber int
}
DoomedRoot names the next ramp step whose empty root row the notification tick can never fill. Returned by GetDoomedNextRoots and rendered by the plan-health step_will_not_attach factor.
type ExecutionScope ¶
type ExecutionScope struct {
// UserID is the caller. An execution with no cloud_account_id is kept when
// this user created it, because a row that cannot be attributed to one
// account is shown to its creator only. "" matches a NULL creator.
UserID string
// AccountIDs lists every account value the scope can allow: the scope's
// literal entries plus the UUID and external number of each registered
// account it allows. Empty keeps no attributed execution (fail closed).
AccountIDs []string
}
ExecutionScope is the SQL form of a restricted account scope.
type ExecutionSettleRequest ¶
type ExecutionSettleRequest struct {
ExecutionID string
Actor string
Reason string
Acknowledge bool
}
ExecutionSettleRequest asks to settle a failed plan execution whose outcome is unknown. Actor is the acting principal's id. Acknowledge must be true: the operator states they checked the cloud account and accept that the row will never be retried.
type ExecutionSettlement ¶
type ExecutionSettlement struct {
ExecutionID string
Status string
SettledAt time.Time
SettledBy string
Settlement string
Replayed bool
}
ExecutionSettlement is the stored settlement. Replayed is true when an identical earlier request had already settled the row and nothing was written.
type ExecutionStatusCounts ¶
ExecutionStatusCounts maps an execution status value to the number of executions in that status, for a single plan. Returned by CountExecutionsByPlanAndStatus; a status with no rows is simply absent from the map, so a plain lookup yields the correct zero.
type ExecutionSummaryGroup ¶
type ExecutionSummaryGroup struct {
Status string
CloudAccountID *string
CreatedByUserID *string
Recommendations []RecommendationRecord
Count int
}
ExecutionSummaryGroup aggregates the purchase_executions rows that share status, cloud_account_id, created_by_user_id and the ordered list of their recommendations' (provider, cloud_account_id) pairs. Recommendations carries only Provider and CloudAccountID (nil when absent or empty), in stored order, which is everything the History handler's execution filters and scope check read.
type ExecutionsByStatusesQuery ¶
type ExecutionsByStatusesQuery struct {
// Start and End bound scheduled_date, inclusive. nil leaves a side open.
Start *time.Time
End *time.Time
// Scope, when non-nil, keeps only executions the account scope can allow.
// nil is an unrestricted caller.
Scope *ExecutionScope
// Provider keeps executions with at least one recommendation for this
// provider. "" applies no provider filter.
Provider string
// PlanID matches purchase_executions.plan_id exactly, as
// HistoryExecutionsPageQuery.PlanID does. "" applies no plan filter.
PlanID string
Statuses []string
// AccountIDs keeps executions whose cloud_account_id is one of these
// values, or, when cloud_account_id is NULL, that have a recommendation
// whose cloud_account_id is one of them. Empty applies no account filter.
AccountIDs []string
Limit int
}
ExecutionsByStatusesQuery selects executions for the History view's actionable class (issue #632). Statuses and Limit mean what they mean for GetExecutionsByStatuses. The other fields push the History filters and the caller's account scope into SQL, so the Limit cap applies to rows the caller can be shown rather than to every tenant's rows.
Every predicate is a superset of the History handler's Go check (matchesExecution and the account scope), which still runs on the result: SQL may keep a row Go then drops, never the reverse.
type GlobalConfig ¶
type GlobalConfig struct {
AutoPurchaseChangedVia *string `json:"-" db:"auto_purchase_changed_via"`
NotificationEmail *string `json:"notification_email,omitempty" dynamodbav:"notification_email,omitempty"`
// AutoPurchaseChanged{By,At,Via} stamp the last change of the switch
// (migration 000115): actor, time, credential kind. NULL = never changed.
// json:"-" so PUT /api/config cannot forge them by unmarshalling onto this
// struct; the whole-config upsert round-trips them (read, modify, write).
AutoPurchaseChangedBy *string `json:"-" db:"auto_purchase_changed_by"`
AutoPurchaseChangedAt *time.Time `json:"-" db:"auto_purchase_changed_at"`
LadderExecutionChangedVia *string `json:"-" db:"ladder_execution_changed_via"`
LadderExecutionChangedAt *time.Time `json:"-" db:"ladder_execution_changed_at"`
// LadderExecutionChanged{By,At,Via} stamp the last change of
// LadderExecutionEnabled (migration 000116); same json:"-" reasoning.
LadderExecutionChangedBy *string `json:"-" db:"ladder_execution_changed_by"`
// GracePeriodDays is a per-provider window (in days) during which
// just-purchased capacity is suppressed from the recommendations
// list so users don't re-buy the same capacity while the cloud
// provider's utilization metrics catch up. Keys are provider slugs
// ("aws", "azure", "gcp"). Missing keys default to DefaultGracePeriodDays
// (7). An explicit 0 disables suppression for that provider. Use
// GracePeriodFor to read a specific provider's effective value (it
// applies the default + safety clamp).
GracePeriodDays map[string]int `json:"grace_period_days,omitempty" dynamodbav:"grace_period_days,omitempty"`
CollectionSchedule string `json:"collection_schedule"`
DefaultRampSchedule string `json:"default_ramp_schedule" dynamodbav:"default_ramp_schedule"`
DefaultPayment string `json:"default_payment" dynamodbav:"default_payment"`
RIExchangeMode string `json:"ri_exchange_mode" dynamodbav:"ri_exchange_mode"`
// OfferingClass controls the EC2 Reserved Instance offering class used
// during purchase. Accepted values: "convertible" (default) and
// "standard". Convertible RIs can be exchanged for a different
// instance family/size/region/OS; Standard RIs are locked to the exact
// instance type for the full term but are ~5% cheaper.
// Unknown values are rejected at purchase time with an explicit error.
OfferingClass string `json:"offering_class,omitempty" dynamodbav:"offering_class,omitempty"`
EnabledProviders []string `json:"enabled_providers" dynamodbav:"enabled_providers"`
RIExchangeMaxPerExchangeUSD float64 `json:"ri_exchange_max_per_exchange_usd" dynamodbav:"ri_exchange_max_per_exchange_usd"`
RIExchangeUtilizationThreshold float64 `json:"ri_exchange_utilization_threshold" dynamodbav:"ri_exchange_utilization_threshold"`
RIExchangeLookbackDays int `json:"ri_exchange_lookback_days" dynamodbav:"ri_exchange_lookback_days"`
// RecommendationsCacheStaleHours is the age (hours) at which the
// recommendations cache is considered stale and a background refresh
// fires automatically (stale-while-revalidate). 0 disables automatic
// background refresh; the cron scheduler and the manual Refresh button
// still work regardless. Valid range: 0–8760 (up to one year).
// Default: 24.
RecommendationsCacheStaleHours int `json:"recommendations_cache_stale_hours" db:"recommendations_cache_stale_hours"`
// RecommendationsLookbackDays is the AWS Cost Explorer lookback window
// (days) used when fetching fresh recommendations. Must be one of 7,
// 30, or 60 -- the AWS Cost Explorer LookbackPeriodInDays enum.
// GCP CUD Recommender has no equivalent lookback parameter (fixed
// internally); this setting applies to AWS only.
// Default: 7.
RecommendationsLookbackDays int `json:"recommendations_lookback_days" db:"recommendations_lookback_days"`
// PurchaseDelayHours is the Gmail-style pre-fire delay (issue #291 wave-2).
// When > 0, approving a purchase defers the actual cloud SDK call by this
// many hours. The user receives a "scheduled, revoke before X" email
// immediately after approval and may cancel at $0 until the window closes.
// 0 means immediate-execute (backward compat). Valid range: [0, 168].
// Default: 48.
PurchaseDelayHours int `json:"purchase_delay_hours" db:"purchase_delay_hours"`
NotificationDaysBefore int `json:"notification_days_before"`
DefaultTerm int `json:"default_term" dynamodbav:"default_term"`
DefaultCoverage float64 `json:"default_coverage" dynamodbav:"default_coverage"`
RIExchangeMaxDailyUSD float64 `json:"ri_exchange_max_daily_usd" dynamodbav:"ri_exchange_max_daily_usd"`
// RI Exchange automation settings
RIExchangeEnabled bool `json:"ri_exchange_enabled" dynamodbav:"ri_exchange_enabled"`
// AutoPurchaseEnabled is the global kill switch for AutoPurchase plans
// (migration 000112; the scheduling.auto_purchase default). Default false:
// no AutoPurchase plan notifies or executes until an operator opts in.
// Manual purchases (Opportunities, token approval) are unaffected.
AutoPurchaseEnabled bool `json:"auto_purchase_enabled" db:"auto_purchase_enabled"`
// LadderExecutionEnabled gates ladder purchases and reshapes (migration
// 000083). BOTH LadderingEnabled AND LadderExecutionEnabled must be true
// for a sweep that buys or reshapes to act. Planning (ladder_run) never
// reads it: its capability always has the disabled write side, which
// returns a typed ErrLadderExecutionDisabled. Default false: deployments
// that enable laddering produce plans but never call AWS purchase APIs
// until an operator explicitly opts in.
LadderExecutionEnabled bool `json:"ladder_execution_enabled" db:"ladder_execution_enabled"`
ApprovalRequired bool `json:"approval_required" dynamodbav:"approval_required"`
// LadderingEnabled is the global kill-switch for the commitment-laddering
// feature (issue #1333 phase 3). When false (the default), no laddering
// engine runs fire regardless of per-account LadderConfig.Enabled settings.
// Set to true to allow per-account configs to activate individually.
LadderingEnabled bool `json:"laddering_enabled" db:"laddering_enabled"`
AutoCollect bool `json:"auto_collect"`
// RequireDifferentApprover enables 4-eyes approval mode (issue #1005).
// When true, the user who created a purchase execution cannot approve it
// themselves; a different person with approval rights must do so. This is
// a standard SOX / SOC2 segregation-of-duties control. Default: false.
// Admins who created an execution and need to approve it must disable this
// mode first (the admin wildcard is NOT exempt from the restriction).
// While it is on, unattended RI exchange runs (RIExchangeMode "auto" and
// ladder reshapes) run as "manual" and only raise pending records
// (issue #679), and recommendation-bearing AutoPurchase steps are not
// auto-executed: they wait for a human approval in the approval queue
// (issue #1771); empty steps still route as before. A step root
// pre-created with the plan keeps its human creator, who then cannot
// approve it. A step root pre-created through the admin API key (no
// creator and not system-created) cannot be approved by anyone while this
// is on: it waits, then expires, and a human recreates the plan; the
// overdue tick does not re-arm such a root (#1785), nobody could approve it.
RequireDifferentApprover bool `json:"require_different_approver" dynamodbav:"require_different_approver"`
// ExperimentalGCPPlanTerm (migration 000173) makes GCP Compute
// recommendation collection take the CUD term from each recommendation's
// root Commitment plan (RecommendationParams.ExperimentalGCPPlanTerm in
// cloud-commitments-go). EXPERIMENTAL: the plan payload shape is unverified
// against a live Recommender. Default false keeps the 1yr term default.
ExperimentalGCPPlanTerm bool `json:"experimental_gcp_plan_term" db:"experimental_gcp_plan_term"`
}
GlobalConfig represents the global CUDly configuration.
func (*GlobalConfig) GetPurchaseDelay ¶
func (g *GlobalConfig) GetPurchaseDelay() time.Duration
GetPurchaseDelay returns the pre-fire delay as a time.Duration. Nil receiver returns the default. Values outside [0, MaxPurchaseDelayHours] are clamped so a rogue DB write cannot break the scheduler.
func (*GlobalConfig) GracePeriodFor ¶
func (g *GlobalConfig) GracePeriodFor(provider string) int
GracePeriodFor returns the effective grace-period window (in days) for the given provider slug ("aws", "azure", "gcp"). Returns the default when the provider has no explicit entry. Preserves an explicit 0 (which disables the feature for that provider). Clamps the result to [0, MaxGracePeriodDays] so a misconfigured DB row can't suppress recs indefinitely.
func (*GlobalConfig) Validate ¶
func (c *GlobalConfig) Validate() error
Validate validates the GlobalConfig.
type HistoryExecutionsPageQuery ¶
type HistoryExecutionsPageQuery struct {
// Start and End bound scheduled_date, inclusive; nil leaves a side open.
Start *time.Time
End *time.Time
Scope *ExecutionScope
// After is the stream position to continue from; nil starts at the top.
After *HistoryPageKey
// PlanID matches purchase_executions.plan_id exactly; empty skips the clause.
PlanID string
// Provider, AccountIDs and Scope mean what they mean for
// ExecutionsByStatusesQuery: supersets of the handler's Go checks.
Provider string
// Statuses the rows must have. Clean completed rows (status completed,
// empty error) are always excluded, as in GetExecutionsByStatuses.
Statuses []string
AccountIDs []string
// Limit caps the row count; clamped to [1, MaxListLimit] with a
// DefaultListLimit fallback when <= 0.
Limit int
}
HistoryExecutionsPageQuery selects one keyset page of executions for the History stream.
type HistoryPageKey ¶
type HistoryPageKey struct {
Timestamp time.Time
ID string
Source HistorySource
}
HistoryPageKey is a position in the History view's paged stream (issue #674): purchase_history rows and terminal executions merged in one order, timestamp DESC, then Source DESC, then ID DESC. Timestamp is purchase_history.timestamp or purchase_executions.scheduled_date, and ID is purchase_history.id or purchase_executions.execution_id (both UUIDs, unique per table), so the key is unique across the stream and a keyset page never repeats or skips a row.
func (HistoryPageKey) SortsBefore ¶
func (k HistoryPageKey) SortsBefore(o HistoryPageKey) bool
SortsBefore reports whether k comes before o in the stream order. IDs are compared as canonical lowercase UUID strings, which order the same way as PostgreSQL's uuid type.
type HistorySource ¶
type HistorySource int
HistorySource identifies the table a row of the History view's paged stream comes from. Its value is part of the stream order (see HistoryPageKey), so the constants must keep their relative order.
const ( // HistorySourceExecution is a terminal purchase_executions row (failed, // expired, canceled, audit-gap completed, partially completed). HistorySourceExecution HistorySource = 1 // HistorySourcePurchase is a purchase_history row. HistorySourcePurchase HistorySource = 2 )
type HistoryStore ¶
type HistoryStore interface {
// Purchase history
SavePurchaseHistory(ctx context.Context, record *PurchaseHistoryRecord) error
GetPurchaseHistory(ctx context.Context, accountID string, limit int) ([]PurchaseHistoryRecord, error)
GetAllPurchaseHistory(ctx context.Context, limit int) ([]PurchaseHistoryRecord, error)
// GetActivePurchaseHistory returns every purchase_history row whose commitment
// is still within its term at asOf (term > 0 AND timestamp + term years >= asOf;
// the expiry boundary is inclusive, matching the API layer's isActiveCommitment),
// newest-first, optionally scoped to a set of accounts. The account scope uses
// the same dual-column predicate as GetPurchaseHistoryFiltered: accountIDs
// match cloud_account_id (cloud_accounts UUIDs) and externalIDsByProvider
// matches account_id per provider, OR'd together so rows carrying only one
// identifier are still returned (issues #701/#498/#866). Both empty means all
// accounts. Unlike GetAllPurchaseHistory it is not row-capped: the analytics
// collector, dashboard KPIs, and inventory endpoints need the complete active
// set, and filtering expired commitments in SQL keeps the result bounded by
// the number of live commitments rather than by all history ever recorded (so
// it cannot silently truncate older-but-still-active 1y/3y commitments the
// way a newest-first capped page does, issue #1140).
GetActivePurchaseHistory(ctx context.Context, asOf time.Time, accountIDs []string, externalIDsByProvider map[string][]string) ([]PurchaseHistoryRecord, error)
// GetPurchaseHistoryFiltered reads purchase_history rows matching the
// PurchaseHistoryFilter, newest-first, capped at filter.Limit. Each field is
// applied independently and only when populated (see PurchaseHistoryFilter).
// The account predicate matches BOTH identifier columns:
// (cloud_account_id = ANY(AccountIDs)
// OR ((provider = ” OR LOWER(provider) = LOWER($p))
// AND account_id = ANY(ExternalIDsByProvider[p])) OR ...)
// because purchase_history rows carry the cloud_accounts UUID FK
// (cloud_account_id, NULL on direct-execute/ambient/pre-000011 rows) and the
// cloud-provider external number (account_id, always populated) independently.
// The top-bar Account chip emits the UUID; matching only one column silently
// dropped rows that carried only the other (issues #701/#498/#866). The caller
// resolves AccountIDs to their external account numbers grouped by provider
// and populates ExternalIDsByProvider so rows that carry only account_id are
// also matched, while the per-provider grouping keeps a reused external number
// across providers (aws/123 vs azure/123) from leaking the wrong rows. The
// provider gate is case-insensitive and a row with an empty (unknown) stored
// provider matches on account_id alone (issue #24).
GetPurchaseHistoryFiltered(ctx context.Context, filter PurchaseHistoryFilter) ([]PurchaseHistoryRecord, error)
// HistorySummaryAggregate returns counts and dollar sums over every row the
// History view would list without its row caps: purchase_history rows
// matched with GetPurchaseHistoryFiltered's predicate and purchase_executions
// rows matched with GetExecutionsByStatuses' predicate (issue #675). Rows are
// grouped by the columns the History handler's account-scope check reads, so
// the caller applies that check to the groups with the same code it applies
// to fetched rows. Both halves are read from one snapshot.
HistorySummaryAggregate(ctx context.Context, filter HistorySummaryFilter) (*HistorySummaryGroups, error)
// GetPurchaseHistoryByPurchaseID returns the single purchase_history row
// whose purchase_id matches (AWS ReservedInstancesId / Azure reservation
// ID). Returns (nil, nil) when no row is found. Used by the revoke
// endpoint to load the record before calling the provider cancel API
// (issue #290) and by the marketplace-list handler to validate
// offering_class and look up the cloud account (issue #292).
GetPurchaseHistoryByPurchaseID(ctx context.Context, purchaseID string) (*PurchaseHistoryRecord, error)
// MarkPurchaseRevoked stamps revoked_at, revoked_via, and optionally
// support_case_id on a purchase_history row identified by purchase_id.
// calcRefundAmount and calcRefundCurrency capture the Azure CalculateRefund
// quote for audit (migration 000071, Finding #4); both nil/empty for
// non-Azure paths or legacy rows written before the migration. Also
// clears revocation_in_flight (migration 000072): a revoked row is no
// longer in flight.
// Returns a not-found error when no row matches. Idempotent: a second
// call for the same row is a no-op (revoked_at is not overwritten when
// it is already non-null). Used by the revoke endpoint (issue #290).
MarkPurchaseRevoked(ctx context.Context, purchaseID string, revokedAt time.Time, revokedVia string, supportCaseID string, calcRefundAmount *float64, calcRefundCurrency string) error
// FlipPurchaseRevocationInFlight atomically claims a purchase_history row
// by setting revocation_in_flight=true. Called immediately before the Azure
// Return API call so that the row can be identified by the finalize sweep if
// the subsequent MarkPurchaseRevoked DB write fails (partial-success
// reconciliation, issue #290 Finding #6, migration 000072). Only an
// unrevoked, unflagged row is flipped, so exactly one concurrent caller
// wins: a revoked row returns an error wrapping ErrPurchaseAlreadyRevoked
// (issue #316), and a row another request already flagged returns an error
// wrapping ErrRevocationInFlight (issue #1518). Returns a not-found error
// when no row matches.
FlipPurchaseRevocationInFlight(ctx context.Context, purchaseID string) error
// ClearRevocationInFlight resets revocation_in_flight=false on a
// purchase_history row. Called when the Azure Return call fails with a
// transient or client error (not "already returned"), so the row is not
// left in a permanently-sticky in-flight state that would prevent future
// retries or mislead the finalize_revocations sweep (issue #290, second-wave
// CR Finding D). No-op when the row is already false. Best-effort: callers
// should log on error but not surface it to the user. Only the caller whose
// FlipPurchaseRevocationInFlight succeeded may call it, so it never clears
// a flag another request set (issue #1518).
ClearRevocationInFlight(ctx context.Context, purchaseID string) error
// GetPurchaseHistoryInFlight returns the purchase_history rows whose
// Return was recorded by MarkRevocationReturnPosted but whose revoked_at
// is still NULL: the Azure Return call succeeded but MarkPurchaseRevoked
// failed. The finalize_revocations scheduled sweep calls this to retry the
// DB write. A flagged row with no recorded Return is not returned
// (issue #1523): no refund is known to have gone out for it.
GetPurchaseHistoryInFlight(ctx context.Context) ([]*PurchaseHistoryRecord, error)
// MarkRevocationReturnPosted records that the provider accepted the
// Return for purchaseID (return_posted_at, migration 000148). Called by
// the revoke handler after the Azure Return succeeds and before
// MarkPurchaseRevoked. The first stamp stands; a revoked row is a no-op.
// Returns a not-found error when no row matches (issue #1523).
MarkRevocationReturnPosted(ctx context.Context, purchaseID string) error
// ReleaseStaleRevocationsInFlight clears revocation_in_flight on unrevoked
// rows flagged for longer than after with no Return recorded, so the
// purchase can be revoked again, and returns their purchase IDs. A flagged
// row with no flip timestamp is stamped now and aged from then. Called by
// the finalize_revocations sweep (issue #1523).
ReleaseStaleRevocationsInFlight(ctx context.Context, after time.Duration) ([]string, error)
// UpdatePurchaseHistoryListing stamps the AWS marketplace listing_id and
// listing_state onto a purchase_history row. Called after
// CreateReservedInstancesListing succeeds (listing_state="active") and
// on subsequent poll/cancel transitions (issue #292). Recording a listing
// resolves the attempt, so it also clears the persisted client token and
// price schedule (issue #525). It never marks a listing the row records as
// canceled or closed live again; that write returns
// ErrMarketplaceListingEnded.
UpdatePurchaseHistoryListing(ctx context.Context, purchaseID, listingID, listingState string) error
}
HistoryStore holds the purchase-history methods of StoreInterface; StoreInterface embeds it.
type HistorySummaryFilter ¶
type HistorySummaryFilter struct {
// ExecutionStart/ExecutionEnd bound purchase_executions.scheduled_date,
// inclusive on both sides like the History handler's in-memory date check.
// nil leaves that side open.
ExecutionStart *time.Time
ExecutionEnd *time.Time
// ExecutionStatuses selects purchase_executions rows with exactly the
// predicate GetExecutionsByStatuses applies (historyExecutionsPredicate).
// Empty skips the executions half.
ExecutionStatuses []string
// ExecutionDateExemptStatuses are not bounded by ExecutionStart/End: the
// History row path never date-filters actionable executions (#1685).
ExecutionDateExemptStatuses []string
// History selects purchase_history rows with exactly the predicate
// GetPurchaseHistoryFiltered applies (purchaseHistoryFilterWhere). Limit is
// ignored: the aggregate covers every matching row.
History PurchaseHistoryFilter
}
HistorySummaryFilter selects the rows HistorySummaryAggregate counts.
type HistorySummaryGroups ¶
type HistorySummaryGroups struct {
Purchases []PurchaseHistorySummaryGroup
Executions []ExecutionSummaryGroup
}
HistorySummaryGroups is the result of HistorySummaryAggregate: row counts and dollar sums grouped by the columns the History handler's provider, account and account-scope checks read. The caller applies those checks to each group with the same functions it applies to fetched rows, so the scope predicate cannot drift between the row list and the totals. The number of groups is bounded by the distinct account/provider/status combinations, not by row volume.
type LadderAmendment ¶
type LadderAmendment struct {
ExpectedRevision *int64 `json:"expected_revision"`
ScheduledDate time.Time `json:"scheduled_date"`
AmountUSDHr string `json:"amount_usd_hr"`
}
func (LadderAmendment) Validate ¶
func (a LadderAmendment) Validate() error
type LadderAmendmentResult ¶
type LadderAmendmentStore ¶
type LadderAmountBasis ¶
type LadderAmountBasis string
const ( LadderAmountOnDemand LadderAmountBasis = "on_demand_equivalent" LadderAmountCommitment LadderAmountBasis = "commitment" )
type LadderChainNode ¶
type LadderChainNode struct {
CreatedAt time.Time
UpdatedAt time.Time
RetryExecutionID *string
// ScheduledExecutionAt is when the fire sweep should run a scheduled
// execution; nil when unset.
ScheduledExecutionAt *time.Time
ExecutionID string
Status string
NoSubmission bool
}
LadderChainNode is the part of one purchase_executions row the reconciler reads. NoSubmission is only meaningful while Status is failed.
type LadderClaimFilter ¶
type LadderClaimFilter struct {
// Layers are the layers that have an instrument builder; empty is an error.
Layers []ladder.LayerType
// TrancheIDs are the ids the pre-claim resolve step accepted; empty claims nothing.
TrancheIDs []string
// CeilingMicros is the config's sweep ceiling in micro-dollars of hourly
// commitment. The claim keeps the longest prefix of due rows that fits under
// it minus what the last LadderCeilingWindow already fired; <= 0 is an error.
CeilingMicros int64
}
LadderClaimFilter narrows a claim. Every field is required and fails closed.
type LadderCloudCheck ¶
LadderCloudCheck is the operator's statement of where they looked for the purchase before declaring an unproven tranche failed.
type LadderConfigDB ¶
type LadderConfigDB struct {
UpdatedAt time.Time `json:"updated_at"`
CreatedAt time.Time `json:"created_at"`
// MaxHourlyCommitPerRun caps the total hourly commitment delta a single run
// may purchase. nil means no cap.
MaxHourlyCommitPerRun *float64 `json:"max_hourly_commit_per_run,omitempty"`
// MaxHourlyCommitPerSweep is the rolling-24h ceiling over all sweeps. It is
// not part of the ladder_configs upsert: the API reads and writes it through
// GetLadderSweepCeiling/SetLadderSweepCeiling so an unmigrated schema keeps
// the four config queries working. nil means not set (the sweep refuses).
MaxHourlyCommitPerSweep *float64 `json:"max_hourly_commit_per_sweep,omitempty"`
CloudAccountID string `json:"cloud_account_id"`
Provider string `json:"provider"`
Mode string `json:"mode"` // ladder.ModeEmailApproval | ladder.ModeAutoApprove
Cadence string `json:"cadence"` // ladder.CadenceDaily | ladder.CadenceWeekly
ID string `json:"id"`
RampSchedule json.RawMessage `json:"ramp_schedule"`
BufferUtilizationThreshold float64 `json:"buffer_utilization_threshold"`
LookbackDays int `json:"lookback_days"`
MaxActionsPerRun int `json:"max_actions_per_run"`
// BaselinePercentile is the statistical percentile used to anchor the base
// commitment layer. Must be in (0, 50].
BaselinePercentile float64 `json:"baseline_percentile"`
BufferFraction float64 `json:"buffer_fraction"`
TargetCoverage float64 `json:"target_coverage"`
Enabled bool `json:"enabled"`
}
LadderConfigDB is the DB-persistence mirror of pkg/ladder.LadderConfig. It stores one per-account, per-provider ladder configuration row and is used by the store layer (GetLadderConfig / UpsertLadderConfig) and the API handler. Mode and Cadence are plain strings whose valid values are defined by pkg/ladder (ModeEmailApproval, ModeAutoApprove, CadenceDaily, CadenceWeekly). Validation calls pkg/ladder's Parse* functions so the internal/config package never redefines those constants.
MaxHourlyCommitPerRun is a pointer because nil means "no cap" (distinct from 0, which would cap all spending). All numeric money fields follow the project rule: absent = nil/pointer, never 0. Field order is optimized for govet fieldalignment (pointer-containing fields grouped first to shrink the GC pointer-scan range, then scalars, bool last). It intentionally does not follow the logical/SQL column order; see the scanLadderConfig / Upsert SQL for the wire order.
func (*LadderConfigDB) Validate ¶
func (c *LadderConfigDB) Validate() error
Validate validates a LadderConfigDB before persist. It delegates mode and cadence checks to pkg/ladder's Parse* functions (single source of truth for those enums) and validates numeric bounds using the same invariants that pkg/ladder.LadderConfig.Validate() enforces.
Returns a specific, descriptive error on any violation. Callers must never silently default away a validation failure.
type LadderDueRow ¶
type LadderDueRow struct {
Tranche LadderTrancheDB
SQLClaimable bool
}
LadderDueRow is a tranche due by date and whether ClaimDueLadderTranches could take it given the layer allowlist, as decided by the claim's own predicate.
type LadderExecutionGate ¶
type LadderExecutionGate struct {
ConfigEnabled *bool
ConfigMode *string
RunStatus *string
TrancheStatus *string
// LayerType is the tranche's own layer (NOT NULL in the schema).
LayerType ladder.LayerType
}
LadderExecutionGate is what the executor re-reads, right before a provider call, about the ladder tranche an execution belongs to. Each field is a pointer because the foreign keys are ON DELETE SET NULL: a nil field means the row is gone, which the caller must treat as "refuse", not as a default. TrancheStatus is the tranche's own status: an operator may have settled the tranche while an execution carrying its key is still waiting to run.
type LadderFiredCursor ¶
LadderFiredCursor is the keyset position after which ListFiredLadderTranches continues: the (scheduled_date, id) of the last tranche of the previous page.
type LadderInFlightRow ¶
type LadderInFlightRow struct {
Layer ladder.LayerType
Family string // EC2 instance family; empty for legacy rows and non-EC2-SP layers
CommitmentUSDPerHour float64
Rate float64
// contains filtered or unexported fields
}
LadderInFlightRow is one netted tranche. Rate is rounded down and the commitment up, so CommitmentUSDPerHour/Rate never understates the exact on-demand-equivalent amount. Legacy on-demand rows carry Rate 1.
type LadderPlanBuilder ¶
type LadderPlanBuilder func(inFlight []LadderInFlightRow) (*LadderRunDB, []LadderTrancheDB, error)
LadderPlanBuilder computes a run and its new tranches from the config's netted tranches. It runs while the per-config lock is held inside the persist transaction: it must be pure compute (no provider or network I/O).
type LadderResolveFailed ¶
type LadderResolveFailed struct {
Now time.Time
Check *LadderCloudCheck
TrancheID string
AccountID string
StatusReason string
// StaleAfter is how long the chain must have been unchanged before an
// unknown outcome may be declared failed (purchase.LadderFiredStaleAfter).
StaleAfter time.Duration
Acknowledge bool
}
LadderResolveFailed asks to move a fired tranche to failed. StatusReason is the complete string to store, built by the caller so that a repeat of the same request compares equal as a whole. Check is set when the caller acknowledges an unknown outcome.
type LadderResolveResult ¶
LadderResolveResult is the tranche after the call. Replayed is true when an identical earlier request had already failed it and nothing was written.
type LadderRunDB ¶
type LadderRunDB struct {
// Required timestamps.
StartedAt time.Time `json:"started_at"`
UpdatedAt time.Time `json:"updated_at"`
CreatedAt time.Time `json:"created_at"`
// Nullable FK and optional text fields (all pointer types).
FireAt *time.Time `json:"fire_at,omitempty"`
Cadence *string `json:"cadence,omitempty"`
CompletedAt *time.Time `json:"completed_at,omitempty"`
ApprovalTokenHash *string `json:"approval_token_hash,omitempty"`
ApprovalTokenExpiresAt *time.Time `json:"approval_token_expires_at,omitempty"`
ApprovedBy *string `json:"approved_by,omitempty"`
CancelledBy *string `json:"cancelled_by,omitempty"`
// Nullable monetary snapshot: nil means "not computed", never $0.
BaselineUSDHr *float64 `json:"baseline_usd_hr,omitempty"`
// Mode and Cadence are nullable in the DB (populated from LadderConfigDB
// at run creation time; nil only for legacy / partially-failed rows).
Mode *string `json:"mode,omitempty"`
ConfigID *string `json:"config_id,omitempty"`
TargetUSDHr *float64 `json:"target_usd_hr,omitempty"`
ExistingUSDHr *float64 `json:"existing_usd_hr,omitempty"`
GapUSDHr *float64 `json:"gap_usd_hr,omitempty"`
// Required string / enum fields.
ID string `json:"id"`
Status ladder.RunStatus `json:"status"`
// Plan JSON blob (JSONB, NOT NULL DEFAULT '{}').
Plan json.RawMessage `json:"plan"`
// Non-nullable accumulator totals (initialised to 0, not measurements;
// zero is a meaningful value for these counters unlike the monetary snapshot).
EstimatedSavings float64 `json:"estimated_savings"`
TotalUpfrontCost float64 `json:"total_upfront_cost"`
TotalHourlyCommit float64 `json:"total_hourly_commit"`
}
LadderRunDB mirrors the ladder_runs table (migration 000080). Monetary snapshot columns are *float64 (nullable, NEVER 0-coerced: NULL means "not computed", not "$0"). Field order minimizes GC pointer-scan range: explicit pointer fields come before scalars.
type LadderStore ¶
type LadderStore interface {
// Ladder configuration (per-account, per-provider).
// GetLadderConfigs returns the rows newest first, capped at MaxListLimit.
// GetLadderConfig returns the single row for (cloudAccountID, provider),
// or (nil, nil) when no row exists.
// UpsertLadderConfig inserts or updates via the UNIQUE(cloud_account_id, provider)
// constraint and returns the persisted row with all DB-stamped fields populated.
GetLadderConfigs(ctx context.Context) ([]LadderConfigDB, error)
GetLadderConfig(ctx context.Context, cloudAccountID, provider string) (*LadderConfigDB, error)
UpsertLadderConfig(ctx context.Context, cfg *LadderConfigDB) (*LadderConfigDB, error)
// GetLadderSweepCeiling and SetLadderSweepCeiling read and write the
// per-sweep ceiling (store_postgres_ladder_ceiling.go); both return
// ErrLadderCeilingUnavailable until the migration is applied.
GetLadderSweepCeiling(ctx context.Context, configID string) (*int64, error)
SetLadderSweepCeiling(ctx context.Context, configID string, usdPerHr *float64) error
// Ladder run/tranche persistence (migration 000080/000081, PR-2).
//
// SaveLadderRun inserts a new ladder_runs row, returning the persisted row
// with all DB-stamped fields (id, created_at, updated_at) populated.
// If run.ID is empty, a new UUID is generated before the insert.
//
// GetLadderRun returns the row for the given id, or (nil, nil) when no
// row exists (mirrors GetLadderConfig semantics).
//
// SaveLadderTranches inserts a batch of ladder_tranches rows inside a
// single transaction. Each tranche must carry a non-empty ID; duplicate
// IDs within the batch are rejected at the DB UNIQUE constraint level.
//
// LatestLadderRunStartedAt returns the maximum started_at for the given
// config_id, or nil when no run has been recorded yet. Powers the per-cadence
// self-gate in the scheduler (Q6).
//
// TransitionLadderRunStatus atomically updates the status of a ladder_runs
// row from one of the fromStatuses to toStatus, returning the updated row.
// Returns (nil, nil) when zero rows are affected (CAS race lost or wrong
// current status), so callers can distinguish a race from a hard error.
// Statuses are typed ladder.RunStatus so callers cannot pass an arbitrary
// string that would never match a stored status. A transition to
// RunStatusCanceled is refused (ErrLadderRunCancelViaTransition).
//
// CancelLadderRun is the only way to cancel a ladder run: a CAS UPDATE
// from one of fromStatuses to cancelled that stamps cancelled_by with the
// actor's email in the same statement. An empty actor is refused
// (ErrLadderRunCancelActorRequired); (nil, nil) means the CAS lost.
// PlanAndSaveLadderRun is the ladder planning persist: in ONE READ COMMITTED
// transaction under the config's advisory lock it reads the in-flight
// commitment (scheduled rows within LadderFireGrace plus fired rows), calls
// build with it, then inserts the run, sweeps overdue tranches and inserts
// the new ones (append-only, L5). Overlapping runs for one config serialize:
// the second nets the first's committed rows. build must be pure compute
// (no I/O); run.StartedAt must equal asOf. asOf MUST be captured before the
// caller reads the existing commitment (E): tranches completed after asOf
// are added to the in-flight figure, so one that completes between the E
// read and the locked read is netted, never missed (a double count is a
// safe under-buy). This holds only if a tranche is marked completed after
// its commitment is visible through E's source (executor PR5a). The lock is
// also taken first by ClaimDueLadderTranches.
PlanAndSaveLadderRun(ctx context.Context, configID string, asOf time.Time, build LadderPlanBuilder) (*LadderRunDB, error)
SaveLadderRun(ctx context.Context, run *LadderRunDB) (*LadderRunDB, error)
GetLadderRun(ctx context.Context, id string) (*LadderRunDB, error)
SaveLadderTranches(ctx context.Context, tranches []LadderTrancheDB) error
LatestLadderRunStartedAt(ctx context.Context, configID string) (*time.Time, error)
// LatestLadderRunID returns the id of the config's run with the latest
// started_at, or an error wrapping ErrNotFound when it has none.
LatestLadderRunID(ctx context.Context, configID string) (string, error)
TransitionLadderRunStatus(ctx context.Context, id string, fromStatuses []ladder.RunStatus, toStatus ladder.RunStatus) (*LadderRunDB, error)
CancelLadderRun(ctx context.Context, id string, fromStatuses []ladder.RunStatus, cancelledBy string) (*LadderRunDB, error)
// CountLadderRunTrancheStatuses returns the number of the run's tranches
// per stored status (raw keys, so a legacy spelling is its own key).
CountLadderRunTrancheStatuses(ctx context.Context, runID string) (map[ladder.TrancheStatus]int, error)
}
LadderStore holds the ladder methods of StoreInterface; StoreInterface embeds it.
type LadderTimelineAction ¶
type LadderTimelineCursor ¶
LadderTimelineCursor is an optional (created_at, id) lower bound on the rows a timeline read returns. Reads never issue one: each returns the whole scope from one snapshot (#668), and the bound is only honored for a client that still follows a next_cursor from the earlier paginated API.
type LadderTimelineEvent ¶
type LadderTimelineEvent struct {
ScheduledDate time.Time `json:"scheduled_date"`
CreatedAt time.Time `json:"created_at"`
AmountBasis *LadderAmountBasis `json:"amount_basis,omitempty"`
ExecutionID *string `json:"execution_id,omitempty"`
CommitmentRate *string `json:"commitment_rate,omitempty"`
RunID string `json:"run_id"`
Family string `json:"family,omitempty"`
AmountUSDHr string `json:"amount_usd_hr"`
ConfigID string `json:"config_id"`
ID string `json:"id"`
ODUSDHr string `json:"od_usd_hr"`
Layer ladder.LayerType `json:"layer_type"`
Term ladder.Term `json:"term"`
Payment ladder.PaymentOption `json:"payment_option"`
Status ladder.TrancheStatus `json:"status"`
RunStatus ladder.RunStatus `json:"run_status"`
Revision int64 `json:"revision"`
}
type LadderTimelinePage ¶
type LadderTimelinePage struct {
TotalUSDHr string `json:"total_usd_hr"`
TotalODUSDHr string `json:"total_od_usd_hr"`
Events []LadderTimelineEvent `json:"events"`
TotalCount int64 `json:"total_count"`
}
type LadderTimelineRun ¶
type LadderTimelineRun struct {
StartedAt time.Time `json:"started_at"`
CreatedAt time.Time `json:"created_at"`
BaselineUSDHr *string `json:"baseline_usd_hr"`
TargetUSDHr *string `json:"target_usd_hr"`
ExistingUSDHr *string `json:"existing_usd_hr"`
GapUSDHr *string `json:"gap_usd_hr"`
ID string `json:"id"`
ConfigID string `json:"config_id"`
TotalHourlyCommit string `json:"total_hourly_commit"`
// ReasonCode is the plan's reason_code, set only when the run could not
// size its gap (for example "missing_discount_rate"). An ordinary run,
// including a target-met Hold, has none.
ReasonCode string `json:"reason_code,omitempty"`
Status ladder.RunStatus `json:"status"`
Actions []LadderTimelineAction `json:"actions"`
// TrancheCounts is the run's tranche rows per settled status; the legacy
// pre-go#554 spelling is folded into Canceled.
TrancheCounts LadderTrancheCounts `json:"tranche_counts"`
// DelayedFirstStep marks a run whose earliest tranche is scheduled later
// than LadderFireGrace after the run started: the claim filter refuses it,
// so the ramp never buys (plan #70 D7(a)). False for a run without tranches.
DelayedFirstStep bool `json:"delayed_first_step"`
}
type LadderTimelineRunPage ¶
type LadderTimelineRunPage struct {
Runs []LadderTimelineRun `json:"runs"`
TotalCount int64 `json:"total_count"`
}
type LadderTimelineStore ¶
type LadderTimelineStore interface {
ListLadderTimeline(context.Context, string, string, *LadderTimelineCursor) (*LadderTimelinePage, error)
ListLadderTimelineRuns(context.Context, string, string, *LadderTimelineCursor) (*LadderTimelineRunPage, error)
}
type LadderTrancheCounts ¶
type LadderTrancheDB ¶
type LadderTrancheDB struct {
ScheduledDate time.Time `json:"scheduled_date"`
CreatedAt time.Time `json:"created_at"`
RunID *string `json:"run_id,omitempty"`
ExecutionID *string `json:"execution_id,omitempty"` // references purchase_executions.execution_id
// SettledAt is stamped by TransitionLadderTrancheTx when the tranche
// becomes completed; a CHECK requires it on every completed row.
SettledAt *time.Time `json:"settled_at,omitempty"`
// Nil basis preserves unproven history; native rates are lossless rational text.
AmountBasis *LadderAmountBasis `json:"amount_basis,omitempty"`
CommitmentRate *string `json:"commitment_rate,omitempty"`
// Family is the EC2 instance family a tranche is allocated to; empty means
// no family (legacy rows and every layer except EC2 Instance SP).
Family string `json:"family,omitempty"`
// Nullable FK pointers.
ConfigID *string `json:"config_id,omitempty"`
// Required fields.
ID string `json:"id"`
PaymentOption ladder.PaymentOption `json:"payment_option"`
Status ladder.TrancheStatus `json:"status"`
Term ladder.Term `json:"term"`
LayerType ladder.LayerType `json:"layer_type"`
// Monetary and timing.
AmountUSDHr float64 `json:"amount_usd_hr"`
}
LadderTrancheDB mirrors the ladder_tranches table (migration 000081). One row per ramp step per allocation; persisted as status=scheduled audit rows only in PR-2 (no firing sweep wired yet). Field order minimizes GC pointer-scan range.
type MarketplaceListingAttempt ¶
type MarketplaceListingAttempt struct {
ListingID string
State string
ClientToken string //nolint:gosec // G117: an idempotency token for AWS, not a credential
}
MarketplaceListingAttempt is the listing state of a purchase_history row as the cancel handler read it: the recorded listing, its state, and the client token of an unresolved list attempt (empty when none).
type MarketplaceListingClaim ¶
type MarketplaceListingClaim struct {
// ListingID is the listing recorded on the row when it was claimed.
ListingID string
// PriorState is the listing_state before the claim; empty when none.
PriorState string
// ClientToken is the token of this attempt: the one passed to the claim, or
// the persisted one when an unresolved attempt already held a token.
ClientToken string //nolint:gosec // G117: an idempotency token for AWS, not a credential
// PriceSchedule is the JSON price schedule stored with ClientToken.
PriceSchedule []byte
// Resumed reports that the token and schedule were already persisted by an
// earlier attempt that never recorded a listing. It is derived from the
// returned row (its token differs from the one this claim tried to write),
// so it stays correct when two claims race. PriorState is then "pending",
// the state the earlier attempt left; releasing restores an empty state
// and the row keeps its recorded listing id, which every list, cancel and
// claim check treats the same as the original dead state.
Resumed bool
}
MarketplaceListingClaim is what ClaimMarketplaceListingSlot reads back from the row it just claimed, so the handler works from the row as it is at claim time instead of a copy read before the claim (issue #525).
type MarketplaceListingProceedsTotal ¶
type MarketplaceListingProceedsTotal struct {
// PurchaseID is the RI (reservation) id.
PurchaseID string
// Currency is the ISO code of the amounts; the poller records USD only.
Currency string
// ProceedsReceivedCents is the seller's net proceeds and FeePaidCents the
// AWS fee, summed over the settled listings, in whole cents of Currency
// (integer minor units: money is never summed or carried as a float).
ProceedsReceivedCents int64
FeePaidCents int64
// SettledListings counts the listings whose amounts are recorded, and
// UnsettledListings those still without amounts (not ended yet, ended
// with an unknown price, or ended before the poller saw them).
SettledListings int
UnsettledListings int
// IsEstimate is always true: the amounts are computed from the AWS
// listing's sold count and price by the poller (D23), not read from an
// AWS payout, so every place that shows or serializes them must label
// them as estimates (issue #1586).
IsEstimate bool
}
MarketplaceListingProceedsTotal is one RI's RI Marketplace sales summed over every listing it has had (issue #1494), in one currency.
type MarketplaceListingSettlement ¶
type MarketplaceListingSettlement struct {
// ListedAt is the listing's AWS CreateDate; nil keeps the stored value.
ListedAt *time.Time
// ProceedsReceived is the USD the seller receives for the sold instances,
// net of the AWS fee, and FeePaid that fee. Both nil when the sale price
// could not be determined; the row is then polled again.
ProceedsReceived *float64
FeePaid *float64
// PurchaseID and ListingID identify the row and the listing it must still
// record; a row that moved on to another listing is left alone.
PurchaseID string
ListingID string
// State is the terminal AWS state: ListingStateClosed or
// ListingStateCancelled.
State string
}
MarketplaceListingSettlement is what the marketplace status poller records when a listing reaches a terminal state on AWS (issue #27).
type MarketplaceStore ¶
type MarketplaceStore interface {
// GetMarketplaceListingAttempt returns the listing id, state and the token
// of an unresolved list attempt of the row for purchaseID, or (nil, nil)
// when there is none. The cancel endpoint uses it to recover a pending row
// (issue #525).
GetMarketplaceListingAttempt(ctx context.Context, purchaseID string) (*MarketplaceListingAttempt, error)
// ResolveMarketplaceListingAttempt records listingID in an ended (or, to
// clear a stuck pending row without a listing, empty) state and drops the
// attempt token, only while the row still matches seen or already holds
// listingID. It reports whether the row was written (issue #525).
ResolveMarketplaceListingAttempt(ctx context.Context, purchaseID string, seen MarketplaceListingAttempt, listingID, state string) (bool, error)
// StampOfferingClass writes the offering_class value to a purchase_history
// row identified by purchase_id. Called by the marketplace-list handler
// when offering_class is absent in the DB (pre-migration 000087 rows and
// externally-created Standard RIs): after fetching the class from AWS
// DescribeReservedInstances it is persisted so subsequent requests do not
// incur an extra AWS API call.
StampOfferingClass(ctx context.Context, purchaseID, offeringClass string) error
// ClaimMarketplaceListingSlot atomically reserves the marketplace-listing
// slot for a purchase_history row so two concurrent marketplace-list
// requests cannot both proceed to create a duplicate AWS listing (issue
// #292). It transitions listing_state to ListingStatePending only when the
// row is not listed, and in the same UPDATE persists clientToken and
// priceSchedule (JSON) unless an unresolved attempt already stored a token,
// in which case that token and schedule are kept so the retry is idempotent
// on AWS (issue #525). A pending row that holds a token is claimable again:
// the same token makes a concurrent or crashed attempt safe to resume.
// It returns the claimed row's values, or (nil, nil) when the row is active,
// pending without a token, or absent (the caller maps that to a 409). The
// caller must persist the real listing on success or call
// ReleaseMarketplaceListingClaim on failure.
ClaimMarketplaceListingSlot(ctx context.Context, purchaseID, clientToken string, priceSchedule []byte) (*MarketplaceListingClaim, error)
// ReleaseMarketplaceListingClaim moves a pending row back to priorState
// (empty for none) after a failed attempt. It only acts on a row whose
// persisted token is clientToken, so a request never releases or drops the
// attempt of another request. keepAttempt keeps the persisted token and
// schedule so the retry resends them (ambiguous AWS outcome); otherwise
// they are cleared because AWS created nothing reusable.
ReleaseMarketplaceListingClaim(ctx context.Context, purchaseID, clientToken, priorState string, keepAttempt bool) error
// ListMarketplaceListingsToPoll returns the AWS listings the marketplace
// status poller reads (issue #27): active listings, listings recorded as
// pending with no list attempt in flight (issue #1494), and
// closed/canceled ones it has seen whose proceeds are not recorded yet,
// both the RI's current listing and the listings it was relisted from
// (issue #1494).
ListMarketplaceListingsToPoll(ctx context.Context) ([]PurchaseHistoryRecord, error)
// RecordMarketplaceListingActive records a listing AWS reports active:
// it stamps listed_at (a zero listedAt keeps the stored one) while the row
// holds listingID as active, and also moves the state to active while the
// row holds it as pending with no list attempt in flight (issue #1494).
// It never writes the state of any other row. Reports whether the row
// changed.
RecordMarketplaceListingActive(ctx context.Context, purchaseID, listingID string, listedAt time.Time) (bool, error)
// SettleMarketplaceListing records a listing that closed or was canceled
// on AWS, with its proceeds and AWS fee when known, in the listing's own
// settlement row and, while the RI still holds the listing, on its
// purchase_history row (issue #1494). It applies once per listing, only
// while the listing is active, pending with no list attempt in flight, or
// already in the same terminal state. Reports whether a row was written.
SettleMarketplaceListing(ctx context.Context, settlement MarketplaceListingSettlement) (bool, error)
// GetMarketplaceListingProceedsTotals sums each RI's marketplace proceeds
// and fees over all of its listings (issue #1494), one total per purchase
// and currency. RIs with no recorded listing are left out. Only purchases
// of the given accounts count (same account arguments as
// GetActivePurchaseHistory; empty scope is an error), and each total is an
// estimate (issue #1586).
GetMarketplaceListingProceedsTotals(ctx context.Context, purchaseIDs, accountIDs []string, externalIDsByProvider map[string][]string) ([]MarketplaceListingProceedsTotal, error)
}
MarketplaceStore holds the marketplace-listing methods of StoreInterface; StoreInterface embeds it.
type PartialProviderSweep ¶
type PartialProviderSweep struct {
// Reasons counts the failure causes by PartialReason* category.
Reasons map[string]int `json:"reasons"`
// HeldSince records when each held account (by HeldAccountIDs entry, or the
// nil UUID for an ambient hold) was first held in the current streak.
HeldSince map[string]time.Time `json:"held_since,omitempty"`
Provider string `json:"provider"`
// HeldAccountIDs lists the platform cloud-account UUIDs (not cloud
// account numbers) whose previous-cycle rows are held through a pricing
// outage; the purchase path refuses their recommendations. It can contain
// the nil UUID (all zeros) for the ambient identity, which has no account;
// the API shows it only to callers with an unrestricted account scope.
HeldAccountIDs []string `json:"held_account_ids,omitempty"`
// ExpiredHoldAccountIDs lists accounts whose hold passed PricingHoldMaxAge
// and whose stale rows were evicted. It is carried until the account
// re-prices or stops being an enabled Azure account.
ExpiredHoldAccountIDs []string `json:"expired_hold_account_ids,omitempty"`
// IncompleteAccounts is how many accounts (registered, or the single
// ambient host identity) returned rows from an incomplete sweep.
IncompleteAccounts int `json:"incomplete_accounts"`
// AttemptedScopes is how many scopes the incomplete sweeps were asked to
// cover. Zero when the provider does not report it (AWS).
AttemptedScopes int `json:"attempted_scopes"`
// FailedScopes is how many of those scopes could not be queried.
FailedScopes int `json:"failed_scopes"`
// FailedDetails is how many individual recommendation details were
// rejected inside scopes that otherwise answered (AWS only).
FailedDetails int `json:"failed_details"`
// SkippedRecommendations is how many recommendations the provider
// dropped as invalid (GCP: non-USD, malformed amount or plan, unknown
// term) while returning the rest. Those accounts' sweeps were complete.
SkippedRecommendations int `json:"skipped_recommendations"`
}
PartialProviderSweep summarizes one provider's incomplete sweeps in a collection. A "scope" is the unit a sweep fails in: a subscription for Azure, a project for GCP, and a service/region collection scope for AWS.
type PaymentSchedule ¶
type PaymentSchedule string
PaymentSchedule is the cash-flow shape a payment-option token implies, stripped of the provider-specific spelling of that token. Two tokens that map to the same PaymentSchedule bill the customer identically; only the word differs (AWS spells all-upfront what Azure spells upfront, and AWS spells no-upfront what Azure and GCP spell monthly).
It exists so callers can tell a rename apart from a real change when NormalizePaymentOption rewrites a token: a rename is bookkeeping, a real change moves the customer's money and has to be disclosed (#1503).
const ( // PaymentScheduleUpfront: the whole commitment is charged once, at purchase. PaymentScheduleUpfront PaymentSchedule = "upfront" // PaymentSchedulePartialUpfront: part is charged at purchase, the rest recurs. PaymentSchedulePartialUpfront PaymentSchedule = "partial-upfront" // PaymentScheduleRecurring: nothing is charged at purchase; the commitment // is billed per period across the term. PaymentScheduleRecurring PaymentSchedule = "recurring" // PaymentScheduleUnknown: the token is not one of the modeled schedules. // Two unrecognized tokens compare equal under this classification, so // callers that must distinguish them have to compare the raw tokens too. // In practice unmapped tokens never reach a coercion comparison: // NormalizePaymentOption returns ok=false for them and the validator // rejects them at the next boundary. PaymentScheduleUnknown PaymentSchedule = "unknown" )
func PaymentScheduleFor ¶
func PaymentScheduleFor(token string) PaymentSchedule
PaymentScheduleFor classifies a payment-option token by the billing schedule it implies. The token must already be lowercased and trimmed (validatePurchaseRecommendation and NormalizePaymentOption both work on such tokens).
type PlanGroupTarget ¶
type PlanGroupTarget struct {
MaxStepCommitment *float64
PlanMaxStepCommitment *float64
GroupID string
}
PlanGroupTarget edits one group of a bound plan by group id. Only caps may change, and only downward: an edit never lets a managed plan buy more (cap raises go through the grant gate, not this path). A nil field keeps the stored value.
type PlanNameTakenError ¶
PlanNameTakenError names the plan that blocked a create. ExistingName is the stored name, which may differ from the requested one in case or surrounding spaces, so a caller can show the plan it would open.
func (*PlanNameTakenError) Error ¶
func (e *PlanNameTakenError) Error() string
func (*PlanNameTakenError) Unwrap ¶
func (e *PlanNameTakenError) Unwrap() error
type PlanRampBaseline ¶
type PlanRampBaseline map[string]PlanRampQuantity
PlanRampBaseline maps RecIdentityKey to the base a ramp plan sizes against.
type PlanRampQuantity ¶
PlanRampQuantity is a quantity of one recommendation identity: whole units for count-based recs, the summed hourly_commitment for Savings Plans.
type PlanScheduleCommand ¶
type PlanScheduleCommand struct {
ExpectedUpdatedAt time.Time
Name *string
NextExecutionDate *time.Time
GroupTarget *PlanGroupTarget
// DatesManaged adopts or releases the editor's ownership of the dates.
DatesManaged *bool
// ReplaceRootDate cancels the open root of the next step and inserts a
// new one on this date; it needs a managed plan. The plan's next date
// follows it.
ReplaceRootDate *time.Time
// Accounts replaces the plan's account set in the same transaction.
Accounts *[]string
CommandID string
PlanID string
Actor string
RequestHash string
}
PlanScheduleCommand is one schedule-editor Save. ExpectedUpdatedAt is the plan version the editor read. Name and NextExecutionDate change only when set. RequestHash is the caller's hash of the canonical request.
type PlanScheduleOutcome ¶
type PlanScheduleOutcome struct {
PlanID string `json:"plan_id"`
Name string `json:"name"`
UpdatedAt time.Time `json:"updated_at"`
NextExecutionDate *time.Time `json:"next_execution_date,omitempty"`
RootExecutionID string `json:"root_execution_id,omitempty"`
Replayed bool `json:"-"`
}
PlanScheduleOutcome is what a command returns and what its receipt stores. Replayed is set on a replay and is never stored.
type PlanScheduleReceipt ¶
type PlanScheduleReceipt struct {
CreatedAt time.Time
CommandID string
PlanID string
Actor string
RequestHash string
Outcome json.RawMessage
}
PlanScheduleReceipt is the immutable record of one schedule-editor command. RequestHash is the caller's hash of the canonical request; Outcome is the response a replay of the same command returns verbatim.
type PlanStore ¶
type PlanStore interface {
// Purchase plans
CreatePurchasePlan(ctx context.Context, plan *PurchasePlan) error
// CreatePurchasePlanWithAccounts creates plan and attaches accountIDs in
// one transaction. It returns *PlanNameTakenError (errors.Is
// ErrPlanNameTaken) when a plan whose accounts satisfy visible already has
// the same name, compared with lower(btrim(name, E' \t\r\n')). visible must be pure.
CreatePurchasePlanWithAccounts(ctx context.Context, plan *PurchasePlan, accountIDs []string, visible func(accounts []CloudAccount) bool) error
GetPurchasePlan(ctx context.Context, planID string) (*PurchasePlan, error)
// UpdatedAt must be the read version; a stale version returns ErrPurchasePlanConflict.
UpdatePurchasePlan(ctx context.Context, plan *PurchasePlan) error
StampPlanNotificationSent(ctx context.Context, planID string, at time.Time) error
// CompletePlanStep records that ramp step stepNumber finished and advances
// the plan's schedule to it, inside a SELECT FOR UPDATE transaction that
// prevents the concurrent-write lost-update race of issue #1071.
//
// It is idempotent in stepNumber: completing a step the plan has already
// counted writes nothing. Which sentinel says so depends on where the ramp
// sits relative to the completing step, and callers branch on the
// difference (purchase.recordRampAdvanceRefusal does):
//
// - CurrentStep == stepNumber reports ErrRampStepCountedBySibling. This
// is the issue #1669 scenario: an operator retries two separately-failed
// accounts of one ramp step, and the second completion finds the ramp
// already sitting on that step because the first advanced it. The step
// WAS counted, so this is routine and is not recorded against the
// execution.
// - CurrentStep > stepNumber reports ErrRampStepAlreadyCounted. The ramp
// moved past the step earlier, so this purchase bought commitment the
// plan will never count. That is an anomaly and IS recorded.
//
// A step counts as complete only when EVERY cloud account the step fanned
// out to has bought, not when any one of them has (issue #1861). Until
// then it reports ErrRampStepIncomplete, which is a "not yet" rather than a
// failure of the purchase that just completed -- the purchase is real and
// already recorded; only the plan's position is withheld.
CompletePlanStep(ctx context.Context, planID string, stepNumber int) error
// GetStuckRampSteps returns, keyed by plan ID, the plan's next ramp step
// and how many of that step's executions have a terminal, unsuccessful
// latest attempt with no retry in flight -- a ramp CompletePlanStep will
// keep refusing to advance until an operator intervenes. Plans with
// nothing stuck are absent from the map. Feeds the plan-health
// ramp_blocked factor (issue #1861).
GetStuckRampSteps(ctx context.Context) (map[string]RampStepBlock, error)
// GetDoomedNextRoots returns, keyed by plan ID, the plans whose next
// empty root row is dated where the notification tick can never attach
// recommendations (inside the notice window, or any future date when the
// plan has no window), evaluated at now. Plans with nothing doomed are
// absent. Feeds the plan-health step_will_not_attach factor.
GetDoomedNextRoots(ctx context.Context, now time.Time) (map[string]DoomedRoot, error)
// LockPurchasePlanTx reads a plan under a row lock held for the rest of tx.
// It is the per-plan ramp lock CompletePlanStep takes, exposed so a caller
// that reads a plan's ramp position and then writes against it does so
// atomically with respect to concurrent completions and creations.
// Returns (nil, nil) when the plan does not exist.
LockPurchasePlanTx(ctx context.Context, tx pgx.Tx, planID string) (*PurchasePlan, error)
// LockPlanProvidersTx takes the transaction-scoped advisory lock of every
// named provider, in sorted order, so two plan steps that resolve the same
// provider's recommendations cannot both attach the same capacity. Lock
// order is advisory lock, then LockPurchasePlanTx. The ladder config lock
// (PlanAndSaveLadderRun, ClaimDueLadderTranches, AmendLadderTranche) is always taken BEFORE both:
// ClaimDueLadderTranches's create callback may take these locks, so they
// come after the ladder lock; code holding an execution or tranche row
// (retry linker, reconciler) must never take the ladder lock. No cycle.
// Duplicates are taken once; an empty list and an empty provider name are
// errors.
LockPlanProvidersTx(ctx context.Context, tx pgx.Tx, providers []string) error
// OccupiedRampStepsInRangeTx returns the steps in [from, to] of planID that
// already have a fan-out unit which bought or is still working, ascending.
// Callers about to mint executions for a step range use it to refuse a step
// that is already covered, which would otherwise re-fan-out across accounts
// that already committed under a fresh idempotency lineage (issue #1861).
// Requires the caller to hold LockPurchasePlanTx on planID in the same
// transaction; without it the answer is advisory and two concurrent callers
// both see the step free.
OccupiedRampStepsInRangeTx(ctx context.Context, tx pgx.Tx, planID string, from, to int) ([]int, error)
// ListExecutionsForPlanStepTx returns EVERY execution row (any status,
// account or retry attempt) recorded for stepNumber of planID. The
// get-or-create of a plan step reads it under LockPurchasePlanTx so any
// existing row, settled or not, blocks minting a second root (platform#631).
ListExecutionsForPlanStepTx(ctx context.Context, tx pgx.Tx, planID string, stepNumber int) ([]PurchaseExecution, error)
// SetPlanRampBaselineTx freezes the plan's ramp baseline if none is set and
// reports whether it wrote. Immutable once set; not part of
// UpdatePurchasePlanTx, so a stale plan save cannot touch it. The caller
// holds LockPurchasePlanTx.
SetPlanRampBaselineTx(ctx context.Context, tx pgx.Tx, planID string, baseline PlanRampBaseline) (bool, error)
// GetPlanRampBaselineTx returns the frozen baseline, nil when none is set.
GetPlanRampBaselineTx(ctx context.Context, tx pgx.Tx, planID string) (PlanRampBaseline, error)
// ListPlanCommittedTx returns what the plan's executions already hold per
// recommendation identity (see its implementation for the status rules).
// The caller holds LockPurchasePlanTx.
ListPlanCommittedTx(ctx context.Context, tx pgx.Tx, planID string) (map[string]PlanRampQuantity, error)
// CompleteTargetMetStepTx records a plan step whose cumulative target is
// already held as a completed no-op row (new, or rootID's empty root row
// completed in place) and advances the ramp over it in the same
// transaction. The caller holds LockPurchasePlanTx.
CompleteTargetMetStepTx(ctx context.Context, tx pgx.Tx, planID string, stepNumber int, rootID, note string) error
// SetExecutionRecommendationsIfEmptyTx attaches resolved recommendations
// and their totals to a pending/notified execution that has none yet.
// Returns false when another resolver already attached them (or the row
// left pending/notified); the caller re-reads instead of overwriting.
SetExecutionRecommendationsIfEmptyTx(ctx context.Context, tx pgx.Tx, executionID string, recs []RecommendationRecord, upfront, savings float64) (bool, error)
// ExpireExecutionAtomic flips a pending/notified execution to expired in
// tx so its suppressions can be deleted in the same transaction. Returns
// false when the row had already left pending/notified or its
// scheduled_date no longer equals observedScheduledDate (a re-armed root
// carries a new date, so a stale sweep list cannot expire it again).
ExpireExecutionAtomic(ctx context.Context, tx pgx.Tx, executionID string, observedScheduledDate time.Time) (bool, error)
// UpdatePurchasePlanTx checks UpdatedAt and replaces it with the returned version.
// The caller must discard the transaction-local plan if the transaction rolls back.
UpdatePurchasePlanTx(ctx context.Context, tx pgx.Tx, plan *PurchasePlan) error
// UpdatePurchasePlanGated is UpdatePurchasePlan with gate run under the
// plan's row lock, before the write (nil gate: plain update).
UpdatePurchasePlanGated(ctx context.Context, plan *PurchasePlan, gate PlanWriteGate) error
DeletePurchasePlan(ctx context.Context, planID string) error
ListPurchasePlans(ctx context.Context, filter PurchasePlanFilter) ([]PurchasePlan, error)
}
PlanStore holds the purchase-plan methods of StoreInterface; StoreInterface embeds it.
type PlanWriteGate ¶
type PlanWriteGate func(locked *PurchasePlan, accountIDs []string) error
PlanWriteGate decides whether a plan write may proceed. The store runs it with the plan row locked, handing it the plan as stored and its account ids (sorted), both read on the write's own transaction. It is pure on purpose: it gets no context and no store, so it cannot take a second pool connection while the transaction holds one. Whatever needs the database or the auth service is resolved before the write and compared here against what the lock shows. A non-nil error aborts the write and is returned unchanged.
type PlannedStep ¶
PlannedStep is one step of a hypothetical plan: the earliest moment the scheduler's daily notification gate admits it (the real attach is in (Attach, Attach+1d] for steps on their grid date), the day it would buy it, and the plan date the scheduler holds for the step (NextExecutionDate: its retry deadline counts from it), all UTC.
func PlannedStepDates ¶
func PlannedStepDates(plan *PurchasePlan, now time.Time) ([]PlannedStep, error)
PlannedStepDates reports the scheduler's real dates for a plan as created at now, assuming each step completes on its date. Step 1 is dated like attachScheduledDate (max of NextExecutionDate and VetoWindowEnd(now)); step k after the completion of step k-1 at T is max(GetNextPurchaseDate, VetoWindowEnd(T)). The scheduler dates step 2 only notify days after step 1 (known issue, kept).
func PlannedStepDatesHeld ¶
func PlannedStepDatesHeld(plan *PurchasePlan, now time.Time, hold func(PlannedStep) time.Time) ([]PlannedStep, error)
PlannedStepDatesHeld is PlannedStepDates where hold may delay a step: it gets each step's dates in order and returns the earliest attach that step may have (the zero time for none). A delayed step buys at max(its date, delayed attach plus the veto window), and the steps after it follow from that completion.
type PostgresStore ¶
type PostgresStore struct {
// contains filtered or unexported fields
}
PostgresStore implements StoreInterface using PostgreSQL.
func NewPostgresStore ¶
func NewPostgresStore(db *database.Connection) *PostgresStore
NewPostgresStore creates a new PostgreSQL-backed config store.
func (*PostgresStore) AcquireClaim ¶
func (s *PostgresStore) AcquireClaim(ctx context.Context, token, holder string, ttl, settle time.Duration) (common.Claim, error)
AcquireClaim implements common.PurchaseClaimer.
func (*PostgresStore) AdvanceClaim ¶
func (s *PostgresStore) AdvanceClaim(ctx context.Context, claim common.Claim, phase common.ClaimPhase) error
AdvanceClaim implements common.PurchaseClaimer.
func (*PostgresStore) AmendLadderTranche ¶
func (s *PostgresStore) AmendLadderTranche(ctx context.Context, id, accountID, provider, actor string, amendment LadderAmendment) (*LadderAmendmentResult, error)
func (*PostgresStore) ApplyPlanScheduleCommand ¶
func (s *PostgresStore) ApplyPlanScheduleCommand(ctx context.Context, cmd PlanScheduleCommand) (*PlanScheduleOutcome, error)
ApplyPlanScheduleCommand applies cmd in one transaction. Lock order is the plan row first (later commits add executions after it). A command id seen before returns its stored outcome without writing; the same id with another request is ErrPlanScheduleCommandConflict; a stale ExpectedUpdatedAt is ErrPurchasePlanConflict. Lock waits, deadlocks and serialization failures are retried a bounded number of times, then reported as ErrPlanScheduleRetryable.
func (*PostgresStore) ApproveAccountRegistration ¶
func (s *PostgresStore) ApproveAccountRegistration(ctx context.Context, reg *AccountRegistration, account *CloudAccount, actor *string) error
ApproveAccountRegistration moves a pending registration to approved, creates its cloud account and links the two, all in one transaction. If any step fails nothing is written, so a registration is never left approved with no account (issue #1102).
The status change runs first and is conditional on status = 'pending'. Its row lock makes a concurrent approve or reject of the same registration wait for this transaction: after a commit the other request matches no row and gets ErrRegistrationConflict; after a rollback it proceeds as if this one never ran. A failed account insert (for example the provider + external_id already being registered) returns the driver error and leaves the registration pending.
func (*PostgresStore) CancelAllPendingExchanges ¶
func (s *PostgresStore) CancelAllPendingExchanges(ctx context.Context) (int64, error)
CancelAllPendingExchanges cancels all pending RI exchange records regardless of origin. Kept for interface compatibility; new callers should prefer CancelPendingExchangesByOrigin to avoid cross-origin contamination.
func (*PostgresStore) CancelExecutionAtomic ¶
func (s *PostgresStore) CancelExecutionAtomic(ctx context.Context, tx pgx.Tx, executionID string, cancelledBy *string) (canceled bool, currentStatus string, err error)
CancelExecutionAtomic atomically transitions an execution from pending or notified to 'canceled' (canonical US spelling), setting canceled_by to the supplied actor (NULL when actor is nil). The UPDATE is conditional on status IN ('pending','notified') so a concurrent approve that has already transitioned the row to 'approved' causes zero rows to be affected and the method returns (false, currentStatus, nil) with the live status fetched via a follow-up SELECT. Returns (true, "canceled", nil) on success and (false, "", err) on a real DB error.
The 'scheduled' status is intentionally NOT accepted here -- the Gmail-style pre-fire delay revoke flow has its own CancelScheduledExecutionAtomic so the two paths surface distinct CAS race outcomes (cancel returns 409 on already-approved; scheduled-revoke returns 410 "window closed" on already-fired).
Callers must run the suppression cleanup in the same transaction; use the WithTx + DeleteSuppressionsByExecutionTx pairing at the call site exactly as the old SavePurchaseExecutionTx path did, except now the status guard is inside the UPDATE rather than checked optimistically before entering the tx.
func (*PostgresStore) CancelExecutionAtomicTokenPinned ¶
func (s *PostgresStore) CancelExecutionAtomicTokenPinned(ctx context.Context, tx pgx.Tx, executionID string, cancelledBy *string, rawToken string) (canceled bool, currentStatus string, err error)
CancelExecutionAtomicTokenPinned is CancelExecutionAtomic that also requires approval_token_hash to equal the hash of rawToken and the token to be unexpired, checked in the same UPDATE as the status change. The email-link cancel validated the token against a snapshot; a re-notification that rotates the token between that read and this write would otherwise still let the old, revoked token cancel the row (issue #1190, the cancel side of #590). A lost token pin on a row still pending/notified returns an error wrapping ErrApprovalTokenChanged; a lost status CAS returns (false, currentStatus, nil) as CancelExecutionAtomic does. An empty rawToken never matches.
func (*PostgresStore) CancelLadderRun ¶
func (s *PostgresStore) CancelLadderRun(ctx context.Context, id string, fromStatuses []ladder.RunStatus, cancelledBy string) (*LadderRunDB, error)
CancelLadderRun atomically transitions a ladder_runs row from one of fromStatuses to RunStatusCanceled and stamps the canceled-by audit column with the actor's email in the same UPDATE. Returns the updated row on success, or (nil, nil) when zero rows are affected (race lost or unexpected current status). An empty actor is rejected with ErrLadderRunCancelActorRequired before any write.
func (*PostgresStore) CancelPendingExchangesByOrigin ¶
func (s *PostgresStore) CancelPendingExchangesByOrigin(ctx context.Context, origin common.ExchangeOrigin) (int64, error)
CancelPendingExchangesByOrigin cancels only pending records that match the given origin (gap G10 / issue #1348):
- common.ExchangeOriginStandalone: cancels WHERE ladder_run_id IS NULL
- common.ExchangeOriginLadder: cancels WHERE ladder_run_id IS NOT NULL
The origin is validated at this boundary; an unknown value fails loud rather than silently canceling the wrong partition on a money path.
DELIBERATE COARSE PARTITION: the ExchangeOriginLadder branch cancels EVERY ladder-linked pending record (ladder_run_id IS NOT NULL) across ALL ladder runs and configs, not just the current run's. This is acceptable today because the ladder never creates pending exchange records: buildRIExchangeConfig forces Mode=auto, which completes or fails immediately without leaving a pending row. Per-run / per-config scoping needs an additional selection key (e.g. the specific ladder_run_id or config_id) and is tracked in TODO(#1367).
func (*PostgresStore) CancelScheduledExecutionAtomic ¶
func (s *PostgresStore) CancelScheduledExecutionAtomic(ctx context.Context, tx pgx.Tx, executionID string, cancelledBy *string) (canceled bool, currentStatus string, err error)
CancelScheduledExecutionAtomic atomically transitions an execution from 'scheduled' to 'canceled' (canonical US spelling), setting canceled_by to the supplied actor (NULL when actor is nil). Used by the Gmail-style pre-fire delay revoke path (issue #290 / #291 wave-2): an approved-but-not-yet-fired execution can be revoked at $0 by flipping it to canceled before the scheduler fires the cloud SDK call.
The 'scheduled' status is the only accepted source. A concurrent scheduler tick that already transitioned the row to 'approved' or 'running' causes zero rows to be affected and the method returns (false, currentStatus, nil) -- the caller maps that to a 410 ("revocation window has closed") so the frontend can fall through to the post-execution Azure direct-cancel API path.
Returns (true, StatusCanceled, nil) on success and (false, "", err) on a real DB error. Must be called inside a WithTx block so the suppression cleanup commits atomically with the status flip.
func (*PostgresStore) CheckAZConfigMigration ¶
func (s *PostgresStore) CheckAZConfigMigration(ctx context.Context) error
CheckAZConfigMigration returns ErrAZConfigMigrationNotReady (wrapped, with the schema version found) until both az_config expand migrations are applied.
func (*PostgresStore) ClaimCollectionInvocation ¶
func (s *PostgresStore) ClaimCollectionInvocation(ctx context.Context, markerToken string) (token string, ok bool, err error)
ClaimCollectionInvocation re-stamps the collection in-flight marker with a fresh, invocation-scoped owner token (issue #84). The scheduler calls it once a token-carrying collect run has WON the task advisory lock, before it starts collecting.
The token MarkCollectionStarted hands out identifies the marker, not the run that serves it: Lambda's async delivery is at-least-once, so a duplicate delivery of the same event carries the same token. Without the re-stamp, a duplicate that is skipped by the advisory lock clears the marker with that shared token while the lock winner is still collecting. After the re-stamp only the winner's new token matches, so the duplicate's skip-path clear is a no-op and the winner's deferred clear (with the new token) is the one that releases the marker.
The marker is taken when it is still owned by markerToken (started_at is kept as MarkCollectionStarted set it) or when it is free or stale under the same 5-minute rule as MarkCollectionStarted (started_at is set to NOW()). The second case covers the window between the winner taking the lock and running this UPDATE, in which a lock-skipped duplicate may already have cleared the marker: the lock winner is the run actually collecting, so it re-establishes the marker rather than collecting with none. It also covers a late redelivery after the original run already finished and cleared.
Returns the new token and true when the caller now owns the marker. Returns ("", false, nil) when a different run holds a fresh marker; the caller then owns nothing and must not clear. An empty markerToken is a boundary error, as in ClearCollectionStarted.
func (*PostgresStore) ClaimDueLadderTranches ¶
func (s *PostgresStore) ClaimDueLadderTranches( ctx context.Context, configID string, asOf time.Time, limit int, filter LadderClaimFilter, create func(ctx context.Context, tx pgx.Tx, tranche LadderTrancheDB) (executionID string, err error), ) ([]LadderTrancheDB, error)
ClaimDueLadderTranches atomically claims up to limit tranches of configID that are due (scheduled_date <= asOf) but not expired (scheduled_date > asOf - LadderFireGrace). For each claimed row, in the same transaction, create runs and must return the id of the purchase_executions row it created; the tranche is then set to fired with that execution_id. If create returns an error the whole transaction rolls back and nothing is claimed, so a claim and its execution row can never disagree after a crash. Rows locked by a concurrent claim are skipped (FOR UPDATE SKIP LOCKED), so exactly one caller wins each tranche. The whole claim runs under the config's ladder lock (taken first), including the create callback: with a caller asOf earlier than the planner's, a claim could otherwise fire a row the planner's netting read had already excluded as expired, and the row would be bought AND re-planned. A callback slower than ladderLockTimeout makes planners fail loudly.
Only rows stored in commitment dollars (amount_basis = 'commitment', which the table constraint pairs with a commitment_rate) are claimable: a buyer spends amount_usd_hr as commitment dollars, and a legacy NULL-basis or on_demand_equivalent row would over-buy by 1/rate (#946). Those rows stay netted until the overdue sweep cancels them, and the next run re-plans their gap in commitment dollars.
The filter fails closed. Empty or unknown Layers is an error and nothing is locked. Empty TrancheIDs claims nothing, and IDs only intersect with the other predicates (config, status, basis and the due window at this asOf), so a stale or foreign id never widens the claim. A layer without an instrument builder must not be listed in Layers.
Only tranches at the owner-decided offering (LadderTerm, LadderPayment) whose run exists and started no earlier than LadderFireGrace before their date are claimable: a ramp step planned days ahead on stale usage, a tranche without a run and any other offering are refused in SQL. A refused row is left scheduled, keeps netting and is canceled as expired by the overdue sweep. Run rows are only read, never locked, so a concurrent amend is not blocked.
CeilingMicros caps the commitment fired in any rolling LadderCeilingWindow: after the filters, the claim keeps the longest prefix (in date, id order) whose exact micro-dollar sum fits under CeilingMicros minus every tranche of this config whose execution was created in the window, in any status. It stops at the first row that does not fit instead of skipping to a smaller later one, and an exhausted budget claims nothing without an error. Trimmed rows stay scheduled.
func (*PostgresStore) ClaimMarketplaceListingSlot ¶
func (s *PostgresStore) ClaimMarketplaceListingSlot(ctx context.Context, purchaseID, clientToken string, priceSchedule []byte) (*MarketplaceListingClaim, error)
ClaimMarketplaceListingSlot atomically reserves the marketplace-listing slot for a purchase_history row so two concurrent marketplace-list requests cannot both proceed to create a duplicate AWS listing (issue #292). The single conditional UPDATE transitions listing_state to ListingStatePending unless the row is active, or pending without a persisted token. It stores clientToken and priceSchedule in the same statement unless an earlier attempt already stored a token, and returns the row's values as of the claim (issue #525): the handler must not trust a row read before the claim. It returns (nil, nil) when the row could not be claimed (active, pending without a token, or absent). The claimed row keeps the previous listing id but no longer records that listing's state, so trigger purchase_history_keep_superseded_listing copies the previous listing into marketplace_listing_settlements when the token is first stored (migration 000153, issue #1494).
Rows saved before migration 000108 can share a purchase_id (#267). The claim then works on the earliest row (created_at, then id), the one GetPurchaseHistoryByPurchaseID returns, and refuses while any duplicate records an active listing, so the returned prior state and listing id belong to one row and a duplicate never reopens a listed RI.
func (*PostgresStore) ClaimRIExchangeIdempotencyKey ¶
func (s *PostgresStore) ClaimRIExchangeIdempotencyKey(ctx context.Context, key string, window time.Duration) (bool, error)
ClaimRIExchangeIdempotencyKey atomically claims an RI exchange submit fingerprint (issue #1642). See the interface doc for the contract.
The whole decision is one statement, so two concurrent submits of the same fingerprint cannot both win: the INSERT and the conditional takeover of an expired row are the same atomic row operation, with no read-then-write window between them. RowsAffected() is 1 only when this call inserted the row or took over an expired one; the ON CONFLICT ... WHERE predicate evaluating false leaves it at 0.
Both the write and the expiry comparison use now(), the DATABASE clock, so clock skew between concurrent application instances cannot distort the window.
func (*PostgresStore) ClaimedByOthers ¶
func (s *PostgresStore) ClaimedByOthers(ctx context.Context, token string, ids []string) ([]string, error)
ClaimedByOthers returns the ids that an attempt under a token other than token recorded as purchased (go#700). It runs on its own pool connection, like RecordAttempt, and must not be called inside a caller's transaction.
func (*PostgresStore) CleanupOldExecutions ¶
CleanupOldExecutions deletes purchase executions older than retentionDays.
Three independent cleanup branches, each with its own retention window so that a row far in one dimension doesn't block cleanup in the other:
Completed-state cleanup: `status = 'completed' AND scheduled_date < NOW() - retention`. Keeps recent completions visible in the UI for at least `retention` days before purging. `scheduled_date` is the right clock here because a completed row executed on (or very near) the day it was scheduled for.
Canceled-state cleanup: `status = 'canceled' AND updated_at < NOW() - retention`.
This branch retains on `updated_at`, NOT `scheduled_date`, and must stay that way: CountExecutionsByPlanAndStatus windows the plan health score's canceled count on `updated_at` over exactly this retention period (see internal/api/plan_health.go planHealthLookbackDays), and CancelExecutionAtomic stamps `updated_at` while leaving `scheduled_date` untouched. Retaining on `scheduled_date` therefore purged rows the score was still counting: cancel a purchase whose scheduled_date is already past the horizon (a plan's rows are created up front, and parseCreatePurchasesRequest accepts a past start date) and the next sweep deleted it the same day, silently raising that plan's health score by up to 20 points overnight with no operator action. Nothing accumulates indefinitely: a genuinely old canceled row still has an old `updated_at`.
This cuts the other way too, and the change is user-visible: a canceled row with a FUTURE `scheduled_date` used to be retained forever, because `scheduled_date < NOW() - retention` was never true for it. It now leaves History `retention` days after the cancellation rather than `retention` days after the date it was scheduled for, so a purchase canceled today for a 2-year-out date disappears in a month instead of in two years. That closes an unbounded-retention leak and is the behavior the health window already assumed.
Expired-row cleanup: `expires_at IS NOT NULL AND expires_at < NOW() - retention`, for a settled row the health score does not count. This is the row's own TTL column (SavePurchaseExecution writes it from PurchaseExecution.TTL), NOT the approval-token deadline -- that is a separate column, `approval_token_expires_at`, added by migration
A settled row whose TTL lapsed longer than `retention` ago is dead, so without this branch it would accumulate indefinitely.
The status gate is an ALLOWLIST: status = ANY(TerminalExecutionStatuses) AND status <> ALL(HealthScoredExecutionStatuses) (#998, #1173). This is the only expires_at retention path since cmd/cleanup-lambda, which ran its own copy of the predicate, was deleted (#357). A lapsed TTL says nothing about whether an executor, scheduler or reaper still needs the row: `expires_at` is set at insert and never rewritten, so an `approved` or `running` row stranded by a dead executor (the rows GetStaleApprovedExecutions and ListStuckExecutions exist to find) used to be deleted here before the reaper could resolve it (#120). Pending and notified rows are kept too: ExpireExecutionAtomic moves a lapsed approval to `expired`, which this branch then reaps. A status added to the schema later is kept until someone classifies it in TerminalExecutionStatuses, the fail-closed direction.
Every status in HealthScoredExecutionStatuses is excluded here, which is the whole reason that slice is exported rather than spelled out twice. `expires_at` is written once at insert and never rewritten when a row later reaches a terminal status, so it can be arbitrarily older than the terminal transition. Without the exclusion, a row that failed or was canceled TODAY but carries a lapsed `expires_at` is purged by this branch the same day, while the score is still counting it -- reintroducing through this branch the exact overnight score jump branch 2 exists to prevent, and at up to -40 for `failed`, twice canceled's worst case. Their own terminal-status branches govern them.
`failed` deliberately has no cleanup branch of its own: the health score's lookback comment (internal/api/plan_health.go planHealthLookbackDays) documents that this sweep "never deletes failed ones", and the score's window depends on that being true.
Note on reachability: `expires_at` currently has exactly one writer, SavePurchaseExecution via timeFromTTL(execution.TTL), and no production path assigns PurchaseExecution.TTL, so rows created by current code leave it NULL and this branch is inert for them. It can still hold non-NULL values on legacy imported rows, which is why the exclusion is written defensively rather than omitted.
A row that a failed row names in retry_execution_id is never deleted, in any branch. The foreign key is ON DELETE SET NULL, and both "already retried" guards read that column, so deleting a completed retry successor would reopen the failed row for another retry. Failed rows are never swept, so the successor stays until the failed row itself is gone. That includes a canceled or expired successor, which used to age out after the retention window: the failed row now keeps answering "already retried" for as long as it exists. Fail-closed by design.
The branches are OR'd: a row that qualifies under ANY is deleted, regardless of the other columns. An earlier revision of this function incorrectly AND'd the `scheduled_date` gate with both branches, which meant pending rows with a far-future `scheduled_date` but a long-past `expires_at` never got cleaned up (a 2-year-out purchase whose row TTL lapsed would leave a dead row accumulating for 1.9 years). Keep each branch fully parenthesized so a future edit can't change the predicate's meaning through AND/OR precedence.
NULL `expires_at` is excluded from branch 3 so rows that never had a TTL are safe from expiry-based cleanup -- which, per the reachability note above, is every row current code writes.
func (*PostgresStore) ClearCollectionStarted ¶
func (s *PostgresStore) ClearCollectionStarted(ctx context.Context, token string) error
ClearCollectionStarted clears last_collection_started_at (and the owner token) so the frontend knows an async collection has finished. Called by the scheduler on both success and failure paths. On the success path, last_collected_at and last_collection_error are updated by UpsertRecommendations, so this method only touches started_at and the owner column.
The clear is scoped to rows where last_collection_owner_id still matches token (issue #261): a caller whose token no longer matches (another run has since started and won the race) has nothing left to clear and this is a documented silent no-op, not an error. An empty token is a boundary error: only a caller that actually won MarkCollectionStarted should ever call Clear; callers with no marker to own (cron, cold-start) must skip the call entirely rather than pass an empty token.
func (*PostgresStore) ClearRegistrationCredentialPayload ¶
func (s *PostgresStore) ClearRegistrationCredentialPayload(ctx context.Context, registrationID string) error
ClearRegistrationCredentialPayload removes the encrypted credential kept with a registration once it has been saved elsewhere. A missing id affects no rows and is not an error.
func (*PostgresStore) ClearRevocationInFlight ¶
func (s *PostgresStore) ClearRevocationInFlight(ctx context.Context, purchaseID string) error
ClearRevocationInFlight sets revocation_in_flight=false on a purchase_history row. Called when the Azure Return call fails transiently (before Azure actually issued a refund) so the row is not left stuck in the in-flight state, which would mislead the finalize_revocations sweep into thinking Azure succeeded (issue #290, second-wave CR Finding D). No-op when already false. The UPDATE is unconditional: only the request whose FlipPurchaseRevocationInFlight claimed the row may call it (issue #1518).
func (*PostgresStore) CompletePlanStep ¶
CompletePlanStep records that ramp step stepNumber of planID completed and advances the schedule to it, inside a transaction. The row is locked with SELECT FOR UPDATE so concurrent callers (overlapping Lambda invocations, multi-tick cron) cannot both read the same CurrentStep value and both write CurrentStep+1, skipping a step (issue #1071).
The operation is idempotent in stepNumber rather than a blind increment: a multi-account plan produces one execution per account per ramp step, and retrying two separately-failed accounts of the same step used to advance the ramp twice, so the plan reported itself a step further along than the commitment it had actually bought (issue #1669). Completing a step at or below CurrentStep therefore writes nothing and reports ErrRampStepAlreadyCounted.
Completing a step more than one beyond CurrentStep is refused for the same reason in the other direction: the steps in between never completed, and advancing over them would silently overstate how much the plan has bought.
Granularity: a step is complete when EVERY cloud account it fanned out to has bought, not when any one of them has (issue #1861) -- see requireRampStepBought. Until then the advance reports ErrRampStepIncomplete and the plan row is left untouched.
Returns nil when the plan no longer exists (deleted between execution and progress update) so the caller is not penalized for a race it cannot control.
func (*PostgresStore) CompleteRIExchange ¶
func (s *PostgresStore) CompleteRIExchange(ctx context.Context, id, exchangeID string) error
CompleteRIExchange marks an RI exchange as completed.
func (*PostgresStore) CompleteRIExchangeWithPayment ¶
func (s *PostgresStore) CompleteRIExchangeWithPayment(ctx context.Context, id, exchangeID, acceptedPaymentDue string) error
CompleteRIExchangeWithPayment marks an RI exchange as completed and updates payment_due to the amount AWS actually accepted. Use this on the manual-approval path instead of CompleteRIExchange so the daily-spend ledger (GetRIExchangeDailySpend) reflects the accepted amount, not the stale pre-execution quote (H3 fix).
func (*PostgresStore) CompleteTargetMetStepTx ¶
func (s *PostgresStore) CompleteTargetMetStepTx(ctx context.Context, tx pgx.Tx, planID string, stepNumber int, rootID, note string) error
CompleteTargetMetStepTx records a plan step whose cumulative target is already held as a completed no-op row and advances the ramp over it, all in the caller's transaction. Without a shared transaction a crash between the row and the advance would leave a settled step the ramp never moves past.
rootID names the pre-created empty root row of the step to complete in place (compare-and-set: it must still be pending/notified and empty; otherwise ErrExecutionNotInExpectedStatus), or is "" to insert a new row. The note is stored as the row's error text; the number of failed rows of unknown outcome that were counted as committed is appended to it so an advance taken on such capacity is visible.
The plan is re-read under the lock AFTER any baseline write in this transaction: that write bumps updated_at, and advancing from a plan read before it would lose the optimistic-lock check in UpdatePurchasePlanTx.
func (*PostgresStore) CountExecutionsByPlanAndStatus ¶
func (s *PostgresStore) CountExecutionsByPlanAndStatus(ctx context.Context, statuses []string, since time.Time) (map[string]ExecutionStatusCounts, error)
CountExecutionsByPlanAndStatus returns, keyed by plan ID, the exact number of executions in each of the supplied statuses that last changed state at or after `since`.
Aggregated with GROUP BY rather than counted from a GetExecutionsByStatuses page: that method's DESC + LIMIT truncation would silently understate any plan whose executions fall outside the newest `limit` rows, which for the plan health score means an unhealthy plan quietly renders as healthy once newer rows from other plans push its failures out of the window. The result set here is bounded by plans x statuses, not by execution volume, so it needs no limit of its own.
The window is on updated_at, NOT scheduled_date, because for the terminal statuses this method exists to count those are different dates pointing in opposite directions. A plan's executions are created up front for the whole ramp, so a pending row carries a scheduled_date months in the FUTURE; canceling it (CancelExecutionAtomic) leaves that future date untouched. Windowing on scheduled_date would therefore count a purchase cancelled today under a date next year, and answer "how many rows are scheduled recently-or-later" instead of "how many changed state recently". updated_at is stamped by CancelExecutionAtomic and TransitionExecutionStatus, and backstopped by the update_purchase_executions_updated_at trigger, so it is when the row actually entered the status being counted.
plan_id has been nullable since migration 000033 (direct-execute purchases from the Recommendations page have no originating plan, and deleting a plan SET NULLs its executions). Those rows belong to no plan and are excluded in SQL; the scan still goes through sql.NullString so a NULL can never turn a per-plan count into a scan error that blanks the score for every plan.
func (*PostgresStore) CountLadderRunTrancheStatuses ¶
func (s *PostgresStore) CountLadderRunTrancheStatuses(ctx context.Context, runID string) (map[ladder.TrancheStatus]int, error)
CountLadderRunTrancheStatuses returns how many of a run's tranches sit in each stored status. The keys are the raw stored statuses, so a legacy spelling shows up as its own key; the caller decides what counts as settled.
func (*PostgresStore) CountLiveExecutionsForAccount ¶
func (s *PostgresStore) CountLiveExecutionsForAccount(ctx context.Context, accountID string) (int, error)
CountLiveExecutionsForAccount returns the number of purchase executions referencing this cloud account whose status is not in TerminalExecutionStatuses: rows an executor, scheduler or reaper may still act on, which need the account to exist. DeleteCloudAccount detaches every other row, so these are exactly the rows that block the delete (issue #265). It includes the pending/notified rows CountPendingExecutionsForAccount counts.
func (*PostgresStore) CountPendingExecutionsForAccount ¶
func (s *PostgresStore) CountPendingExecutionsForAccount(ctx context.Context, accountID string) (int, error)
CountPendingExecutionsForAccount returns the number of pending/notified purchase executions still referencing this cloud account. The deleteAccount handler calls this before issuing DELETE FROM cloud_accounts so it can short-circuit with a 409 instead of letting migration 000053's ON DELETE RESTRICT bubble up as an opaque FK-violation error. See issue #606.
func (*PostgresStore) CreateAccountRegistration ¶
func (s *PostgresStore) CreateAccountRegistration(ctx context.Context, reg *AccountRegistration) error
CreateAccountRegistration inserts a new registration request. It returns an error wrapping ErrDuplicatePendingRegistration when the partial unique index rejects a second pending registration for the same provider+external_id, and one wrapping ErrReferenceTokenCollision when reg.ReferenceToken is taken.
func (*PostgresStore) CreateCloudAccount ¶
func (s *PostgresStore) CreateCloudAccount(ctx context.Context, account *CloudAccount) error
CreateCloudAccount inserts a new cloud account record.
func (*PostgresStore) CreatePurchasePlan ¶
func (s *PostgresStore) CreatePurchasePlan(ctx context.Context, plan *PurchasePlan) error
CreatePurchasePlan creates a new purchase plan.
func (*PostgresStore) CreatePurchasePlanWithAccounts ¶
func (s *PostgresStore) CreatePurchasePlanWithAccounts(ctx context.Context, plan *PurchasePlan, accountIDs []string, visible func(accounts []CloudAccount) bool) error
CreatePurchasePlanWithAccounts inserts plan and attaches accountIDs in one transaction, refusing the create when a plan the caller can see already has the same name (issue #1734).
A name matches when lower(btrim(name, E' \t\r\n')) agrees, so a trailing tab or newline does not make a different name. The key is computed by the database once and used for both the advisory lock and the match, so Postgres alone defines the equivalence: an exact repeat always matches, whatever the database ctype. Case folding beyond ASCII follows that ctype. There is no unique index because plans in disjoint account scopes may share a name.
Concurrent creates of one name queue on the lock. The plan and its accounts commit together, so a queued create always sees an account-bearing row.
visible is called in the transaction with the accounts of each existing plan of that name, oldest first, and must be pure: it decides whether the caller may know about that plan. The first visible plan is reported as *PlanNameTakenError (errors.Is ErrPlanNameTaken). A match the caller cannot see is ignored and never disclosed.
func (*PostgresStore) CreateSuppression ¶
func (s *PostgresStore) CreateSuppression(ctx context.Context, sup *PurchaseSuppression) error
CreateSuppression inserts a suppression row using a one-call transaction. Callers that need to bundle this write with other statements (e.g. the matching execution insert) should use CreateSuppressionTx inside a WithTx block instead.
func (*PostgresStore) CreateSuppressionTx ¶
func (s *PostgresStore) CreateSuppressionTx(ctx context.Context, tx pgx.Tx, sup *PurchaseSuppression) error
CreateSuppressionTx inserts a suppression row inside a caller-owned transaction. sup.ID is populated from the Postgres-generated UUID if the caller left it blank.
func (*PostgresStore) DeleteAccountCredentials ¶
func (s *PostgresStore) DeleteAccountCredentials(ctx context.Context, accountID string) error
DeleteAccountCredentials removes all credential records for an account.
func (*PostgresStore) DeleteAccountRegistration ¶
func (s *PostgresStore) DeleteAccountRegistration(ctx context.Context, id string) error
DeleteAccountRegistration removes a registration record by ID.
func (*PostgresStore) DeleteAccountServiceOverride ¶
func (s *PostgresStore) DeleteAccountServiceOverride(ctx context.Context, accountID, provider, service string) error
DeleteAccountServiceOverride removes an override, reverting to global defaults.
func (*PostgresStore) DeleteAccountServiceOverrideAuditedTx ¶
func (s *PostgresStore) DeleteAccountServiceOverrideAuditedTx(ctx context.Context, tx pgx.Tx, accountID, provider, service string, audit AuditContext) error
DeleteAccountServiceOverrideAuditedTx deletes the override inside tx and records the deleted row as the event's before. Deleting an override that does not exist records nothing.
func (*PostgresStore) DeleteCloudAccount ¶
func (s *PostgresStore) DeleteCloudAccount(ctx context.Context, id string) error
DeleteCloudAccount deletes a cloud account. Cascades to credentials and overrides. Terminal purchase executions are kept as history with cloud_account_id set to NULL; a live execution still blocks the delete through the FK (issue #265). If an approved account_registrations row points at this account, it is reset to 'pending' in the same transaction so the admin can re-approve through the normal flow instead of being left with a dead-end "Approved (account pending link)" row. Enabled plans whose only target is this account are disabled in the same transaction (issue #264); see disableSoleAccountPlansTx.
func (*PostgresStore) DeletePurchasePlan ¶
func (s *PostgresStore) DeletePurchasePlan(ctx context.Context, planID string) error
DeletePurchasePlan deletes a purchase plan.
func (*PostgresStore) DeleteSuppressionsByExecution ¶
func (s *PostgresStore) DeleteSuppressionsByExecution(ctx context.Context, executionID string) error
DeleteSuppressionsByExecution deletes all suppression rows for the given execution using a one-call transaction. Used by the cancel path when the whole execution's capacity should be un-suppressed.
func (*PostgresStore) DeleteSuppressionsByExecutionTx ¶
func (s *PostgresStore) DeleteSuppressionsByExecutionTx(ctx context.Context, tx pgx.Tx, executionID string) error
DeleteSuppressionsByExecutionTx deletes all suppression rows for the given execution inside a caller-owned transaction. Safe to call on an execution with no suppression rows (e.g. grace_period_days=0 at insert time) — returns nil, no error.
func (*PostgresStore) DisableLadderConfigTx ¶
func (s *PostgresStore) DisableLadderConfigTx(ctx context.Context, tx pgx.Tx, configID string) (bool, error)
DisableLadderConfigTx sets ladder_configs.enabled to false inside the caller's transaction and reports whether it flipped a row (false: the config is gone or was already disabled). It locks the config row with NOWAIT and never waits: the reconciler already holds a tranche row, and amend takes the config row before the tranche row, so waiting here could deadlock. A busy row returns ErrLadderConfigBusy. It takes no advisory lock (see withLadderConfigLock).
func (*PostgresStore) ExpireExecutionAtomic ¶
func (s *PostgresStore) ExpireExecutionAtomic(ctx context.Context, tx pgx.Tx, executionID string, observedScheduledDate time.Time) (bool, error)
ExpireExecutionAtomic implements StoreInterface.
func (*PostgresStore) FailRIExchange ¶
func (s *PostgresStore) FailRIExchange(ctx context.Context, id, errorMsg string) error
FailRIExchange marks an RI exchange as failed.
func (*PostgresStore) FamilyRetryClaimedTx ¶
func (s *PostgresStore) FamilyRetryClaimedTx(ctx context.Context, tx pgx.Tx, family, planID, selfID string, selfIsRoot bool) (bool, error)
FamilyRetryClaimedTx reports whether a row of the opposite kind in the same plan and key family already has a retry successor: an account row when selfIsRoot, the root when not. Same-kind siblings never count, and neither does selfID. A fan-out root and its account rows are linked only by the key family (the root key K and the account keys K:<account>), and each has its own retry link, so the per-row CAS alone lets both kinds be retried. Call it under LockRetryFamilyTx.
func (*PostgresStore) FinalizeRIExchangeDirectExecution ¶
func (s *PostgresStore) FinalizeRIExchangeDirectExecution(ctx context.Context, id string, outcome RIExchangeDirectOutcome) error
FinalizeRIExchangeDirectExecution records the provider outcome on a submitted audit row. It is a compare-and-set on status = 'submitted', so a row is finalized at most once: a second finalize, concurrent or later, updates nothing and returns ErrRIExchangeDirectExecutionNotSubmitted rather than overwriting the outcome already recorded.
func (*PostgresStore) FindOpenRedshiftLineageConflictsTx ¶
func (s *PostgresStore) FindOpenRedshiftLineageConflictsTx(ctx context.Context, tx pgx.Tx, selfID, family string, tuples []RedshiftTuple, accountID *string, horizon time.Duration, stamp time.Time, window, settle time.Duration) ([]RedshiftLineageConflict, error)
FindOpenRedshiftLineageConflictsTx returns the other executions whose node this lineage could buy twice or adopt. Account: row's else rec's vs execution's else tuple's; NULL matches any. Running rows conflict at any age; other open rows within horizon of their stamp. Other-family rows that may have bought (finished, or failed without the no-submission proof) within window of stamp; other-family retryable failed rows within horizon. Same-family rows: running, or failed (unlinked) or finished after a possible send, within settle.
func (*PostgresStore) FlipPurchaseRevocationInFlight ¶
func (s *PostgresStore) FlipPurchaseRevocationInFlight(ctx context.Context, purchaseID string) error
FlipPurchaseRevocationInFlight claims the revocation of the purchase_history row for purchaseID by setting revocation_in_flight=true. Called immediately before the Azure Return API call to enable partial-success reconciliation (issue #290 Finding #6).
It is a compare-and-set on two predicates:
- revoked_at IS NULL (issue #316): a stale request that reaches the flip after another request's MarkPurchaseRevoked committed must not flag the revoked row again, since MarkPurchaseRevoked (guarded on the same predicate) would then never clear it. That returns an error wrapping ErrPurchaseAlreadyRevoked.
- revocation_in_flight = false (issue #1518): only one request may hold the claim, so two first-time revokes cannot both post a Return. The request that loses gets an error wrapping ErrRevocationInFlight.
The row lock serializes concurrent flips and marks, and under READ COMMITTED a waiting UPDATE re-checks both predicates against the committed row, so exactly one flip of an unrevoked, unflagged row succeeds. A missing row keeps the not-found error.
func (*PostgresStore) GetAccountCredential ¶
func (s *PostgresStore) GetAccountCredential(ctx context.Context, accountID, credentialType string) (string, error)
GetAccountCredential returns the encrypted blob for an account credential. A missing row returns ErrNotFound, never ("", nil): that is what an empty stored blob returns, and a caller that read an empty result as "no credential, use the ambient identity" would act in the wrong account (#120).
func (*PostgresStore) GetAccountRegistration ¶
func (s *PostgresStore) GetAccountRegistration(ctx context.Context, id string) (*AccountRegistration, error)
GetAccountRegistration returns a single registration by UUID.
func (*PostgresStore) GetAccountRegistrationByToken ¶
func (s *PostgresStore) GetAccountRegistrationByToken(ctx context.Context, token string) (*AccountRegistration, error)
GetAccountRegistrationByToken returns a registration by its reference_token.
func (*PostgresStore) GetAccountServiceOverride ¶
func (s *PostgresStore) GetAccountServiceOverride(ctx context.Context, accountID, provider, service string) (*AccountServiceOverride, error)
GetAccountServiceOverride returns a single override, or nil if none exists.
func (*PostgresStore) GetActivePurchaseHistory ¶
func (s *PostgresStore) GetActivePurchaseHistory(ctx context.Context, asOf time.Time, accountIDs []string, externalIDsByProvider map[string][]string) ([]PurchaseHistoryRecord, error)
GetActivePurchaseHistory retrieves every purchase_history row still within its commitment term at asOf, optionally scoped to a set of accounts via the same dual-column predicate as GetPurchaseHistoryFiltered (appendAccountPredicate): both accountIDs (cloud_accounts UUIDs matched on cloud_account_id) and externalIDsByProvider (provider-scoped external numbers matched on account_id) are applied with OR semantics so rows carrying only one identifier are still returned (issues #701/#498/#866). Both empty means all accounts. The active filter is pushed into SQL so the result is bounded by the number of live commitments (not by all history ever recorded), which is what the analytics collector, dashboard KPIs, and inventory endpoints need: it cannot silently truncate older-but-still-active 1y/3y commitments the way a newest-first LIMIT page does (issue #1140). term*8760 hours matches the collector's HoursPerYear and the API layer's commitmentExpiry (both 365*24) so the SQL and Go term windows agree. The expiry comparison is inclusive (expiry >= asOf): a commitment expiring exactly at asOf is still active, matching the API layer's isActiveCommitment (!now.After(expiry)) so the SQL result set and the Go-side active checks share one boundary definition.
The expiry is compared as Unix epoch seconds (activeExpiryEpochExpr) so the predicate can use idx_purchase_history_active_expiry (migration 000126) instead of evaluating every row ever recorded (issue #33).
func (*PostgresStore) GetAllPurchaseHistory ¶
func (s *PostgresStore) GetAllPurchaseHistory(ctx context.Context, limit int) ([]PurchaseHistoryRecord, error)
GetAllPurchaseHistory retrieves all purchase history.
func (*PostgresStore) GetCloudAccount ¶
func (s *PostgresStore) GetCloudAccount(ctx context.Context, id string) (*CloudAccount, error)
GetCloudAccount returns a single cloud account by ID with credentials_configured derived.
func (*PostgresStore) GetCloudAccountByExternalID ¶
func (s *PostgresStore) GetCloudAccountByExternalID(ctx context.Context, provider, externalID string) (*CloudAccount, error)
GetCloudAccountByExternalID returns a single cloud account matched by (provider, external_id). Used by the scheduler ambient-path tagging fix for issue #604 — when the Lambda's STS identity matches a registered account (regardless of enabled state), rec rows are stamped with that account's UUID so the approve modal shows the account name instead of `(ambient)`. Returns (nil, nil) when no row matches.
The cloud_accounts table declares `UNIQUE(provider, external_id)` (migration 000011), which guarantees the lookup hits an index.
func (*PostgresStore) GetDoomedNextRoots ¶
func (s *PostgresStore) GetDoomedNextRoots(ctx context.Context, now time.Time) (map[string]DoomedRoot, error)
GetDoomedNextRoots returns, keyed by plan ID, the plans whose next empty root is certainly doomed at now. A root dated in the last slice of the window the tick may still fill is deliberately not reported. Plans with nothing doomed are absent from the map.
func (*PostgresStore) GetExecutionByID ¶
func (s *PostgresStore) GetExecutionByID(ctx context.Context, executionID string) (*PurchaseExecution, error)
GetExecutionByID retrieves a purchase execution by execution ID. Returns an error wrapping ErrNotFound when no row matches executionID so callers can cleanly distinguish "not found" (errors.Is(err, ErrNotFound)) from a real DB failure (any other non-nil error). A nil error guarantees a non-nil execution (fail-loud contract; issues #976, #1339).
func (*PostgresStore) GetExecutionByPlanAndDate ¶
func (s *PostgresStore) GetExecutionByPlanAndDate(ctx context.Context, planID string, scheduledDate time.Time) (*PurchaseExecution, error)
GetExecutionByPlanAndDate retrieves execution for a specific plan and date.
func (*PostgresStore) GetExecutionFanOutShape ¶
func (s *PostgresStore) GetExecutionFanOutShape(ctx context.Context, lineageKey string) (string, error)
GetExecutionFanOutShape returns the fan-out shape pinned for the execution lineage keyed by lineageKey, or "" when none is pinned yet.
func (*PostgresStore) GetExecutionsByStatuses ¶
func (s *PostgresStore) GetExecutionsByStatuses(ctx context.Context, statuses []string, limit int) ([]PurchaseExecution, error)
GetExecutionsByStatuses returns executions whose Status is any of the supplied values, newest-first, capped at `limit`. Used by the History handler to merge pending/failed/expired rows alongside completed purchases without changing the narrower GetPendingExecutions contract the scheduler depends on.
Pending rows dated in the future are the one exception to newest-first (issue #680): plan creation writes every ramp step up front as a pending row, up to 52 per plan, so about 20 plans fill MaxListLimit with steps months ahead and a plain scheduled_date DESC would cut off a pending approval due today. Those future pending steps sort after every other row, and among themselves soonest first, so the cap drops the farthest steps. No other status is affected: a notified, scheduled or in-flight row is actionable whatever its date, and terminal statuses never match the pending predicate, so their order is unchanged.
Executions with status 'completed' and an empty error are excluded: they are already represented by their purchase_history rows, so returning them would only consume the cap (the History handler skips them anyway).
func (*PostgresStore) GetExecutionsByStatusesFiltered ¶
func (s *PostgresStore) GetExecutionsByStatusesFiltered(ctx context.Context, q ExecutionsByStatusesQuery) ([]PurchaseExecution, error)
GetExecutionsByStatusesFiltered is GetExecutionsByStatuses with the History filters and account scope in q applied in SQL, before the limit (issue #632). Order and the clean-completed exclusion are GetExecutionsByStatuses'.
func (*PostgresStore) GetGlobalConfig ¶
func (s *PostgresStore) GetGlobalConfig(ctx context.Context) (*GlobalConfig, error)
GetGlobalConfig retrieves the global configuration.
func (*PostgresStore) GetGlobalConfigTx ¶
func (s *PostgresStore) GetGlobalConfigTx(ctx context.Context, tx pgx.Tx) (*GlobalConfig, error)
GetGlobalConfigTx reads the global config inside the caller's transaction, so the value is as fresh as the statement and not a snapshot taken earlier.
func (*PostgresStore) GetLadderConfig ¶
func (s *PostgresStore) GetLadderConfig(ctx context.Context, cloudAccountID, provider string) (*LadderConfigDB, error)
GetLadderConfig returns the ladder_config row for the given (cloud_account_id, provider) pair. Returns (nil, nil) when no row exists.
func (*PostgresStore) GetLadderConfigs ¶
func (s *PostgresStore) GetLadderConfigs(ctx context.Context) ([]LadderConfigDB, error)
GetLadderConfigs returns the ladder_configs rows, newest first, capped at MaxListLimit like the package's other list reads (#120). There is one row per (cloud_account_id, provider), so the cap is only reached with more than a thousand account/provider pairs. Returns an empty slice (not nil) when no rows exist.
func (*PostgresStore) GetLadderExecutionGate ¶
func (s *PostgresStore) GetLadderExecutionGate(ctx context.Context, idempotencyKey string) (*LadderExecutionGate, error)
GetLadderExecutionGate finds the ladder tranche whose id equals an execution's idempotency key and returns its config switches and run status. The key is compared as text, so non-ladder keys (legacy execution ids, "<root>:<account>" multi-account keys, fingerprints) match nothing and return (nil, nil): "not a ladder execution". Only a real database error is an error, and the caller must fail closed on it.
func (*PostgresStore) GetLadderRun ¶
func (s *PostgresStore) GetLadderRun(ctx context.Context, id string) (*LadderRunDB, error)
GetLadderRun returns the ladder_runs row for the given id, or (nil, nil) when no row exists.
func (*PostgresStore) GetLadderSweepCeiling ¶
GetLadderSweepCeiling returns the config's rolling-24h commitment ceiling in exact micro-dollars per hour. nil means not set, which the sweep must treat as refuse, never as unlimited. An unmigrated schema returns ErrLadderCeilingUnavailable.
func (*PostgresStore) GetMarketplaceListingAttempt ¶
func (s *PostgresStore) GetMarketplaceListingAttempt(ctx context.Context, purchaseID string) (*MarketplaceListingAttempt, error)
GetMarketplaceListingAttempt returns the listing id, state and unresolved attempt token of the row for purchaseID, or (nil, nil) when there is none. With duplicate rows for one purchase_id it reads the earliest.
func (*PostgresStore) GetMarketplaceListingProceedsTotals ¶
func (s *PostgresStore) GetMarketplaceListingProceedsTotals(ctx context.Context, purchaseIDs, accountIDs []string, externalIDsByProvider map[string][]string) ([]MarketplaceListingProceedsTotal, error)
GetMarketplaceListingProceedsTotals returns, for each of purchaseIDs that has any marketplace listing recorded, the net proceeds and AWS fees summed over all of its settled listings, from marketplace_listing_settlements only (issue #1494). Each listing has one row there, so a sale is counted once however often the RI was relisted; purchase_history's settlement columns (the latest listing only) are never added in. One total is returned per purchase and currency, ordered by purchase id then currency.
Only purchases of the given accounts are summed (accountIDs are cloud_accounts UUIDs, externalIDsByProvider the external account numbers grouped by provider, as for GetPurchaseHistoryFiltered), so a caller cannot read another account's proceeds by naming its purchase ids (issue #1586). Empty scope is an error, never "all accounts". Every total is an estimate (MarketplaceListingProceedsTotal.IsEstimate).
func (*PostgresStore) GetPendingExecutions ¶
func (s *PostgresStore) GetPendingExecutions(ctx context.Context) ([]PurchaseExecution, error)
GetPendingExecutions retrieves all pending purchase executions.
func (*PostgresStore) GetPlanAccounts ¶
func (s *PostgresStore) GetPlanAccounts(ctx context.Context, planID string) ([]CloudAccount, error)
GetPlanAccounts returns all cloud accounts associated with a plan.
func (*PostgresStore) GetPlanRampBaselineTx ¶
func (s *PostgresStore) GetPlanRampBaselineTx(ctx context.Context, tx pgx.Tx, planID string) (PlanRampBaseline, error)
GetPlanRampBaselineTx refuses cumulative sizing when retained history is untrusted. Fresh protected plans return nil until their baseline freezes under the plan lock.
func (*PostgresStore) GetPlanScheduleReceiptTx ¶
func (s *PostgresStore) GetPlanScheduleReceiptTx(ctx context.Context, tx pgx.Tx, commandID string) (*PlanScheduleReceipt, error)
GetPlanScheduleReceiptTx reads a receipt on tx. A missing receipt is (nil, nil).
func (*PostgresStore) GetPlannedExecutions ¶
func (s *PostgresStore) GetPlannedExecutions(ctx context.Context, statuses []string, limit int) ([]PurchaseExecution, error)
GetPlannedExecutions returns executions whose Status is any of the supplied values, ordered by scheduled_date ASC (soonest first), capped at `limit`. Used by the Planned Purchases handler where the user expects to act on imminent rows first.
Distinct from GetExecutionsByStatuses (DESC + LIMIT for History's newest-first semantics): when total rows exceed `limit`, a DESC truncation drops the soonest rows, exactly the ones this list must surface. Sorting the already-truncated subset in-memory cannot recover them.
Secondary sort by id ASC keeps ordering stable when multiple rows share a scheduled_date. NULLS LAST is defensive: the schema makes scheduled_date NOT NULL today, but the clause guards against a future relaxation silently hiding rows at the top of the list.
func (*PostgresStore) GetPurchaseHistory ¶
func (s *PostgresStore) GetPurchaseHistory(ctx context.Context, accountID string, limit int) ([]PurchaseHistoryRecord, error)
GetPurchaseHistory retrieves purchase history for an account.
func (*PostgresStore) GetPurchaseHistoryByPurchaseID ¶
func (s *PostgresStore) GetPurchaseHistoryByPurchaseID(ctx context.Context, purchaseID string) (*PurchaseHistoryRecord, error)
GetPurchaseHistoryByPurchaseID returns the single purchase_history row whose purchase_id matches purchaseID. Returns (nil, nil) when the row does not exist. The revocation-window columns (revocation_window_closes_at, revoked_at, revoked_via, support_case_id) are read alongside the base columns so the revoke endpoint can check idempotency without a second round trip (issue #290). The marketplace columns (offering_class, listing_id, listing_state) are read so the marketplace-list handler can validate offering_class and look up the cloud account (issue #292). Rows saved before migration 000108 can share a purchase_id; the earliest one (created_at, then id) is returned, the same row ClaimMarketplaceListingSlot claims (#267). return_posted_at (migration 000148) is read last so the revoke handler can tell an accepted Azure Return from one still in progress (issue #1522).
func (*PostgresStore) GetPurchaseHistoryFiltered ¶
func (s *PostgresStore) GetPurchaseHistoryFiltered( ctx context.Context, filter PurchaseHistoryFilter, ) ([]PurchaseHistoryRecord, error)
GetPurchaseHistoryFiltered reads purchase_history rows matching the supplied filter set, newest-first, capped at filter.Limit. See the StoreInterface docstring and PurchaseHistoryFilter for the per-field semantics. Each WHERE clause is appended only when its field is populated, so an empty filter gets the same plan-shape as GetAllPurchaseHistory. Implementation mirrors buildRecommendationFilter (store_postgres_recommendations.go).
The account predicate matches BOTH identifier columns:
(cloud_account_id = ANY($uuids) OR ((provider = '' OR LOWER(provider) = LOWER($p)) AND account_id = ANY($extsForP)) OR ...)
purchase_history carries two account identifiers and either may be the only one populated on a given row: cloud_account_id (the cloud_accounts UUID FK, added in migration 000011 with no backfill, so NULL on every direct-execute / ambient / pre-000011 row) and account_id (the cloud-provider external number, e.g. an AWS account number, always populated). The top-bar Account chip emits the UUID, so a UUID-only predicate silently dropped every NULL-cloud_account_id row (issue #701/#498) while an external-only predicate dropped every row that only has the UUID (issue #866). Matching both columns includes rows written by either path. The caller resolves the requested UUIDs to their (provider, external_id) pairs scoped to the user's accessible accounts and groups the external ids by provider, so the external-id half stays provider-scoped and a reused external number (aws/123 vs azure/123) cannot leak the wrong rows.
func (*PostgresStore) GetPurchaseHistoryInFlight ¶
func (s *PostgresStore) GetPurchaseHistoryInFlight(ctx context.Context) ([]*PurchaseHistoryRecord, error)
GetPurchaseHistoryInFlight returns the purchase_history rows whose Azure Return was recorded as accepted (return_posted_at set by MarkRevocationReturnPosted) but whose revoked_at is still NULL. Used by the finalize_revocations scheduled sweep to retry MarkPurchaseRevoked for rows where the Azure Return succeeded but the subsequent DB write failed (issue #290 Finding #6).
revocation_in_flight alone is not enough (issue #1523): a row is also left flagged when a request dies between the flip and the Return, and marking that row revoked would record a refund that never happened. The flag is not required either: once the Return is recorded the purchase is refunded, even if a concurrent request's failed Return cleared the flag.
func (*PostgresStore) GetPurchasePlan ¶
func (s *PostgresStore) GetPurchasePlan(ctx context.Context, planID string) (*PurchasePlan, error)
GetPurchasePlan retrieves a purchase plan by ID.
func (*PostgresStore) GetRIExchangeDailySpend ¶
func (s *PostgresStore) GetRIExchangeDailySpend(ctx context.Context, date time.Time) (string, error)
GetRIExchangeDailySpend returns total payment_due for completed and in-flight (processing) exchanges on a given date (UTC).
M5 fix: including 'processing' rows prevents a TOCTOU race where two concurrent approvals both read the same daily-spend total (before either exchange's ledger row is committed) and together exceed the daily cap. For 'completed' rows the time anchor is completed_at; for 'processing' rows it is updated_at (the moment the record transitioned to processing, i.e. when it was approved).
func (*PostgresStore) GetRIExchangeDirectExecution ¶
func (s *PostgresStore) GetRIExchangeDirectExecution(ctx context.Context, id string) (*RIExchangeDirectRow, error)
GetRIExchangeDirectExecution returns one AWS direct row of any status, or ErrRIExchangeResolveNotFound for a missing or non-AWS row.
func (*PostgresStore) GetRIExchangeHistory ¶
func (s *PostgresStore) GetRIExchangeHistory(ctx context.Context, since time.Time, limit int) ([]RIExchangeRecord, error)
GetRIExchangeHistory retrieves RI exchange history records.
func (*PostgresStore) GetRIExchangeHistoryForAccounts ¶
func (s *PostgresStore) GetRIExchangeHistoryForAccounts(ctx context.Context, since time.Time, limit int, accountIDs []string) ([]RIExchangeRecord, error)
GetRIExchangeHistoryForAccounts retrieves RI exchange history records for the given account ids only. The account predicate runs in SQL, before the LIMIT, so a scoped caller gets up to limit of their own records rather than whatever survives a filter applied to the newest limit records of every account (issue #308). An empty or nil accountIDs matches no records: "= ANY('{}')" is false and "= ANY(NULL)" is NULL for every row.
func (*PostgresStore) GetRIExchangeRecord ¶
func (s *PostgresStore) GetRIExchangeRecord(ctx context.Context, id string) (*RIExchangeRecord, error)
GetRIExchangeRecord retrieves an RI exchange record by ID. A missing record is a wrapped ErrNotFound, so callers can tell it from a failed query and answer it as a client error rather than a 500 (issue #601).
func (*PostgresStore) GetRIExchangeRecordByToken ¶
func (s *PostgresStore) GetRIExchangeRecordByToken(ctx context.Context, token string) (*RIExchangeRecord, error)
GetRIExchangeRecordByToken retrieves an RI exchange record by approval token. token is the raw, caller-supplied value; only its hash is stored (approval_token_hash, issue #103), so the lookup hashes it first.
func (*PostgresStore) GetRIUtilizationCache ¶
func (s *PostgresStore) GetRIUtilizationCache(ctx context.Context, key RIUtilizationCacheKey) (*RIUtilizationCacheEntry, error)
GetRIUtilizationCache returns the cached Cost Explorer utilization result for (cloud_account_id, region, lookback_days) or nil if no row exists. Staleness is evaluated by the caller — the query doesn't filter on fetched_at so a caller with a longer TTL than expected can still use the row.
func (*PostgresStore) GetRecommendationsFreshness ¶
func (s *PostgresStore) GetRecommendationsFreshness(ctx context.Context) (*RecommendationsFreshness, error)
GetRecommendationsFreshness returns the singleton freshness row. The table is seeded with id=1 by the migration so a row always exists; LastCollectedAt, LastCollectionError, LastCollectionStartedAt and LastCollectionPartial can be NULL.
func (*PostgresStore) GetRedshiftRetryClock ¶
func (s *PostgresStore) GetRedshiftRetryClock(ctx context.Context, executionID string) (RedshiftRetryClock, error)
GetRedshiftRetryClock returns how long ago the row was last written and first dispatched, both computed from now() in SQL so app clock skew cannot shorten the settle wait or the horizon.
func (*PostgresStore) GetScheduledExecutionsDue ¶
func (s *PostgresStore) GetScheduledExecutionsDue(ctx context.Context) ([]PurchaseExecution, error)
GetScheduledExecutionsDue returns purchase_executions with status='scheduled' whose scheduled_execution_at has elapsed (scheduled_execution_at <= NOW()). Used by the Gmail-style pre-fire delay scheduler tick (issue #291 wave-2). Results are ordered oldest-due-first so the scheduler fires them in FIFO order. Capped at MaxListLimit per sweep to bound the per-tick blast radius.
func (*PostgresStore) GetServiceConfig ¶
func (s *PostgresStore) GetServiceConfig(ctx context.Context, provider, service string) (*ServiceConfig, error)
GetServiceConfig retrieves configuration for a specific service.
func (*PostgresStore) GetStaleApprovedExecutions ¶
func (s *PostgresStore) GetStaleApprovedExecutions(ctx context.Context, olderThan time.Duration) ([]PurchaseExecution, error)
GetStaleApprovedExecutions returns executions stuck in the "approved" status whose last update is older than olderThan. These are executions that were flipped to "approved" by ApproveAndExecute but whose synchronous purchase run never finalized (Lambda timeout, cold-start eviction, panic) — issue #632. updated_at is stamped to NOW() at the moment of the approved transition (see TransitionExecutionStatus) and is not touched again unless the run finalizes, so it is the age of the strand. Mirrors GetStaleProcessingExchanges.
func (*PostgresStore) GetStaleProcessingExchanges ¶
func (s *PostgresStore) GetStaleProcessingExchanges(ctx context.Context, olderThan time.Duration) ([]RIExchangeRecord, error)
GetStaleProcessingExchanges returns processing exchanges older than the given duration.
func (*PostgresStore) GetStuckRampSteps ¶
func (s *PostgresStore) GetStuckRampSteps(ctx context.Context) (map[string]RampStepBlock, error)
GetStuckRampSteps returns, keyed by plan ID, the plan's next ramp step and how many of that step's units are stuck on it -- never bought, latest attempt terminal and unsuccessful, no retry in flight.
Derived on every read rather than stamped on a row when the advance was refused, which is what makes it safe to score a plan's health on: a stamped refusal is true only at the instant it is written and nothing clears it, so a plan that recovered would stay marked unhealthy until an operator noticed. Recomputing from the same rows the advance gate reads means the report disappears exactly when the ramp unfreezes, and cannot drift from the gate.
Plans with nothing stuck are absent from the map rather than present with a zero, so a caller cannot confuse "healthy" with "not reported".
func (*PostgresStore) GetUserEmailByID ¶
GetUserEmailByID resolves the email address of the auth user identified by userID. The `users` table belongs to internal/auth's schema, but internal/ auth already imports internal/config (service_mfa.go), so internal/config cannot import internal/auth back without a cycle. This method queries the shared database directly by table/column name instead, returning a plain string so no auth.User type crosses the package boundary. Returns ("", nil) when userID does not resolve to a row -- callers must treat that as "identity unresolved," not as a legitimately blank email.
func (*PostgresStore) HasAccountCredentials ¶
HasAccountCredentials returns true if at least one credential exists for the account.
func (*PostgresStore) HistorySummaryAggregate ¶
func (s *PostgresStore) HistorySummaryAggregate(ctx context.Context, filter HistorySummaryFilter) (*HistorySummaryGroups, error)
HistorySummaryAggregate returns grouped counts and dollar sums over every purchase_history and purchase_executions row the History view's fetches would select without their row caps (issue #675). Both halves are read in one REPEATABLE READ, READ ONLY transaction, so a purchase that moves from an in-flight execution to a purchase_history row while the totals are computed is counted exactly once.
func (*PostgresStore) InsertPlanScheduleReceiptTx ¶
func (s *PostgresStore) InsertPlanScheduleReceiptTx(ctx context.Context, tx pgx.Tx, r *PlanScheduleReceipt) error
InsertPlanScheduleReceiptTx stores r on tx. A duplicate command id reports ErrPlanScheduleReceiptExists.
func (*PostgresStore) IsNotificationMuted ¶
func (s *PostgresStore) IsNotificationMuted(ctx context.Context, recipientEmail, scope string) (bool, error)
IsNotificationMuted returns true when (email, scope) has a matching row in muted_recipients. The email lookup is case-insensitive (LOWER on insert plus LOWER($1) here).
func (*PostgresStore) LadderTrancheScope ¶
func (*PostgresStore) LatestLadderRunID ¶
LatestLadderRunID returns the id of the run with the latest started_at for the config, or an error wrapping ErrNotFound when it has no run. Ties break on created_at then id so the answer is deterministic.
func (*PostgresStore) LatestLadderRunStartedAt ¶
func (s *PostgresStore) LatestLadderRunStartedAt(ctx context.Context, configID string) (*time.Time, error)
LatestLadderRunStartedAt returns the maximum started_at for the given config_id, or nil when no run has been recorded yet. Drives the per-cadence self-gate in handleLadderRun (Q6).
func (*PostgresStore) LinkRetryExecutionAtomic ¶
func (s *PostgresStore) LinkRetryExecutionAtomic(ctx context.Context, tx pgx.Tx, executionID, retryExecutionID string) (linked bool, err error)
LinkRetryExecutionAtomic stamps retry_execution_id on a failed execution row, conditional on status = 'failed' AND retry_execution_id IS NULL, without touching any other column. This replaces a full-row SavePurchaseExecutionTx upsert of a stale in-memory copy of the failed row (issue #220): that upsert both raced two concurrent retries of the same row past the in-memory already-retried guard (both would insert an approvable successor and send an approval email) and reverted any column another writer changed on the failed row in between.
Returns (true, nil) when this call won the race and wrote the linkage, (false, nil) when zero rows were affected because a concurrent retry already claimed the row (or it is no longer 'failed', or an operator settled it: SettleFailedExecution, issue #999), and (false, err) on a real DB error. Must be called inside the same tx that inserts the successor row, after that insert, so the FK on retry_execution_id is satisfied.
func (*PostgresStore) LinkUnsentRetryExecutionAtomic ¶
func (s *PostgresStore) LinkUnsentRetryExecutionAtomic(ctx context.Context, tx pgx.Tx, executionID, retryExecutionID string) (linked bool, err error)
LinkUnsentRetryExecutionAtomic is LinkRetryExecutionAtomic for a retry the handler allowed only because the row is a proven-unsent first attempt: the same conditional UPDATE plus no_submission AND retry_attempt_n = 0, so a row that stopped being that proof between the gate and the link is not linked.
func (*PostgresStore) ListAccountRegistrations ¶
func (s *PostgresStore) ListAccountRegistrations(ctx context.Context, filter AccountRegistrationFilter) ([]AccountRegistration, error)
ListAccountRegistrations returns registrations matching the filter, newest first, capped at MaxListLimit like the package's other list reads (#120).
func (*PostgresStore) ListAccountServiceOverrides ¶
func (s *PostgresStore) ListAccountServiceOverrides(ctx context.Context, accountID string) ([]AccountServiceOverride, error)
ListAccountServiceOverrides returns all overrides for an account.
func (*PostgresStore) ListActiveSuppressions ¶
func (s *PostgresStore) ListActiveSuppressions(ctx context.Context) ([]PurchaseSuppression, error)
ListActiveSuppressions returns every suppression row whose expiry hasn't passed. The scheduler groups these by the 6-tuple key (account, provider, service, region, resource_type, engine) and matches each row's variant (availability zone, platform, tenancy; issue #816) to subtract cumulative suppressed counts from its rec-list output. A row with NULL variant columns comes back with a nil Variant.
Deliberately unbounded (#120 review): every active row subtracts from a rec's count, and one purchase can write up to 1000 rows that live 7-90 days, so normal use can exceed MaxListLimit. A capped read would either under-suppress (re-offering capacity just bought) or fail every caller.
func (*PostgresStore) ListCloudAccounts ¶
func (s *PostgresStore) ListCloudAccounts(ctx context.Context, filter CloudAccountFilter) ([]CloudAccount, error)
ListCloudAccounts returns accounts matching the filter, with credentials_configured derived.
func (*PostgresStore) ListDueLadderTranches ¶
func (s *PostgresStore) ListDueLadderTranches(ctx context.Context, configID string, asOf time.Time, limit int, layers []ladder.LayerType) ([]LadderDueRow, error)
ListDueLadderTranches returns up to limit scheduled tranches of configID that are due by date (scheduled_date in (asOf - LadderFireGrace, asOf]), whatever their layer, term or basis, in the claim's date, id order. It is the sweep's pre-claim resolve read: a plain read with no lock, so the claim stays the authority. A corrupt row (basis and rate disagree) is returned as it is, never an error, so one bad row cannot hide the good ones; the caller must resolve it as unclaimable. Like the claim it fails on a non-positive limit or an empty or unknown layer allowlist.
func (*PostgresStore) ListExecutionsForPlanStepTx ¶
func (s *PostgresStore) ListExecutionsForPlanStepTx(ctx context.Context, tx pgx.Tx, planID string, stepNumber int) ([]PurchaseExecution, error)
ListExecutionsForPlanStepTx implements StoreInterface.
func (*PostgresStore) ListFiredLadderTranches ¶
func (s *PostgresStore) ListFiredLadderTranches(ctx context.Context, after *LadderFiredCursor, limit int) ([]LadderTrancheDB, error)
ListFiredLadderTranches returns fired tranches that have an execution, oldest first (scheduled_date, id), for the reconciler to examine one by one. A nil after starts at the oldest; otherwise only rows strictly after it.
func (*PostgresStore) ListHistoryExecutionsPage ¶
func (s *PostgresStore) ListHistoryExecutionsPage(ctx context.Context, q HistoryExecutionsPageQuery) ([]PurchaseExecution, error)
ListHistoryExecutionsPage returns up to q.Limit executions in q.Statuses, clean completed rows excluded, in History stream order (scheduled_date DESC, execution_id DESC), starting after q.After. See StoreInterface.ListHistoryExecutionsPage.
func (*PostgresStore) ListLadderTimeline ¶
func (s *PostgresStore) ListLadderTimeline(ctx context.Context, accountID, provider string, cursor *LadderTimelineCursor) (*LadderTimelinePage, error)
func (*PostgresStore) ListLadderTimelineRuns ¶
func (s *PostgresStore) ListLadderTimelineRuns(ctx context.Context, accountID, provider string, cursor *LadderTimelineCursor) (*LadderTimelineRunPage, error)
func (*PostgresStore) ListMarketplaceListingsToPoll ¶
func (s *PostgresStore) ListMarketplaceListingsToPoll(ctx context.Context) ([]PurchaseHistoryRecord, error)
ListMarketplaceListingsToPoll returns the AWS listings the poller must read: every active listing; every listing recorded as pending, i.e. one AWS gave no status for when it was created, or whose rollback cancel failed (issue #1494); and closed or canceled listings the poller has seen (listed_at set) whose proceeds are not recorded yet and whose terminal_at is not older than MarketplaceTerminalPollCutoffDays (or is NULL). It reads both the RI's current listing on purchase_history and the listings the RI was relisted from, which marketplace_listing_settlements keeps (issue #1494). A pending row that holds a list attempt's token is a claim in flight, whose listing_id is the RI's previous listing; that listing is not polled until the claim resolves (it is then polled from the settlement table) or is released. The terminal set covers a cancel recorded by the cancel handler before the poller saw the listing end, and a terminal listing whose sale price could not be determined on an earlier poll. Only the fields the poller uses are populated: AccountID, PurchaseID, Provider, Region, CloudAccountID, ListingID and ListingState. One row is returned per (purchase_id, listing_id), the earliest, so legacy duplicate rows cost one AWS call.
func (*PostgresStore) ListPendingExecutionIDsForAccount ¶
func (s *PostgresStore) ListPendingExecutionIDsForAccount(ctx context.Context, accountID string) ([]string, error)
ListPendingExecutionIDsForAccount returns the execution IDs that the frontend's Cancel-All-Then-Delete flow needs to POST cancel for. Capped at 1000 rows — a single account with more pending executions than that is an unusual operator-cleanup task rather than a button-click flow.
func (*PostgresStore) ListPlanCommittedTx ¶
func (s *PostgresStore) ListPlanCommittedTx(ctx context.Context, tx pgx.Tx, planID string) (map[string]PlanRampQuantity, error)
ListPlanCommittedTx returns, per recommendation identity, what the plan's executions already hold, committed or still in flight. It is the ledger the plan's next step subtracts from its cumulative target. It reads the executions themselves, never the suppressions, because a suppression expires while the capacity it covered is still held.
A row counts unless it is provably unbought: canceled (both spellings), expired, or failed with NoSubmission set. A failed row without NoSubmission is an unknown outcome and counts, as does any status this code does not know (the fail-safe direction: over-counting only under-buys). Every selected rec of a counted row counts, including a failed rec of a partially_completed row, because a rec error can be a timeout after the provider accepted it.
Within one step the root row of a fan-out, its per-account rows and a retry chain all carry the same recs, so each identity counts once per step as the largest quantity any counted row holds; steps then add up.
The caller must hold the plan's lock (LockPurchasePlanTx) in tx or the answer is advisory.
func (*PostgresStore) ListPlansWithAttachableEmptyRoot ¶
func (s *PostgresStore) ListPlansWithAttachableEmptyRoot(ctx context.Context, now time.Time) (map[string]struct{}, error)
ListPlansWithAttachableEmptyRoot returns the IDs of plans whose next empty root is inside the attach window at now. It is only a trigger for the notification tick: the claim re-derives every gate under the locks.
func (*PostgresStore) ListPlansWithReadoptableExpiredRoot ¶
func (s *PostgresStore) ListPlansWithReadoptableExpiredRoot(ctx context.Context, now time.Time, requireDifferentApprover bool) (map[string]struct{}, error)
ListPlansWithReadoptableExpiredRoot returns the IDs of the plans that may have an expired root to re-arm. It is only a trigger for the notification tick: the claim re-derives every condition under the plan and provider locks. It returns an empty set until migration 164 is applied.
func (*PostgresStore) ListPurchaseHistoryPage ¶
func (s *PostgresStore) ListPurchaseHistoryPage(ctx context.Context, filter PurchaseHistoryFilter, after *HistoryPageKey) ([]PurchaseHistoryPageRow, error)
ListPurchaseHistoryPage returns up to filter.Limit purchase_history rows matching filter, in History stream order (timestamp DESC, id DESC), starting after `after` (nil starts at the newest row). See StoreInterface.ListPurchaseHistoryPage.
func (*PostgresStore) ListPurchasePlans ¶
func (s *PostgresStore) ListPurchasePlans(ctx context.Context, filter PurchasePlanFilter) ([]PurchasePlan, error)
ListPurchasePlans lists purchase plans, optionally filtered by account IDs. When filter.AccountIDs is non-empty the result includes plans that reference at least one of the given accounts and, with filter.IncludeUnassigned, plans with zero plan_accounts rows (flagged with Unassigned=true). The no-filter case returns all plans with Unassigned=false.
func (*PostgresStore) ListRIExchangeDirectHistory ¶
func (s *PostgresStore) ListRIExchangeDirectHistory(ctx context.Context, f RIExchangeDirectHistoryFilter) ([]RIExchangeDirectHistoryRow, error)
ListRIExchangeDirectHistory returns direct exchanges created since f.Since, newest first, restricted by the filter's account set. Until migration 163 (resolved_* columns) is applied it returns ErrRIExchangeDirectResolveNotReady.
func (*PostgresStore) ListRecentSubmitsTx ¶
func (s *PostgresStore) ListRecentSubmitsTx(ctx context.Context, tx pgx.Tx, creatorID string, since time.Time) ([]PurchaseExecution, error)
ListRecentSubmitsTx serializes concurrent submits by creatorID and returns that creator's web-submitted executions scheduled at or after since, in every state in submitDedupeStatuses. The transaction-scoped advisory lock is held until tx ends, so a second submit by the same creator waits here, then reads the first one's committed row and can collapse onto it. SELECT ... FOR UPDATE could not do this: it locks only rows that already exist, so two concurrent submits both saw nothing and both inserted. The status set is wider than pending/notified because a direct execute moves its row to approved/running/completed within seconds, and a retry arriving then must still be recognized. An empty creatorID matches rows with no creator.
func (*PostgresStore) ListServiceConfigs ¶
func (s *PostgresStore) ListServiceConfigs(ctx context.Context) ([]ServiceConfig, error)
ListServiceConfigs lists all service configurations.
LIMIT 1000 caps the result set at three orders of magnitude above the realistic upper bound (each cloud has a bounded set of services, so the total is roughly (providers × service-types × per-service-variants), which stays under ~150 even with generous provider growth). The cap is defense-in-depth against a compromised admin inserting millions of rows and matches the sibling GetPendingExecutions limit.
func (*PostgresStore) ListStoredRecommendationTriples ¶
func (s *PostgresStore) ListStoredRecommendationTriples(ctx context.Context, scope RecommendationListScope) ([]RecommendationTriple, error)
ListStoredRecommendationTriples returns the distinct (account, provider, service) combinations of the rows scope selects, read from the payload, so the caller can resolve account overrides for exactly those keys before PageStoredRecommendations (issue #981).
func (*PostgresStore) ListStoredRecommendations ¶
func (s *PostgresStore) ListStoredRecommendations(ctx context.Context, filter RecommendationFilter) ([]RecommendationRecord, error)
ListStoredRecommendations reads recommendations matching the filter. SQL-pushed conditions (Provider, Service, Region, AccountIDs, MinSavingsUSD) are applied in SQL so Postgres prunes the rows; the MinSavingsPct filter is applied in-process because the on-demand baseline lives inside the JSONB payload (not a native column).
func (*PostgresStore) ListStoredRecommendationsChunk ¶
func (s *PostgresStore) ListStoredRecommendationsChunk(ctx context.Context, filter RecommendationFilter, after *RecommendationScanKey, limit int) (RecommendationChunk, error)
ListStoredRecommendationsChunk reads at most limit rows matching filter, ordered by recommendation ID (byte-wise) and then by the table's UUID primary key, starting strictly after the position after (nil means from the beginning). The primary key gives rows that share an ID a total order, so resuming from Last never skips or repeats a row, even at a run of duplicate IDs.
The SQL-pushed conditions are the same as ListStoredRecommendations; the MinSavingsPct floor is still applied in-process, so Recs can be shorter than the rows read. Last is the position of the last row read (before that floor), and Done reports that fewer than limit rows were read, meaning nothing matches after Last. Each call is a single statement, so a chunk is one consistent snapshot; consecutive chunks are not.
func (*PostgresStore) ListStuckExecutions ¶
func (s *PostgresStore) ListStuckExecutions(ctx context.Context, statuses []string, olderThan time.Duration) ([]PurchaseExecution, error)
ListStuckExecutions returns purchase executions whose Status is any of the supplied values and whose updated_at is older than the given duration. Used by the reaper sweep (issue #678) to find executions stuck in approved/running long enough that the synchronous executor has clearly failed without flipping the row to a terminal state.
Returns rows oldest-first (ORDER BY updated_at ASC) so the longest-stuck rows are processed first within a single sweep, capped at MaxListLimit so an unbounded backlog doesn't blow up the Lambda's memory budget. The reaper invokes the sweep periodically; a backlog larger than MaxListLimit just gets drained across successive invocations.
olderThan must be > 0; a zero/negative value would invert the WHERE clause into "updated_at < NOW() + |olderThan|" and reap fresh rows. Defense-in- depth: the caller (ParseReapAfterFromEnv) also rejects non-positive env values.
olderThan is passed as a Postgres interval (seconds) so the comparison happens server-side against NOW() — keeping the cutoff in the DB clock avoids any drift between the API process and the database.
func (*PostgresStore) ListUnresolvedRIExchangeDirectAccountRegions ¶
func (s *PostgresStore) ListUnresolvedRIExchangeDirectAccountRegions(ctx context.Context) ([]RIExchangeDirectAccountRegion, error)
ListUnresolvedRIExchangeDirectAccountRegions returns the distinct (account, region) pairs of unresolved AWS rows, so the handler can ask the authorization service about each pair once. The unresolved partial index serves it.
func (*PostgresStore) ListUnresolvedRIExchangeDirectExecutions ¶
func (s *PostgresStore) ListUnresolvedRIExchangeDirectExecutions(ctx context.Context, f RIExchangeDirectListFilter) (*RIExchangeDirectListPage, error)
ListUnresolvedRIExchangeDirectExecutions returns one keyset page of unresolved AWS direct rows (submitted or unknown), oldest first, restricted to the filter's allowed (account, region) pairs. The pairs travel as two arrays so no caller input reaches the SQL text, a NULL account matches only a NULL pair entry, and a NULL region matches the empty region.
func (*PostgresStore) LockLadderTrancheChainTx ¶
func (s *PostgresStore) LockLadderTrancheChainTx(ctx context.Context, tx pgx.Tx, trancheID string) ([]LadderChainNode, error)
LockLadderTrancheChainTx locks a fired tranche, follows retry_execution_id from its execution to the tail (at most LadderChainMaxDepth nodes, which also stops a retry cycle), then locks the tail execution row and re-reads it. LinkRetryExecutionAtomic updates that same row, so once this returns a retry cannot link a successor until the caller's transaction ends. The chain is returned head first. A chain that was cut short by the depth cap (a cycle hits it) or a tail that changed between the walk and the lock ends with a node whose RetryExecutionID is set; the caller must treat that as unresolved.
func (*PostgresStore) LockLadderTrancheForRetryTx ¶
func (s *PostgresStore) LockLadderTrancheForRetryTx(ctx context.Context, tx pgx.Tx, idempotencyKey string) (status ladder.TrancheStatus, found bool, err error)
LockLadderTrancheForRetryTx locks the ladder tranche whose id equals a purchase execution's idempotency key, so Retry can decide inside its own transaction before it inserts a successor. The key is compared as text: non-ladder keys (legacy execution ids, "<root>:<account>" multi-account keys, content fingerprints) are not UUIDs and simply match nothing, which is "not a ladder execution" (found=false), not an error. Lock order is tranche first, then execution rows, the same as LockLadderTrancheChainTx.
func (*PostgresStore) LockPlanProvidersTx ¶
func (s *PostgresStore) LockPlanProvidersTx(ctx context.Context, tx pgx.Tx, providers []string) error
LockPlanProvidersTx implements StoreInterface.LockPlanProvidersTx.
func (*PostgresStore) LockPurchasePlanTx ¶
func (s *PostgresStore) LockPurchasePlanTx(ctx context.Context, tx pgx.Tx, planID string) (*PurchasePlan, error)
LockPurchasePlanTx reads a purchase plan under a row lock held for the rest of tx. It is the single definition of "the per-plan ramp lock": every path that reads a plan's ramp position in order to write against it calls THIS method, so completions and creations serialize against each other rather than each racing on its own read. CompletePlanStep below is one caller; the create-planned-purchases handler is the other.
Returns (nil, nil) when the plan does not exist, which callers must handle explicitly: CompletePlanStep treats it as a benign race it cannot control, the create path turns it into a 404.
func (*PostgresStore) LockRedshiftTuplesTx ¶
func (s *PostgresStore) LockRedshiftTuplesTx(ctx context.Context, tx pgx.Tx, tuples []RedshiftTuple) error
LockRedshiftTuplesTx takes a transaction-scoped advisory lock per tuple in sorted key order, so two dispatches in different sessions cannot deadlock. It must be the first thing run in tx (the isolation level can only be set before any query). Parallels planStepLockKeys + LockPlanProvidersTx.
func (*PostgresStore) LockRetryFamilyTx ¶
LockRetryFamilyTx takes a transaction-scoped advisory lock on a fan-out key family, so a retry of the root and a retry of one of its account rows serialize: the second one then sees the first one's committed link. It is taken after the submit and ladder tranche locks and before any row write of the retry, and nothing else takes it, so it cannot deadlock. The caller's transaction must already be READ COMMITTED (the default) so the claim read after the wait sees the winner's commit.
func (*PostgresStore) MarkCollectionStarted ¶
func (s *PostgresStore) MarkCollectionStarted(ctx context.Context) (token string, ok bool, err error)
MarkCollectionStarted atomically sets last_collection_started_at = NOW() only when no in-flight collection is currently running. The WHERE clause treats a started_at older than 5 minutes as stale (the scheduler Lambda must have crashed) so a new collection can proceed rather than being permanently blocked. A fresh owner token is stamped into last_collection_owner_id alongside the timestamp so the caller that wins the race is the only one that can later clear the marker (issue #261 compare-and-clear guard; see ClearCollectionStarted).
Returns the token and true when this caller won the race (rowsAffected == 1) and should proceed with the async invoke, threading the token through so it can be passed to ClearCollectionStarted later. Returns ("", false, nil) when another collection is already in flight (rowsAffected == 0), signaling the handler to return 409 Conflict.
func (*PostgresStore) MarkPurchaseRevoked ¶
func (s *PostgresStore) MarkPurchaseRevoked(ctx context.Context, purchaseID string, revokedAt time.Time, revokedVia, supportCaseID string, calcRefundAmount *float64, calcRefundCurrency string) error
MarkPurchaseRevoked stamps revoked_at / revoked_via / support_case_id and the refund-quote audit columns (calc_refund_amount, calc_refund_currency) on the purchase_history row identified by purchaseID, and clears revocation_in_flight as migration 000072 documents: a completed revocation is no longer in flight (issue #316). The UPDATE is a no-op when revoked_at is already non-null (idempotency guard). Returns a not-found error when zero rows are affected and revoked_at was previously NULL.
func (*PostgresStore) MarkRevocationReturnPosted ¶
func (s *PostgresStore) MarkRevocationReturnPosted(ctx context.Context, purchaseID string) error
MarkRevocationReturnPosted records that the provider accepted the Return for purchaseID (issue #1523, migration 000148). The revoke handler calls it right after Azure accepts the Return and before MarkPurchaseRevoked, so the finalize_revocations sweep can tell "refunded, audit write failed" (finalize) from "flagged, but no Return ever went out" (never finalize).
The first stamp stands (COALESCE), so a retry does not move it. A revoked row is left alone and returns nil: there is nothing left to finalize. A missing row returns a not-found error.
func (*PostgresStore) NoteRIExchangeOutcomeUnknown ¶
func (s *PostgresStore) NoteRIExchangeOutcomeUnknown(ctx context.Context, id, note string) error
NoteRIExchangeOutcomeUnknown records why a processing exchange was left processing: AWS may have accepted it (#1050). It touches only a row that is still processing, so it never rewrites a settled one.
func (*PostgresStore) OccupiedRampStepsInRangeTx ¶
func (s *PostgresStore) OccupiedRampStepsInRangeTx(ctx context.Context, tx pgx.Tx, planID string, from, to int) ([]int, error)
OccupiedRampStepsInRangeTx returns the steps between from and to (inclusive) of planID that already have a fan-out unit which bought or is still working, ascending. It runs in the caller's transaction so the answer can be acted on atomically; see the lock requirement below.
It exists so a caller about to mint executions for a range of steps can refuse to target one that is already covered. Both halves of the predicate are load-bearing and neither subsumes the other:
- A step some account BOUGHT must not get a fresh root row. The completeness gate holds CurrentStep still while an account is outstanding, so the plan-scoped create endpoint keeps stamping CurrentStep+1, the same step. Approving that row re-fans-out across every account including the ones that already bought, under a fresh idempotency lineage whose derived tokens miss the provider-side dedupe entirely: a genuine duplicate commitment, not a no-op.
- A step that already has a LIVE unit must not get a second one either. Two concurrent creates both find nothing bought, and each mints its own root row for the same step; approving both double-buys exactly as above. The first create's own pending row is what the second must see, and it is not "bought", so the bought half alone cannot stop it.
A step whose units all settled without buying (canceled) is NOT occupied: the operator abandoned it and rescheduling it is the intended recovery.
CALLER CONTRACT: hold LockPurchasePlanTx on planID for the same transaction before calling this and until the resulting inserts commit. Without that lock the answer is advisory -- two callers read it concurrently, both see the step free and both insert.
func (*PostgresStore) PageStoredRecommendations ¶
func (s *PostgresStore) PageStoredRecommendations(ctx context.Context, q RecommendationPageQuery) (RecommendationPage, error)
PageStoredRecommendations reads one page of the recommendations list with every list filter evaluated in SQL (issue #981): the query-string filter, the MinSavingsPct floor, the enabled providers, the account scope, account overrides (q.Rules) and suppressions (rows on q.SuppressionKeys are decided by q.DecideSuppressed). It returns the summary of the whole filtered set from one aggregate query and at most q.Limit rows after q.AfterID, so the rows handed to Go are the page, not the tenant.
All reads run in one REPEATABLE READ, READ ONLY transaction: the rows DecideSuppressed sees, the summary and the page come from the same snapshot, so a collection committing mid-request cannot make the page disagree with its summary.
When SQL cannot reproduce the Go filters faithfully the page comes back with Fallback set instead (see RecommendationPage).
func (*PostgresStore) PinExecutionFanOutShape ¶
func (s *PostgresStore) PinExecutionFanOutShape(ctx context.Context, lineageKey, shape string) (string, error)
PinExecutionFanOutShape records shape as the fan-out shape of the execution lineage keyed by lineageKey unless one is already recorded, and returns the recorded shape. The first writer wins and the row is never updated, so every later attempt of the lineage gets back the shape its first attempt ran with, however the plan's accounts have changed since.
func (*PostgresStore) PlanAndSaveLadderRun ¶
func (s *PostgresStore) PlanAndSaveLadderRun(ctx context.Context, configID string, asOf time.Time, build LadderPlanBuilder) (*LadderRunDB, error)
PlanAndSaveLadderRun reads the config's in-flight commitment, lets build turn it into a run plus tranches, and persists both, all in ONE transaction under the config's ladder lock. Two overlapping runs for one config therefore cannot both plan the same gap: the second waits, then reads the first's committed tranches as in-flight. build must be pure compute. The run's ConfigID must equal configID and its StartedAt must equal asOf, which bounds both the netting read and the overdue sweep.
asOf MUST be captured before the caller reads the existing commitment (E, GetLayerStates), which happens outside this transaction. Tranches that completed after asOf are added to the in-flight figure, so one completing between the E read and the locked read is netted (counted twice if E already has it: a safe under-buy, never a miss). This relies on a tranche being marked completed only after its commitment is visible through the same source as E, and on visibility never reverting; it is safe only once the visibility adapter (executor PR5a) provides that.
func (*PostgresStore) PredecessorProvenUnsent ¶
func (s *PostgresStore) PredecessorProvenUnsent(ctx context.Context, executionID string) (bool, error)
PredecessorProvenUnsent reports whether executionID is the retry successor of a no_submission attempt 0 row, i.e. the whole lineage never submitted.
func (*PostgresStore) PriorAttempts ¶
func (s *PostgresStore) PriorAttempts(ctx context.Context, token string) ([]common.AttemptRecord, error)
PriorAttempts returns every attempt of the token across executions. An empty result is not an error. Like RecordAttempt it runs on its own connection.
func (*PostgresStore) PruneStaleRecommendations ¶
func (s *PostgresStore) PruneStaleRecommendations(ctx context.Context, retentionDays int) (int64, error)
PruneStaleRecommendations deletes the cached recommendations of every (provider, account) pair that has not collected for retentionDays, and returns how many rows it deleted (issue #120).
UpsertRecommendations only evicts rows of the pairs that collected successfully in the current run, so the rows of a pair that never collects again (its provider was disabled, its account disabled, or its credentials keep failing) would otherwise stay on the Recommendations page forever. Registered accounts that are deleted outright are already covered: the cloud_account_id FK cascades.
A pair's newest row is its last collection: every collection stamps the rows it upserts with its own collected_at, and a successful one evicts the pair's older rows. A pair counts as stale only when it has no row at all collected inside the window, and only rows of such pairs are deleted. A pair with even one recent row keeps every row, however old the rest are (a partial collection leaves the failed services' rows behind on purpose).
Concurrent collections: the table lock below (SHARE ROW EXCLUSIVE conflicts with the ROW EXCLUSIVE lock every INSERT, UPDATE and DELETE takes, and with itself) makes the prune wait for any UpsertRecommendations transaction still in flight, and makes collections that start meanwhile wait for the prune. The DELETE's snapshot is taken after the lock is granted, so a collection that committed fresh rows for a pair always counts, and no collection can commit between the pair check and the delete. Readers take ACCESS SHARE, which this lock does not block. The prune holds no other lock before requesting this one, and nothing in the codebase row-locks recommendations without writing them, so the wait cannot deadlock.
The row-level collected_at bound is implied by the NOT EXISTS (every row of a stale pair is older than the cutoff); it is kept so the planner can drive the delete from recommendations_collected_idx rather than scan the table.
func (*PostgresStore) ReadoptExpiredRootTx ¶
func (s *PostgresStore) ReadoptExpiredRootTx(ctx context.Context, tx pgx.Tx, executionID string, scheduledDate, now time.Time, requireDifferentApprover bool) (*PurchaseExecution, error)
ReadoptExpiredRootTx re-arms one expired root inside the caller's transaction, once. It is the row-level backstop: the plan gates live in the caller. It checks the schema itself and answers ErrReadoptNotReady before migration 164, and ErrExecutionNotInExpectedStatus when the row no longer qualifies (lost race, already re-armed, too old, shape changed).
func (*PostgresStore) RecordAttempt ¶
func (s *PostgresStore) RecordAttempt(ctx context.Context, rec common.AttemptRecord) error
RecordAttempt durably records one purchase attempt. It validates the record, then upserts in its own autocommit statement. It must not be called inside a caller's transaction: the record has to be committed before it returns.
func (*PostgresStore) RecordMarketplaceListingActive ¶
func (s *PostgresStore) RecordMarketplaceListingActive(ctx context.Context, purchaseID, listingID string, listedAt time.Time) (bool, error)
RecordMarketplaceListingActive records that AWS reports the row's listing active. On a row that holds listingID as active it stamps listed_at and never writes listing_state, so a cancel or relist recorded after the poller read AWS is kept. On a row that holds listingID as pending with no list attempt in flight (no client token) it also moves the state to active (issue #1494); a pending row with a token is a claim whose listing_id is the RI's previous listing and is left alone. A zero listedAt (AWS reported no CreateDate) keeps the stored listed_at. Any settlement still on the row belongs to an earlier listing of the same RI and is cleared. It reports whether the row changed.
func (*PostgresStore) RecoverReapedExecution ¶
func (s *PostgresStore) RecoverReapedExecution(ctx context.Context, execution *PurchaseExecution) error
RecoverReapedExecution is RecoverReapedExecutionTx in its own transaction.
func (*PostgresStore) RecoverReapedExecutionTx ¶
func (s *PostgresStore) RecoverReapedExecutionTx(ctx context.Context, tx pgx.Tx, execution *PurchaseExecution) error
RecoverReapedExecutionTx persists a late successful outcome over a row the reaper already failed: it writes execution (whose Status must be completed or partially_completed) only if the stored row is still failed with no retry successor linked. A different status returns ErrExecutionNotInExpectedStatus; a linked successor returns ErrExecutionRetryLinked and writes nothing.
func (*PostgresStore) ReleaseClaim ¶
func (s *PostgresStore) ReleaseClaim(ctx context.Context, claim common.Claim, outcome common.ClaimOutcome) error
ReleaseClaim implements common.PurchaseClaimer.
func (*PostgresStore) ReleaseMarketplaceListingClaim ¶
func (s *PostgresStore) ReleaseMarketplaceListingClaim(ctx context.Context, purchaseID, clientToken, priorState string, keepAttempt bool) error
ReleaseMarketplaceListingClaim moves a pending row back to priorState and, unless keepAttempt, clears the persisted token and schedule. It only touches a pending row whose token is clientToken, so it never overwrites a recorded listing or the attempt of another request.
func (*PostgresStore) ReleaseStaleRevocationsInFlight ¶
func (s *PostgresStore) ReleaseStaleRevocationsInFlight(ctx context.Context, after time.Duration) ([]string, error)
ReleaseStaleRevocationsInFlight clears revocation_in_flight on unrevoked rows that have been flagged for longer than after with no Return recorded (issue #1523), and returns their purchase IDs. Such a row is one whose request died between the flip and the Return, or whose Return was never recorded as accepted. Clearing the flag lets the user revoke it again; if Azure did take a Return that went unrecorded, Azure refuses the second one.
A flagged row with no revocation_in_flight_at (flagged before migration 000148, or by a binary that predates it) is stamped now and released once after has passed from then, so its age is never overstated.
Both statements use the database clock. Each UPDATE re-checks its predicate on the locked row under READ COMMITTED, so a concurrent MarkRevocationReturnPosted or a fresh flip that commits first makes the row no longer match; one that commits after the release still records its Return, which GetPurchaseHistoryInFlight finds with or without the flag.
func (*PostgresStore) RenewClaim ¶
func (s *PostgresStore) RenewClaim(ctx context.Context, claim common.Claim, ttl time.Duration) error
RenewClaim implements common.PurchaseClaimer.
func (*PostgresStore) RescheduleAwaitingExecution ¶
func (s *PostgresStore) RescheduleAwaitingExecution(ctx context.Context, executionID string, scheduledDate time.Time) (bool, error)
RescheduleAwaitingExecution is a conditional single-column update: the status predicate makes a lost race a benign no-op instead of an overwrite.
func (*PostgresStore) ReserveApprovedRIExchange ¶
func (s *PostgresStore) ReserveApprovedRIExchange(ctx context.Context, id, dailyCapUSD, perExchangeCapUSD string) (string, error)
ReserveApprovedRIExchange reserves the full execution ceiling for an approved exchange whose row is already processing. It runs under the same global advisory lock as ReserveRIExchange, so manual approvals and AUTO exchanges share one headroom protocol, and it leaves the row's own amount out of the spend it checks against. The row's payment_due becomes the reserved ceiling until CompleteRIExchangeWithPayment settles the accepted amount.
func (*PostgresStore) ReserveRIExchange ¶
func (s *PostgresStore) ReserveRIExchange(ctx context.Context, record *RIExchangeRecord, dailyCapUSD, perExchangeCapUSD string) (string, error)
ReserveRIExchange atomically records the full execution ceiling before a provider call.
func (*PostgresStore) ResolveLadderTrancheFailed ¶
func (s *PostgresStore) ResolveLadderTrancheFailed(ctx context.Context, req LadderResolveFailed) (*LadderResolveResult, error)
ResolveLadderTrancheFailed moves a fired tranche to failed on an operator's word, releasing its netting. It locks the tranche, then the retry-chain tail, in the same order as the reconciler and Retry. It refuses while any execution of the chain may still run or has bought something, and, when a node's outcome is unknown (for example reaped), unless the operator acknowledged that and named where they checked.
func (*PostgresStore) ResolveManagedPlanRootTx ¶
func (s *PostgresStore) ResolveManagedPlanRootTx(ctx context.Context, tx pgx.Tx, plan *PurchasePlan) (*PurchaseExecution, error)
ResolveManagedPlanRootTx requires the plan row lock before execution locks.
func (*PostgresStore) ResolveMarketplaceListingAttempt ¶
func (s *PostgresStore) ResolveMarketplaceListingAttempt(ctx context.Context, purchaseID string, seen MarketplaceListingAttempt, listingID, state string) (bool, error)
ResolveMarketplaceListingAttempt records listingID in state on the row and drops any unresolved attempt token, but only while the row still matches seen, or already holds listingID (another request recorded the listing the caller just canceled). state must be an ended state (canceled or closed) or empty, which clears a stuck pending row that has no listing; an empty listingID clears the listing id too. A new listing id drops the previous listing's listed_at and settlement (issue #27); the previous listing is kept in marketplace_listing_settlements (migration 000153, issue #1494). It reports whether the row was written.
func (*PostgresStore) ResolveRIExchangeDirectExecution ¶
func (s *PostgresStore) ResolveRIExchangeDirectExecution(ctx context.Context, req RIExchangeDirectResolve) (*RIExchangeDirectResolveResult, error)
ResolveRIExchangeDirectExecution settles an AWS direct row an operator has verified at AWS. It records the resolution beside the row's original status and completed_at, which are never rewritten, and the in-flight guard then stops treating the row as holding its source RIs. One transaction locks the row, so two resolves and a concurrent finalize each see the other's commit. Every time comparison uses the database clock.
func (*PostgresStore) ResolveStaleRIExchange ¶
func (s *PostgresStore) ResolveStaleRIExchange(ctx context.Context, req RIExchangeResolve) (*RIExchangeResolveResult, error)
ResolveStaleRIExchange settles a processing RI exchange that no running writer can still settle. It locks the row and refuses unless it is still processing, has been unchanged for StaleAfter (measured on the database clock), and the operator's check names the row's own account and region and postdates its last change. Releasing (failed) is also refused when the row carries a provider exchange id, since AWS then reported the exchange done. A row a late writer completed or failed is never overwritten.
func (*PostgresStore) RotatePendingApprovalToken ¶
func (s *PostgresStore) RotatePendingApprovalToken(ctx context.Context, executionID, tokenHash string, expiresAt time.Time) (bool, error)
RotatePendingApprovalToken implements StoreInterface. The same statement that stores the emailed token promotes the row to 'notified' (a no-op for a row already there), so the status never claims a notice that was not sent.
func (*PostgresStore) SaveAccountCredential ¶
func (s *PostgresStore) SaveAccountCredential(ctx context.Context, accountID, credentialType, encryptedBlob string) error
SaveAccountCredential upserts an encrypted credential blob for an account.
func (*PostgresStore) SaveAccountServiceOverride ¶
func (s *PostgresStore) SaveAccountServiceOverride(ctx context.Context, o *AccountServiceOverride) error
SaveAccountServiceOverride upserts an account service override.
func (*PostgresStore) SaveAccountServiceOverrideAuditedTx ¶
func (s *PostgresStore) SaveAccountServiceOverrideAuditedTx(ctx context.Context, tx pgx.Tx, o *AccountServiceOverride, audit AuditContext) error
SaveAccountServiceOverrideAuditedTx upserts o inside tx and records the change in config_audit_events. It takes a transaction-scoped advisory lock on the override's (account, provider, service), then reads the stored row FOR UPDATE, so the event's before is exactly the row this write replaces even when another writer creates or changes the same override at the same moment (a row lock alone cannot serialize two creates of a row that does not exist yet). after is read back from the upsert, so it is what the columns hold (coverage rounded to DECIMAL(5,2)). A write that changes no setting records no event. o is updated to the stored row (its ID is the existing override's when one was replaced).
Callers writing several overrides in one tx must call this in a consistent key order, or two such transactions could deadlock on each other's locks.
func (*PostgresStore) SaveConfigAuditEventTx ¶
func (s *PostgresStore) SaveConfigAuditEventTx(ctx context.Context, tx pgx.Tx, ev *AuditEvent) error
SaveConfigAuditEventTx records ev inside tx. An empty ID is filled in, so a caller can link later events to it via ParentEventID.
func (*PostgresStore) SaveExecutionIfStatus ¶
func (s *PostgresStore) SaveExecutionIfStatus(ctx context.Context, execution *PurchaseExecution, expected []string) error
SaveExecutionIfStatus is SavePurchaseExecution that only writes when the stored row is still in one of the expected statuses. A stale in-memory copy can therefore never rewrite a status another writer moved on (issue #829). A missing row returns ErrNotFound and a status mismatch returns ErrExecutionNotInExpectedStatus; neither writes anything.
func (*PostgresStore) SaveExecutionIfStatusTx ¶
func (s *PostgresStore) SaveExecutionIfStatusTx(ctx context.Context, tx pgx.Tx, execution *PurchaseExecution, expected []string) error
SaveExecutionIfStatusTx is the tx-accepting variant of SaveExecutionIfStatus, for callers that bundle the save with other writes (for example releasing suppressions). It reuses SavePurchaseExecutionTx for the write, so the column list and the no_submission and INSERT-only rules exist in one place.
func (*PostgresStore) SaveGlobalConfig ¶
func (s *PostgresStore) SaveGlobalConfig(ctx context.Context, config *GlobalConfig) error
SaveGlobalConfig saves the global configuration.
func (*PostgresStore) SaveLadderRun ¶
func (s *PostgresStore) SaveLadderRun(ctx context.Context, run *LadderRunDB) (*LadderRunDB, error)
SaveLadderRun inserts a new ladder_runs row. If run.ID is empty a fresh UUID is generated. Returns the persisted row with all DB-stamped fields populated.
func (*PostgresStore) SaveLadderRunWithTranches ¶
func (s *PostgresStore) SaveLadderRunWithTranches(ctx context.Context, run *LadderRunDB, tranches []LadderTrancheDB) (*LadderRunDB, error)
SaveLadderRunWithTranches inserts the ladder_runs row AND its ladder_tranches rows in ONE transaction. If any tranche insert fails, the whole transaction (including the run row) is rolled back, so a run is never persisted without its tranches. This prevents a status=planned run with zero tranches, which the cadence self-gate (keyed on any run's started_at) would otherwise use to suppress the retry for the full cadence window. Scheduled tranches of the same config that are past LadderFireGrace at run.StartedAt are canceled in the same transaction, so expired rows are swept at each persisted run. If run.ID is empty a fresh UUID is generated. Returns the persisted run row.
func (*PostgresStore) SaveLadderTranches ¶
func (s *PostgresStore) SaveLadderTranches(ctx context.Context, tranches []LadderTrancheDB) error
SaveLadderTranches inserts a batch of ladder_tranches rows within a single transaction. Each tranche must carry a non-empty ID; duplicate IDs are rejected at the DB UNIQUE PRIMARY KEY constraint. An empty slice is a no-op.
func (*PostgresStore) SavePurchaseExecution ¶
func (s *PostgresStore) SavePurchaseExecution(ctx context.Context, execution *PurchaseExecution) error
SavePurchaseExecution saves a purchase execution record.
func (*PostgresStore) SavePurchaseExecutionTx ¶
func (s *PostgresStore) SavePurchaseExecutionTx(ctx context.Context, tx pgx.Tx, execution *PurchaseExecution) error
SavePurchaseExecutionTx is the tx-accepting variant of SavePurchaseExecution. Used from handlers that need to bundle the execution insert with other writes (e.g. purchase_suppressions rows) in a single atomic transaction.
func (*PostgresStore) SavePurchaseHistory ¶
func (s *PostgresStore) SavePurchaseHistory(ctx context.Context, record *PurchaseHistoryRecord) error
SavePurchaseHistory saves a purchase history record. It is idempotent per (provider, account_id, purchase_id): a re-drive or root retry that adopts a commitment the first attempt already bought saves the same key again, and a second row would double-count spend and savings (#704). The NOT EXISTS covers rows that predate the unique index from migration 000108; the index and ON CONFLICT cover two concurrent saves. An existing row is left as is.
cloud_account_id is the record's CloudAccountID when set. Otherwise it is resolved from (provider, account_id) in the same statement (see savePurchaseHistoryQuery), so the direct-execute, ambient and legacy single-account paths, which carry no CloudAccountID, store it too (#1235).
func (*PostgresStore) SaveRIExchangeDirectExecution ¶
func (s *PostgresStore) SaveRIExchangeDirectExecution(ctx context.Context, record *RIExchangeDirectExecution) error
SaveRIExchangeDirectExecution inserts the audit row for a direct-API RI exchange as "submitted", before the provider call (issue #82). The status is not taken from the record: every row starts submitted, and created_at is stamped by the database clock after the guards ran.
An AWS row is inserted under the same advisory lock as the history reservations, after refusing any source RI another exchange still holds (ErrRIExchangeSourceInFlight): a processing history row, or a direct row that is submitted or unknown (#1829). Azure rows are not guarded.
func (*PostgresStore) SaveRIExchangeRecord ¶
func (s *PostgresStore) SaveRIExchangeRecord(ctx context.Context, record *RIExchangeRecord) error
SaveRIExchangeRecord saves an RI exchange record. This is the single write path for ri_exchange_history (an INSERT, never an update-in-place of an existing row's token), so it is the correct place to hash the token into approval_token_hash (issue #103): record.ApprovalToken always carries a fresh raw value freshly generated by the caller (pkg/exchange in cloud-commitments-go), never a value previously read back from this column, so hashing it here can never double-hash an already-hashed value.
func (*PostgresStore) SaveServiceConfig ¶
func (s *PostgresStore) SaveServiceConfig(ctx context.Context, config *ServiceConfig) error
SaveServiceConfig saves configuration for a service.
func (*PostgresStore) ScheduleApprovedExecution ¶
func (s *PostgresStore) ScheduleApprovedExecution(ctx context.Context, executionID string, fromStatuses []string, transitionedBy *string, scheduledAt time.Time, approvedBy *string) (*PurchaseExecution, error)
ScheduleApprovedExecution implements StoreInterface for the session path: no approval token is pinned.
func (*PostgresStore) ScheduleApprovedExecutionTokenPinned ¶
func (s *PostgresStore) ScheduleApprovedExecutionTokenPinned(ctx context.Context, executionID string, fromStatuses []string, transitionedBy *string, rawToken string, scheduledAt time.Time, approvedBy *string) (*PurchaseExecution, error)
ScheduleApprovedExecutionTokenPinned implements StoreInterface for the email-link path. An empty rawToken fails closed before any write, so a caller that lost its token cannot silently skip the pin (#1794).
func (*PostgresStore) SetCancelledBy ¶
func (s *PostgresStore) SetCancelledBy(ctx context.Context, executionID, cancelledBy string) error
SetCancelledBy stamps canceled_by for a single execution without touching any other column. This avoids the full-row overwrite that a SavePurchaseExecution follow-up would perform, eliminating the lost-update window between TransitionExecutionStatus and the attribution write (Finding #5).
func (*PostgresStore) SetExecutionRecommendationsIfEmptyTx ¶
func (s *PostgresStore) SetExecutionRecommendationsIfEmptyTx(ctx context.Context, tx pgx.Tx, executionID string, recs []RecommendationRecord, upfront, savings float64) (bool, error)
SetExecutionRecommendationsIfEmptyTx implements StoreInterface.
func (*PostgresStore) SetLadderSweepCeiling ¶
func (s *PostgresStore) SetLadderSweepCeiling(ctx context.Context, configID string, usdPerHr *float64) error
SetLadderSweepCeiling stores the ceiling in USD per hour of commitment; nil clears it. The value must pass the same validation as the per-run cap and is written as an exact decimal built from micro-dollars, never the float.
func (*PostgresStore) SetPlanAccounts ¶
func (s *PostgresStore) SetPlanAccounts(ctx context.Context, planID string, accountIDs []string) error
SetPlanAccounts replaces the full account list for a plan atomically.
func (*PostgresStore) SetPlanAccountsGated ¶
func (s *PostgresStore) SetPlanAccountsGated(ctx context.Context, planID string, accountIDs []string, gate PlanWriteGate) error
SetPlanAccountsGated is SetPlanAccounts with gate (may be nil) run while the plan row is locked FOR UPDATE, before any write. Plan writers that decide on the plan's accounts (the auto-purchase arming gate) lock the same row, so the gate's decision cannot be overtaken by a concurrent arm or retarget. The plan is locked before the account rows the inserts touch, the order DeleteCloudAccount uses.
func (*PostgresStore) SetPlanRampBaselineTx ¶
func (s *PostgresStore) SetPlanRampBaselineTx(ctx context.Context, tx pgx.Tx, planID string, baseline PlanRampBaseline) (bool, error)
SetPlanRampBaselineTx freezes a baseline only while retention can prove its lineage. The caller holds the plan lock; full-row plan writes cannot promote trust.
func (*PostgresStore) SetRecommendationsCollectionError ¶
func (s *PostgresStore) SetRecommendationsCollectionError(ctx context.Context, errMsg string) error
SetRecommendationsCollectionError records the most recent collection's error message without touching last_collected_at or last_collection_started_at. Used by the scheduler when a collect fails partially or fully so the frontend banner surfaces the issue while existing cached rows stay visible.
This method must NOT clear last_collection_started_at (issue #261): it is called mid-run from persistCollection on every CollectRecommendations invocation that hits a provider error, including tokenless cron/cold-start/ background runs. Clearing the marker here, unconditionally and with no owner check, previously let a tokenless run's routine provider error wipe a concurrent owner run's in-flight marker, reopening the exact race the compare-and-clear guard exists to close. Only the deferred, token-guarded clearCollectionStartedBestEffort (which runs on both the success and failure exit paths of CollectRecommendations) may clear started_at.
func (*PostgresStore) SettleFailedExecution ¶
func (s *PostgresStore) SettleFailedExecution(ctx context.Context, req ExecutionSettleRequest) (*ExecutionSettlement, error)
SettleFailedExecution records an operator's audited settlement of a failed plan execution, so it stops blocking the delete of its editor-managed plan (requireManagedDeleteTx). It never changes the status or no_submission, so the ramp ledger and the retention trigger count the row exactly as before (possibly bought, unless it was never submitted). A settled row can no longer be retried (LinkRetryExecutionAtomic), because a retry of a row whose plan was deleted would buy with no plan.
Locks, in the order the editor command and DeletePurchasePlan use: the plan row FOR SHARE, the execution FOR UPDATE, then its retry-chain tail FOR UPDATE. It refuses while the chain may still buy (a tail that is not terminal, a failed tail that can still be retried, or a chain longer than LadderChainMaxDepth).
func (*PostgresStore) SettleMarketplaceListing ¶
func (s *PostgresStore) SettleMarketplaceListing(ctx context.Context, st MarketplaceListingSettlement) (bool, error)
SettleMarketplaceListing records a listing that ended on AWS: its terminal state, listed_at and, when known, the proceeds and AWS fee. In one transaction it writes the purchase_history row while the row still holds the listing (the RI's latest listing settlement, as before) and the listing's marketplace_listing_settlements row (issue #1494), which is what per-RI totals read. Each write applies only while that row has no proceeds recorded and is active, pending with no list attempt in flight, or already in the same terminal state, and never while a purchase_history row holds the listing as a list claim in flight. So proceeds are recorded once however many polls race, a recorded cancel is never turned into a sale (or the reverse), a mid-claim row is left alone (#1508), and a listing the RI was relisted from is still settled, in its own row. The purchase_history row is written first, so a poll and a relist of the same RI take their locks in the same order. It reports whether either row was written.
func (*PostgresStore) StampFirstDispatchTx ¶
func (s *PostgresStore) StampFirstDispatchTx(ctx context.Context, tx pgx.Tx, executionID string, horizon time.Duration) (StampResult, error)
StampFirstDispatchTx stamps a lineage's first dispatch time on the claimed running row, with the database clock, and returns it. An existing stamp is kept. A stamp is minted only at attempt 0, or when the predecessor is a no_submission attempt 0 (the whole lineage never submitted); otherwise a stamp-less successor gets At == nil and the caller must refuse it. A row that is not running returns ErrExecutionNotInExpectedStatus.
It takes a tx so the dispatch gate can stamp and check conflicts atomically.
func (*PostgresStore) StampOfferingClass ¶
func (s *PostgresStore) StampOfferingClass(ctx context.Context, purchaseID, offeringClass string) error
StampOfferingClass writes the offering_class value onto a purchase_history row identified by purchase_id. Used by the marketplace-list handler to lazily persist offering_class fetched from AWS DescribeReservedInstances for rows created before migration 000087 or for externally-created Standard RIs. A no-match (row not found) is treated as a non-fatal warning by callers.
func (*PostgresStore) StampPlanNotificationSent ¶
func (s *PostgresStore) StampPlanNotificationSent(ctx context.Context, planID string, at time.Time) error
StampPlanNotificationSent never writes a snapshot of the plan's ramp state.
func (*PostgresStore) StampRIExchangeApprovedBy ¶
func (s *PostgresStore) StampRIExchangeApprovedBy(ctx context.Context, id, approverEmail string) error
StampRIExchangeApprovedBy sets the approved_by column on an RI exchange row (issue #300). Called after CompleteRIExchangeWithPayment when approval came from a session-authed user. The stamping is best-effort (log + continue on failure so the exchange itself isn't rolled back just because the audit stamp failed).
func (*PostgresStore) TransitionExecutionStatus ¶
func (s *PostgresStore) TransitionExecutionStatus(ctx context.Context, executionID string, fromStatuses []string, toStatus string, actor *string) (*PurchaseExecution, error)
TransitionExecutionStatus atomically transitions an execution from one of the allowed statuses to a new status. Returns the updated record, or an error if the execution was not found or not in an allowed status. actor is the UUID of the user performing the transition (nil for system-initiated paths); it is stamped onto transitioned_by and transitioned_at is always set to NOW(). A transition to StatusCanceled also stamps the actor's email onto canceled_by (issue #119), matching what the other cancel paths record and what History reads.
func (*PostgresStore) TransitionExecutionStatusPinned ¶
func (s *PostgresStore) TransitionExecutionStatusPinned(ctx context.Context, executionID string, fromStatuses []string, toStatus string, actor *string, sawEmptyRecommendations bool) (*PurchaseExecution, error)
TransitionExecutionStatusPinned is TransitionExecutionStatus that also requires the row's recommendations to still be empty (or not empty), as the caller saw them. A recommendation attach landing between a gate check and the claim makes the pin fail with ErrExecutionNotInExpectedStatus, so a row is never run on a snapshot different from the one that was gated.
func (*PostgresStore) TransitionExecutionStatusPinnedTx ¶
func (s *PostgresStore) TransitionExecutionStatusPinnedTx(ctx context.Context, tx pgx.Tx, executionID string, fromStatuses []string, toStatus string, actor *string, sawEmptyRecommendations bool) (*PurchaseExecution, error)
TransitionExecutionStatusPinnedTx is TransitionExecutionStatusPinned inside the caller's transaction. The UPDATE's row lock is held until that transaction ends, so the status change commits or rolls back together with the caller's other writes and no other writer can touch the row in between.
func (*PostgresStore) TransitionExecutionStatusTokenPinned ¶
func (s *PostgresStore) TransitionExecutionStatusTokenPinned(ctx context.Context, executionID string, fromStatuses []string, toStatus string, actor *string, rawToken string) (*PurchaseExecution, error)
TransitionExecutionStatusTokenPinned is TransitionExecutionStatus that also requires approval_token_hash to equal the hash of rawToken and the token to be unexpired, checked in the same UPDATE as the status change. The caller's earlier token check ran against a snapshot; a re-notification that rotates the token between that read and this write would otherwise still let the old token win the transition (issue #590). An empty rawToken never matches.
func (*PostgresStore) TransitionLadderRunStatus ¶
func (s *PostgresStore) TransitionLadderRunStatus(ctx context.Context, id string, fromStatuses []ladder.RunStatus, toStatus ladder.RunStatus) (*LadderRunDB, error)
TransitionLadderRunStatus atomically transitions a ladder_runs row from one of fromStatuses to toStatus via a CAS UPDATE. Returns the updated row on success, or (nil, nil) when zero rows are affected (race lost or unexpected current status). A hard DB error is returned as a non-nil error. A transition to RunStatusCanceled is refused with ErrLadderRunCancelViaTransition: cancels go through CancelLadderRun, which stamps cancelled_by in the same UPDATE.
func (*PostgresStore) TransitionLadderTranche ¶
func (s *PostgresStore) TransitionLadderTranche(ctx context.Context, id string, from, to ladder.TrancheStatus, reason string) (bool, error)
TransitionLadderTranche moves one tranche from `from` to `to` with a compare-and-set UPDATE. It returns false (and no error) when the row is missing or no longer in `from`, so a lost race is distinguishable from a DB failure. An illegal edge is an error. scheduled -> fired is not allowed here because a claim must create the execution in the same transaction; use ClaimDueLadderTranches. A scheduled tranche that already has an execution cannot be canceled. reason is stored in status_reason and is required for the failed and canceled outcomes, so a terminal tranche always says why.
func (*PostgresStore) TransitionLadderTrancheTx ¶
func (s *PostgresStore) TransitionLadderTrancheTx(ctx context.Context, tx pgx.Tx, id string, from, to ladder.TrancheStatus, reason string) (bool, error)
TransitionLadderTrancheTx is TransitionLadderTranche inside the caller's transaction, for callers that must re-check other rows under lock first.
func (*PostgresStore) TransitionRIExchangeStatus ¶
func (s *PostgresStore) TransitionRIExchangeStatus(ctx context.Context, id, fromStatus, toStatus string, actor *string) (*RIExchangeRecord, error)
TransitionRIExchangeStatus atomically transitions an RI exchange record status. Uses a single UPDATE...WHERE...RETURNING for atomicity, then diagnoses failure only if zero rows are returned (ErrRIExchangeExpired or ErrRIExchangeNotInExpectedStatus, wrapped, for an existing record). actor is the UUID of the user performing the transition (nil for system-initiated paths).
func (*PostgresStore) TransitionRegistrationStatus ¶
func (s *PostgresStore) TransitionRegistrationStatus(ctx context.Context, reg *AccountRegistration, fromStatus string, actor *string) error
TransitionRegistrationStatus atomically updates a registration's workflow fields only if the current status matches fromStatus. Returns ErrRegistrationConflict when 0 rows are affected (another request already changed the status). actor is the UUID of the reviewer (nil for system-initiated transitions).
func (*PostgresStore) UpdateAccountRegistration ¶
func (s *PostgresStore) UpdateAccountRegistration(ctx context.Context, reg *AccountRegistration) error
UpdateAccountRegistration updates the mutable workflow fields of a registration.
func (*PostgresStore) UpdateAccountServiceOverrideAtomic ¶
func (s *PostgresStore) UpdateAccountServiceOverrideAtomic(ctx context.Context, accountID, provider, service string, audit AuditContext, merge func(existing *AccountServiceOverride) (*AccountServiceOverride, error)) (*AccountServiceOverride, error)
UpdateAccountServiceOverrideAtomic is a serialized read-merge-write of one override (issue #1775). In one transaction it takes the same advisory lock and FOR UPDATE read as SaveAccountServiceOverrideAuditedTx, hands the stored row (nil when none) to merge, and writes and audits the row merge returns. Two partial PUTs of one override therefore cannot merge onto the same stale base and lose a field. merge must not modify existing, and must not touch the database: the transaction holds a pooled connection. An error from merge aborts the transaction and is returned unchanged. The saved row is returned.
func (*PostgresStore) UpdateCloudAccount ¶
func (s *PostgresStore) UpdateCloudAccount(ctx context.Context, account *CloudAccount) error
UpdateCloudAccount updates mutable fields of a cloud account. An external_id change is refused with ErrAccountExternalIDHasHistory while history rows key on the stored value (purchase_history by provider, ri_exchange_history for AWS); the check is part of the UPDATE so it cannot race a separate read.
func (*PostgresStore) UpdateGlobalConfigAtomic ¶
func (s *PostgresStore) UpdateGlobalConfigAtomic(ctx context.Context, apply func(*GlobalConfig) error) (*GlobalConfig, error)
UpdateGlobalConfigAtomic performs a serialized read-modify-write of the global_config singleton. It opens a transaction, takes a transaction-scoped advisory lock (which serializes even the first insert, since a row-level FOR UPDATE cannot lock a not-yet-existing singleton row), reads the current config, applies the caller's in-place mutation, and upserts the result in the SAME transaction. This eliminates the lost-update race where two concurrent partial PUTs each read the same stale base and the later save silently drops the earlier change.
apply mutates the loaded config in place (e.g. json.Unmarshal the request body over it and validate); an error it returns aborts the transaction and is propagated unchanged (so callers can surface a 400 from validation while transport/DB errors surface as 500).
func (*PostgresStore) UpdatePurchaseHistoryListing ¶
func (s *PostgresStore) UpdatePurchaseHistoryListing(ctx context.Context, purchaseID, listingID, listingState string) error
UpdatePurchaseHistoryListing stamps the marketplace listing fields onto a purchase_history row identified by its purchase_id (RI reservation ID). Called by the marketplace-list handler after CreateReservedInstancesListing succeeds (listing_id + listing_state="active") and by the status-poll path on the later closed/canceled transitions.
func (*PostgresStore) UpdatePurchasePlan ¶
func (s *PostgresStore) UpdatePurchasePlan(ctx context.Context, plan *PurchasePlan) error
UpdatePurchasePlan publishes the new version only after the transaction commits.
func (*PostgresStore) UpdatePurchasePlanGated ¶
func (s *PostgresStore) UpdatePurchasePlanGated(ctx context.Context, plan *PurchasePlan, gate PlanWriteGate) error
UpdatePurchasePlanGated is UpdatePurchasePlan with gate (may be nil) run after the plan row is locked and before the write. A missing plan skips the gate and reports ErrNotFound from the update.
func (*PostgresStore) UpdatePurchasePlanTx ¶
func (s *PostgresStore) UpdatePurchasePlanTx(ctx context.Context, tx pgx.Tx, plan *PurchasePlan) error
UpdatePurchasePlanTx rejects snapshots that lost a race with another plan writer and refuses changes to what the editor owns on a managed plan. It re-locks the row, which every caller already holds, to judge the guard on the locked version.
func (*PostgresStore) UpdateServiceConfigAtomic ¶
func (s *PostgresStore) UpdateServiceConfigAtomic(ctx context.Context, provider, service string, apply func(existing *ServiceConfig) (*ServiceConfig, error)) (*ServiceConfig, error)
UpdateServiceConfigAtomic performs a serialized read-merge-write of one service_configs row (issue #1488). In one transaction it takes a transaction-scoped advisory lock on (provider, service), reads the row FOR UPDATE, hands it to apply and upserts the row apply returns.
Both locks are needed. The advisory lock serializes two saves of a row that does not exist yet, which a row lock cannot do because there is nothing to lock: without it both would read nothing and the second insert would overwrite the first. The row lock makes writers that do not take the advisory lock, such as the global-defaults propagation in UpdateGlobalConfigAtomic, wait for this transaction (and this transaction wait for them), so the row read here is the row the write replaces.
apply receives nil when no row exists. It must return the full row to write, keyed on the same provider and service; an error it returns aborts the transaction and is propagated unchanged.
func (*PostgresStore) UpsertLadderConfig ¶
func (s *PostgresStore) UpsertLadderConfig(ctx context.Context, cfg *LadderConfigDB) (*LadderConfigDB, error)
UpsertLadderConfig inserts or updates the per-account ladder configuration. The upsert key is (cloud_account_id, provider). If ID is empty a new UUID is generated; existing rows retain their original id and created_at.
Validate() must be called by the API handler before this method; the store does not re-validate to avoid duplicating error messages.
func (*PostgresStore) UpsertNotificationMute ¶
func (s *PostgresStore) UpsertNotificationMute(ctx context.Context, recipientEmail, scope, unmuteToken string) error
UpsertNotificationMute inserts or replaces the mute row for (recipientEmail, scope). ON CONFLICT updates muted_at and unmute_token so a repeated one-click opt-out resets the audit timestamp without error.
func (*PostgresStore) UpsertRIUtilizationCache ¶
func (s *PostgresStore) UpsertRIUtilizationCache(ctx context.Context, key RIUtilizationCacheKey, payload []byte, fetchedAt time.Time) error
UpsertRIUtilizationCache writes or overwrites the cached utilization payload for (cloud_account_id, region, lookback_days). fetchedAt should be "now" at the time of the underlying Cost Explorer call — readers compare this against their TTL to decide freshness.
func (*PostgresStore) UpsertRecommendations ¶
func (s *PostgresStore) UpsertRecommendations(ctx context.Context, collectedAt time.Time, recs []RecommendationRecord, successfulCollects []SuccessfulCollect) error
UpsertRecommendations is the incremental write path: it upserts each row by natural key (cloud_account_id, provider, service, region, resource_type, engine, term, payment_option, availability_zone, platform, tenancy, az_config) and then evicts stale rows for the set of (provider, account) pairs that successfully collected in this run. Pairs whose collection failed are NOT in successfulCollects and their stale rows stay — callers see older data with a banner rather than a blank section.
Migration 000032 broadened the natural key to include term + payment_option, so per-rec ON CONFLICT no longer collides on SQLSTATE 21000. Migration 000109 added availability_zone, a GENERATED column derived from payload that is never written here. Migration 000111 added the platform and tenancy generated columns the same way, and migration 000158 the az_config one; the upsert arbiter is the 12-column recommendations_natural_key_az_tp_azc_idx (issues #792, #806, #408).
The eviction predicate uses (provider, account_key) IN (unnest($2, $3)) where account_key matches the generated column on the table — nil CloudAccountID maps to uuid.Nil at the Go boundary, matching the COALESCE(cloud_account_id, '00000000-...') rule the table applies on insert. This collapses ambient and registered identities consistently on both sides of the join.
func (*PostgresStore) UpsertRecommendationsWithPartial ¶
func (s *PostgresStore) UpsertRecommendationsWithPartial(ctx context.Context, collectedAt time.Time, recs []RecommendationRecord, successfulCollects []SuccessfulCollect, partial *RecommendationsCollectionPartial) error
UpsertRecommendationsWithPartial is UpsertRecommendations that records the collection's incomplete-sweep summary in the same transaction. The previous Azure pricing hold is read under a row lock and merged into partial (see carryAzureHold), so overlapping collections cannot drop each other's hold and a failed read or write rolls the rows back with the marker.
type PurchaseAmountBasis ¶
type PurchaseAmountBasis string
PurchaseAmountBasis says how a purchase_history row's dollar amounts were derived. Empty is a normal row. It is distinct from LadderAmountBasis, which describes ladder tranche amounts.
const PurchaseAmountBasisLegacyWindow PurchaseAmountBasis = "legacy_window"
PurchaseAmountBasisLegacyWindow marks an Azure row whose upfront_cost and estimated_savings were estimated over a window before the repricing fix (issue #669). Totals skip its dollars; the row stays listed and counted.
type PurchaseExecution ¶
type PurchaseExecution struct {
ScheduledDate time.Time `json:"scheduled_date" dynamodbav:"scheduled_date"`
CompletedAt *time.Time `json:"completed_at,omitempty" dynamodbav:"completed_at,omitempty"`
// ApprovedBy / CancelledBy carry the email of the session-authenticated
// user who acted on this execution via the auth-gated deep-link flow
// (frontend /purchases/{action}/:id → login-if-needed → session-authed
// endpoint). Nil on legacy token-only approve/cancel paths — the
// handler / History UI falls back to the notification email as the
// accountable party in that case. Nullable TEXT in Postgres.
ApprovedBy *string `json:"approved_by,omitempty" dynamodbav:"approved_by,omitempty"`
// ScheduledExecutionAt is set by the Gmail-style pre-fire delay path
// (issue #291 wave-2) when an approve defers the cloud SDK call. The
// scheduler fires the actual SDK call when this timestamp is in the past.
// NULL on every immediate-execute row. Migration 000065.
ScheduledExecutionAt *time.Time `json:"scheduled_execution_at,omitempty" dynamodbav:"scheduled_execution_at,omitempty"`
// RetryExecutionID points from a *failed* execution to the new
// execution created when the user clicked Retry (issue #47). Set
// only on the original failed row; NULL on every other row including
// the retry itself (the retry's own RetryAttemptN > 0 is the
// "this is a retry" marker). Forms a forward-pointing chain:
// failed_v1.retry_execution_id = failed_v2.execution_id, etc.
// Migration 000042 self-FKs the column ON DELETE SET NULL so a
// cleanup of a successor doesn't cascade-delete its predecessor.
RetryExecutionID *string `json:"retry_execution_id,omitempty" dynamodbav:"retry_execution_id,omitempty"`
NotificationSent *time.Time `json:"notification_sent,omitempty" dynamodbav:"notification_sent,omitempty"`
// FirstDispatchAt is the time of the first dispatch of a purchase lineage.
// Server-only; insert-only in the upsert, set once by the dispatch stamp (migration 000154).
FirstDispatchAt *time.Time `json:"-" dynamodbav:"-"`
// ExecutedByUserID is the UUID of the session user who triggered a
// direct-execute (issue #289, execute-any/execute-own) or a run-now. NULL on rows
// that went through the normal approval flow. Together with
// pre_approval_skip_reason it marks a skipped approval email/wait (see ApprovedBy).
// Migration 000058 adds the column.
ExecutedByUserID *string `json:"executed_by_user_id,omitempty" dynamodbav:"executed_by_user_id,omitempty"`
// CreatedByUserID is the UUID of the session-authenticated user who
// triggered this execution (e.g. clicked Execute on the Recommendations
// page or submitted the bulk-purchase modal). NULL on rows created
// before the column was introduced (migration 000041) and on
// scheduler-driven executions where there is no human creator. Used
// by the session-authed cancel handler to enforce cancel:own_executions
// — a non-admin may cancel only executions they themselves created.
// NULL is treated as "not the current user".
CreatedByUserID *string `json:"created_by_user_id,omitempty" dynamodbav:"created_by_user_id,omitempty"`
// ApprovalTokenExpiresAt is the UTC deadline after which the
// ApprovalToken must be rejected by ApproveExecution and
// loadCancelableExecution (issue #397). Set at execution creation to
// ScheduledDate + ApprovalTokenTTL. NULL on rows created before
// migration 000051 — legacy rows are treated as not-yet-expired
// (backward-compatible: the TTL-checking gate only fires when the
// field is non-nil). Migration 000051 adds the column; new rows
// always carry a non-nil value.
ApprovalTokenExpiresAt *time.Time `json:"approval_token_expires_at,omitempty" dynamodbav:"approval_token_expires_at,omitempty"`
// PreApprovalSkipReason is a human-readable token describing why the
// approval email/scheduled wait was skipped: "direct-execute permission" or
// "run-now". NULL on every normal-flow row.
// Migration 000058.
PreApprovalSkipReason *string `json:"pre_approval_skip_reason,omitempty" dynamodbav:"pre_approval_skip_reason,omitempty"`
CloudAccountID *string `json:"cloud_account_id,omitempty" dynamodbav:"cloud_account_id,omitempty"`
// ExecutedAt is the UTC timestamp when the direct-execute or run-now path fired.
// NULL for rows on the normal approval flow. Migration 000058.
ExecutedAt *time.Time `json:"executed_at,omitempty" dynamodbav:"executed_at,omitempty"`
CancelledBy *string `json:"cancelled_by,omitempty" dynamodbav:"cancelled_by,omitempty"`
Status string `json:"status" dynamodbav:"status"` // pending, notified, approved, canceled, completed, failed
// Source identifies the CUDly surface that triggered this execution
// ("cudly-cli" or "cudly-web"). Propagated into PurchaseOptions and
// stamped as a tag/label onto every commitment this execution buys.
Source string `json:"source,omitempty" dynamodbav:"source,omitempty"`
Error string `json:"error,omitempty" dynamodbav:"error,omitempty"`
// IdempotencyKey is the stable lineage anchor the per-rec provider
// idempotency token is derived from (issue #1012). Unlike ExecutionID
// it is NOT regenerated on Retry or multi-account fan-out: it is
// generated once at first creation, copied verbatim onto every Retry
// successor, and combined with the account ID to seed each per-account
// fan-out row. This makes DeriveIdempotencyToken reproduce the same
// token across a strand-and-re-drive so the provider dedupes and the
// commitment is never bought twice. Empty on rows created before
// migration 000066 — the derivation falls back to ExecutionID for those
// (identical to the pre-fix behavior for a single un-retried execution).
IdempotencyKey string `json:"idempotency_key,omitempty" dynamodbav:"idempotency_key,omitempty"`
PlanID string `json:"plan_id" dynamodbav:"plan_id"`
ApprovalToken string `json:"approval_token,omitempty" dynamodbav:"approval_token,omitempty"` // SHA-256 hex digest (approval_token_hash column), never the raw token
ExecutionID string `json:"execution_id" dynamodbav:"execution_id"`
Recommendations []RecommendationRecord `json:"recommendations" dynamodbav:"recommendations"`
// CapacityPercent records what fraction of the originally-recommended
// counts the user chose when the bulk Purchase flow submitted this
// execution (1..100). Audit-only: the Recommendations slice already
// carries the scaled counts, so backend math is unaffected by this
// field. Defaults to 100 for legacy and scheduler-driven executions.
CapacityPercent int `json:"capacity_percent,omitempty" dynamodbav:"capacity_percent,omitempty"`
// RetryAttemptN is the position of this execution in a retry chain.
// 0 (default) on every fresh execution; 1 on the first retry of any
// failed row; n+1 on the n+1-th retry. The handler reads the
// predecessor's count and stamps n+1 atomically with the new
// INSERT inside the retry transaction. The History UI uses this to
// soft-block retries past a threshold so an obviously-stuck
// configuration doesn't accumulate dozens of dead retry rows.
// Migration 000042 added the column with default 0 so legacy rows
// look exactly like fresh first-retry candidates.
RetryAttemptN int `json:"retry_attempt_n,omitempty" dynamodbav:"retry_attempt_n,omitempty"`
TTL int64 `json:"ttl,omitempty" dynamodbav:"ttl,omitempty"`
EstimatedSavings float64 `json:"estimated_savings" dynamodbav:"estimated_savings"`
TotalUpfrontCost float64 `json:"total_upfront_cost" dynamodbav:"total_upfront_cost"`
StepNumber int `json:"step_number" dynamodbav:"step_number"`
// CreatedBySystem marks a row the scheduler sweep minted with no human
// initiator (issue #233). Server-only and insert-only: never bound from a
// request, never rewritten by the upsert. Implies CreatedByUserID == nil
// (CHECK in migration 000130).
CreatedBySystem bool `json:"-" dynamodbav:"-"`
// NoSubmission is the persisted proof that this execution failed before
// any cloud purchase call was made (migration 000113). Only the
// pre-submission failure paths set it; the reaper and every
// outcome-unknown failure leave it false. It is monotone: the upsert can
// set it but never clear it, so a stale in-memory copy cannot erase it.
// The ladder reconciler treats a failed execution as "nothing was bought"
// only when this is true.
NoSubmission bool `json:"no_submission,omitempty" dynamodbav:"no_submission,omitempty"`
}
PurchaseExecution represents a single execution of a purchase plan.
func (*PurchaseExecution) IsCancelable ¶
func (e *PurchaseExecution) IsCancelable() bool
IsCancelable reports whether an execution may still be canceled. Only the pre-approval states ("pending"/"notified") qualify. A "scheduled" row is not canceled: it is revoked through the revoke endpoint (CancelScheduledExecutionAtomic), which carries its own RBAC. Once a row reaches "approved" or "running" the AWS commitment is being or has been created, so canceling would leave the DB and the cloud out of sync; "canceled", "completed", "failed", "expired", and "paused" are likewise non-cancelable. Both cancel paths (purchase.Manager.CancelExecution on the email-token flow and the session-authed cancelPurchaseViaSession) call this single predicate so the policy can never drift between them (issue #645).
type PurchaseHistoryFilter ¶
type PurchaseHistoryFilter struct {
// ExternalIDsByProvider matches purchase_history.account_id (the
// cloud-provider external account number) scoped per provider. The caller
// resolves AccountIDs to their (provider, external_id) pairs and groups the
// external ids by provider, so the predicate matches each external id only
// against rows of its own provider:
//
// ((provider = ” OR LOWER(provider) = LOWER($p)) AND account_id = ANY($extsForP))
//
// This keeps the (provider, external_id) pairing intact so a filter for
// aws/123 never pulls azure/123 rows that reuse the same external number.
// The provider comparison ignores case, and a row whose stored provider is
// empty (unknown) matches on account_id alone (issue #24).
// The "" provider key means "provider unknown" (legacy raw external number)
// and matches account_id without a provider gate. Empty/nil skips this half
// of the account predicate.
ExternalIDsByProvider map[string][]string
// Start/End bound purchase_history.timestamp. nil for both skips the clause;
// nil for either leaves that side open (caller owns any range cap, see
// api.MaxHistoryDateRangeDays).
Start *time.Time
End *time.Time
// Scope, when non-nil, keeps only rows whose account_id is one of
// Scope.AccountIDs (UserID is not read: purchase_history rows have no
// creator). Empty AccountIDs keeps nothing (fail closed); nil is an
// unrestricted caller. Like the execution scope it is a superset of the
// handler's Go scope check, which still runs on the rows.
Scope *ExecutionScope
// Provider matches purchase_history.provider exactly. Empty skips the clause.
Provider string
// PlanID matches purchase_history.plan_id exactly; HistorySummaryAggregate
// also applies it to purchase_executions.plan_id. Empty skips the clause.
PlanID string
// AccountIDs matches purchase_history.cloud_account_id (the cloud_accounts
// UUID FK) with ANY($). Empty/nil skips this half of the account predicate.
AccountIDs []string
// Limit caps the row count; clamped to [1, MaxListLimit] with a
// DefaultListLimit fallback when <= 0.
Limit int
}
PurchaseHistoryFilter is the filter set consumed by StoreInterface.GetPurchaseHistoryFiltered. Each field is optional; a zero-valued filter selects all rows (same plan-shape as GetAllPurchaseHistory). See the implementation docstring for the per-field semantics and the dual-column account predicate.
type PurchaseHistoryPageRow ¶
type PurchaseHistoryPageRow struct {
RowID string
PurchaseHistoryRecord
}
PurchaseHistoryPageRow is a purchase_history row read by ListPurchaseHistoryPage, with the row's primary key: the keyset tiebreaker for rows that share a timestamp, which purchase_id cannot be because legacy rows may repeat it (migration 000108).
func (*PurchaseHistoryPageRow) Key ¶
func (r *PurchaseHistoryPageRow) Key() HistoryPageKey
Key returns the row's position in the History stream.
type PurchaseHistoryRecord ¶
type PurchaseHistoryRecord struct {
Timestamp time.Time `json:"timestamp" dynamodbav:"timestamp"`
// --- Revocation window fields (issue #290) ---
//
// RevocationWindowClosesAt is set when the purchase_history row is
// written: Timestamp + the provider-specific free-cancel window
// (Azure: 7 days). NULL for AWS EC2 (no direct cancel API) and GCP
// (no free-cancel window). Persisted in purchase_history.
RevocationWindowClosesAt *time.Time `json:"revocation_window_closes_at,omitempty" dynamodbav:"revocation_window_closes_at,omitempty"`
UpfrontCost *float64 `json:"upfront_cost" dynamodbav:"upfront_cost"`
// ReturnPostedAt is when the revoke handler recorded that Azure accepted
// the Return (MarkRevocationReturnPosted, migration 000148). Set means the
// refund was issued; unset proves nothing, because the stamp is best-effort
// (issue #1522). Read only by GetPurchaseHistoryByPurchaseID and never
// serialized, so history responses do not expose it.
ReturnPostedAt *time.Time `json:"-" dynamodbav:"-"`
// --- Refund-quote audit fields (issue #290 Finding #4, migration 000071) ---
//
// CalcRefundAmount is the amount Azure quoted at CalculateRefund time, captured
// for audit and TOCTOU-divergence detection in the two-step revoke confirm flow.
// NULL for revocations that predate this feature or where Azure returned no amount.
CalcRefundAmount *float64 `json:"calc_refund_amount,omitempty" dynamodbav:"calc_refund_amount,omitempty"`
// RevokedAt is set by the revoke endpoint when the provider API
// confirmed the cancellation / refund. Persisted.
RevokedAt *time.Time `json:"revoked_at,omitempty" dynamodbav:"revoked_at,omitempty"`
CloudAccountID *string `json:"cloud_account_id,omitempty" dynamodbav:"cloud_account_id,omitempty"`
// MonthlyCost is nil when the provider API did not return a monthly
// recurring breakdown for this commitment (e.g. Azure all-upfront where
// no recurring charge exists at the commitment layer). GCP commitments
// are monthly-billed in this repo, so they always populate MonthlyCost.
// The frontend renders "—" for nil, "$X.XX" when populated. Aggregations
// must skip nil entries rather than treating them as $0 to avoid
// distorting totals. Migration 000063 dropped the NOT NULL constraint so
// new rows can carry NULL; existing rows with 0.0 are preserved as-is
// (those are real zeros from AWS all-upfront commitments).
MonthlyCost *float64 `json:"monthly_cost" dynamodbav:"monthly_cost"`
// CreatedByUserEmail is the email address of the user who created the
// underlying execution, resolved from CreatedByUserID via the auth
// service. Populated only on synthesized execution rows (pending,
// notified, failed, expired, canceled) when a valid user ID is
// present; empty for scheduler-driven executions, legacy NULL-creator
// rows, and completed purchase_history rows. Excluded from DB
// persistence (resolved at read time). The UI renders this in the
// Approval Queue "Created by" column instead of the raw UUID.
CreatedByUserEmail string `json:"created_by_user_email,omitempty" dynamodbav:"-"`
// SupportCaseID is non-empty when RevokedVia == "support-case".
// Persisted.
SupportCaseID string `json:"support_case_id,omitempty" dynamodbav:"support_case_id,omitempty"`
// ListingState mirrors the AWS marketplace listing state (see the
// ListingState* constants). Empty when not listed. Persisted in
// purchase_history via migration 000087.
ListingState string `json:"listing_state,omitempty" dynamodbav:"listing_state,omitempty"`
// ListingID is the AWS ReservedInstancesListingId returned by
// CreateReservedInstancesListing. Empty when the RI has not been
// listed. Persisted in purchase_history via migration 000087.
ListingID string `json:"listing_id,omitempty" dynamodbav:"listing_id,omitempty"`
// OfferingClass records whether this commitment is a 'standard' or
// 'convertible' RI. NULL on pre-migration rows. The Sell-on-Marketplace
// button renders only when this equals "standard" (issue #292).
// Persisted in purchase_history via migration 000087.
OfferingClass string `json:"offering_class,omitempty" dynamodbav:"offering_class,omitempty"`
PlanID string `json:"plan_id,omitempty" dynamodbav:"plan_id,omitempty"`
PlanName string `json:"plan_name,omitempty" dynamodbav:"plan_name,omitempty"`
Source string `json:"source,omitempty" dynamodbav:"source,omitempty"`
ResourceType string `json:"resource_type" dynamodbav:"resource_type"`
// AmountBasis is set from the amount_basis column; no writer names it.
AmountBasis PurchaseAmountBasis `json:"amount_basis,omitempty" dynamodbav:"-"`
Status string `json:"status,omitempty" dynamodbav:"-"`
PurchaseID string `json:"purchase_id" dynamodbav:"purchase_id"`
Provider string `json:"provider" dynamodbav:"provider"`
// OpsHint is a short operator-actionable message rendered inline in
// place of the Retry button when the failure reason on the row
// matches a known-persistent-misconfiguration pattern (e.g.
// "FROM_EMAIL not configured" → "Set FROM_EMAIL tfvar then retry").
// Set only on `failed` rows whose Error matches the persistent map;
// empty otherwise. Excluded from DB persistence (computed at read
// time so updates to the persistent-failure map land instantly).
OpsHint string `json:"ops_hint,omitempty" dynamodbav:"-"`
// CreatedByUserID propagates the originating execution's
// created_by_user_id so the History UI can decide whether to render
// the inline Cancel button (issue #46): a non-admin user only sees
// the button on their own pending rows. Set only for synthesized
// pending/notified rows (executions); empty on completed history
// rows (where the action has already completed). Excluded from DB
// persistence.
CreatedByUserID string `json:"created_by_user_id,omitempty" dynamodbav:"-"`
// CalcRefundCurrency is the ISO-4217 currency code from the CalculateRefund quote
// (e.g. "USD"). NULL when CalcRefundAmount is NULL.
CalcRefundCurrency string `json:"calc_refund_currency,omitempty" dynamodbav:"calc_refund_currency,omitempty"`
// RetryExecutionID propagates the originating execution's pointer to
// its successor when the user retried it (issue #47). Set only on
// the *original* failed row that has been retried; the History UI
// renders an inline "Retried as #abc" link to the successor row when
// this is non-empty. Excluded from DB persistence (synthesized from
// purchase_executions).
RetryExecutionID string `json:"retry_execution_id,omitempty" dynamodbav:"-"`
Service string `json:"service" dynamodbav:"service"`
// StatusDescription carries a short human-readable explanation for non-
// completed rows. For "failed", this is the stored Error message (e.g.
// "send failed: Missing domain"). For "expired", a canned reminder that
// the 7-day approval window elapsed. Empty on completed/pending rows —
// those speak for themselves via Status alone.
StatusDescription string `json:"status_description,omitempty" dynamodbav:"-"`
Payment string `json:"payment" dynamodbav:"payment"`
// RevokedVia identifies how the revocation was completed: "direct-api"
// (provider returned 2xx) or "support-case" (AWS Support case filed).
// Persisted.
RevokedVia string `json:"revoked_via,omitempty" dynamodbav:"revoked_via,omitempty"`
// Approver holds the email address the approval request was sent to (or
// would have been, if SES failed). Set only on pending rows, so the
// History UI can show "awaiting approval from <addr>" and the user knows
// exactly whose inbox to check. Excluded from DB persistence.
Approver string `json:"approver,omitempty" dynamodbav:"-"`
AccountID string `json:"account_id" dynamodbav:"account_id"`
Region string `json:"region" dynamodbav:"region"`
// RetryAttemptN propagates the originating execution's retry-chain
// position so the History UI can render "↻ Retry of #xyz" inline
// links on retry rows (n > 0) and gate the Retry button against the
// soft-block threshold (n >= 5). Excluded from DB persistence.
RetryAttemptN int `json:"retry_attempt_n,omitempty" dynamodbav:"-"`
RampStep int `json:"ramp_step,omitempty" dynamodbav:"ramp_step,omitempty"`
EstimatedSavings float64 `json:"estimated_savings" dynamodbav:"estimated_savings"`
Count int `json:"count" dynamodbav:"count"`
Term int `json:"term" dynamodbav:"term"`
// IsAuditGap marks a synthesized "completed" row whose purchase_history
// write failed after a successful purchase (issue #621). Such a row is
// reconstructed from the execution so the purchase stays visible, but its
// execution-level dollars are excluded from the committed totals: a
// partially-saved multi-rec execution can have BOTH some real
// purchase_history rows AND this synthesized row, so adding the full
// execution total would double-count the recs that did save. The dollars
// are surfaced via the individual purchase_history rows that succeeded;
// this row is the audit flag, not a money source. Real purchase_history
// rows loaded from the DB always leave this false. Excluded from DB
// persistence (set only at read time on synthesized rows).
IsAuditGap bool `json:"is_audit_gap,omitempty" dynamodbav:"-"`
// RedriveUnsafe is true when OpsHint is a permanent refusal from
// purchase.RetryRefusalReason (provider has no duplicate guard), not an
// operator-fixable misconfiguration. Computed at read time, like OpsHint.
RedriveUnsafe bool `json:"redrive_unsafe,omitempty" dynamodbav:"-"`
// CreatedBySystem propagates the execution's scheduler-created marker (#233).
CreatedBySystem bool `json:"created_by_system,omitempty" dynamodbav:"-"`
// --- Partial-success reconciliation (issue #290 Finding #6, migration 000072) ---
//
// RevocationInFlight is set to true immediately before the Azure Return API call
// and cleared (set to false) by a successful MarkPurchaseRevoked. When all DB
// retries fail, the flag stays true so the finalize_revocations scheduled sweep
// can detect and retry the MarkPurchaseRevoked write without re-calling Azure
// (preventing a duplicate-refund error).
RevocationInFlight bool `json:"revocation_in_flight,omitempty" dynamodbav:"revocation_in_flight,omitempty"`
}
PurchaseHistoryRecord is the response-layer representation for rows on the /api/history page. DB-backed rows always describe *completed* purchases; the handler additionally synthesizes rows for pending executions so users can see (and cancel) in-flight approvals. Status is the discriminator — the DB layer never writes it (tag `dynamodbav:"-"` keeps it out of persistence), and the API layer populates it as "completed" or "pending" before returning.
func (*PurchaseHistoryRecord) IsLegacyEstimate ¶
func (r *PurchaseHistoryRecord) IsLegacyEstimate() bool
IsLegacyEstimate reports whether the row's dollar amounts are a legacy estimate that totals must skip.
func (*PurchaseHistoryRecord) Validate ¶
func (r *PurchaseHistoryRecord) Validate() error
Validate rejects a record SavePurchaseHistory cannot store without losing it: one with no purchase id (see ErrEmptyPurchaseID).
type PurchaseHistorySummaryGroup ¶
type PurchaseHistorySummaryGroup struct {
CloudAccountID *string
// UpfrontCost is the sum of upfront_cost, or nil when any row in the
// group has an unknown (NULL) upfront cost, matching how the History
// summary treats a single unknown cost.
UpfrontCost *float64
AccountID string
Provider string
Count int
EstimatedSavings float64
Revoked bool
}
PurchaseHistorySummaryGroup aggregates the purchase_history rows that share account_id, cloud_account_id, provider and revoked state.
type PurchasePlan ¶
type PurchasePlan struct {
CreatedAt time.Time `json:"created_at" dynamodbav:"created_at"`
UpdatedAt time.Time `json:"updated_at" dynamodbav:"updated_at"`
Services map[string]ServiceConfig `json:"services" dynamodbav:"services"`
LastNotificationSent *time.Time `json:"last_notification_sent,omitempty" dynamodbav:"last_notification_sent,omitempty"`
LastExecutionDate *time.Time `json:"last_execution_date,omitempty" dynamodbav:"last_execution_date,omitempty"`
NextExecutionDate *time.Time `json:"next_execution_date,omitempty" dynamodbav:"next_execution_date,omitempty"`
// MaxStepCommitment caps the TOTAL commitment (RecommendationRecord.TotalCommitment)
// one ramp step may auto-purchase. nil means no cap is set, and auto-purchase of
// recommendation-bearing steps is refused (fail closed). Always > 0 when set.
MaxStepCommitment *float64 `json:"max_step_commitment,omitempty" dynamodbav:"max_step_commitment,omitempty"`
ID string `json:"id" dynamodbav:"id"`
Name string `json:"name" dynamodbav:"name"`
RampSchedule RampSchedule `json:"ramp_schedule" dynamodbav:"ramp_schedule"`
NotificationDaysBefore int `json:"notification_days_before" dynamodbav:"notification_days_before"`
AutoPurchase bool `json:"auto_purchase" dynamodbav:"auto_purchase"`
Enabled bool `json:"enabled" dynamodbav:"enabled"`
// Unassigned is true when the plan has zero rows in plan_accounts.
// This can happen for legacy plans created before target_accounts was
// required (issue #743). Such plans are invisible when an account filter
// is active because the normal JOIN excludes them; ListPurchasePlans
// surfaces them alongside filtered results so operators can find and
// re-scope them. The field is omitted (false) in the no-filter case
// where all plans are returned unconditionally.
Unassigned bool `json:"unassigned,omitempty" dynamodbav:"unassigned,omitempty"`
}
PurchasePlan represents a saved purchase plan for automated execution.
func MergePlanGroupTarget ¶
func MergePlanGroupTarget(plan *PurchasePlan, edit PlanGroupTarget) (*PurchasePlan, error)
MergePlanGroupTarget returns a copy of plan with edit applied to the one group entry whose GroupID matches (keyed "provider/service#<group_id>"). Every other entry and the allocation_mode marker are kept as stored. The effective cap of a step is min(group cap, plan cap), a missing cap counting as unbounded; a set cap may stay equal or drop, never rise.
func (*PurchasePlan) CheckBoundKeys ¶
func (p *PurchasePlan) CheckBoundKeys() error
CheckBoundKeys refuses a bound plan whose entries are not keyed by their own provider, service and group (checkGroupKey). A gate that reads a stored plan without validating it calls this before it derives grant scopes from the keys.
func (*PurchasePlan) CheckNoMultiStepSavingsPlans ¶
func (p *PurchasePlan) CheckNoMultiStepSavingsPlans() error
CheckNoMultiStepSavingsPlans refuses an armed (enabled and auto-purchase) plan that has more than one ramp step and an enabled Savings Plans service. It is the one definition, shared by plan validation (create, update, arm) and the step precheck at attach. Single-step plans are unaffected.
func (*PurchasePlan) EnabledProviders ¶
func (p *PurchasePlan) EnabledProviders() []string
EnabledProviders returns the sorted distinct providers of the plan's enabled services: the set the scheduler attaches steps for.
func (*PurchasePlan) GraceDays ¶
func (p *PurchasePlan) GraceDays(global *GlobalConfig) int
GraceDays is the longest recent-purchase grace window among the plan's enabled providers, the scheduler's retry deadline for a step with no match.
func (*PurchasePlan) RequireVetoWindow ¶
func (p *PurchasePlan) RequireVetoWindow() error
RequireVetoWindow refuses a plan that cannot give an emailed purchase at least one day before it runs. Attaching recommendations to a plan step and re-scheduling a resumed recommendation-bearing row both call it.
func (*PurchasePlan) Validate ¶
func (p *PurchasePlan) Validate() error
Validate validates the PurchasePlan.
func (*PurchasePlan) ValidateDeescalation ¶
func (p *PurchasePlan) ValidateDeescalation() error
ValidateDeescalation is Validate without the bound-group checks, for a write that only disables or disarms the plan: stopping a plan must never be blocked by a group conflict it already stores (issue #1746). Every other check runs.
func (*PurchasePlan) VetoWindowEnd ¶
func (p *PurchasePlan) VetoWindowEnd(now time.Time) time.Time
VetoWindowEnd is the earliest time a freshly emailed step may be bought: NotificationDaysBefore fixed 24h days from now, in UTC. Fixed hours, not calendar days, so a non-UTC time.Local or a DST change cannot shift it; this matches the notification tick's own arithmetic (notifications.go).
type PurchasePlanFilter ¶
type PurchasePlanFilter struct {
AccountIDs []string // nil/empty = all plans
// IncludeUnassigned adds plans with zero plan_accounts rows to an
// AccountIDs-filtered result. Only unrestricted callers may set it.
IncludeUnassigned bool
}
PurchasePlanFilter parameterises ListPurchasePlans. Zero-value means "no filter" (all plans are returned). Non-empty AccountIDs restricts the result to plans that reference at least one of the given account IDs via the plan_accounts join table.
type PurchaseSuppression ¶
type PurchaseSuppression struct {
ExpiresAt time.Time `json:"expires_at"`
CreatedAt time.Time `json:"created_at"`
// Variant narrows the row to one availability zone, platform and tenancy
// on its 6-tuple (issue #816, migration 000134). nil means the variant is
// unknown: rows written before 000134 or by code predating #816. Such a
// row is a wildcard over its 6-tuple (see AppliesTo).
Variant *SuppressionVariant `json:"variant,omitempty"`
ID string `json:"id"`
ExecutionID string `json:"execution_id"`
AccountID string `json:"account_id"`
Provider string `json:"provider"`
Service string `json:"service"`
Region string `json:"region"`
ResourceType string `json:"resource_type"`
Engine string `json:"engine"`
SuppressedCount int `json:"suppressed_count"`
}
PurchaseSuppression records the per-tuple grace window after a bulk purchase. See migration 000037 for the full SQL shape + lifecycle documentation. Written inside the same transaction as the execution insert; deleted inside the same transaction as a cancel/expire status transition.
func BuildSuppressions ¶
func BuildSuppressions(recs []RecommendationRecord, executionID string, cfg *GlobalConfig, now time.Time) []PurchaseSuppression
BuildSuppressions converts the recs on an executePurchase request into purchase_suppressions rows, one per unique 6-tuple (account, provider, service, region, resource_type, engine) and variant (availability zone, platform, tenancy; issue #816), so a purchase of one zonal EC2 variant does not hide its sibling AZ, regional, platform or tenancy recs. Counts for duplicate keys within the same request are summed (defensive — the UI should collapse them client-side, but the backend doesn't trust that). Providers with a grace period of 0 (feature disabled) contribute no rows.
func (*PurchaseSuppression) AppliesTo ¶
func (s *PurchaseSuppression) AppliesTo(v *SuppressionVariant) bool
AppliesTo reports whether the suppression counts against a recommendation on the same 6-tuple whose variant is v. A row without a variant (legacy) applies to every variant, and a nil v (the rec's Details could not be read) matches every row: both fall back to the pre-#816 6-tuple match, which over-suppresses (under-buys) rather than over-shows.
type RIExchangeCloudCheck ¶
RIExchangeCloudCheck is the operator's statement of where they verified the exchange's outcome at AWS before resolving it.
type RIExchangeDirectAccountRegion ¶
RIExchangeDirectAccountRegion is one (account, region) pair of a row. A nil CloudAccountID is a row whose deployment mapped to no registered account.
type RIExchangeDirectCursor ¶
RIExchangeDirectCursor is the keyset position after the last row of a page.
type RIExchangeDirectExecution ¶
type RIExchangeDirectExecution struct {
// QuotedNetPayable is Azure's pre-execute re-quote; nil for AWS.
QuotedNetPayable *string `json:"quoted_net_payable,omitempty"`
ExecutedByAPIKeyID *string `json:"executed_by_api_key_id,omitempty"`
// CloudAccountID is the registered cloud account the exchange was
// authorized against; nil when none is registered.
CloudAccountID *string `json:"cloud_account_id,omitempty"`
// ProviderAccountID is the Azure subscription ID; nil for AWS.
ProviderAccountID *string `json:"provider_account_id,omitempty"`
// Region is the AWS region; nil for Azure.
Region *string `json:"region,omitempty"`
ExecutedByUserID *string `json:"executed_by_user_id,omitempty"`
MaxPaymentCurrency string `json:"max_payment_currency"`
MaxPaymentDue string `json:"max_payment_due"`
// ID is generated by the caller, so the caller can finalize the row
// without depending on the store writing it back.
ID string `json:"id"`
// ProviderReference is the Azure session ID when known before the call.
ProviderReference string `json:"provider_reference,omitempty"`
ExecutedBy string `json:"executed_by"`
Provider string `json:"provider"`
// Targets is the submitted target list, a non-empty JSON array.
Targets json.RawMessage `json:"targets"`
// Sources is the submitted source list with per-source quantities, a
// non-empty JSON array; nil for AWS, which exchanges whole RIs.
Sources json.RawMessage `json:"sources,omitempty"`
SourceIDs []string `json:"source_ids"`
}
RIExchangeDirectExecution is the audit-trail record of one RI exchange executed directly through the API, as opposed to through the scheduled approve/reject flow that persists to ri_exchange_history (issue #82).
The fields set before the provider call are inserted by SaveRIExchangeDirectExecution; the outcome is recorded once by FinalizeRIExchangeDirectExecution.
func (*RIExchangeDirectExecution) Validate ¶
func (r *RIExchangeDirectExecution) Validate() error
Validate rejects a record the table would refuse, so a malformed audit row fails before it can block an exchange on a database round trip, and with a message naming the field.
type RIExchangeDirectHistoryFilter ¶
type RIExchangeDirectHistoryFilter struct {
Since time.Time
AccountIDs []string
Limit int
AllAccounts bool
}
RIExchangeDirectHistoryFilter bounds the History listing. AllAccounts lifts the account restriction (and admits rows with no registered account); otherwise only rows whose cloud_account_id is in AccountIDs match.
type RIExchangeDirectHistoryRow ¶
type RIExchangeDirectHistoryRow struct {
CreatedAt time.Time
NetPayable *string
ResolvedAt *time.Time
CompletedAt *time.Time
CloudAccountID *string
ProviderAccountID *string
MaxPaymentDue string
ID string
MaxPaymentCurrency string
NetPayableCurrency string
Error string
ExecutedBy string
Region string
Status string
ResolvedStatus string
Provider string
Targets json.RawMessage
SourceIDs []string
}
RIExchangeDirectHistoryRow is one direct (interactive) RI exchange as the History view shows it, of any provider, status and resolved state. Error is the raw stored provider text: callers pass it through purchase.SanitizeStoredError and never return it as is.
type RIExchangeDirectHistoryStore ¶
type RIExchangeDirectHistoryStore interface {
ListRIExchangeDirectHistory(ctx context.Context, f RIExchangeDirectHistoryFilter) ([]RIExchangeDirectHistoryRow, error)
}
RIExchangeDirectHistoryStore is the read-only History listing of direct exchanges, newest first.
type RIExchangeDirectListFilter ¶
type RIExchangeDirectListFilter struct {
After *RIExchangeDirectCursor
RIID string // matched like the in-flight guard: trimmed, lower case
Region string
Allowed []RIExchangeDirectAccountRegion
Statuses []string // submitted and/or unknown; empty means both
Limit int
}
RIExchangeDirectListFilter selects unresolved AWS direct rows. Allowed is the set of (account, region) pairs the caller may see, derived by the handler from the caller's own authorization; an empty set returns nothing.
type RIExchangeDirectListPage ¶
type RIExchangeDirectListPage struct {
Next *RIExchangeDirectCursor
Rows []RIExchangeDirectRow
}
RIExchangeDirectListPage is one page, oldest first. Next is nil at the end.
type RIExchangeDirectListStore ¶
type RIExchangeDirectListStore interface {
ListUnresolvedRIExchangeDirectAccountRegions(ctx context.Context) ([]RIExchangeDirectAccountRegion, error)
ListUnresolvedRIExchangeDirectExecutions(ctx context.Context, f RIExchangeDirectListFilter) (*RIExchangeDirectListPage, error)
GetRIExchangeDirectExecution(ctx context.Context, id string) (*RIExchangeDirectRow, error)
}
RIExchangeDirectListStore is the read side of the direct-row resolve API. Errors are the ErrRIExchangeResolve* values.
type RIExchangeDirectOutcome ¶
type RIExchangeDirectOutcome struct {
// Status is one of the terminal RIExchangeDirectStatus* values.
Status string
// ProviderReference is the AWS exchange ID or the Azure session ID the
// provider echoed; empty keeps the value recorded at submit time.
ProviderReference string
// NetPayable is the provider-reported net amount as a decimal string;
// nil when the provider reported none.
NetPayable *string
NetPayableCurrency string
// ProviderStatus is Azure's operation status string.
ProviderStatus string
Error string
}
RIExchangeDirectOutcome is what the provider call produced, recorded once by FinalizeRIExchangeDirectExecution.
func (*RIExchangeDirectOutcome) Validate ¶
func (o *RIExchangeDirectOutcome) Validate() error
Validate rejects an outcome that is not terminal: finalizing a row back to "submitted" would erase the fact that its outcome was ever recorded.
type RIExchangeDirectResolve ¶
type RIExchangeDirectResolve struct {
ID string
Outcome string
ExpectedStatus string
Note string
CheckedAt time.Time
ResolvedByUserID *string
ResolvedBy string
}
RIExchangeDirectResolve asks to settle a stuck AWS direct row on an operator's word. Outcome is completed or failed; ExpectedStatus is the status (submitted or unknown) the operator saw. Note is the complete text stored in resolution_note, built by the caller so a repeat compares equal as a whole. CheckedAt is when the operator checked AWS.
type RIExchangeDirectResolveResult ¶
type RIExchangeDirectResolveResult struct {
ID string
Status string
ResolvedStatus string
ResolvedAt time.Time
Note string
Replayed bool
}
RIExchangeDirectResolveResult is the row after the call. Status is the original status, unchanged. Replayed is true when an identical earlier request had already resolved the row and nothing was written.
type RIExchangeDirectResolveStore ¶
type RIExchangeDirectResolveStore interface {
RIExchangeDirectListStore
ResolveRIExchangeDirectExecution(ctx context.Context, req RIExchangeDirectResolve) (*RIExchangeDirectResolveResult, error)
}
RIExchangeDirectResolveStore is the store surface of the direct-row list and resolve endpoints.
type RIExchangeDirectRow ¶
type RIExchangeDirectRow struct {
CreatedAt time.Time
ResolvedAt *time.Time
CloudAccountID *string
CompletedAt *time.Time
MaxPaymentDue string
ID string
MaxPaymentCurrency string
Error string
ExecutedBy string
Region string
Status string
Targets json.RawMessage
SourceIDs []string
}
RIExchangeDirectRow is an AWS direct-execute audit row as the operator resolve API reads it. It carries no executing user id or API key id. Error is the raw stored provider text: callers pass it through purchase.SanitizeStoredError and never return it as is.
type RIExchangeRecord ¶
type RIExchangeRecord struct {
UpdatedAt time.Time `json:"updated_at"`
CreatedAt time.Time `json:"created_at"`
// CreatedByUserID is the UUID of the session user who submitted the exchange.
// Always nil today: every exchange is created by the scheduler or the ladder
// engine, and pkg/exchange.ExchangeRecord carries no creator (the 4-eyes
// policy for creator-less rows is requireDifferentRIExchangeApprover in
// internal/api, issue #518). Exposed to the frontend so the Approve button
// can apply the approve-own ownership check client-side.
CreatedByUserID *string `json:"created_by_user_id,omitempty"`
CloudAccountID *string `json:"cloud_account_id,omitempty"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
CompletedAt *time.Time `json:"completed_at,omitempty"`
// LadderRunID links this exchange record to the ladder run that created it
// (cudly-ladder engine). Nil for standalone ri_exchange_reshape task records.
// The database column ri_exchange_history.ladder_run_id was added in migration
// 000080 and is the authoritative source for origin scoping in
// CancelPendingExchangesByOrigin.
//
// KNOWN/ACCEPTABLE: the FK is ON DELETE SET NULL (migration 000080), so
// deleting a ladder_runs row nulls this column and reclassifies the record
// as standalone. A still-pending reshape then becomes standalone-cancellable
// (the standalone-origin sweep would cancel it). This is acceptable: a
// deleted run has no owner to approve its pendings, so canceling them on the
// next standalone sweep is the safe outcome, not a leak.
LadderRunID *string `json:"ladder_run_id,omitempty"`
// ApprovedBy carries the email of the session user who approved the exchange
// via the dashboard Approve button (issue #300). Nil when no session resolves (pure email-link approval).
ApprovedBy *string `json:"approved_by,omitempty"`
SourceInstanceType string `json:"source_instance_type"`
TargetInstanceType string `json:"target_instance_type"`
PaymentDue string `json:"payment_due"`
Status string `json:"status"`
ApprovalToken string `json:"approval_token,omitempty"` // raw when passed to SaveRIExchangeRecord (hashed there); the hash when read back
Error string `json:"error,omitempty"`
Mode string `json:"mode"`
AccountID string `json:"account_id"`
TargetOfferingID string `json:"target_offering_id"`
ExchangeID string `json:"exchange_id"`
ID string `json:"id"`
Region string `json:"region"`
SourceRIIDs []string `json:"source_ri_ids"`
SourceCount int `json:"source_count"`
TargetCount int `json:"target_count"`
}
RIExchangeRecord represents a record in the ri_exchange_history table.
type RIExchangeResolve ¶
type RIExchangeResolve struct {
Check RIExchangeCloudCheck
Actor *string
ID string
Outcome string
ExchangeID string
Note string
StaleAfter time.Duration
}
RIExchangeResolve asks to settle a stale processing RI exchange on an operator's word. Outcome is StatusCompleted (the exchange happened: the row keeps its reserved amount and counts on today's UTC day) or StatusFailed (the exchange did not happen: the hold is released). Note is the complete text stored in the error column, built by the caller so that a repeat of the same request compares equal as a whole.
type RIExchangeResolveResult ¶
type RIExchangeResolveResult struct {
ID string
Status string
PaymentDue string
Note string
Replayed bool
}
RIExchangeResolveResult is the row after the call. Replayed is true when an identical earlier request had already resolved it and nothing was written.
type RIExchangeResolveStore ¶
type RIExchangeResolveStore interface {
ResolveStaleRIExchange(ctx context.Context, req RIExchangeResolve) (*RIExchangeResolveResult, error)
}
RIExchangeResolveStore is the store surface of the operator resolve endpoint.
type RIExchangeStore ¶
type RIExchangeStore interface {
// ClaimRIExchangeIdempotencyKey atomically claims key for an RI exchange
// submit, so a client that retries a timed-out execute request cannot
// commit the same exchange twice (issue #1642). key is a fingerprint of
// what the request buys; the caller derives it and claims it immediately
// before the irreversible provider call.
//
// Returns (true, nil) when this call won the claim and may proceed to
// commit, and (false, nil) when another submit of the same fingerprint
// claimed it less than window ago (the caller maps this to a 409).
// A claim older than window is reclaimable, so a genuine intentional
// repeat of the same exchange is not blocked forever.
//
// There is no release: once taken, a claim stands for the rest of the
// window whatever the provider call does, including when it fails. Past
// the point of submission the outcome is ambiguous, and holding the claim
// is the fail-closed choice. The consequence for the caller's 409 is that
// it cannot promise the earlier submit committed, only that it claimed the
// window.
ClaimRIExchangeIdempotencyKey(ctx context.Context, key string, window time.Duration) (bool, error)
// RI Exchange history
SaveRIExchangeRecord(ctx context.Context, record *RIExchangeRecord) error
ReserveRIExchange(ctx context.Context, record *RIExchangeRecord, dailyCapUSD, perExchangeCapUSD string) (string, error)
// ReserveApprovedRIExchange reserves the execution ceiling for an already
// processing (approved) exchange under the shared daily-cap lock, excluding
// the row's own amount, and stores the ceiling as its payment_due.
ReserveApprovedRIExchange(ctx context.Context, id, dailyCapUSD, perExchangeCapUSD string) (string, error)
// GetRIExchangeRecord returns a wrapped ErrNotFound when no record has id.
GetRIExchangeRecord(ctx context.Context, id string) (*RIExchangeRecord, error)
GetRIExchangeRecordByToken(ctx context.Context, token string) (*RIExchangeRecord, error)
GetRIExchangeHistory(ctx context.Context, since time.Time, limit int) ([]RIExchangeRecord, error)
// GetRIExchangeHistoryForAccounts is GetRIExchangeHistory restricted to
// records whose account_id is in accountIDs, with the limit applied after
// that restriction. An empty accountIDs matches no records.
GetRIExchangeHistoryForAccounts(ctx context.Context, since time.Time, limit int, accountIDs []string) ([]RIExchangeRecord, error)
// TransitionRIExchangeStatus atomically transitions an RI exchange record status.
// actor is the UUID of the user performing the transition (nil for system-initiated paths).
// A lost transition returns a wrapped ErrRIExchangeExpired when the record
// has expired, or ErrRIExchangeNotInExpectedStatus when its status moved on.
TransitionRIExchangeStatus(ctx context.Context, id string, fromStatus string, toStatus string, actor *string) (*RIExchangeRecord, error)
CompleteRIExchange(ctx context.Context, id string, exchangeID string) error
// CompleteRIExchangeWithPayment marks an RI exchange as completed and
// updates payment_due to the amount AWS actually accepted. Use this instead
// of CompleteRIExchange on the manual-approval path so the daily-spend
// ledger (GetRIExchangeDailySpend) reflects the real accepted amount rather
// than the stale pre-execution quote (H3 fix).
CompleteRIExchangeWithPayment(ctx context.Context, id string, exchangeID string, acceptedPaymentDue string) error
// StampRIExchangeApprovedBy sets the approved_by column on a completed
// exchange row (issue #300). Called after CompleteRIExchangeWithPayment when
// the approval came from a session-authed user rather than an email token.
StampRIExchangeApprovedBy(ctx context.Context, id string, approverEmail string) error
FailRIExchange(ctx context.Context, id string, errorMsg string) error
// NoteRIExchangeOutcomeUnknown sets the error note on a row that is still
// processing, leaving it processing for the operator to resolve (#1050).
NoteRIExchangeOutcomeUnknown(ctx context.Context, id, note string) error
GetRIExchangeDailySpend(ctx context.Context, date time.Time) (string, error)
CancelAllPendingExchanges(ctx context.Context) (int64, error)
// CancelPendingExchangesByOrigin cancels only pending records whose origin
// matches:
// - common.ExchangeOriginStandalone: cancels WHERE ladder_run_id IS NULL
// - common.ExchangeOriginLadder: cancels WHERE ladder_run_id IS NOT NULL
// The origin is validated at the boundary and an unknown value fails loud.
// This prevents the standalone ri_exchange_reshape task from wiping out
// ladder-linked pending reshapes and vice versa (gap G10 / issue #1348).
CancelPendingExchangesByOrigin(ctx context.Context, origin common.ExchangeOrigin) (int64, error)
GetStaleProcessingExchanges(ctx context.Context, olderThan time.Duration) ([]RIExchangeRecord, error)
// RI exchange direct-execute audit trail (issue #82). Exchanges executed
// directly through the API, not through the approval flow above, are
// recorded in their own table: SaveRIExchangeDirectExecution inserts the
// row as "submitted" before the provider call, and
// FinalizeRIExchangeDirectExecution records the outcome on it exactly
// once (ErrRIExchangeDirectExecutionNotSubmitted when the row is absent or
// already finalized). They are not in ri_exchange_history, but the daily
// spend query counts them (#145): completed rows by net payable, unresolved
// submitted/unknown rows by their max_payment_due.
SaveRIExchangeDirectExecution(ctx context.Context, record *RIExchangeDirectExecution) error
FinalizeRIExchangeDirectExecution(ctx context.Context, id string, outcome RIExchangeDirectOutcome) error
}
RIExchangeStore holds the RI exchange methods of StoreInterface; StoreInterface embeds it.
type RIUtilizationCacheEntry ¶
type RIUtilizationCacheEntry struct {
FetchedAt time.Time
CloudAccountID string
Region string
Payload []byte
LookbackDays int
}
RIUtilizationCacheEntry is a single cached Cost Explorer GetReservationUtilization result keyed by RIUtilizationCacheKey. Payload is the JSON encoding of the caller's utilization slice — kept opaque here so the config package stays free of AWS-provider types. TTL freshness is evaluated in the caller (api-layer cache wrapper) based on FetchedAt vs. a caller-supplied TTL.
type RIUtilizationCacheKey ¶
RIUtilizationCacheKey identifies one cached Cost Explorer GetReservationUtilization result. CloudAccountID is the cloud_accounts UUID of the account whose credentials made the call, or "" when the deployment's ambient identity is not registered in cloud_accounts. It is part of the key so two accounts reading the same region never share a row (issue #120).
type RampAllocationMode ¶
type RampAllocationMode string
const ( RampAllocationEqualCount RampAllocationMode = "equal_count" // RampAllocationBoundGroups marks a plan whose services entries are bound // to selected recommendations (issue #1746). It sizes like the default // mode; binaries that predate it refuse the plan (fail closed on rollback). RampAllocationBoundGroups RampAllocationMode = "bound_groups" )
func (RampAllocationMode) SizesByPercent ¶
func (m RampAllocationMode) SizesByPercent() bool
SizesByPercent reports whether the mode sizes each step by PercentPerStep.
type RampSchedule ¶
type RampSchedule struct {
StartDate time.Time `json:"start_date" dynamodbav:"start_date"`
Type string `json:"type" dynamodbav:"type"` // immediate, weekly, monthly, custom
AllocationMode RampAllocationMode `json:"allocation_mode,omitempty" dynamodbav:"allocation_mode,omitempty"`
PercentPerStep float64 `json:"percent_per_step" dynamodbav:"percent_per_step"`
StepIntervalDays int `json:"step_interval_days" dynamodbav:"step_interval_days"`
CurrentStep int `json:"current_step" dynamodbav:"current_step"`
TotalSteps int `json:"total_steps" dynamodbav:"total_steps"`
DatesManaged bool `json:"dates_managed,omitempty" dynamodbav:"dates_managed,omitempty"`
}
RampSchedule defines how purchases are spread over time.
func (*RampSchedule) CumulativePercent ¶
func (r *RampSchedule) CumulativePercent(step int) float64
CumulativePercent is the share of the base (0..100) a ramp has bought once step steps are complete: step*PercentPerStep capped at 100, and 100 for an immediate schedule. It is the one definition of cumulative ramp progress.
func (*RampSchedule) FirstExecutionDate ¶
func (r *RampSchedule) FirstExecutionDate(now time.Time) *time.Time
FirstExecutionDate is create's first NextExecutionDate: tomorrow for immediate, else now + interval, nil without an interval (the persisted create path in api/types_plan_request.go; handler_plans.go's tomorrow fallback only fills a nil on read).
func (*RampSchedule) GetCurrentCoverage ¶
func (r *RampSchedule) GetCurrentCoverage(baseCoverage float64) float64
GetCurrentCoverage calculates the current effective coverage based on ramp progress.
func (*RampSchedule) GetNextPurchaseDate ¶
func (r *RampSchedule) GetNextPurchaseDate() time.Time
GetNextPurchaseDate calculates when the next purchase step should occur.
func (*RampSchedule) IsComplete ¶
func (r *RampSchedule) IsComplete() bool
IsComplete returns true if all ramp steps are done.
func (*RampSchedule) Validate ¶
func (r *RampSchedule) Validate() error
Validate validates the RampSchedule.
func (*RampSchedule) ValidateAllocationMode ¶
func (r *RampSchedule) ValidateAllocationMode() error
type RampStepBlock ¶
RampStepBlock reports a plan's next ramp step and how many of that step's executions are stuck on it. Returned by GetStuckRampSteps and rendered by the plan-health ramp_blocked factor (issue #1861).
StuckExecutions counts executions rather than accounts because that is what the query can prove: a fanned-out step writes one row per cloud account, so the two coincide for the multi-account plans the factor exists for, but a step that never fanned out (an approval that expired before it ran) has one row standing for the whole step. Naming the count for the rows keeps the tooltip from asserting an account total it did not measure.
type RecommendationChunk ¶
type RecommendationChunk struct {
Last *RecommendationScanKey
Recs []RecommendationRecord
Done bool
}
RecommendationChunk is one keyset read of the recommendations cache. Recs holds the rows that passed the filter, in scan order. Last is the position of the last row read (nil when no row was read) and is where the next chunk resumes. Done is true when fewer rows than the limit were read, so nothing matches after Last.
type RecommendationFilter ¶
type RecommendationFilter struct {
Provider string // "aws" / "azure" / "gcp" / "" (all)
Service string // "" = all services
Region string // "" = all regions
ID string // "" = all ids; non-empty = exact match on the id column
AccountIDs []string // nil/empty = all accounts
MinSavingsUSD float64 // 0 = no floor on monthly savings dollar amount
MinSavingsPct float64 // 0 = no floor on savings percentage (0–100 scale)
RequireAzurePricingMigration bool
}
RecommendationFilter parameterises ListStoredRecommendations and the handler-facing scheduler.ListRecommendations wrapper. Zero-value fields mean "no filter"; non-empty AccountIDs restricts to the given IDs.
MinSavingsUSD is a dollar floor: only recommendations whose monthly savings are >= MinSavingsUSD are returned. 0 means no floor.
MinSavingsPct is a percentage floor (0–100): only recommendations whose effective savings percentage (savings/on-demand*100) meets or exceeds this threshold are returned. 0 means no floor. Applied in-process after the DB query rather than in SQL (avoids a computed column). These two filters are independent and can be combined.
type RecommendationListScope ¶
type RecommendationListScope struct {
// EnabledProviders keeps only rows whose provider is listed. Empty keeps
// every provider (FilterRecommendationsByEnabledProviders).
EnabledProviders []string
AllowedAccountIDs []string
Filter RecommendationFilter
// Restricted keeps only rows whose cloud_account_id is one of
// AllowedAccountIDs; rows without an account are dropped. The caller
// resolves the account scope to the exact set of IDs it allows.
Restricted bool
}
RecommendationListScope is the row filter of one recommendations list request: the query-string filter plus the handler-side filters, all applied to the decoded payload the way the Go filters see it.
type RecommendationOverrideRule ¶
type RecommendationOverrideRule struct {
Config *ServiceConfig
Key string
MinCountExempt bool
}
RecommendationOverrideRule is the resolved account-override configuration of one AccountConfigKey. Config is nil when neither a global service configuration nor an account override exists, so the rows pass unfiltered. MinCountExempt is set for Savings Plans services, whose count is not an instance count.
type RecommendationPage ¶
type RecommendationPage struct {
Fallback string
Regions []string
Rows []RecommendationRecord
TotalCount int
TotalSavings float64
TotalUpfront float64
// TotalAmortizedUpfront sums AmortizedUpfrontMonthly over the same rows.
TotalAmortizedUpfront float64
}
RecommendationPage is one page of the filtered recommendations with the summary of the whole filtered set. TotalSavings, TotalUpfront and TotalAmortizedUpfront are summed in ID order, the order the Go summary added them in. Regions holds each non-empty region once.
Fallback is non-empty when SQL cannot reproduce the Go filters for this read (for example a value whose float arithmetic SQL would reject, or a row whose overrides were not resolved); the caller must then serve the request from the Go-side scan, and the other fields are unset.
type RecommendationPageQuery ¶
type RecommendationPageQuery struct {
DecideSuppressed func(rows []StoredRecommendation) (keepRowIDs []string, err error)
// AfterID returns only rows whose ID sorts byte-wise after it; "" starts
// at the first row.
AfterID string
Rules []RecommendationOverrideRule
SuppressionKeys []string
Scope RecommendationListScope
// Limit caps the returned rows.
Limit int
}
RecommendationPageQuery parameterizes PageStoredRecommendations.
Rules must hold an entry for every AccountConfigKey the scope's rows can produce (ListStoredRecommendationTriples); a row whose key has no entry makes the page fall back, because its overrides were never resolved.
SuppressionKeys are the suppression 6-tuples (see SuppressionTupleKey) with every stored spelling of the service. Rows on one of them are read first and handed to DecideSuppressed, which returns the primary keys of the rows that survive suppressions and overrides; the other rows are filtered by Rules in SQL.
type RecommendationRecord ¶
type RecommendationRecord struct {
// MonthlyCost is nil when the provider API did not return a monthly
// recurring breakdown (rendered as "—" in the UI, not "$0").
// Backward-compatible with DynamoDB: existing items with a numeric 0
// attribute unmarshal as a pointer to 0.0; absent attributes unmarshal
// as nil. No migration needed.
MonthlyCost *float64 `json:"monthly_cost" dynamodbav:"monthly_cost"`
MemoryGB *float64 `json:"memory_gb,omitempty" dynamodbav:"-"`
// VCPU and MemoryGB surface the compute size of the recommended
// instance type so the frontend's Capacity column can render
// "<vcpu> vCPU / <memory> GB" without parsing the opaque Details blob
// (#219). They are NOT persisted: the canonical source is the typed
// ComputeDetails nested inside Details (config must stay free of
// pkg/common imports). The api layer decodes Details via
// common.DecodeServiceDetailsFor in buildRecommendationsResponse and
// stamps these top-level fields on the way out, so the API JSON carries
// them at the top level where the frontend already reads them.
//
// Pointers (not plain int/float64) so "absent / non-compute / unknown
// size" serializes as omitted rather than a misleading 0: the frontend
// renders absent as "—", and a literal 0 would otherwise look like a
// real "0 vCPU / 0 GB" capacity. dynamodbav:"-" because they are
// derived-on-read, never stored.
VCPU *int `json:"vcpu,omitempty" dynamodbav:"-"`
// PrimarySuppressionExecutionID identifies the execution whose
// suppression contributed the most to this tuple (ties broken by
// newest created_at). The frontend badge deep-links to Purchase
// History filtered to this execution.
PrimarySuppressionExecutionID *string `json:"primary_suppression_execution_id,omitempty" dynamodbav:"primary_suppression_execution_id,omitempty"`
// SuppressionExpiresAt is the earliest expiry across all active
// suppression rows contributing to this tuple. The frontend uses it
// to render "Xd remaining" on the recently-purchased badge.
SuppressionExpiresAt *time.Time `json:"suppression_expires_at,omitempty" dynamodbav:"suppression_expires_at,omitempty"`
SourceAccountID *string `json:"source_account_id,omitempty" dynamodbav:"source_account_id,omitempty"`
CloudAccountID *string `json:"cloud_account_id,omitempty" dynamodbav:"cloud_account_id,omitempty"`
// SavingsPercentage is the provider-authoritative effective savings %
// reported directly by the cloud provider (AWS Cost Explorer
// `EstimatedMonthlySavingsPercentage`, Azure / GCP converters' computed
// SavingsPercentage). It is the same figure the CLI/reporter prints
// verbatim (github.com/LeanerCloud/cloud-commitments-go/pkg/reporter);
// persisting it lets the GUI show the identical number instead of
// re-deriving it client-side from savings / on-demand. Persisted via
// the recommendations row's JSONB `payload` column; no DDL needed.
//
// nil means the provider did not report a percentage; the frontend then
// falls back to the client-side reconstruction (effectiveSavingsPct).
// When non-nil, the frontend prefers this value so the displayed % cannot
// drift from the provider's authoritative number and AWS recs missing
// on_demand_cost still render a real % rather than an em-dash (see #323).
SavingsPercentage *float64 `json:"savings_percentage" dynamodbav:"savings_percentage,omitempty"`
// OnDemandCost is the canonical on-demand monthly baseline for the
// recommended commitment, sourced directly from the cloud provider
// (Azure `CostWithNoReservedInstances`, AWS Cost Explorer
// `EstimatedMonthlyOnDemandCost`). Persisted via the recommendations
// row's JSONB `payload` column — no DDL needed.
//
// nil means the provider API did not return a baseline; the frontend
// falls back to reconstructing on-demand from `monthly_cost + savings
// + amortized_upfront`. When non-nil, the frontend prefers the raw
// value over reconstruction so anomalies in the reconstructed
// denominator (e.g. Azure all-upfront recs where monthly_cost=$0
// collapses the denominator) don't inflate the displayed effective
// savings %. See #274.
OnDemandCost *float64 `json:"on_demand_cost,omitempty" dynamodbav:"on_demand_cost,omitempty"`
Error string `json:"error,omitempty" dynamodbav:"error,omitempty"`
ResourceType string `json:"resource_type" dynamodbav:"resource_type"`
Payment string `json:"payment" dynamodbav:"payment"`
Provider string `json:"provider" dynamodbav:"provider"`
Service string `json:"service" dynamodbav:"service"`
Region string `json:"region" dynamodbav:"region"`
Engine string `json:"engine,omitempty" dynamodbav:"engine,omitempty"`
// CommitmentCurrency is the ISO 4217 code UpfrontCost and MonthlyCost are
// denominated in, copied from common.Recommendation.CommitmentCurrency at
// collection time. Empty means unknown: the provider parser could not
// prove the currency of every payment leg, or the row predates the field.
// The purchase spend caps are USD, so a rec that is not provably USD is
// never compared against one (issue #361). Persisted via the
// recommendations row's JSONB `payload` column, and with the execution's
// recommendations JSONB; no DDL needed.
CommitmentCurrency string `json:"commitment_currency,omitempty" dynamodbav:"commitment_currency,omitempty"`
// AvailabilityZone is the zonal EC2 reservation's AZ name (e.g.
// "us-east-1a"), empty for regional and non-EC2 recs. It mirrors
// ComputeDetails.AvailabilityZone inside Details (config must not import
// pkg/common) so the identity tuple, the rec ID and the recommendations
// natural key can distinguish two zonal recs that differ only by AZ
// (issue #792). The scheduler stamps it at collection time; request recs
// echo it from the listed rec.
AvailabilityZone string `json:"availability_zone,omitempty" dynamodbav:"availability_zone,omitempty"`
ID string `json:"id" dynamodbav:"id"`
PurchaseID string `json:"purchase_id,omitempty" dynamodbav:"purchase_id,omitempty"`
// Details preserves the full common.ServiceDetails payload from the
// source common.Recommendation so the purchase path can reconstruct
// the correct typed *Details pointer at execute time (issue #453).
// Stored as raw JSON because RecommendationRecord lives in the
// config package, which must NOT import pkg/common (the dependency
// graph is config <- common in callers, never the reverse). The
// scheduler populates this at collection time via
// common.MarshalServiceDetails; the purchase manager reads it via
// common.DecodeServiceDetailsFor when it builds the
// common.Recommendation handed to the cloud service client.
//
// Empty for rows persisted before #453 — DecodeServiceDetailsFor
// returns a zero-valued typed pointer in that case so the cloud
// client's findOfferingID type-assertion still succeeds (the
// service-side buildOfferingFilters substitutes default
// Platform / Tenancy / Scope / AZConfig values). New rows always
// carry the full Details, so non-default platforms (Windows EC2,
// Postgres RDS, etc.) round-trip correctly.
Details json.RawMessage `json:"details,omitempty" dynamodbav:"-"`
// UsageHistory is a short time-series of daily RI-coverage percentages
// (0-100) for the last N days of the lookback window, ordered from
// oldest to newest. nil means the collector did not populate it (e.g.
// provider not yet wired); an empty non-nil slice means the collector
// ran but returned no daily data. The frontend renders nil as "—" and
// a non-empty slice as a thumbnail sparkline. Stored inside the
// recommendations JSONB payload — no DDL change needed (closes #239
// Part 1 for AWS).
UsageHistory []float64 `json:"usage_history,omitempty" dynamodbav:"usage_history,omitempty"`
Count int `json:"count" dynamodbav:"count"`
// SuppressedCount is the cumulative count already committed against
// this recommendation's suppression key (account, provider, service,
// region, resource_type, engine, plus availability zone, platform and
// tenancy, issue #816) within the active grace window. The
// scheduler subtracts this from Count before returning the rec to
// the frontend; a rec where SuppressedCount ≥ original count is
// dropped entirely. Populated by the scheduler — zero on writes.
SuppressedCount int `json:"suppressed_count,omitempty" dynamodbav:"suppressed_count,omitempty"`
Term int `json:"term" dynamodbav:"term"`
Savings float64 `json:"savings" dynamodbav:"savings"`
// RecommendedCount is the pre-scaling count the collector originally
// recommended, before the bulk-purchase Capacity % slider scaled it down.
// The web execute path stamps it so the backend can verify the
// client-supplied capacity_percent against the scaled Count
// (floor(RecommendedCount*pct/100) must equal Count) rather than trusting
// a decorative audit field that could silently disagree (#647). Optional:
// 0 / absent means "not supplied" (legacy callers, scheduler/CLI rows,
// retry replays) and the consistency check is skipped for that rec.
RecommendedCount int `json:"recommended_count,omitempty" dynamodbav:"recommended_count,omitempty"`
UpfrontCost float64 `json:"upfront_cost" dynamodbav:"upfront_cost"`
Purchased bool `json:"purchased" dynamodbav:"purchased"`
Selected bool `json:"selected" dynamodbav:"selected"`
}
RecommendationRecord stores a recommendation with purchase status.
func FilterRecommendationsByEnabledProviders ¶
func FilterRecommendationsByEnabledProviders(recs []RecommendationRecord, enabled []string) []RecommendationRecord
FilterRecommendationsByEnabledProviders drops recs whose Provider is absent from enabled. An empty enabled list is the permissive default (nothing is configured), so recs pass through unchanged. Shared by Opportunities and the plan-step resolver so both show and buy the same set.
func (*RecommendationRecord) AmortizedUpfrontMonthly ¶
func (r *RecommendationRecord) AmortizedUpfrontMonthly() float64
AmortizedUpfrontMonthly is the upfront spread over the term in months: add it to Savings for the gross monthly savings a payback divides by. 0 when Savings is not net of upfront, there is no upfront or the term is unknown. Mirrors grossMonthlySavings (frontend/src/lib/payback.ts) and the SQL page aggregate.
func (*RecommendationRecord) ComputeIdentity ¶
func (r *RecommendationRecord) ComputeIdentity() (ComputeIdentity, error)
ComputeIdentity reads platform and tenancy from the rec's Details blob. It mirrors the generated columns of migration 000111 (COALESCE(payload->'details'->>'platform', ”)) and is pinned to them by the shared vectors in TestComputeIdentity_Vectors: absent Details, JSON null, a missing key and a null value all yield "". Only ComputeDetails carries these keys, so the result is service-agnostic. config cannot import pkg/common, so this decodes just the two keys. A non-string value is an error.
func (*RecommendationRecord) DetailsAZConfig ¶
func (r *RecommendationRecord) DetailsAZConfig() (string, error)
DetailsAZConfig reads the database AZ configuration (RDS "single-az" / "multi-az", Azure SQL "zoneRedundant" / "none") from the rec's Details blob, VERBATIM. Single-AZ and Multi-AZ RDS reservations are different offerings with different prices, yet share every other identity field (issue #408). For AWS RDS rows it mirrors the generated az_config column of migration 000158 (COALESCE(payload->'details'->>'az_config', ”); the column is ” for every other rec, like IdentityAZConfig) and is pinned to it by the shared vectors in TestDetailsAZConfig_Vectors: absent Details, JSON null, a missing key and a null value all yield "". Only DatabaseDetails carries the key. A non-string value is an error.
func (*RecommendationRecord) IdentityAZConfig ¶
func (r *RecommendationRecord) IdentityAZConfig() (string, error)
IdentityAZConfig is the az_config component of the rec ID, identity key, purchase fingerprint and suppression variant: DetailsAZConfig for AWS RDS, "" for every other rec.
func (*RecommendationRecord) OnDemandBaseline ¶
func (r *RecommendationRecord) OnDemandBaseline() (float64, bool)
OnDemandBaseline is the monthly on-demand cost the rec's savings percentage is measured against, by the rule the Recommendations filter and the GUI share (#323): never rebuilt for AWS, and not without a MonthlyCost for the other providers. ok is false when the rule yields nothing or a baseline that is not positive.
func (*RecommendationRecord) SuppressionVariant ¶
func (r *RecommendationRecord) SuppressionVariant() (SuppressionVariant, error)
SuppressionVariant is the rec's availability zone, platform, tenancy and (AWS RDS only) az_config as the purchase suppression key carries them (issues #816, #408): the platform and tenancy come from the same Details read (ComputeIdentity) as RecIdentityKey, so the write side (BuildSuppressions) and the read side (the scheduler's subtraction pass) cannot drift from it or from each other. For AWS EC2 only, legacy tenancy "shared" is canonicalised to "default" and an AZ stored only in Details is used when the AZ field is empty (issue #1232).
func (*RecommendationRecord) TotalCommitment ¶
func (r *RecommendationRecord) TotalCommitment() float64
TotalCommitment returns the recommendation's full committed spend: the upfront cost plus the recurring monthly cost over the term. UpfrontCost and MonthlyCost are totals for the rec's Count, so they sum with no per-instance scaling. Term is in years (converted with *12). A nil MonthlyCost (all-upfront commitments) or a non-positive Term contributes nothing to the recurring leg. Used for spend caps instead of UpfrontCost alone, which is $0 for no-upfront commitments (Azure monthly billing).
type RecommendationScanKey ¶
RecommendationScanKey is a stored recommendation's position in the keyset scan order of ListStoredRecommendationsChunk (issue #981): the application recommendation ID compared byte-wise, then the cache table's UUID primary key (RowID), which keeps rows that share an ID in a total order.
type RecommendationStore ¶
type RecommendationStore interface {
// Recommendations cache (ADR: store recommendations in Postgres so the
// dashboard serves provider-switch clicks from SQL instead of live cloud
// API calls). UpsertRecommendations is the only write path and takes a
// list of (provider, account) pairs that successfully collected this
// cycle. Stale-row eviction is scoped to that union so a partially-failed
// provider preserves the failed accounts' previous-cycle rows. See
// SuccessfulCollect for the per-row semantics. There is deliberately no
// unscoped "replace everything" method (issue #159).
UpsertRecommendations(ctx context.Context, collectedAt time.Time, recs []RecommendationRecord, successfulCollects []SuccessfulCollect) error
// UpsertRecommendationsWithPartial is UpsertRecommendations that also
// records the collection's incomplete-sweep summary (nil clears it) in the
// same transaction, so the rows and the marker commit or roll back together.
UpsertRecommendationsWithPartial(ctx context.Context, collectedAt time.Time, recs []RecommendationRecord, successfulCollects []SuccessfulCollect, partial *RecommendationsCollectionPartial) error
// PruneStaleRecommendations deletes the rows of every (provider,
// account) pair with no row collected in the last retentionDays days,
// leaving every pair that collected inside the window untouched, and
// returns the number of rows deleted (issue #120).
PruneStaleRecommendations(ctx context.Context, retentionDays int) (int64, error)
ListStoredRecommendations(ctx context.Context, filter RecommendationFilter) ([]RecommendationRecord, error)
// ListStoredRecommendationsChunk is ListStoredRecommendations for a
// keyset walk: at most limit rows after the position after, in
// byte-wise ID order then primary-key order (issue #981).
ListStoredRecommendationsChunk(ctx context.Context, filter RecommendationFilter, after *RecommendationScanKey, limit int) (RecommendationChunk, error)
// ListStoredRecommendationTriples lists the distinct (account,
// provider, service) keys of the rows scope selects, for resolving
// account overrides before PageStoredRecommendations (issue #981).
ListStoredRecommendationTriples(ctx context.Context, scope RecommendationListScope) ([]RecommendationTriple, error)
// PageStoredRecommendations reads one page of the recommendations list
// and the summary of the whole filtered set with every list filter
// evaluated in SQL, in one snapshot (issue #981).
PageStoredRecommendations(ctx context.Context, q RecommendationPageQuery) (RecommendationPage, error)
GetRecommendationsFreshness(ctx context.Context) (*RecommendationsFreshness, error)
SetRecommendationsCollectionError(ctx context.Context, errMsg string) error
// MarkCollectionStarted atomically sets last_collection_started_at = now
// only when no in-flight collection is running (last_collection_started_at IS NULL
// OR older than 5 minutes), and stamps a freshly generated owner token
// alongside it. Returns the token and true when this caller won the race
// and should proceed with the async invoke, passing the token through so
// only this caller can later clear the marker; ("", false, nil) when
// another collection is already in flight and the caller should return
// 409.
MarkCollectionStarted(ctx context.Context) (token string, ok bool, err error)
// ClearCollectionStarted clears last_collection_started_at, but only if
// last_collection_owner_id still matches token: a compare-and-clear
// guard (issue #261) so a caller that never won MarkCollectionStarted
// (cron, cold-start) cannot wipe another caller's in-flight marker. A
// mismatched token is a documented silent no-op (the marker belongs to
// someone else); an empty token is a boundary error, since only a
// caller that actually owns a marker should ever call Clear.
ClearCollectionStarted(ctx context.Context, token string) error
// ClaimCollectionInvocation is called by a token-carrying collect run
// once it holds the task advisory lock (issue #84). It re-stamps the
// marker with a fresh invocation-scoped token when the marker is still
// owned by markerToken, or free/stale, so a lock-skipped duplicate
// delivery of the same event (same markerToken) can no longer clear
// it. Returns the new token and true when the caller now owns the
// marker; ("", false, nil) when another run holds a fresh marker.
ClaimCollectionInvocation(ctx context.Context, markerToken string) (token string, ok bool, err error)
// RI utilization cache. Postgres-backed TTL cache for Cost Explorer
// GetReservationUtilization; shared across Lambda containers so
// dashboard loads don't each fan out to a paid CE API call. A
// per-process in-memory cache effectively never hits because each
// cold container starts empty. GetRIUtilizationCache returns nil
// when the (cloud_account_id, region, lookback_days) key is absent —
// callers treat that as a miss and re-fetch.
GetRIUtilizationCache(ctx context.Context, key RIUtilizationCacheKey) (*RIUtilizationCacheEntry, error)
UpsertRIUtilizationCache(ctx context.Context, key RIUtilizationCacheKey, payload []byte, fetchedAt time.Time) error
// Purchase suppressions. Written inside a WithTx block during bulk
// purchase submit so the execution insert + the suppression rows
// commit atomically. Deleted on cancel/expire of the execution,
// also inside a WithTx block paired with the status update.
//
// The plain variants (no Tx) open their own single-call transaction
// — useful for tests and one-off admin operations. The Tx variants
// reuse a caller-provided transaction so multi-write operations
// can roll back atomically.
CreateSuppression(ctx context.Context, sup *PurchaseSuppression) error
CreateSuppressionTx(ctx context.Context, tx pgx.Tx, sup *PurchaseSuppression) error
DeleteSuppressionsByExecution(ctx context.Context, executionID string) error
DeleteSuppressionsByExecutionTx(ctx context.Context, tx pgx.Tx, executionID string) error
ListActiveSuppressions(ctx context.Context) ([]PurchaseSuppression, error)
}
RecommendationStore holds the recommendation cache and suppression methods of StoreInterface; StoreInterface embeds it.
type RecommendationTriple ¶
type RecommendationTriple struct {
AccountID string
Provider string
Service string
HasAccount bool
}
RecommendationTriple is an (account, provider, service) combination of the stored rows, the key account overrides are resolved by. AccountID is "" when the payload has no cloud_account_id; HasAccount tells that apart from a present but empty one, which override resolution treats differently.
type RecommendationsCollectionPartial ¶
type RecommendationsCollectionPartial struct {
// Providers lists one entry per provider with at least one incomplete
// sweep, in the configured provider order.
Providers []PartialProviderSweep `json:"providers"`
}
RecommendationsCollectionPartial records that the most recent collection was incomplete without having failed: its rows were kept and stored, but some subscriptions, projects or collection scopes were never queried, so the stored recommendations under-state the real opportunity (issue #87).
It is deliberately aggregate-only. recommendations_state is one global row that every user with view:recommendations reads, while accounts are access-scoped, so it carries counts and a fixed set of reason categories -- never raw provider error text or subscription/project identifiers. The failed identifiers are named in the scheduler's WARN log for operators.
type RecommendationsFreshness ¶
type RecommendationsFreshness struct {
LastCollectedAt *time.Time `json:"last_collected_at"`
LastCollectionError *string `json:"last_collection_error"`
LastCollectionStartedAt *time.Time `json:"last_collection_started_at"`
LastCollectionPartial *RecommendationsCollectionPartial `json:"last_collection_partial"`
NextCollectionAt *time.Time `json:"next_collection_at"`
// LastCollectionPartialUnreadable is set when the stored marker could not be
// decoded (LastCollectionPartial is then nil). It stays out of the API: it
// only lets the purchase gate refuse instead of reading "no marker".
LastCollectionPartialUnreadable bool `json:"-"`
}
RecommendationsFreshness describes the cache staleness state surfaced to the frontend. LastCollectedAt is nil on a cold start. LastCollectionError is non-nil when the most recent collect attempt partially or fully failed. LastCollectionStartedAt is non-nil while an async collect is in flight; the scheduler clears it on completion (success or failure). A value older than 5 minutes means the scheduler crashed mid-run — the refresh handler treats it as stale and allows a new collection. LastCollectionPartial is non-nil when the most recent persisted collection kept rows from a sweep that did not cover everything it was asked to (for example 9 of 10 Azure subscriptions answered). It is cleared by the next collection whose every sweep is complete. NextCollectionAt is not stored: the API handler computes it from the deployment's schedule (issue #756) and leaves it nil when scheduled collection is off or its next run cannot be known.
type RedshiftLineageConflict ¶
type RedshiftLineageConflict struct {
FirstDispatchAt *time.Time
ExecutionID string
Status string
Error string
Recommendations []RecommendationRecord
SameFamily bool
RecentBuy bool
}
RedshiftLineageConflict is an open execution whose Redshift rec matches a candidate tuple. SameFamily is true when it shares the candidate's lineage root (idempotency key up to the first colon). RecentBuy marks an other-family row that may have bought and was written inside the adoption window.
type RedshiftRetryClock ¶
RedshiftRetryClock is a row's age measured on the database clock. SinceStamp is nil when the row has no first_dispatch_at, so a missing stamp never reads as fresh.
type RedshiftTuple ¶
type RedshiftTuple struct {
// CloudAccountID is the rec's own account; nil falls back to the accountID argument.
CloudAccountID *string `json:"cloud_account_id,omitempty"`
Region string `json:"region"`
NodeType string `json:"node_type"`
Payment string `json:"payment"`
Term int `json:"term"`
Count int `json:"count"`
}
RedshiftTuple identifies one Redshift reserved-node purchase. Go's dedupe window matches on exactly these fields (account is implicit in the client).
func (RedshiftTuple) LockKey ¶
func (t RedshiftTuple) LockKey() string
LockKey is the advisory lock key of the tuple. It leaves the account out because a NULL account on either side of the conflict query matches any.
type ServiceConfig ¶
type ServiceConfig struct {
MaxStepCommitment *float64 `json:"max_step_commitment,omitempty" dynamodbav:"max_step_commitment,omitempty"`
UpdatedAt *time.Time `json:"updated_at,omitempty" dynamodbav:"updated_at,omitempty"`
// CreatedAt and UpdatedAt are the service_configs row's own timestamps
// (issue #8), read-only. The store fills them on every read and from the
// upsert's RETURNING clause; no write path stores a caller's value. Nil
// (omitted from JSON) on a config that is not a stored row, such as an
// entry of a purchase plan's services map.
CreatedAt *time.Time `json:"created_at,omitempty" dynamodbav:"created_at,omitempty"`
Provider string `json:"provider" dynamodbav:"provider"`
Service string `json:"service" dynamodbav:"service"`
// GroupID, BoundIdentities and MaxStepCommitment describe one config group
// of a bound plan (issue #1746). BoundIdentities holds RecIdentityKey values;
// MaxStepCommitment is the group's own per-step cap. All are empty on legacy
// entries and on the global and per-account service settings.
GroupID string `json:"group_id,omitempty" dynamodbav:"group_id,omitempty"`
Payment string `json:"payment" dynamodbav:"payment"`
RampSchedule string `json:"ramp_schedule" dynamodbav:"ramp_schedule"`
ExcludeRegions []string `json:"exclude_regions,omitempty" dynamodbav:"exclude_regions,omitempty"`
IncludeRegions []string `json:"include_regions,omitempty" dynamodbav:"include_regions,omitempty"`
ExcludeEngines []string `json:"exclude_engines,omitempty" dynamodbav:"exclude_engines,omitempty"`
IncludeTypes []string `json:"include_types,omitempty" dynamodbav:"include_types,omitempty"`
ExcludeTypes []string `json:"exclude_types,omitempty" dynamodbav:"exclude_types,omitempty"`
IncludeEngines []string `json:"include_engines,omitempty" dynamodbav:"include_engines,omitempty"`
BoundIdentities []string `json:"bound_identities,omitempty" dynamodbav:"bound_identities,omitempty"`
// MinCount is the GUI/persisted equivalent of the CLI --min-count flag:
// the minimum instance/node count a recommendation must carry to be
// surfaced. Applied at read time by
// scheduler.filterRecsByResolvedConfigs against the persisted
// RecommendationRecord.Count. 0 (the default) disables the filter,
// matching the CLI flag's 0-no-floor semantics.
MinCount int `json:"min_count,omitempty" dynamodbav:"min_count,omitempty"`
Coverage float64 `json:"coverage" dynamodbav:"coverage"`
Term int `json:"term" dynamodbav:"term"`
// BoundCount is response-only: plan responses replace BoundIdentities with
// its length so a large selection does not bloat every plan read. It is
// never stored or read from a request.
BoundCount int `json:"bound_count,omitempty" dynamodbav:"-"`
Enabled bool `json:"enabled" dynamodbav:"enabled"`
}
ServiceConfig represents per-service configuration.
Coverage is a percentage whose meaning depends on where the config lives. In a PurchasePlan's Services it is the plan's sizing target (planstep sizes each ramp step by it). In the global and per-account service settings it is display-only: the dashboard scales projected savings by it and nothing in purchase execution reads it (issue #345).
func ResolveServiceConfig ¶
func ResolveServiceConfig(provider, service string, global *ServiceConfig, override *AccountServiceOverride) *ServiceConfig
ResolveServiceConfig merges a sparse per-account override on top of a global ServiceConfig. Any non-nil pointer field in override replaces the global value; nil fields inherit from global. Slice fields (include/exclude lists) are replaced wholesale when non-empty in the override.
If override is nil the global is returned unchanged (no copy is made). If global is nil but override is non-nil, a baseline ServiceConfig is synthesized with safe defaults (Enabled: true, Provider/Service from the override context via the provider and service parameters) and the override is merged into it. This lets a per-account override take effect even when no global ServiceConfig row exists for that (provider, service) pair. If both are nil, nil is returned. When merging, slice fields from the global are copied to avoid callers mutating the global's underlying arrays through the resolved config.
func (*ServiceConfig) EffectiveGroupID ¶
func (c *ServiceConfig) EffectiveGroupID(key string) string
EffectiveGroupID is the entry's group id: GroupID when set, otherwise its services map key (a legacy entry is its own one-entry group).
func (*ServiceConfig) Validate ¶
func (c *ServiceConfig) Validate() error
Validate validates the ServiceConfig.
type StampResult ¶
StampResult is the outcome of StampFirstDispatchTx. At is nil when no stamp exists and none may be minted; WithinHorizon is judged on the database clock and is false when At is nil.
type StoreInterface ¶
type StoreInterface interface {
// Global configuration
GetGlobalConfig(ctx context.Context) (*GlobalConfig, error)
SaveGlobalConfig(ctx context.Context, config *GlobalConfig) error
// UpdateGlobalConfigAtomic serializes a read-modify-write of the
// global_config singleton under an advisory-locked transaction so
// concurrent partial PUTs cannot lose each other's updates. apply mutates
// the loaded config in place; its error aborts the write and is propagated.
// Each default_* value apply changes is copied onto every service config
// in the same transaction.
UpdateGlobalConfigAtomic(ctx context.Context, apply func(*GlobalConfig) error) (*GlobalConfig, error)
// Service configuration
GetServiceConfig(ctx context.Context, provider, service string) (*ServiceConfig, error)
SaveServiceConfig(ctx context.Context, config *ServiceConfig) error
// UpdateServiceConfigAtomic serializes a read-merge-write of one service
// config row under a locked transaction so concurrent partial PUTs of the
// same row cannot lose each other's updates. apply receives the stored row
// (nil when none exists) and returns the full row to write; its error
// aborts the write and is propagated.
UpdateServiceConfigAtomic(ctx context.Context, provider, service string, apply func(existing *ServiceConfig) (*ServiceConfig, error)) (*ServiceConfig, error)
ListServiceConfigs(ctx context.Context) ([]ServiceConfig, error)
PlanStore
// Purchase executions
SavePurchaseExecution(ctx context.Context, execution *PurchaseExecution) error
// SaveExecutionIfStatus saves only while the stored status is one of
// expected (ErrExecutionNotInExpectedStatus otherwise), so a stale
// in-memory copy cannot rewrite a status another writer moved on.
SaveExecutionIfStatus(ctx context.Context, execution *PurchaseExecution, expected []string) error
// RecoverReapedExecution persists a late completed/partially_completed
// outcome over a reaper-failed row that has no retry successor linked
// (ErrExecutionRetryLinked when one is).
RecoverReapedExecution(ctx context.Context, execution *PurchaseExecution) error
// PinExecutionFanOutShape records shape (FanOutShapeSingle or
// FanOutShapeMulti) for the execution lineage lineageKey unless one is
// already recorded, and returns the recorded shape (issue #97).
PinExecutionFanOutShape(ctx context.Context, lineageKey, shape string) (string, error)
// GetExecutionFanOutShape returns the shape pinned for lineageKey, or ""
// when none is pinned yet (issue #97).
GetExecutionFanOutShape(ctx context.Context, lineageKey string) (string, error)
GetPendingExecutions(ctx context.Context) ([]PurchaseExecution, error)
// GetExecutionsByStatuses returns executions in any of the given states,
// newest first, capped at `limit`, except that pending rows dated in the
// future (not-yet-due ramp steps) sort last, soonest first, so they cannot
// push a due row past the cap (issue #680). Used by the History handler to render
// pending + failed + expired alongside completed purchases; the scheduler
// keeps using GetPendingExecutions (which is narrower and doesn't share
// this method's status filter) to avoid accidental double-processing of
// failed / expired rows.
GetExecutionsByStatuses(ctx context.Context, statuses []string, limit int) ([]PurchaseExecution, error)
// GetExecutionsByStatusesFiltered is GetExecutionsByStatuses with the
// History filters and account scope in q applied in SQL before the limit,
// so the cap counts only rows the caller can be shown (issue #632).
GetExecutionsByStatusesFiltered(ctx context.Context, q ExecutionsByStatusesQuery) ([]PurchaseExecution, error)
// ListHistoryExecutionsPage and ListPurchaseHistoryPage read one keyset
// page each of the History view's paged stream (issue #674): rows strictly
// after q.After / after (nil starts at the top) in the stream order of
// HistoryPageKey, capped at the limit. The executions half excludes clean
// completed rows like GetExecutionsByStatuses and bounds scheduled_date
// inclusively; the purchase_history half applies GetPurchaseHistoryFiltered's
// predicate. Rows inserted or changed between two page reads never shift
// the rows a later page returns.
ListHistoryExecutionsPage(ctx context.Context, q HistoryExecutionsPageQuery) ([]PurchaseExecution, error)
ListPurchaseHistoryPage(ctx context.Context, filter PurchaseHistoryFilter, after *HistoryPageKey) ([]PurchaseHistoryPageRow, error)
// CountExecutionsByPlanAndStatus returns, keyed by plan ID, the exact
// number of executions in each of the supplied statuses that last
// changed state (updated_at) at or after `since` -- not those merely
// scheduled since then, which for a canceled row is a future date. Rows
// with a NULL plan_id (direct-execute purchases, and executions orphaned
// by a deleted plan) belong to no plan and are excluded.
//
// Deliberately NOT derived from a GetExecutionsByStatuses page: that
// method is capped by `limit` across ALL plans, so any caller counting
// per-plan rows out of it silently understates plans whose executions
// fall outside the newest `limit` rows. The plan health score
// (internal/api/plan_health.go) needs exact counts -- an understated
// count renders a confidently-healthy badge for an unhealthy plan --
// so the aggregation happens in SQL and the result is bounded by
// plans x statuses rather than by execution volume.
CountExecutionsByPlanAndStatus(ctx context.Context, statuses []string, since time.Time) (map[string]ExecutionStatusCounts, error)
// GetPlannedExecutions returns executions in any of the given states
// ordered by scheduled_date ASC (soonest first), the order the Planned
// Purchases UI lists rows so the user acts on imminent purchases first.
// Distinct from GetExecutionsByStatuses (which is DESC for History's
// "newest first" semantics): when the result set exceeds `limit`, an
// ORDER-BY-DESC + LIMIT in SQL truncates away the soonest rows, exactly
// the rows this list must surface. Secondary sort by id ASC stabilizes
// ordering when multiple rows share a scheduled_date.
GetPlannedExecutions(ctx context.Context, statuses []string, limit int) ([]PurchaseExecution, error)
// GetStaleApprovedExecutions returns executions stuck in the "approved"
// status with updated_at older than olderThan — strands left behind when a
// synchronous purchase run was interrupted before finalizing (issue #632).
// The recovery sweep in the purchase manager re-drives these into a
// terminal "failed" state so they can never sit permanently approved.
GetStaleApprovedExecutions(ctx context.Context, olderThan time.Duration) ([]PurchaseExecution, error)
// GetExecutionByID retrieves a purchase execution by execution ID.
// Returns an error wrapping ErrNotFound when no execution exists;
// never returns (nil, nil). A nil error guarantees a non-nil execution.
GetExecutionByID(ctx context.Context, executionID string) (*PurchaseExecution, error)
GetExecutionByPlanAndDate(ctx context.Context, planID string, scheduledDate time.Time) (*PurchaseExecution, error)
// GetUserEmailByID resolves the email address of the auth user identified
// by userID (the `users` table, owned by internal/auth). Read-only helper
// used by the 4-eyes approval policy (issue #1005) to compare the acting
// approver's identity against a PurchaseExecution.CreatedByUserID without
// internal/purchase importing internal/auth (which would create an import
// cycle: internal/auth already imports internal/config). Returns ("", nil)
// when no user matches userID — the caller treats an empty result as
// "identity unresolved" and fails closed, never as "email intentionally
// blank".
GetUserEmailByID(ctx context.Context, userID string) (string, error)
// CountPendingExecutionsForAccount returns the number of purchase_executions
// in status 'pending' or 'notified' that reference the given cloud account.
// Used by the deleteAccount handler to preflight DB-level FK violations
// (migration 000053 tightened the FK to ON DELETE RESTRICT) and emit a
// 409 with a count so the frontend can offer Cancel-All-Then-Delete UX
// instead of surfacing a raw constraint error. See issue #606.
CountPendingExecutionsForAccount(ctx context.Context, accountID string) (int, error)
// CountLiveExecutionsForAccount returns the number of purchase_executions
// referencing the given cloud account whose status is not in
// TerminalExecutionStatuses (pending, notified, approved, running,
// scheduled, paused, or any status not yet classified). These are the
// rows that block DeleteCloudAccount; terminal rows are detached and kept
// as history instead (issue #265).
CountLiveExecutionsForAccount(ctx context.Context, accountID string) (int, error)
// ListPendingExecutionIDsForAccount returns the execution IDs of all
// pending / notified executions referencing this account, used by the
// frontend's Cancel-All-Then-Delete flow when the operator opts to
// cancel everything in one go after a 409. Capped at 1000 rows; if a
// single account has more pending executions than that, the cleanup
// is a one-off operator task rather than a button click anyway.
ListPendingExecutionIDsForAccount(ctx context.Context, accountID string) ([]string, error)
CleanupOldExecutions(ctx context.Context, retentionDays int) (int64, error)
// TransitionExecutionStatus atomically transitions an execution status.
// actor is the UUID of the user performing the transition (nil for system-initiated paths).
// When non-nil the actor is stamped onto transitioned_by + transitioned_at; when nil,
// transitioned_by is set to NULL and transitioned_at is still set to NOW() for ordering.
TransitionExecutionStatus(ctx context.Context, executionID string, fromStatuses []string, toStatus string, actor *string) (*PurchaseExecution, error)
// TransitionExecutionStatusPinned is TransitionExecutionStatus that also
// requires the row's recommendations to be empty (sawEmptyRecommendations)
// or non-empty exactly as the caller saw them, so a claim cannot land on a
// row whose recommendations were attached after the caller's gate check. A
// lost pin returns ErrExecutionNotInExpectedStatus like any lost CAS.
TransitionExecutionStatusPinned(ctx context.Context, executionID string, fromStatuses []string, toStatus string, actor *string, sawEmptyRecommendations bool) (*PurchaseExecution, error)
// TransitionExecutionStatusPinnedTx is TransitionExecutionStatusPinned
// inside a caller-owned transaction, so the status change commits or
// rolls back with the caller's other writes (issue #1052).
TransitionExecutionStatusPinnedTx(ctx context.Context, tx pgx.Tx, executionID string, fromStatuses []string, toStatus string, actor *string, sawEmptyRecommendations bool) (*PurchaseExecution, error)
// TransitionExecutionStatusTokenPinned is TransitionExecutionStatus that
// also requires the row's stored approval token hash to match rawToken and
// to be unexpired, in the same statement as the status change, so a token
// rotated or expired after the caller validated it cannot win the
// transition (issue #590). A lost token pin on a row still in an allowed
// status returns ErrApprovalTokenChanged; a lost status CAS returns
// ErrExecutionNotInExpectedStatus as usual.
TransitionExecutionStatusTokenPinned(ctx context.Context, executionID string, fromStatuses []string, toStatus string, actor *string, rawToken string) (*PurchaseExecution, error)
// ScheduleApprovedExecution moves a delayed approval to "scheduled" and
// stamps scheduled_execution_at (and approved_by when non-nil) in one
// transaction, so a failed stamp can never leave a scheduled row that no
// scheduler run picks up (#348 F6). It pins no approval token (session
// path); the errors match the two transition methods.
ScheduleApprovedExecution(ctx context.Context, executionID string, fromStatuses []string, transitionedBy *string, scheduledAt time.Time, approvedBy *string) (*PurchaseExecution, error)
// ScheduleApprovedExecutionTokenPinned is ScheduleApprovedExecution for the
// email-link path: it pins the approval token as
// TransitionExecutionStatusTokenPinned does and fails closed
// (ErrApprovalTokenChanged, no write) on an empty rawToken. The split keeps
// a future caller that passes "" from silently skipping the pin (#1794).
ScheduleApprovedExecutionTokenPinned(ctx context.Context, executionID string, fromStatuses []string, transitionedBy *string, rawToken string, scheduledAt time.Time, approvedBy *string) (*PurchaseExecution, error)
// RescheduleAwaitingExecution sets scheduled_date on an execution that is
// still pending or notified and touches no other column. It returns false
// (and writes nothing) when the row has left those statuses, so a cancel or
// approve that lands first is never overwritten.
RescheduleAwaitingExecution(ctx context.Context, executionID string, scheduledDate time.Time) (bool, error)
// SetCancelledBy stamps canceled_by on an execution without overwriting
// any other columns. Used after TransitionExecutionStatus to fold the actor
// attribution into the same logical write without the full-row
// SavePurchaseExecution clobber risk (Finding #5 / PR #889).
SetCancelledBy(ctx context.Context, executionID string, cancelledBy string) error
// LinkRetryExecutionAtomic stamps retry_execution_id on a failed
// execution row without a full-row overwrite, conditional on
// status = 'failed' AND retry_execution_id IS NULL. Replaces a
// SavePurchaseExecutionTx upsert of a stale in-memory copy of the
// failed row, which let two concurrent retries of the same row both
// pass the in-memory already-retried guard and both persist an
// approvable successor (issue #220). Returns (true, nil) when this
// call won the race, (false, nil) when a concurrent retry already
// claimed the row (or it left 'failed'), and (false, err) on a real
// DB error. Must be called inside the same tx that inserts the
// successor row, after that insert.
LinkRetryExecutionAtomic(ctx context.Context, tx pgx.Tx, executionID, retryExecutionID string) (linked bool, err error)
// LinkUnsentRetryExecutionAtomic is LinkRetryExecutionAtomic with the extra
// condition no_submission AND retry_attempt_n = 0 (a proven-unsent first
// attempt). The handler uses it for retries it allowed only on that proof.
LinkUnsentRetryExecutionAtomic(ctx context.Context, tx pgx.Tx, executionID, retryExecutionID string) (linked bool, err error)
// LockLadderTrancheForRetryTx row-locks the ladder tranche whose id equals
// idempotencyKey (matched as text; found=false for any non-ladder key) so
// Retry can refuse a settled tranche before inserting a successor.
LockLadderTrancheForRetryTx(ctx context.Context, tx pgx.Tx, idempotencyKey string) (status ladder.TrancheStatus, found bool, err error)
// GetLadderExecutionGate returns the ladder config switches and run status
// behind the tranche whose id equals idempotencyKey (matched as text), or
// (nil, nil) for any non-ladder key. The executor rechecks it before a
// provider call and fails closed on error.
GetLadderExecutionGate(ctx context.Context, idempotencyKey string) (*LadderExecutionGate, error)
// RotatePendingApprovalToken sets approval_token_hash and its expiry only
// while the row is still pending/notified, touching no other column, so a
// re-notification can never clobber a concurrent approve/cancel the way a
// full-row upsert of a stale copy would. Returns false when the row left
// pending/notified (issue #103).
RotatePendingApprovalToken(ctx context.Context, executionID, tokenHash string, expiresAt time.Time) (rotated bool, err error)
// CancelExecutionAtomic atomically flips status from pending / notified
// to 'canceled' (canonical US spelling), setting canceled_by. The
// 'scheduled' status is NOT accepted here; scheduled rows are revoked via
// CancelScheduledExecutionAtomic (Gmail-style pre-fire delay revoke
// path, issue #291 wave-2) so the two flows surface distinct CAS race
// outcomes. Returns (true, "canceled", nil) on success and (false,
// currentStatus, nil) when zero rows were affected (the execution had
// already been approved or otherwise transitioned). Must be called
// inside a WithTx block so the suppression cleanup and the status flip
// commit atomically.
CancelExecutionAtomic(ctx context.Context, tx pgx.Tx, executionID string, cancelledBy *string) (canceled bool, currentStatus string, err error)
// CancelExecutionAtomicTokenPinned is CancelExecutionAtomic that also
// requires the row's stored approval token hash to match rawToken and to
// be unexpired, in the same statement as the status change, so a token
// rotated or expired after the email-link cancel validated it cannot
// cancel the row (issue #1190). A lost token pin on a row still
// pending/notified returns an error wrapping ErrApprovalTokenChanged; a
// lost status CAS returns (false, currentStatus, nil) as usual.
CancelExecutionAtomicTokenPinned(ctx context.Context, tx pgx.Tx, executionID string, cancelledBy *string, rawToken string) (canceled bool, currentStatus string, err error)
// CancelScheduledExecutionAtomic atomically flips status from 'scheduled' to
// 'canceled' (canonical US spelling), setting canceled_by. Used by the
// Gmail-style pre-fire delay revoke path (issue #291 wave-2) to cancel a
// scheduled execution at $0 before the scheduler fires the SDK call. The
// 'pending'/'notified' set accepted by CancelExecutionAtomic is
// intentionally not extended here so the two revoke flows surface distinct
// CAS race outcomes -- a scheduled row that the scheduler has already
// transitioned to 'approved' / 'running' must surface as a 410 ("window
// closed") rather than a 409 ("not pending"). Returns (true, "canceled",
// nil) on success and (false, currentStatus, nil) when zero rows were
// affected. Must be called inside a WithTx block.
CancelScheduledExecutionAtomic(ctx context.Context, tx pgx.Tx, executionID string, cancelledBy *string) (canceled bool, currentStatus string, err error)
// ListStuckExecutions returns executions in any of the given statuses
// whose updated_at is older than the given duration. Used by the
// reaper sweep (issue #678) to find rows stuck in approved/running
// after the synchronous executor failed mid-flight without flipping
// them to a terminal state. Oldest-stuck-first (ORDER BY updated_at
// ASC), capped at MaxListLimit per sweep.
ListStuckExecutions(ctx context.Context, statuses []string, olderThan time.Duration) ([]PurchaseExecution, error)
// GetScheduledExecutionsDue returns purchase_executions with
// status='scheduled' whose scheduled_execution_at is in the past
// (scheduled_execution_at <= NOW()). Used by the Gmail-style pre-fire
// delay scheduler tick (issue #291 wave-2) to find rows ready to fire.
// Oldest-due-first (ORDER BY scheduled_execution_at ASC), capped at
// MaxListLimit per sweep.
GetScheduledExecutionsDue(ctx context.Context) ([]PurchaseExecution, error)
HistoryStore
MarketplaceStore
RIExchangeStore
AccountStore
RecommendationStore
// SavePurchaseExecutionTx is the tx-accepting variant of
// SavePurchaseExecution. Used from executePurchase's WithTx block
// so the execution insert + suppression writes commit atomically.
SavePurchaseExecutionTx(ctx context.Context, tx pgx.Tx, execution *PurchaseExecution) error
// SaveExecutionIfStatusTx and RecoverReapedExecutionTx are the
// tx-accepting variants of SaveExecutionIfStatus and RecoverReapedExecution.
SaveExecutionIfStatusTx(ctx context.Context, tx pgx.Tx, execution *PurchaseExecution, expected []string) error
RecoverReapedExecutionTx(ctx context.Context, tx pgx.Tx, execution *PurchaseExecution) error
// StampFirstDispatchTx sets the lineage's first_dispatch_at on the
// running row (kept once set; minted only per the mint rule) and reports
// whether it is within horizon on the database clock.
StampFirstDispatchTx(ctx context.Context, tx pgx.Tx, executionID string, horizon time.Duration) (StampResult, error)
// LockRetryFamilyTx takes a transaction-scoped advisory lock on a fan-out
// key family so a root retry and an account-row retry serialize.
LockRetryFamilyTx(ctx context.Context, tx pgx.Tx, family string) error
// FamilyRetryClaimedTx reports whether a row of the opposite kind (account
// rows when selfIsRoot, the root otherwise) in the same plan and key family
// already has a retry successor. Call it under LockRetryFamilyTx.
FamilyRetryClaimedTx(ctx context.Context, tx pgx.Tx, family, planID, selfID string, selfIsRoot bool) (claimed bool, err error)
// PredecessorProvenUnsent reports whether executionID's retry predecessor
// is a no_submission attempt 0 row (the lineage provably sent nothing).
PredecessorProvenUnsent(ctx context.Context, executionID string) (bool, error)
// LockRedshiftTuplesTx takes a transaction-scoped advisory lock per
// distinct tuple, in sorted order, serializing dispatches that share one.
LockRedshiftTuplesTx(ctx context.Context, tx pgx.Tx, tuples []RedshiftTuple) error
// FindOpenRedshiftLineageConflictsTx returns the other open executions
// holding a Redshift rec for one of tuples that a dispatch of family must
// not race (see the implementation for the predicate).
FindOpenRedshiftLineageConflictsTx(ctx context.Context, tx pgx.Tx, selfID, family string, tuples []RedshiftTuple, accountID *string, horizon time.Duration, stamp time.Time, window, settle time.Duration) ([]RedshiftLineageConflict, error)
// GetRedshiftRetryClock returns how long ago an execution was last written
// and first dispatched, both measured on the database clock.
GetRedshiftRetryClock(ctx context.Context, executionID string) (RedshiftRetryClock, error)
// ListRecentSubmitsTx takes a per-creator transaction-scoped lock and
// returns the creator's web-submitted executions scheduled at or after
// since that are pending, in flight or bought. executePurchase's
// duplicate guard reads it inside the WithTx block that inserts the new
// execution, so concurrent identical submits serialize and a retry
// that arrives after a direct execute left "pending" is still seen.
ListRecentSubmitsTx(ctx context.Context, tx pgx.Tx, creatorID string, since time.Time) ([]PurchaseExecution, error)
// WithTx opens a pgx transaction, runs fn, and commits on success or
// rolls back on error. fn can call any *Tx method on the store to
// participate in the transaction. Nested transactions are not
// supported — fn must not call WithTx recursively.
WithTx(ctx context.Context, fn func(tx pgx.Tx) error) error
LadderStore
// Notification mutes (issue #297 / migration 000091).
// UpsertNotificationMute inserts or updates a mute row for (email, scope).
// Idempotent for row existence: calling it again for an already-muted
// address refreshes muted_at and replaces unmute_token if the token changes.
UpsertNotificationMute(ctx context.Context, recipientEmail, scope, unmuteToken string) error
// IsNotificationMuted returns true when (email, scope) has a row in
// muted_recipients. The email comparison is case-insensitive.
IsNotificationMuted(ctx context.Context, recipientEmail, scope string) (bool, error)
}
StoreInterface defines the methods required for configuration storage.
type StoredRecommendation ¶
type StoredRecommendation struct {
RowID string
Rec RecommendationRecord
}
StoredRecommendation is a decoded cache row with its table primary key.
type SuccessfulCollect ¶
SuccessfulCollect identifies a (provider, account) pair whose collection completed in the current cycle. UpsertRecommendations scopes the stale-row eviction DELETE to the union of these pairs so a partially- failed provider preserves the failed accounts' previous-cycle rows (the dashboard for those accounts isn't blanked out by transient cloud-API failures).
CloudAccountID is nil for the AWS ambient-credentials path (no registered account); the eviction collapses nil to the zero UUID via the same generated-column rule that applies to inserts, so ambient rows are evicted independently of any registered-account rows under the same provider.
type SuppressionVariant ¶
type SuppressionVariant struct {
AvailabilityZone string `json:"availability_zone"`
Platform string `json:"platform"`
Tenancy string `json:"tenancy"`
AZConfig string `json:"az_config,omitempty"`
}
SuppressionVariant is the part of the suppression key beyond the 6-tuple: the zonal EC2 availability zone, the EC2 platform and tenancy, and the AWS RDS az_config, the same fields the rec identity key carries (issues #792, #806, #408). Empty AvailabilityZone, Platform and Tenancy are known values (a regional rec, a non-EC2 rec), not wildcards. AZConfig is the exception: "" means "not applicable or unknown" and matches any az_config (see AppliesTo), because suppressions written before migration 000159 have none and must keep suppressing both the Single-AZ and the Multi-AZ rec.
Source Files
¶
- approval_token.go
- aws_partition.go
- azure_hold_carry.go
- commitment.go
- constants.go
- defaults.go
- errors.go
- interfaces.go
- interfaces_accounts.go
- interfaces_history.go
- interfaces_ladder.go
- interfaces_marketplace.go
- interfaces_plans.go
- interfaces_recommendations.go
- interfaces_ri_exchange.go
- ladder_amend.go
- ladder_cap.go
- ladder_provenance.go
- ladder_timeline.go
- ladder_timeline_od.go
- plan_group_target.go
- plan_schedule_command.go
- plan_schedule_receipt.go
- plan_schedule_roots.go
- plan_step_dates.go
- plan_veto_window.go
- purchase_plan_providers.go
- recommendation_enabled_providers.go
- recommendation_identity.go
- recommendation_overrides.go
- recommendation_payback.go
- recommendations_page.go
- resolver.go
- ri_exchange_direct_execution.go
- ri_exchange_direct_history.go
- ri_exchange_direct_list.go
- ri_exchange_direct_resolve.go
- store_postgres.go
- store_postgres_account_credentials.go
- store_postgres_attachable_root.go
- store_postgres_attempts.go
- store_postgres_claims.go
- store_postgres_cloud_accounts.go
- store_postgres_cloud_accounts_delete.go
- store_postgres_cloud_accounts_list.go
- store_postgres_cloud_accounts_update.go
- store_postgres_config_audit.go
- store_postgres_doomed_root.go
- store_postgres_execution_guarded.go
- store_postgres_execution_settle.go
- store_postgres_executions_cancel.go
- store_postgres_executions_cleanup.go
- store_postgres_executions_count.go
- store_postgres_executions_filtered.go
- store_postgres_executions_get.go
- store_postgres_executions_list.go
- store_postgres_executions_plan_locks.go
- store_postgres_executions_retry.go
- store_postgres_executions_save.go
- store_postgres_executions_scan.go
- store_postgres_executions_stale.go
- store_postgres_executions_transition.go
- store_postgres_expired_root.go
- store_postgres_expired_root_cas.go
- store_postgres_fan_out_shape.go
- store_postgres_first_dispatch.go
- store_postgres_global_config.go
- store_postgres_global_config_save.go
- store_postgres_global_config_update.go
- store_postgres_history_by_purchase.go
- store_postgres_history_filtered.go
- store_postgres_history_inflight.go
- store_postgres_history_listing.go
- store_postgres_history_page.go
- store_postgres_history_read.go
- store_postgres_history_save.go
- store_postgres_history_scan.go
- store_postgres_history_summary.go
- store_postgres_ladder.go
- store_postgres_ladder_amend.go
- store_postgres_ladder_amend_ceiling.go
- store_postgres_ladder_cancel.go
- store_postgres_ladder_ceiling.go
- store_postgres_ladder_claim_ceiling.go
- store_postgres_ladder_due.go
- store_postgres_ladder_lifecycle.go
- store_postgres_ladder_lock.go
- store_postgres_ladder_reconcile.go
- store_postgres_ladder_resolve.go
- store_postgres_ladder_rollup.go
- store_postgres_ladder_runs.go
- store_postgres_ladder_settled.go
- store_postgres_ladder_timeline.go
- store_postgres_managed_guard.go
- store_postgres_marketplace_attempt.go
- store_postgres_marketplace_settlement.go
- store_postgres_notification_mutes.go
- store_postgres_plan_accounts.go
- store_postgres_plan_accounts_read.go
- store_postgres_plan_mutations.go
- store_postgres_plan_schedule_clock.go
- store_postgres_plan_step.go
- store_postgres_plan_writes.go
- store_postgres_plans.go
- store_postgres_plans_list.go
- store_postgres_ramp_baseline.go
- store_postgres_ramp_step.go
- store_postgres_ramp_target_met.go
- store_postgres_recommendations.go
- store_postgres_recommendations_collection.go
- store_postgres_recommendations_insert.go
- store_postgres_recommendations_page.go
- store_postgres_recommendations_page_sql.go
- store_postgres_recommendations_prune.go
- store_postgres_recommendations_read.go
- store_postgres_recommendations_scan.go
- store_postgres_redshift_lineage.go
- store_postgres_redshift_retry.go
- store_postgres_registrations.go
- store_postgres_retry_family.go
- store_postgres_revocation_return.go
- store_postgres_ri_exchange_cancel.go
- store_postgres_ri_exchange_ceiling.go
- store_postgres_ri_exchange_direct.go
- store_postgres_ri_exchange_direct_get.go
- store_postgres_ri_exchange_direct_history.go
- store_postgres_ri_exchange_direct_list.go
- store_postgres_ri_exchange_direct_resolve.go
- store_postgres_ri_exchange_queries.go
- store_postgres_ri_exchange_reserve.go
- store_postgres_ri_exchange_resolve.go
- store_postgres_ri_exchange_save.go
- store_postgres_ri_exchange_source_guard.go
- store_postgres_ri_exchange_spend.go
- store_postgres_ri_exchange_status.go
- store_postgres_ri_utilization.go
- store_postgres_schema_version.go
- store_postgres_service_config.go
- store_postgres_service_config_update.go
- store_postgres_service_overrides.go
- store_postgres_suppressions.go
- suppressions_build.go
- types.go
- types_accounts.go
- types_executions.go
- types_history.go
- types_ladder.go
- types_recommendations.go
- types_recommendations_freshness.go
- validation.go
- validation_bound_groups.go
- validation_ladder.go
- validation_payment.go
- validation_plan.go