app

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const (
	StageAdmit   = "admit"
	StageSettle  = "settle"
	StageRelease = "release"
	StageQuery   = "query"

	ProviderUsageAuthority = "usage_authority"

	OutcomeOK          = "ok"
	OutcomeDeny        = "deny"
	OutcomeTimeout     = "timeout"
	OutcomeError       = "error"
	OutcomeCanceled    = "canceled"
	OutcomeDisabled    = "disabled"
	OutcomeUnavailable = "unavailable"
)

Variables

View Source
var (
	ErrDisabled            = &Error{kind: "disabled"}
	ErrDegraded            = &Error{kind: "degraded"}
	ErrUnavailable         = &Error{kind: "unavailable"}
	ErrCapacityExceeded    = &Error{kind: "capacity_exceeded"}
	ErrReservationConflict = &Error{kind: "reservation_conflict"}
	ErrDuplicateSettlement = &Error{kind: "duplicate_settlement"}
	ErrInvalidQuery        = &Error{kind: "invalid_query"}
	ErrUnsupportedFilter   = &Error{kind: "unsupported_filter"}
	ErrEvaluationTimeout   = &Error{kind: "evaluation_timeout"}
	// ErrRequiredEvidence identifies a recorder failure that must prevent
	// protected pre-work from starting. Best-effort evidence failures use the
	// ordinary unavailable/error paths instead.
	ErrRequiredEvidence = &Error{kind: "required_evidence"}
)

Functions

func ProjectAccountingAuthorityEvent

func ProjectAccountingAuthorityEvent(status domain.AuthorityStatus, reserved bool, in Evidence) (controlplane.Event, error)

ProjectAccountingAuthorityEvent projects safe accounting evidence into a control-plane accounting-authority event.

func ProjectPolicyDecision

func ProjectPolicyDecision(status domain.AuthorityStatus, reserved bool, in Evidence) (policydecision.Record, bool)

ProjectPolicyDecision projects safe accounting evidence into policydecision records.

func ReleaseSequence

func ReleaseSequence(kind ReleaseKind) int

ReleaseSequence preserves the reservation-level release idempotency key. Releases are terminal for a reservation, so distinct release labels must still converge on the same replay sequence.

func ReservationFailureRuleID

func ReservationFailureRuleID(err error) string

ReservationFailureRuleID returns the originating rule for an attributed reservation failure. Store-wide failures intentionally return no rule ID.

func SettlementSequence

func SettlementSequence(kind SettlementKind, authority domain.AuthorityLevel) int

SettlementSequence returns the stable replay sequence for one lifecycle stage. Authoritative final reconciliation is deliberately distinct from an estimated final settlement even though both use SettlementKindFinal.

func SnapshotStateFromAuthority

func SnapshotStateFromAuthority(st domain.AuthorityStatus) economics.SnapshotState

SnapshotStateFromAuthority maps usage-authority status onto economics.SnapshotState.

func WrapError

func WrapError(kind *Error, op string, err error) error

WrapError annotates an authority error with operation context while preserving sentinel matching through errors.Is.

Types

type ActiveLimitQuery

type ActiveLimitQuery struct {
	RuleID     string
	Dimensions domain.Dimensions
	At         time.Time
}

ActiveLimitQuery resolves one configured rule's current live row using the same normalized dimensions and window time as reservation matching.

type AdmissionInput

type AdmissionInput struct {
	Correlation    controlplane.Correlation
	Scope          scope.PrincipalScopeView
	Dimensions     domain.Dimensions
	Request        domain.Amount
	RequestCount   domain.Amount
	PreflightUsage domain.PreflightUsage
	Authority      domain.AuthorityLevel
	ReservationKey domain.ReservationKey
	EstimateOnly   bool
	// SkipEvidence suppresses durable policy/accounting evidence projection.
	// Clamp preview uses this with EstimateOnly so repeated preview admits do
	// not write audit noise; estimate-only precheck denials still record.
	SkipEvidence bool
	// Phase 7.2: lifecycle stage for rule filtering; exposure/facts for amount selection.
	LifecycleScope metering.LifecycleScope
	Perspective    metering.EconomicPerspective
	Exposure       economics.ExposureBasis
	Facts          []metering.Fact
}

AdmissionInput carries the safe quantity data required for pre-backend quota admission.

type AdmissionReservation

type AdmissionReservation struct {
	ReservationID  string
	RuleID         string
	ReservedAmount domain.Amount
}

AdmissionReservation reports one applied reservation created by Admit. The legacy single-reservation fields on AdmissionResult remain the primary reservation for compatibility with older callers.

type AdmissionResult

type AdmissionResult struct {
	Allowed bool
	Outcome domain.DecisionOutcome
	RuleIDs []string
	// AdvisoryRuleIDs are the matched rules configured with RuleModeAdvisory.
	// They are tracked separately from RuleIDs so the runtime can apply final
	// advisory usage to advisory windows even when no strict reservation was
	// created (requirement 7.7). Advisory rules never reserve.
	AdvisoryRuleIDs []string
	// UnreservedRuleIDs are matched rules whose allowed execution created no
	// reservation (advisory and strict fail-open paths). Their final usage is
	// applied through ApplyUsage at lifecycle completion.
	UnreservedRuleIDs []string
	// SelectedRuleID identifies the rule whose outcome won admission severity.
	// RuleIDs remains the complete matched set for multi-rule evidence.
	SelectedRuleID  string
	RuleKind        domain.RuleKind
	ReservationID   string
	Reserved        bool
	ReservedAmount  domain.Amount
	Reservations    []AdmissionReservation
	PolicyRecord    policydecision.Record
	AccountingEvent controlplane.Event
	// BoundVersion is the policy snapshot identity captured at admission (11.2).
	BoundVersion economics.PolicySnapshotRef
	// BoundRatingVersion is the rating/catalog snapshot identity when known (14.3).
	BoundRatingVersion economics.RatingSnapshotRef
}

AdmissionResult reports the legal pre-backend accounting decision.

type ApplyUsageCommand

type ApplyUsageCommand struct {
	Correlation          controlplane.Correlation
	Scope                scope.PrincipalScopeView
	Dimensions           domain.Dimensions
	RuleIDs              []string
	Usage                domain.PreflightUsage
	RequestCount         domain.Amount
	Authority            domain.AuthorityLevel
	MeasurementAuthority MeasurementAuthority
	Kind                 SettlementKind
	UsagePresent         bool
	At                   time.Time
	SourceKey            string
}

ApplyUsageCommand applies final quantity usage to matched advisory or otherwise unreserved accounting windows without creating a reservation.

type ApplyUsageResult

type ApplyUsageResult struct {
	Applied bool
	RuleIDs []string
}

ApplyUsageResult reports which advisory windows were updated. Applied is true when at least one matched rule's window consumed usage. RuleIDs lists the rules that were actually updated (rules with no matching live window are skipped).

type Clock

type Clock interface {
	Now() time.Time
}

Clock reports the current time for deterministic orchestration and tests. A nil Clock means "use system wall-clock time" (see Service.now).

type DecisionHistoryResult

type DecisionHistoryResult struct {
	State QueryState
	Page  controlplane.Page[controlplane.AccountingDecisionRow]
}

type Error

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

Error is the stable application error wrapper used for authority orchestration failures.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Is

func (e *Error) Is(target error) bool

func (*Error) Unwrap

func (e *Error) Unwrap() error

type Evidence

type Evidence struct {
	At              time.Time
	Correlation     controlplane.Correlation
	Scope           scope.PrincipalScopeView
	RuleID          string
	MatchedRuleIDs  []string
	RuleType        string
	Outcome         controlplane.AccountingOutcome
	ReasonCode      policydecision.AccountingReasonCode
	ReservationID   string
	SettlementState controlplane.AccountingSettlementState
	// SourceKind and SourceSequence are included in event identity for mutation
	// stages. Admission evidence leaves them empty and zero.
	SourceKind       string
	SourceSequence   int
	Unit             string
	Limit            int64
	Consumed         int64
	Reserved         int64
	Adjustment       int64
	Authority        domain.AuthorityLevel
	Stage            string
	BackendAttempted bool
	OutputCommitted  bool
	// Dual-plane identity and version refs (requirements 1.6, 14.3, 17.4).
	AuthorityNamespace string
	Perspective        string
	LifecycleScope     string
	Basis              string
	RuleVersion        string
	Surfaced           string
	ReservationType    string
	ParentRequestID    string
	BoundPolicyVersion economics.PolicySnapshotRef
	BoundRatingVersion economics.RatingSnapshotRef
}

Evidence is the slim, varying subset of fields that an admission, settlement, or release call site contributes to the policydecision and control-plane projectors. Authority, WindowStart/End/ResetAt, Remaining, and the non-varying source identity, visibility, evidence/redaction state are derived by the projector from (status, reserved, in).

func EnrichEvidenceWithRule

func EnrichEvidenceWithRule(in Evidence, rules []domain.Rule) Evidence

EnrichEvidenceWithRule returns evidence with dual-plane rule identity applied.

type EvidenceSink

type EvidenceSink interface {
	RecordPolicyDecision(ctx context.Context, record policydecision.Record) error
	RecordAccountingAuthority(ctx context.Context, event controlplane.Event) error
}

EvidenceSink projects app outcomes into policydecision and control-plane evidence without exposing storage or HTTP concerns.

type LimitStatusResult

type LimitStatusResult struct {
	State QueryState
	Page  controlplane.Page[controlplane.AccountingLimitStatusRow]
}

LimitStatusResult and DecisionHistoryResult are bounded query DTOs that keep live authority state distinct from historical rows.

type MeasurementAuthority

type MeasurementAuthority struct {
	Usage domain.AuthorityLevel
}

MeasurementAuthority describes the evidence authority for quantity facts.

func (MeasurementAuthority) ForUnit

type QueryState

type QueryState string

QueryState classifies the bounded live authority query posture.

const (
	QueryStateDisabled     QueryState = "disabled"
	QueryStateEmpty        QueryState = "empty"
	QueryStateUnsupported  QueryState = "unsupported"
	QueryStateTooBroad     QueryState = "too_broad"
	QueryStateAdvisoryOnly QueryState = "advisory_only"
	QueryStateDegraded     QueryState = "degraded"
	QueryStateUnavailable  QueryState = "unavailable"
	QueryStateReady        QueryState = "ready"
)

type ReleaseCommand

type ReleaseCommand struct {
	Reservations     []ReleaseDescriptor
	Correlation      controlplane.Correlation
	Scope            scope.PrincipalScopeView
	ReleaseKey       domain.ReleaseKey
	ReservationKey   domain.ReservationKey
	ReservationID    string
	RuleID           string
	Kind             ReleaseKind
	Amount           domain.Amount
	Authority        domain.AuthorityLevel
	Stage            string
	BackendAttempted bool
	OutputCommitted  bool
	At               time.Time
	SourceKey        string
}

type ReleaseDescriptor

type ReleaseDescriptor struct {
	Reservation ReservationDescriptor
	SourceKey   string
	Sequence    int
}

ReleaseDescriptor carries one rule's reservation to release. The store applies all descriptors in one atomic operation.

type ReleaseInput

type ReleaseInput struct {
	Reservations   []ReleaseDescriptor
	Correlation    controlplane.Correlation
	Scope          scope.PrincipalScopeView
	ReservationKey domain.ReservationKey
	ReservationID  string
	RuleID         string
	Kind           ReleaseKind
	// Sequence distinguishes release stages that share one reservation identity.
	Sequence         int
	Amount           domain.Amount
	Authority        domain.AuthorityLevel
	Stage            string
	BackendAttempted bool
	OutputCommitted  bool
}

ReleaseInput carries the safe request data required to release a reservation without attributing surfaced usage to the released attempt.

func DeriveReleaseScalars

func DeriveReleaseScalars(in ReleaseInput) ReleaseInput

DeriveReleaseScalars copies aggregate fields from the first reservation descriptor when callers supply only the descriptor set (runtime lifecycle path).

type ReleaseKind

type ReleaseKind string

ReleaseKind classifies the release path for swallowed or losing attempts.

const (
	ReleaseKindSwallowed        ReleaseKind = "swallowed"
	ReleaseKindLosing           ReleaseKind = "losing"
	ReleaseKindAdmissionFailure ReleaseKind = "admission_failure"
)

type ReleaseMutation

type ReleaseMutation struct {
	RuleID        string
	ReservationID string
	ReleasedDelta domain.Amount
}

ReleaseMutation contains the per-rule result of one atomic release set.

type ReleaseResult

type ReleaseResult struct {
	Applied          bool
	ReservationID    string
	ReleasedDelta    domain.Amount
	Mutations        []ReleaseMutation
	PolicyRecords    []policydecision.Record
	AccountingEvents []controlplane.Event
	PolicyRecord     policydecision.Record
	AccountingEvent  controlplane.Event
}

ReleaseResult reports the release outcome for swallowed or losing attempts.

type ReservationCapacityError

type ReservationCapacityError struct {
	Requested domain.Amount
	Remaining domain.Amount
}

ReservationCapacityError reports a successful atomic determination that a strict window lacks capacity. It remains a reservation conflict for older callers, but admission must never treat it as unavailable infrastructure.

func (*ReservationCapacityError) Error

func (e *ReservationCapacityError) Error() string

func (*ReservationCapacityError) Is

func (e *ReservationCapacityError) Is(target error) bool

type ReservationDescriptor

type ReservationDescriptor struct {
	RuleID         string
	Kind           domain.RuleKind
	Unit           domain.AmountUnit
	Dimensions     domain.Dimensions
	ReservationKey domain.ReservationKey
	ReservationID  string
	Amount         domain.Amount
	SourceKey      string
	Authority      domain.AuthorityLevel
}

ReservationDescriptor is the app-owned, per-rule mutation descriptor. A reservation set is passed to the store as one logical operation so every matched strict rule observes the same atomic commit boundary.

type ReservationSet

type ReservationSet []ReservationDescriptor

ReservationSet is the complete set of strict rule reservations for one logical request/B-leg mutation.

type ReserveCommand

type ReserveCommand struct {
	Reservations       ReservationSet
	Correlation        controlplane.Correlation
	Scope              scope.PrincipalScopeView
	ReservationKey     domain.ReservationKey
	RuleID             string
	RuleType           string
	Dimensions         domain.Dimensions
	Request            domain.Amount
	Authority          domain.AuthorityLevel
	EstimateOnly       bool
	At                 time.Time
	SourceKey          string
	Surfaced           controlplane.UsageSurfaced
	ParentRequestID    string
	BoundPolicyVersion controlplane.VersionRef
	BoundRatingVersion controlplane.VersionRef
}

ReserveCommand, SettleCommand, and ReleaseCommand are the app-owned mutation ports passed to the backing authority store.

type ReserveResult

type ReserveResult struct {
	Applied        bool
	ReservationID  string
	ReservedAmount domain.Amount
	RuleID         string
	RuleType       string
	Reservations   []AdmissionReservation
}

type RuleReservationError

type RuleReservationError struct {
	RuleID string
	Err    error
}

RuleReservationError identifies the rule whose reservation descriptor failed while preserving the underlying error's sentinel identity.

func (*RuleReservationError) Error

func (e *RuleReservationError) Error() string

func (*RuleReservationError) Unwrap

func (e *RuleReservationError) Unwrap() error

type RuleSnapshot

type RuleSnapshot struct {
	ID                 string
	Version            string
	EffectiveAt        time.Time
	FetchedAt          time.Time
	State              economics.SnapshotState
	Status             domain.AuthorityStatus
	UnknownAttribution domain.UnknownAttribution
	Rules              []domain.Rule
}

RuleSnapshot is the immutable rule set consumed by admission orchestration.

func (RuleSnapshot) PolicyRef

PolicyRef returns the bindable policy snapshot identity for this rule set.

type RuleSource

type RuleSource interface {
	Snapshot(ctx context.Context) (RuleSnapshot, error)
}

RuleSource provides immutable rule snapshots to the app layer.

type Service

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

Service owns usage-authority orchestration for admission, settlement, release, status, and bounded query flows.

func NewService

func NewService(rules RuleSource, store StateStore, evidence EvidenceSink, clock Clock, options ...ServiceOptions) *Service

NewService constructs a service with explicit dependencies. A nil clock means "use system wall-clock time" (see Service.now).

func (*Service) Admit

func (s *Service) Admit(ctx context.Context, in AdmissionInput) (res AdmissionResult, err error)

Admit evaluates the configured rules and reserves strict exposure before any protected backend work starts.

Rule-level availability scenarios — authority-unavailable outcomes (authoritative-only rules under estimated evidence), unavailable reservation infrastructure, best-effort evidence projection failures, and evaluation timeouts — are resolved through the matched rules' effective failure behavior and returned as AdmissionResult values (not Go errors) so the runtime maps them through the normal outcome path (requirement 4.6, 5.5, 6.3, 6.6, 8.3, 10.1-10.3). Go errors are still returned for system-wide disabled/degraded/unavailable status where no matched rules could be enforced; the runtimebundle startup-posture fallback handles those. Deterministic capacity and reservation conflicts always deny.

func (*Service) ApplyUsage

func (s *Service) ApplyUsage(ctx context.Context, cmd ApplyUsageCommand) (ApplyUsageResult, error)

ApplyUsage applies final usage/cost to matched advisory (or otherwise unreserved) accounting windows without creating a reservation (requirement 7.7). It is independent of the reservation lifecycle: it runs whether or not the request was reserved, updating advisory windows so they accumulate actual usage. Idempotent via the store source key. The store records an advisory decision row; this method intentionally skips policydecision/control-plane projection to keep the advisory path minimal and best-effort.

func (*Service) Decisions

Decisions returns bounded live accounting decision rows plus a query state classification.

func (*Service) Limits

Limits returns bounded live limit rows plus a query state classification.

func (*Service) Release

func (s *Service) Release(ctx context.Context, in ReleaseInput) (result ReleaseResult, err error)

Release marks reservations for swallowed and losing attempts without attributing surfaced usage to the released attempt.

func (*Service) SetStageMetrics

func (s *Service) SetStageMetrics(m StageMetrics)

SetStageMetrics attaches stage latency metrics after construction (bundle wiring).

func (*Service) Settle

func (s *Service) Settle(ctx context.Context, in SettleInput) (result SettleResult, err error)

Settle reconciles surfaced-attempt usage against a matching reservation.

func (*Service) Status

Status returns the operator-visible accounting authority posture.

type ServiceOptions

type ServiceOptions struct {
	EvaluationTimeout      time.Duration
	CleanupTimeout         time.Duration
	DefaultFailureBehavior domain.FailureBehavior
	StageMetrics           StageMetrics
}

ServiceOptions controls application-level admission behavior without making the domain or storage ports aware of runtime configuration.

type SettleCommand

type SettleCommand struct {
	Reservations         []SettlementDescriptor
	Correlation          controlplane.Correlation
	Scope                scope.PrincipalScopeView
	SettlementKey        domain.SettlementKey
	ReservationKey       domain.ReservationKey
	ReservationID        string
	RuleID               string
	Kind                 SettlementKind
	FinalUsage           domain.Amount
	ReservedUsage        domain.Amount
	EstimatedUsage       domain.Amount
	Authority            domain.AuthorityLevel
	MeasurementAuthority MeasurementAuthority
	FinalUsagePresent    bool
	Stage                string
	BackendAttempted     bool
	OutputCommitted      bool
	ClientCanceled       bool
	At                   time.Time
	SourceKey            string
}

type SettleInput

type SettleInput struct {
	Reservations   []SettlementDescriptor
	Correlation    controlplane.Correlation
	Scope          scope.PrincipalScopeView
	ReservationKey domain.ReservationKey
	ReservationID  string
	RuleID         string
	Kind           SettlementKind
	// Sequence distinguishes partial, cancellation, final, and authoritative
	// reconciliation mutations that share one reservation identity.
	Sequence             int
	FinalUsage           domain.Amount
	ReservedUsage        domain.Amount
	EstimatedUsage       domain.Amount
	Authority            domain.AuthorityLevel
	MeasurementAuthority MeasurementAuthority
	FinalUsagePresent    bool
	Stage                string
	BackendAttempted     bool
	OutputCommitted      bool
	ClientCanceled       bool
	// Facts/Exposure carry quantity evidence for dual-plane rules.
	Exposure economics.ExposureBasis
	Facts    []metering.Fact
	// BoundVersion pins settlement to the admission-time policy snapshot (11.4).
	BoundVersion economics.PolicySnapshotRef
	// BoundRatingVersion pins rating identity when known at settlement (14.3).
	BoundRatingVersion economics.RatingSnapshotRef
}

SettleInput carries the safe request data required for surfaced-attempt settlement orchestration.

func DeriveSettleScalars

func DeriveSettleScalars(in SettleInput) SettleInput

DeriveSettleScalars copies aggregate fields from the first reservation descriptor when callers supply only the descriptor set (runtime lifecycle path).

type SettleResult

type SettleResult struct {
	Applied          bool
	ReservationID    string
	ReleasedDelta    domain.Amount
	OverageDelta     domain.Amount
	AdjustmentDelta  domain.Amount
	Mutations        []SettlementMutation
	PolicyRecords    []policydecision.Record
	AccountingEvents []controlplane.Event
	PolicyRecord     policydecision.Record
	AccountingEvent  controlplane.Event
}

SettleResult reports the settlement outcome for surfaced attempts.

type SettlementDescriptor

type SettlementDescriptor struct {
	Reservation          ReservationDescriptor
	FinalUsage           domain.Amount
	EstimatedUsage       domain.Amount
	SourceKey            string
	Sequence             int
	Authority            domain.AuthorityLevel
	MeasurementAuthority MeasurementAuthority
}

SettlementDescriptor carries one rule's reserved and final enforceable amounts. The store applies all descriptors in one atomic operation.

type SettlementKind

type SettlementKind string

SettlementKind classifies the settlement path.

const (
	SettlementKindFinal        SettlementKind = "final"
	SettlementKindPartial      SettlementKind = "partial"
	SettlementKindUnavailable  SettlementKind = "unavailable"
	SettlementKindCancellation SettlementKind = "cancellation"
	SettlementKindSwallowed    SettlementKind = "swallowed"
	SettlementKindLosing       SettlementKind = "losing"
)

type SettlementMutation

type SettlementMutation struct {
	RuleID          string
	ReservationID   string
	ReleasedDelta   domain.Amount
	OverageDelta    domain.Amount
	AdjustmentDelta domain.Amount
}

SettlementMutation contains the per-rule result of one atomic settlement set. The first mutation is mirrored into the legacy aggregate fields on SettleResult for callers that only enforce one rule.

type StageMetrics

type StageMetrics interface {
	ObserveStage(stage, provider, outcome string, seconds float64)
}

StageMetrics observes bounded authority stage latency and outcomes (req 16.5). Implementations must not retain request payloads or unbounded labels.

type StateStore

StateStore provides atomic reservation, settlement, release, advisory usage application, and bounded query operations without leaking storage details into the app layer.

type Store

type Store = StateStore

Store is an alias for StateStore to align with canonical store naming.

Jump to

Keyboard shortcuts

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