insurance

package
v0.0.0-...-b2804b8 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: OSL-3.0 Imports: 19 Imported by: 0

Documentation

Overview

Package insurance is the shared bounded context for Archera insured-commitment quote previews across the CLI, MCP server, and platform consumers.

Contract basis (public documentation only, no live calls in this package's tests):

  • Operation: GET /v1/org/{org_id}/commitment-plans/{plan_id}/comparison, response schema LineItemOfferComparisonResponse (docs.archera.ai/api-reference/public-api/commitment-plans.md)
  • Auth: x-api-key header on https://api.archera.ai (docs.archera.ai/api-reference/public-api/api-key-access.md)

Invariants every consumer must preserve:

  • archera_premium is already included in commitment_cost.total. Money decoded from the API passes through verbatim; this package deliberately has no helper that adds or subtracts a premium from an API total.
  • All commitment_financials_monthly_rate blocks are 730-hour monthly rates. commitment_upfront_cost is one-time dollars at signing and is never summed with a rate.
  • The API schemas carry no currency field; Currency stays nil (unknown). Nil money fields are unknown, never silently zero.
  • No documented quote TTL or expiry exists; FetchedAt records when the data was retrieved and freshness policy belongs to the consumer.
  • A plan comparison is a hypothetical rollup, never a bindable insurance quote, and never a purchase. An insured target of 100% is a requested target subject to Archera underwriting allowances, not a guarantee. The API exposes no per-line product support or allowance verdict, so consumers render both as unknown.

Index

Constants

View Source
const BaseURL = "https://api.archera.ai"

BaseURL is the fixed Archera API origin. Callers cannot override it; tests use the unexported newClient with an httptest origin.

Variables

This section is empty.

Functions

func ContractTerms

func ContractTerms() []string

ContractTerms returns the documented Archera contract_term values accepted in ComparisonRequest.ContractTerms and returned in the ContractTerm fields, as a new slice on every call. The order is lexicographic, which is NOT a duration order ("eleven_month" sorts before "five_month"); a consumer that shows the terms to people must impose its own ordering.

Types

type Client

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

Client is the real read-only QuoteClient. It issues single-shot GETs and never follows redirects, so the API key cannot be forwarded to another host.

The API key is held only inside the setAuth and redact closures, never in a field fmt or reflection can read, so no fmt verb prints it wherever the Client (or a pointer to it) is stored.

func NewClient

func NewClient(cfg Config, hc *http.Client) (*Client, error)

NewClient returns a Client for the fixed Archera origin. hc is optional; nil uses the shared SSRF-hardened client with a 30-second timeout.

func (*Client) Comparison

func (c *Client) Comparison(ctx context.Context, req ComparisonRequest) (*Comparison, error)

Comparison reads the documented comparison operation. Empty request slices follow the documented defaults.

func (*Client) LineItems

func (c *Client) LineItems(ctx context.Context, planID string) ([]LineItem, error)

LineItems returns all paginated rows or an error; partial pages never escape.

func (*Client) Plan

func (c *Client) Plan(ctx context.Context, planID string) (*Plan, error)

Plan reads the documented CommitmentPlan operation.

type Comparison

type Comparison struct {
	OrgID string
	// PlanID is an Archera plan identifier, not a local recommendation ID.
	PlanID string
	// Current is the plan-wide rollup for the line items currently in scope.
	Current Totals
	// Hypotheticals holds one rollup per requested (or candidate-derived)
	// (contract term, payment option) combination.
	Hypotheticals []Hypothetical
	// Rows holds per-line current and candidate offers, in vendor order
	// (by line item ID).
	Rows []ComparisonRow
	// Currency is always nil with the current API schemas: no currency field
	// is documented. Consumers must render it as unknown.
	Currency *string
	// FetchedAt records when the response was retrieved; there is no
	// documented TTL, so staleness policy belongs to the consumer.
	FetchedAt time.Time
}

Comparison is the decoded result of the documented comparison operation. Vendor totals pass through verbatim with the premium already inside them. It is a plan hypothetical, not a bindable quote.

func DecodeComparison

func DecodeComparison(r io.Reader, orgID, planID string, fetchedAt time.Time) (*Comparison, error)

DecodeComparison parses exactly one LineItemOfferComparisonResponse JSON value and maps it into the shared Comparison type. orgID and planID come from the request, not the response body. fetchedAt is recorded verbatim; the API documents no TTL.

type ComparisonRequest

type ComparisonRequest struct {
	PlanID         string
	LineItemIDs    []string
	ContractTerms  []string
	PaymentOptions []PaymentOption
}

ComparisonRequest selects the line items, target terms, and payment options for a comparison read. Empty slices follow the documented defaults: all selected line items, every distinct candidate term, no_upfront only.

type ComparisonRow

type ComparisonRow struct {
	LineItemID string
	Current    OfferEntry
	Candidates []OfferEntry
}

ComparisonRow mirrors LineItemOfferComparisonRow: a line item's current offer plus its alternatives, ordered by the vendor (monthly net savings descending).

type Config

type Config struct {
	APIKey Secret
	OrgID  string
}

Config identifies the vendor organization and credential. APIKey is sent only as the x-api-key header. Secret redacts itself under every printer, so a Config is safe to print or hold in any struct field.

type Financials

type Financials struct {
	// CommitmentCostTotal is the headline monthly cost paid:
	// CloudProviderCost + Premium, with the premium already included.
	CommitmentCostTotal *big.Rat
	// CloudProviderCost is the amortized monthly cost paid to the cloud
	// provider.
	CloudProviderCost *big.Rat
	// Premium is archera_premium. Already included in CommitmentCostTotal;
	// never add it on top or subtract it again.
	Premium *big.Rat
	// GrossSavings is savings before the premium.
	GrossSavings *big.Rat
	// NetSavings is savings after the premium. It can be negative.
	NetSavings *big.Rat
	// CoveredOnDemandCost is the on-demand cost of usage covered by
	// commitments: the savings baseline, not a cost the user pays.
	CoveredOnDemandCost *big.Rat
}

Financials mirrors the documented CommitmentFinancialsNoRebate schema. Every field is a 730-hour monthly rate. Any field may be nil: the nested API schemas declare no required properties, so absent means unknown, never zero.

type HTTPError

type HTTPError struct {
	StatusCode int
	// RetryAfter is the parsed Retry-After header, zero when absent or not a
	// number of seconds. The client never retries on its own.
	RetryAfter time.Duration
	Message    string
}

HTTPError is a non-2xx vendor response. Only the status, the Retry-After header and a truncated message from the documented error shapes are kept; the raw body is never echoed.

func (*HTTPError) Error

func (e *HTTPError) Error() string

type Hypothetical

type Hypothetical struct {
	// ContractTerm is nullable in the schema.
	ContractTerm  *string
	PaymentOption PaymentOption
	Totals        Totals
	// Deltas compare this hypothetical against the CURRENT plan, not against
	// on-demand. Positive DeltaMonthlyNetSavings means switching saves more
	// than the plan does today.
	DeltaMonthlyNetSavings     *big.Rat
	DeltaMonthlyCommitmentCost *big.Rat
	// DeltaUpfrontCost is one-time dollars, NOT a rate.
	DeltaUpfrontCost *big.Rat
	LineItems        []HypotheticalLineItem
}

Hypothetical mirrors the documented HypotheticalTotal schema: the plan-wide rollup for one (contract term, payment option) combination.

type HypotheticalLineItem

type HypotheticalLineItem struct {
	LineItemID           string
	ActualTerm           *string
	ActualPaymentOption  *PaymentOption
	ActualCommitmentType *string
	Reason               TermReason
}

HypotheticalLineItem mirrors the documented HypotheticalLineItem schema: how one line item actually lands inside a hypothetical rollup. The three Actual* identities are nullable in the schema; nil means the vendor sent null. It carries no lease, so it never says whether the line is guaranteed.

type LineItem

type LineItem struct {
	ID, PlanID, OfferID string
	AccountID           *string
	SelectedQuantity    int64
	SelectedCommitment  *big.Rat
	IsSelected          bool
	ContractTerm        string
	PaymentOption       PaymentOption
	ContractSpec        LineItemContractSpec
	Offer               LineItemOffer
}

LineItem retains purchase identity without inferring missing account or offer attributes. ID, PlanID and OfferID keep the vendor's case; compare UUIDs case-insensitively (strings.EqualFold) when joining to comparison line_item_id values.

func DecodeLineItems

func DecodeLineItems(r io.Reader, planID string) ([]LineItem, error)

DecodeLineItems rejects incomplete identity and preserves explicit null attributes.

type LineItemContractSpec

type LineItemContractSpec struct {
	CommitmentType string         `json:"commitment_type"`
	Term           *string        `json:"term"`
	PaymentOption  *PaymentOption `json:"payment_option"`
}

LineItemContractSpec preserves the vendor's explicit terms for consistency checks.

type LineItemOffer

type LineItemOffer struct {
	ID                 string
	ProviderOfferingID string
	Type               string
	Provider           common.ProviderType
	OfferingID         *string
	Region             *string
	AZ                 *string
	InstanceType       *string
	InstanceFamily     *string
	ProductDescription *string
	Tenancy            *string
	PlanType           *string
	IsMultiAZ          *bool
	IsFlexible         *bool
	DurationSeconds    *big.Rat
	OfferingClass      *string
	PaymentOption      *PaymentOption
}

LineItemOffer keeps provider and catalog offering identifiers distinct.

type OfferDelta

type OfferDelta struct {
	MonthlyNetSavings *big.Rat
	// UpfrontCost is one-time dollars, NOT a rate.
	UpfrontCost  *big.Rat
	DiscountRate *big.Rat
	// BreakevenDays is nil when either side has no finite breakeven.
	BreakevenDays *big.Rat
}

OfferDelta mirrors OfferComparisonDelta: the vendor's candidate-minus-current difference, passed through so no consumer recomputes it.

type OfferEntry

type OfferEntry struct {
	// IsCurrent is true when this entry matches the line item's current
	// offer and lease.
	IsCurrent bool
	OfferID   string
	// SelectedAmount is a count for RI/unit CUD, or $/hour for spend commitments.
	SelectedAmount *big.Rat
	// CommitmentType is the vendor's offer type string. The docs give both
	// "aws/AmazonEC2"-style and "ri"/"savings_plan"/"cud"-style examples;
	// treat it as opaque display text.
	CommitmentType string
	Provider       common.ProviderType
	// ContractTerm is the effective lock-in term (lease lock-in when a lease
	// is attached). Nullable in the schema.
	ContractTerm *string
	// PaymentOption is nullable in the schema.
	PaymentOption *PaymentOption
	// LeaseMenuItemID is the attached Archera lease, nil for none.
	LeaseMenuItemID *string
	// GuaranteedDisplayName is the offer name when purchased as an Archera
	// Guaranteed Commitment; nil when the vendor sends none.
	GuaranteedDisplayName *string
	// Region is nil when the offer does not report one.
	Region *string
	// DiscountRate is the discount versus on-demand on a 0-1 basis.
	DiscountRate *big.Rat
	// BreakevenDays is nil when breakeven is undefined.
	BreakevenDays *big.Rat
	// Monthly holds the 730-hour monthly rate financials.
	Monthly Financials
	// UpfrontCost is one-time dollars at signing, NOT a rate.
	UpfrontCost *big.Rat
	Delta       OfferDelta
}

OfferEntry mirrors the consumed subset of OfferComparisonEntry: one offer (current or candidate) for a line item.

func (OfferEntry) LeaseBacked

func (e OfferEntry) LeaseBacked() bool

LeaseBacked reports whether an Archera lease is attached to this offer. The API does not state that this means guaranteed or insured, and it is not evidence of active protection; render it as "lease attached".

type PaymentOption

type PaymentOption string

PaymentOption is the comparison schema's payment option enum.

const (
	PaymentNoUpfront      PaymentOption = "no_upfront"
	PaymentPartialUpfront PaymentOption = "partial_upfront"
	PaymentAllUpfront     PaymentOption = "all_upfront"
)

type Plan

type Plan struct {
	ID     string
	Status PlanStatus
	// IsCalculating is true while Archera recomputes the plan; consumers
	// show a non-final state instead of treating the figures as current.
	IsCalculating bool
	// FeeHourly is the vendor's fee_hourly, unit basis undocumented.
	FeeHourly *big.Rat
	// SavingsHourly is the vendor's savings_hourly, unit basis undocumented.
	SavingsHourly *big.Rat
	// CommitmentCoverage is the vendor's commitment_coverage; its scale
	// (0-1 or percent) is undocumented. It is native commitment coverage,
	// never insured coverage.
	CommitmentCoverage *big.Rat
	// MonthlySavings is the vendor's monthly_savings, basis undocumented.
	MonthlySavings *big.Rat
}

Plan mirrors the subset of the documented CommitmentPlan schema that consumers display. The schema gives these numbers no description or unit; render them verbatim with their vendor field names and never convert them (no hourly-to-monthly scaling, no percent conversion of CommitmentCoverage).

func DecodePlan

func DecodePlan(r io.Reader) (*Plan, error)

DecodePlan parses exactly one CommitmentPlan JSON value.

type PlanStatus

type PlanStatus string

PlanStatus mirrors the documented CommitmentPlan.status enum.

const (
	PlanStatusNew         PlanStatus = "new"
	PlanStatusReviewed    PlanStatus = "reviewed"
	PlanStatusScheduled   PlanStatus = "scheduled"
	PlanStatusCompleted   PlanStatus = "completed"
	PlanStatusDraft       PlanStatus = "draft"
	PlanStatusNeedsReview PlanStatus = "needs_review"
	PlanStatusInProgress  PlanStatus = "in_progress"
	PlanStatusCancelled   PlanStatus = "cancelled" //nolint:misspell // vendor wire value
)

type ProductSupport

type ProductSupport struct {
	Status ProductSupportStatus
	// Source is the documentation URL a non-unknown verdict rests on.
	Source string
	// Evidence is the statement quoted from Source.
	Evidence string
}

ProductSupport is the documentation-derived verdict for one commitment type.

func AssessProductSupport

func AssessProductSupport(provider common.ProviderType, commitmentType string) ProductSupport

AssessProductSupport looks up the documented support verdict for a provider and vendor commitment_type. Anything not in the table, including every unrecognized type string, is ProductSupportUnknown.

type ProductSupportStatus

type ProductSupportStatus string

ProductSupportStatus is whether Archera's public documentation states that a commitment type is offered as a Guaranteed Commitment. It says nothing about underwriting allowances or a customer's eligibility: the API exposes neither, and a "supported" product can still be capped or refused. Consumers render allowance and customer eligibility as unknown in every case.

const (
	// ProductSupportSupported means the documentation lists guaranteed terms
	// for the type.
	ProductSupportSupported ProductSupportStatus = "supported"
	// ProductSupportUnknown means the documentation was not matched to this
	// type, which is the default.
	ProductSupportUnknown ProductSupportStatus = "unknown"
)

type QuoteClient

type QuoteClient interface {
	Comparison(ctx context.Context, req ComparisonRequest) (*Comparison, error)
	Plan(ctx context.Context, planID string) (*Plan, error)
}

QuoteClient is the read-only seam implemented by Client. It has no method that creates, updates, applies, or binds anything.

type Secret

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

Secret holds a credential so that no printer can reach it. The value lives only in a closure, so reflection-based printers (fmt on unexported fields, spew, encoders) see a func address, never the string. The zero Secret holds the empty string.

func NewSecret

func NewSecret(s string) Secret

NewSecret wraps a credential.

func (Secret) Format

func (Secret) Format(f fmt.State, _ rune)

Format redacts the value for every fmt verb and for slog text output.

func (Secret) MarshalText

func (Secret) MarshalText() ([]byte, error)

MarshalText redacts the value for encoding/json, encoding/xml, yaml and slog's JSON handler.

func (Secret) Reveal

func (s Secret) Reveal() string

Reveal returns the credential. Call it only where the value is sent, such as the header-set site.

type TermReason

type TermReason string

TermReason explains why a line item landed at its actual term inside a hypothetical rollup. Values mirror the documented actual_term_reason enum.

const (
	// TermReasonExactMatch means the target term was available.
	TermReasonExactMatch TermReason = "exact_match"
	// TermReasonFallbackShorter means the longest available term at or below
	// the target with the same payment option was used.
	TermReasonFallbackShorter TermReason = "fallback_closest_shorter"
	// TermReasonNoAlternative means nothing qualified and the line item kept
	// its current term.
	TermReasonNoAlternative TermReason = "no_alternative"
	// TermReasonBundleMember means the line item belongs to a GPU CUD bundle
	// that cannot be term-swapped per member, so it kept its current term.
	TermReasonBundleMember TermReason = "bundle_member"
)

type Totals

type Totals struct {
	// Monthly holds the 730-hour monthly rate financials.
	Monthly Financials
	// UpfrontCost is one-time dollars due at signing (required by the
	// schema). It is NOT a rate and must never be summed with Monthly.
	UpfrontCost *big.Rat
}

Totals mirrors LineItemOfferComparisonTotals: plan-wide rollup for a set of line items.

Jump to

Keyboard shortcuts

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