domain

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: 9 Imported by: 0

Documentation

Overview

Package domain contains the pure accounting-authority policy model.

It stays free of I/O, SQL, HTTP, runtime orchestration, and provider SDKs. The package owns amounts, safe dimensions, fixed windows, rule matching, reservations, settlements, status classification, and validation helpers.

Index

Constants

View Source
const (
	NamespaceLegacy  = "legacy"
	NamespaceDefault = "usage-authority/v2"
)

AuthorityNamespace isolates persisted limit/decision identity (Phase 7).

Variables

View Source
var (
	ErrInvalidAmount            = errors.New("invalid amount")
	ErrInvalidDimension         = errors.New("invalid dimension")
	ErrInvalidWindow            = errors.New("invalid window")
	ErrInvalidRule              = errors.New("invalid rule")
	ErrInvalidStatus            = errors.New("invalid status")
	ErrUnsupportedAlgorithm     = errors.New("unsupported window algorithm")
	ErrUnsupportedRuleUnit      = errors.New("unsupported rule unit")
	ErrRetiredMonetaryAuthority = errors.New("retired monetary usage authority rule; migration required")
	ErrUnsupportedAuthority     = errors.New("unsupported authority requirement")
	ErrUnsupportedFailurePolicy = errors.New("unsupported failure behavior")
)

Functions

func StrictUnavailableRuleIDs

func StrictUnavailableRuleIDs(matches []RuleMatch) []string

StrictUnavailableRuleIDs returns strict matches whose authority or accounting basis is unavailable. The app layer uses this set to resolve configured failure behavior before applying ordinary outcome severity.

Types

type Amount

type Amount struct {
	Unit  AmountUnit
	Value int64
}

func (Amount) String

func (a Amount) String() string

func (Amount) Validate

func (a Amount) Validate() error

type AmountSelectionSource

type AmountSelectionSource struct {
	Amount         Amount
	RequestCount   Amount
	PreflightUsage PreflightUsage
	Exposure       economics.ExposureBasis
	Facts          []metering.Fact
	FinalUsage     Amount
	ForSettlement  bool
}

AmountSelectionSource carries quantity evidence for admission and settlement. Monetary exposure/facts may be present for telemetry, but this selector never reads them and therefore cannot turn them into authority state.

type AmountUnit

type AmountUnit string
const (
	AmountUnitRequests         AmountUnit = "requests"
	AmountUnitInputTokens      AmountUnit = "input_tokens"
	AmountUnitOutputTokens     AmountUnit = "output_tokens"
	AmountUnitCacheReadTokens  AmountUnit = "cache_read_tokens"
	AmountUnitCacheWriteTokens AmountUnit = "cache_write_tokens"
	AmountUnitReasoningTokens  AmountUnit = "reasoning_tokens"
	AmountUnitTotalTokens      AmountUnit = "total_tokens"
)

func (AmountUnit) IsKnown

func (u AmountUnit) IsKnown() bool

type AuthorityConfig

type AuthorityConfig struct {
	Enabled            bool
	Backing            BackingCapability
	UnknownAttribution UnknownAttribution
	Rules              []Rule
}

func (AuthorityConfig) Status

func (c AuthorityConfig) Status() AuthorityStatus

func (AuthorityConfig) Validate

func (c AuthorityConfig) Validate() error

type AuthorityLevel

type AuthorityLevel string
const (
	AuthorityLevelAny           AuthorityLevel = ""
	AuthorityLevelEstimated     AuthorityLevel = "estimated"
	AuthorityLevelAuthoritative AuthorityLevel = "authoritative"
	AuthorityLevelUnavailable   AuthorityLevel = "unavailable"
)

func (AuthorityLevel) IsKnown

func (a AuthorityLevel) IsKnown() bool

type AuthorityRequirement

type AuthorityRequirement string
const (
	AuthorityRequirementAny           AuthorityRequirement = ""
	AuthorityRequirementEstimated     AuthorityRequirement = "estimated"
	AuthorityRequirementAuthoritative AuthorityRequirement = "authoritative"
)

func (AuthorityRequirement) IsKnown

func (r AuthorityRequirement) IsKnown() bool

type AuthorityState

type AuthorityState string
const (
	AuthorityStateDisabled     AuthorityState = "disabled"
	AuthorityStateReady        AuthorityState = "ready"
	AuthorityStateDegraded     AuthorityState = "degraded"
	AuthorityStateUnavailable  AuthorityState = "unavailable"
	AuthorityStateAdvisoryOnly AuthorityState = "advisory_only"
)

func (AuthorityState) IsKnown

func (s AuthorityState) IsKnown() bool

type AuthorityStatus

type AuthorityStatus struct {
	State  AuthorityState
	Reason StatusReason
}

func StatusFromBacking

func StatusFromBacking(backing BackingCapability) AuthorityStatus

func (AuthorityStatus) Validate

func (s AuthorityStatus) Validate() error

type BackingCapability

type BackingCapability string
const (
	BackingCapabilityDisabled     BackingCapability = "disabled"
	BackingCapabilityAtomic       BackingCapability = "atomic"
	BackingCapabilityAdvisoryOnly BackingCapability = "advisory_only"
	BackingCapabilityDegraded     BackingCapability = "degraded"
	BackingCapabilityUnavailable  BackingCapability = "unavailable"
)

func (BackingCapability) IsKnown

func (b BackingCapability) IsKnown() bool

func (BackingCapability) StrictCapable

func (b BackingCapability) StrictCapable() bool

type DecisionOutcome

type DecisionOutcome string
const (
	DecisionOutcomeAllow       DecisionOutcome = "allow"
	DecisionOutcomeAdvisory    DecisionOutcome = "advisory"
	DecisionOutcomeDeny        DecisionOutcome = "deny"
	DecisionOutcomeClamp       DecisionOutcome = "clamp"
	DecisionOutcomeUnavailable DecisionOutcome = "unavailable"
	DecisionOutcomeError       DecisionOutcome = "error"
)

type Dimensions

type Dimensions = authorityattribution.Dimensions

type EvaluationContext

type EvaluationContext struct {
	Dimensions     Dimensions
	Amount         Amount
	RequestCount   Amount
	PreflightUsage PreflightUsage
	Authority      AuthorityLevel
	At             time.Time
	// LifecycleScope filters rules for request vs attempt admission (Phase 7.2).
	// Empty disables filtering.
	LifecycleScope metering.LifecycleScope
	Exposure       economics.ExposureBasis
	Facts          []metering.Fact
}

type EvaluationResult

type EvaluationResult struct {
	Matches  []RuleMatch
	Selected RuleMatch
}

func EvaluateRules

func EvaluateRules(rules []Rule, ctx EvaluationContext) EvaluationResult

type FailureBehavior

type FailureBehavior string
const (
	FailureBehaviorDefault    FailureBehavior = ""
	FailureBehaviorFailClosed FailureBehavior = "fail_closed"
	FailureBehaviorFailOpen   FailureBehavior = "fail_open"
)

func (FailureBehavior) IsKnown

func (b FailureBehavior) IsKnown() bool

type MatchValue

type MatchValue = DimensionMatcher

type MeteringBasis

type MeteringBasis string

MeteringBasis identifies which metering boundary or compatibility path a rule uses when selecting amounts (requirements 1.3, 9.2, 9.6).

const (
	// BasisLegacyProviderPreferredAttempt is the explicit compatibility basis
	// for pre-Phase-7 rules. Perspective/lifecycle may be empty when this is set.
	BasisLegacyProviderPreferredAttempt MeteringBasis = "legacy_provider_preferred_attempt"

	BasisFrontendIngress MeteringBasis = MeteringBasis(metering.BoundaryFrontendIngress)
	BasisBackendIngress  MeteringBasis = MeteringBasis(metering.BoundaryBackendIngress)
	BasisBackendEgress   MeteringBasis = MeteringBasis(metering.BoundaryBackendEgress)
	BasisFrontendEgress  MeteringBasis = MeteringBasis(metering.BoundaryFrontendEgress)
)

func (MeteringBasis) IsKnown

func (b MeteringBasis) IsKnown() bool

func (MeteringBasis) IsLegacyCompatibility

func (b MeteringBasis) IsLegacyCompatibility() bool

type PreflightUsage

type PreflightUsage struct {
	InputTokens      int64
	OutputTokens     int64
	CacheReadTokens  int64
	CacheWriteTokens int64
	ReasoningTokens  int64
	TotalTokens      int64
	// TotalTokensPresent distinguishes an authoritative total (including explicit
	// zero) from an omitted total that may be inferred via the inclusion schema.
	TotalTokensPresent bool
}

PreflightUsage carries per-unit pre-backend estimates used during admission when configured rules enforce dimensions other than input tokens.

func (PreflightUsage) AmountForUnit

func (p PreflightUsage) AmountForUnit(unit AmountUnit) (Amount, bool)

type ReleaseKey

type ReleaseKey struct {
	ReservationKey ReservationKey
	Sequence       int
}

func (ReleaseKey) String

func (k ReleaseKey) String() string

type ReleaseResult

type ReleaseResult struct {
	Applied       bool
	ReleasedDelta Amount
}

type ReservationKey

type ReservationKey struct {
	LogicalRequestID string
	ALegID           string
	BLegID           string
	AttemptID        string
	RuleID           string
	Sequence         int
	// Namespace isolates dual-plane reservations. Empty keeps the pre-Phase-7
	// key string format for legacy compatibility.
	Namespace string
}

func (ReservationKey) String

func (k ReservationKey) String() string

type Rule

type Rule struct {
	ID                   string
	Kind                 RuleKind
	Mode                 RuleMode
	Unit                 AmountUnit
	Limit                Amount
	AuthorityRequirement AuthorityRequirement
	FailureBehavior      FailureBehavior
	Window               WindowSpec
	Match                DimensionsMatcher
	// Dual-plane metadata (Phase 7). Legacy rules must set Basis to
	// BasisLegacyProviderPreferredAttempt; new rules require perspective,
	// lifecycle_scope, basis, and namespace.
	Perspective    metering.EconomicPerspective
	LifecycleScope metering.LifecycleScope
	Basis          MeteringBasis
	Namespace      string
	Version        string
}

func (Rule) AppliesToLifecycle

func (r Rule) AppliesToLifecycle(stage metering.LifecycleScope) bool

AppliesToLifecycle reports whether the rule should evaluate at the given admission/settlement lifecycle stage. Empty stage disables filtering.

func (Rule) IsDualPlaneConfigured

func (r Rule) IsDualPlaneConfigured() bool

IsDualPlaneConfigured reports whether the rule carries explicit dual-plane fields.

func (Rule) Matches

func (r Rule) Matches(actual Dimensions) bool

func (Rule) SelectAmount

func (r Rule) SelectAmount(src AmountSelectionSource) (Amount, bool)

SelectAmount resolves the quantity amount for one rule.

func (Rule) SupportsAuthority

func (r Rule) SupportsAuthority(authority AuthorityLevel) bool

SupportsAuthority reports whether this rule can consume a usage fact at the supplied authority level. It is intentionally read-only so application orchestration can filter unreserved usage without duplicating rule semantics.

func (Rule) Validate

func (r Rule) Validate() error

type RuleKind

type RuleKind string
const (
	RuleKindQuota RuleKind = "quota"
	RuleKindRate  RuleKind = "rate"
)

func (RuleKind) IsKnown

func (k RuleKind) IsKnown() bool

type RuleMatch

type RuleMatch struct {
	RuleID   string
	RuleIDs  []string
	Kind     RuleKind
	Mode     RuleMode
	Exceeded bool
	Outcome  DecisionOutcome
}

func SelectRuleOutcome

func SelectRuleOutcome(matches []RuleMatch, excluded map[string]struct{}) RuleMatch

SelectRuleOutcome selects the most restrictive outcome from matches while optionally excluding rules whose configured failure behavior is fail-open. Rule matching remains pure; application code decides which unavailable rules may be excluded after resolving their configured posture.

type RuleMode

type RuleMode string
const (
	RuleModeStrict   RuleMode = "strict"
	RuleModeAdvisory RuleMode = "advisory"
)

func (RuleMode) IsKnown

func (m RuleMode) IsKnown() bool

type SettlementKey

type SettlementKey struct {
	ReservationKey ReservationKey
	Sequence       int
}

func (SettlementKey) String

func (k SettlementKey) String() string

type SettlementResult

type SettlementResult struct {
	Applied       bool
	ConsumedDelta Amount
	ReleasedDelta Amount
	OverageDelta  Amount
}

type StatusReason

type StatusReason string
const (
	StatusReasonNone               StatusReason = "none"
	StatusReasonDisabledByConfig   StatusReason = "disabled_by_config"
	StatusReasonBackingUnavailable StatusReason = "backing_unavailable"
	StatusReasonBackingDegraded    StatusReason = "backing_degraded"
	StatusReasonAdvisoryOnly       StatusReason = "advisory_only"
	StatusReasonValidationFailed   StatusReason = "validation_failed"
)

func (StatusReason) IsKnown

func (r StatusReason) IsKnown() bool

type UnknownAttribution

type UnknownAttribution string

UnknownAttribution controls how unknown attribution fields are normalized before rule matching and evidence projection.

const (
	UnknownAttributionPreserve   UnknownAttribution = "preserve"
	UnknownAttributionUnknown    UnknownAttribution = "unknown"
	UnknownAttributionKnownEmpty UnknownAttribution = "known_empty"
)

func (UnknownAttribution) IsKnown

func (m UnknownAttribution) IsKnown() bool

func (UnknownAttribution) NormalizeDimensions

func (m UnknownAttribution) NormalizeDimensions(d Dimensions) Dimensions

NormalizeDimensions applies the configured unknown-attribution mode to attribution dimensions used for rule matching and store projection.

func (UnknownAttribution) NormalizeScope

NormalizeScope applies the configured unknown-attribution mode to a scope view.

func (UnknownAttribution) NormalizeValue

func (m UnknownAttribution) NormalizeValue(v scope.Value) scope.Value

NormalizeValue maps unknown attribution according to the configured mode.

type WindowAlgorithm

type WindowAlgorithm string
const (
	WindowAlgorithmFixed WindowAlgorithm = "fixed"
)

func (WindowAlgorithm) IsKnown

func (a WindowAlgorithm) IsKnown() bool

type WindowBalance

type WindowBalance struct {
	Consumed Amount
	Reserved Amount
	Released Amount
	Overage  Amount
	// contains filtered or unexported fields
}

func (*WindowBalance) Release

func (b *WindowBalance) Release(key ReleaseKey, amount Amount) ReleaseResult

func (*WindowBalance) Settle

func (b *WindowBalance) Settle(key SettlementKey, reserved, actual Amount) SettlementResult

type WindowBounds

type WindowBounds struct {
	Start time.Time
	End   time.Time
}

type WindowKey

type WindowKey struct {
	RuleID       string
	DimensionKey DimensionKey
	Start        time.Time
	End          time.Time
}

func (WindowKey) String

func (k WindowKey) String() string

type WindowSpec

type WindowSpec struct {
	Algorithm WindowAlgorithm
	Size      time.Duration
	Anchor    time.Time
}

func (WindowSpec) Bounds

func (s WindowSpec) Bounds(at time.Time) (WindowBounds, error)

func (WindowSpec) Key

func (s WindowSpec) Key(ruleID string, dims Dimensions, at time.Time) WindowKey

Jump to

Keyboard shortcuts

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