operation

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: MIT Imports: 13 Imported by: 1 module, 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 operation provides transport-neutral, process-local admission. Call Begin with trusted metadata, use Permit.Context for nested work, and Finish only when the actual operation lifetime ends. Cancellation never releases a permit automatically.

Index

Constants

This section is empty.

Variables

View Source
var ErrNested = errors.New("gatewise: nested admission on the same engine; use a separate budget")
View Source
var ErrUntrustedCost = errors.New("gatewise: untrusted operation metadata")

Functions

This section is empty.

Types

type AdaptiveConfig

type AdaptiveConfig struct {
	// Profile is legacy (default) or stable (opt-in). Operator bounds remain hard.
	Profile           string
	MinConcurrent     int
	InitialConcurrent int
	Interval          time.Duration
	MinSamples        int
	TargetLatency     time.Duration
}

AdaptiveConfig enables request-driven adjustment when attached to Config. Zero fields select conservative defaults. MaxConcurrent remains the ceiling.

type Config

type Config struct {
	// Decisions is optional. The caller owns observation collection and lifecycle.
	Decisions *decisionpkg.Engine
	// Queue nil preserves immediate rejection.
	Queue *QueueConfig
	// Name identifies this service in rejection responses and logs; default "service".
	Name string
	// MaxConcurrent is required and must be positive.
	MaxConcurrent int
	// ReservedCritical ranges from zero through MaxConcurrent, inclusive.
	ReservedCritical int
	// Logger optionally records rejections. Nil disables library logging.
	Logger *slog.Logger
	// Adaptive nil retains fixed mode.
	Adaptive *AdaptiveConfig
	// Tenants nil preserves service-only admission.
	Tenants    *TenantConfig
	Priorities *prioritypkg.Config
}

type ControllerState

type ControllerState struct {
	ControlRatio, ControlFailureFraction          float64
	ControlPriority                               string
	Profile                                       string
	SmoothedControlRatio                          float64
	SparseWindow, ExternalLimit                   bool
	PressureStreak, HealthyStreak, PendingSamples int
	WindowStartedAt                               time.Time
	WindowInterval                                time.Duration
	Enabled                                       bool
	EvaluatedAt                                   time.Time
	Samples                                       int
	P90Ratio, FailureFraction                     float64
	PreviousLimit, Limit                          int
	Saturated                                     bool
	Decision, Reason                              string
}

ControllerState contains the last evaluated adaptive window. EvaluatedAt is zero until an ordinary or sparse window is evaluated. Decision is one of not_evaluated, hold, increase or decrease. These are observations, not controls.

type DecisionState

type DecisionState struct {
	Enabled   bool
	Mode      decision.Mode
	Last      decision.Result
	Proposals [3]uint64 // allow, limit, reject; includes only evaluated signals.
	Budgets   []decision.BudgetSnapshot
	Signals   []decision.SignalSnapshot
}

DecisionState contains the last completed admission decision and bounded proposal counters. A limit proposal does not imply this request would reject.

type Engine

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

Engine must be constructed with New; its zero value is not usable. It is safe for concurrent use. Reuse one instance for operations sharing capacity; construct separate instances for independent service budgets.

func New

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

func (*Engine) Begin

func (s *Engine) Begin(ctx context.Context, request Request) (*Permit, error)

Begin waits only when Queue is configured. No execution/resource/tenant permit is retained while waiting. A successful Permit must still be explicitly finished.

func (*Engine) ControllerSnapshot

func (s *Engine) ControllerSnapshot() ControllerState

func (*Engine) DecisionSnapshot

func (s *Engine) DecisionSnapshot() DecisionState

func (*Engine) Do

func (s *Engine) Do(ctx context.Context, request Request, fn func(context.Context) error) (err error)

Do reports failures/panics and releases after fn actually returns, even if fn ignores cancellation. The panic propagates after accounting is released.

func (*Engine) NeedsCost

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

NeedsCost reports whether a server-owned resource matches accounting rules.

func (*Engine) QueueEnabled added in v0.10.0

func (s *Engine) QueueEnabled() bool

func (*Engine) QueueSnapshot added in v0.10.0

func (s *Engine) QueueSnapshot() QueueState

func (*Engine) Reject

func (s *Engine) Reject(priority Priority, reason string, stage string) decision.Result

Reject records an adapter identity failure before Begin; later stages remain unvisited.

func (*Engine) Snapshot

func (s *Engine) Snapshot() ServiceState

func (*Engine) Statistics

func (s *Engine) Statistics() Statistics

Statistics returns coherent histogram buckets/counts/sums and a live capacity snapshot. Scraping this method does not count as service traffic.

func (*Engine) TenantSnapshot

func (s *Engine) TenantSnapshot() TenantState

type Outcome

type Outcome struct {
	Err                error
	StatusCode         int
	Canceled, Panicked bool
}

type OutcomeStatistics

type OutcomeStatistics struct {
	Outcome         string
	StatusClasses   [7]uint64 // 1xx, 2xx, 3xx, 4xx, 5xx, other, none
	Count           uint64
	DurationSum     float64
	DurationBuckets [11]uint64 // cumulative, seconds
}

type Permit

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

func (*Permit) Context

func (p *Permit) Context() context.Context

func (*Permit) Cost

func (p *Permit) Cost() decision.Cost

func (*Permit) Decision

func (p *Permit) Decision() decision.Result

func (*Permit) Finish

func (p *Permit) Finish(outcome Outcome)

func (*Permit) QueueWait added in v0.10.0

func (p *Permit) QueueWait() time.Duration

QueueWait is admission waiting only; processing feedback excludes this time.

func (*Permit) TenantAllocation

func (p *Permit) TenantAllocation() (kind string, share, ceiling int)

type Priority

type Priority string
const (
	Critical   Priority = "critical"
	Background Priority = "background"
)

type PriorityStatistics

type PriorityStatistics struct {
	RejectedQueue                                                                                                 [5]uint64 // full, reserved, timeout, deadline, canceled
	RejectedResources                                                                                             [8]uint64
	RejectedSignals                                                                                               [3]uint64 // pressure, unavailable, concurrency limit
	RejectedTenantShare                                                                                           uint64
	RejectedTier, RejectedCohort, RejectedPriorityInvalid, RejectedPriorityUntrusted                              uint64
	Priority                                                                                                      Priority
	Admitted, RejectedConcurrency, RejectedReservation                                                            uint64
	RejectedTenant, RejectedTenantRegistry, RejectedTenantMissing, RejectedTenantInvalid, RejectedTenantUntrusted uint64
	Outcomes                                                                                                      [3]OutcomeStatistics // completed, canceled, panicked
}

type QueueConfig added in v0.10.0

type QueueConfig struct {
	MaxWaiting int
	MaxWait    time.Duration
	AgingAfter time.Duration // zero defaults to half MaxWait (at least 1ns).
	Reserved   map[Priority]int
}

QueueConfig enables process-local waiting only for local execution-capacity refusals. Other policy refusals stay immediate. Limits count requests, not bytes. Reserved protects higher tiers' waiting slots from combined lower-tier occupancy. AgingAfter changes selection order only; it never overrides execution policy.

type QueuePriorityState added in v0.10.0

type QueuePriorityState struct {
	Priority                                                                        Priority
	Waiting                                                                         int
	Enqueued, Admitted, Full, Reserved, Timeout, Deadline, Canceled, PolicyRejected uint64
	WaitCount                                                                       uint64
	WaitSum                                                                         float64
	WaitBuckets                                                                     [11]uint64
}

type QueueState added in v0.10.0

type QueueState struct {
	Enabled                        bool
	MaxWaiting, Waiting, HighWater int
	MaxWait, AgingAfter            time.Duration
	Tiers                          []QueuePriorityState
	Reservations                   map[Priority]int
}

type Rejection

type Rejection struct {
	Reason   string
	Input    bool
	Decision decision.Result
}

func (*Rejection) Error

func (r *Rejection) Error() string

type Request

type Request struct {
	// NoWait opts this operation out of waiting while preserving queue ordering.
	NoWait           bool
	Kind             string // operation (default) or http; bounded diagnostic classification.
	ResolveCost      func(context.Context) (decision.Cost, error)
	Priority         Priority
	Tenant, Resource string
	Cost             decision.Cost
	LatencyTarget    time.Duration
}

Request metadata must come from a validated operation plan/authenticated context. Priority defaults to Critical. Resource names are configured by the server, not selected by an untrusted caller.

type ResolutionStatistics

type ResolutionStatistics struct {
	Priority Priority
	Source   string
	Count    uint64
}

type ServiceState

type ServiceState struct {
	Mode                                                                      string
	Limit, Active, Background, ReservedCritical, MinConcurrent, MaxConcurrent int
}

ServiceState is a read-only snapshot. Active may temporarily exceed Limit after a reduction while previously admitted requests drain; they are not interrupted.

type Statistics

type Statistics struct {
	Queue             QueueState
	Work              [2]WorkStatistics // operation, http. Outcomes: success, failed, canceled, panicked.
	Decisions         DecisionState
	TenantAllocations [3]uint64 // share, borrowed, fallback; successful service admissions only.
	Name              string
	State             ServiceState
	Controller        ControllerState
	Tenants           TenantState
	Priorities        [2]PriorityStatistics
	Tiers             []PriorityStatistics
	Resolutions       []ResolutionStatistics
	TierActive        map[Priority]int
	PriorityEnabled   bool
	DurationBounds    [11]float64
	Adjustments       [2][3]uint64 // decrease/increase; latency_pressure/server_errors/healthy_saturation
}

type TenantConfig

type TenantConfig struct {
	Sharing                       *TenantSharingConfig
	MaxConcurrent                 int
	Limits                        map[string]int // Optional overrides; copied and hashed at construction.
	MaxTracked                    int            // Default 1024 identified tenants, plus two bounded fallback buckets.
	IdleTTL                       time.Duration  // Default 5m; only inactive entries expire.
	MissingPolicy, OverflowPolicy TenantPolicy   // Default reject; shared uses a bounded bucket.
}

type TenantPolicy

type TenantPolicy string
const (
	TenantReject TenantPolicy = "reject"
	TenantShared TenantPolicy = "shared"
)

type TenantSharingConfig

type TenantSharingConfig struct {
	MaxConcurrent int            // Borrowing ceiling; zero selects the service maximum.
	Limits        map[string]int // Optional per-identity borrowing ceilings.
	DemandTTL     time.Duration  // Default 500ms; positive and no greater than IdleTTL.
}

TenantSharingConfig enables lending beyond configured tenant shares. The existing MaxConcurrent/Limits become target shares only when Sharing is set.

type TenantState

type TenantState struct {
	SharingEnabled, BorrowingPaused                                                     bool
	DemandingTenants, BorrowedActive                                                    int
	DemandShares                                                                        int64
	Enabled                                                                             bool
	MaxConcurrent, MaxTracked, Tracked, IdentifiedActive, MissingActive, OverflowActive int
	EntriesExpired                                                                      uint64
}

type WorkStatistics

type WorkStatistics struct {
	Admitted, Rejected uint64
	Completed          [4]uint64
	DurationSum        float64
	DurationBuckets    [11]uint64
}

Statistics is a bounded snapshot independent of any metrics backend. Histograms contain admitted work only. Rejected requests do not pollute handler latency.

Jump to

Keyboard shortcuts

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