decision

package
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 15 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package decision combines cached overload observations into bounded admission proposals. It never samples a provider or makes a network call during Evaluate.

Index

Constants

This section is empty.

Variables

View Source
var ErrFutureObservation = errors.New("decision: future observation")
View Source
var ErrInvalidObservation = errors.New("decision: invalid observation")
View Source
var ErrOutOfOrder = errors.New("decision: out-of-order observation")

Functions

func ValidName

func ValidName(s string) bool

func WithResult

func WithResult(ctx context.Context, r Result) context.Context

Types

type Assessment

type Assessment struct {
	Name             string
	Scope            Scope
	State            string // missing, healthy, pressure, unknown, stale
	Value, Threshold float64
	ObservedAt       time.Time
	MaxAge           time.Duration
	Action           string // allow, limit, reject
	Limit            int
	Cause            string // pressure, unavailable, or empty
	Binding          bool
}

type Budget added in v0.7.0

type Budget struct {
	Name, Resource string
	MaxWriteBytes  int64
	Keys           *KeyBudget
}

type BudgetAssessment added in v0.7.0

type BudgetAssessment struct {
	Name, Action, Reason                        string
	WriteBytes, ActiveWriteBytes, MaxWriteBytes int64
	KeyActive, KeyLimit                         int
	KeyBucket                                   string
}

type BudgetSnapshot added in v0.7.0

type BudgetSnapshot struct {
	Name, Resource                                                          string
	MaxWriteBytes, ActiveWriteBytes                                         int64
	Active, Tracked, TrackingLimit, KeyLimit, MissingActive, OverflowActive int
	Expired, Attempts, WouldReject, Rejected, Admitted                      uint64
}

type Collector

type Collector struct {
	Name              string
	Interval, Timeout time.Duration
	Provider          Provider
}

type Config

type Config struct {
	Mode    Mode
	Rules   []Rule
	Budgets []Budget
}

type Cost added in v0.7.0

type Cost struct {
	WriteBytes int64  `json:"write_bytes"`
	Key        string `json:"key,omitempty"`
}

Cost is server-resolved operation metadata. WriteBytes describes planned logical writes, not HTTP body length, WAL bytes or an inferred database cost. Key is never retained in plaintext, returned in diagnostics or used as a label.

type Effect

type Effect struct {
	MaxConcurrent int  `json:"max_concurrent,omitempty"`
	Reject        bool `json:"reject,omitempty"`
}

type Engine

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

func New

func New(c Config) (*Engine, error)

func (*Engine) AcquireResources added in v0.7.0

func (e *Engine) AcquireResources(target Target, cost Cost, now time.Time) (*Lease, []BudgetAssessment, string)

AcquireResources combines all matching byte/key checks atomically under the engine lock. No partial reservation is retained when enforcement rejects. Observe mode tracks actual occupancy in bounded fallback buckets while recording proposals, including registry overflow; it does not create unbounded keys.

func (*Engine) BudgetSnapshot added in v0.7.0

func (e *Engine) BudgetSnapshot() []BudgetSnapshot

func (*Engine) Evaluate

func (e *Engine) Evaluate(target Target, baseline int, now time.Time) Evaluation

func (*Engine) HasActorRules

func (e *Engine) HasActorRules() bool

func (*Engine) HasBudgets added in v0.7.0

func (e *Engine) HasBudgets() bool

HasBudgets reports whether HTTP integration requires trusted operation metadata.

func (*Engine) Mode

func (e *Engine) Mode() Mode

func (*Engine) NeedsCost added in v0.7.0

func (e *Engine) NeedsCost(resource string) bool

func (*Engine) Publish

func (e *Engine) Publish(name string, o Observation) error

func (*Engine) Run

func (e *Engine) Run(ctx context.Context, collectors []Collector) error

Run owns background sampling until cancellation. At most one sample per signal can be in flight, including across Run restarts. A provider that ignores its context can leave one worker blocked; it cannot create unbounded replacement workers.

func (*Engine) Snapshot

func (e *Engine) Snapshot() []SignalSnapshot

func (*Engine) Unavailable

func (e *Engine) Unavailable(name string) error

Unavailable publishes a current unknown state, never the provider's error text.

func (*Engine) ValidateCollectors

func (e *Engine) ValidateCollectors(collectors []Collector) error

type Evaluation

type Evaluation struct {
	Mode                                         Mode
	BaselineLimit, ProposedLimit, EffectiveLimit int
	SignalCeiling                                int // Smallest matching raw cap; independent of a moving adaptive baseline.
	Action, Reason                               string
	Reject                                       bool // Enforced explicit rejection. A cap is checked atomically later.
	Assessments                                  []Assessment
}

type HTTPProvider

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

func NewHTTPProvider

func NewHTTPProvider(address string) (*HTTPProvider, error)

NewHTTPProvider reads a small observation document from an operator-selected endpoint. It disables redirects/environment proxies and validates TLS normally.

func (*HTTPProvider) Close

func (p *HTTPProvider) Close()

func (*HTTPProvider) Sample

func (p *HTTPProvider) Sample(ctx context.Context) (Observation, error)

type KeyBudget added in v0.7.0

type KeyBudget struct {
	MaxConcurrent, MaxTracked int
	IdleTTL                   time.Duration
	Missing, Overflow         string // reject (default), or shared bounded fallback.
}

type Lease added in v0.7.0

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

Lease tracks only resource reservations; it is not an operation-level service admission API. Middleware rolls it back on later rejection and releases it at handler completion, including cancellation/panic. Release is idempotent.

func (*Lease) Release added in v0.7.0

func (l *Lease) Release()

func (*Lease) Retain added in v0.7.0

func (l *Lease) Retain()

type Mode

type Mode string
const (
	Enforce Mode = "enforce"
	Observe Mode = "observe"
)

type Observation

type Observation struct {
	Value      float64   `json:"value"`
	ObservedAt time.Time `json:"observed_at"`
	State      string    `json:"state"`
}

Observation timestamps describe measurement time, not delivery time. Unknown explicitly invalidates an earlier value. Duplicate timestamps never renew age.

type Provider

type Provider interface {
	Sample(context.Context) (Observation, error)
}

type ProviderFunc

type ProviderFunc func(context.Context) (Observation, error)

func (ProviderFunc) Sample

func (f ProviderFunc) Sample(ctx context.Context) (Observation, error)

type Result

type Result struct {
	Kind                              string
	Allowed                           bool
	Priority, Resource, Reason, Stage string
	Evaluation                        Evaluation
	Stages                            []Stage
	Budgets                           []BudgetAssessment
}

func FromContext

func FromContext(ctx context.Context) (Result, bool)

func NewResult

func NewResult(priority, resource string) Result

func (Result) Clone

func (r Result) Clone() Result

func (*Result) Mark

func (r *Result) Mark(stage, reason string)

type Rule

type Rule struct {
	Name         string
	Scope        Scope
	Threshold    float64
	MaxAge       time.Duration
	OnUnknown    string // allow (default), reject, or limit.
	UnknownLimit int
	Pressure     Effect
}

type Scope

type Scope struct {
	Kind string `json:"kind"`
	Key  string `json:"key,omitempty"`
}

type SignalSnapshot

type SignalSnapshot struct {
	Assessment
	Accepted   uint64
	Dropped    [3]uint64
	Failures   [4]uint64
	Collecting bool
}

type Stage

type Stage struct{ Name, State, Reason string }

type Target

type Target struct{ Resource, Actor string }

Jump to

Keyboard shortcuts

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