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 ¶
- Variables
- type AdaptiveConfig
- type Config
- type ControllerState
- type DecisionState
- type Engine
- func (s *Engine) Begin(ctx context.Context, request Request) (*Permit, error)
- func (s *Engine) ControllerSnapshot() ControllerState
- func (s *Engine) DecisionSnapshot() DecisionState
- func (s *Engine) Do(ctx context.Context, request Request, fn func(context.Context) error) (err error)
- func (s *Engine) NeedsCost(resource string) bool
- func (s *Engine) QueueEnabled() bool
- func (s *Engine) QueueSnapshot() QueueState
- func (s *Engine) Reject(priority Priority, reason string, stage string) decision.Result
- func (s *Engine) Snapshot() ServiceState
- func (s *Engine) Statistics() Statistics
- func (s *Engine) TenantSnapshot() TenantState
- type Outcome
- type OutcomeStatistics
- type Permit
- type Priority
- type PriorityStatistics
- type QueueConfig
- type QueuePriorityState
- type QueueState
- type Rejection
- type Request
- type ResolutionStatistics
- type ServiceState
- type Statistics
- type TenantConfig
- type TenantPolicy
- type TenantSharingConfig
- type TenantState
- type WorkStatistics
Constants ¶
This section is empty.
Variables ¶
var ErrNested = errors.New("gatewise: nested admission on the same engine; use a separate budget")
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 (*Engine) Begin ¶
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 ¶
NeedsCost reports whether a server-owned resource matches accounting rules.
func (*Engine) QueueEnabled ¶ added in v0.10.0
func (*Engine) QueueSnapshot ¶ added in v0.10.0
func (s *Engine) QueueSnapshot() QueueState
func (*Engine) Reject ¶
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 OutcomeStatistics ¶
type Permit ¶
type Permit struct {
// contains filtered or unexported fields
}
func (*Permit) QueueWait ¶ added in v0.10.0
QueueWait is admission waiting only; processing feedback excludes this time.
func (*Permit) TenantAllocation ¶
type PriorityStatistics ¶
type PriorityStatistics struct {
RejectedQueue [5]uint64 // full, reserved, timeout, deadline, canceled
RejectedResources [8]uint64
RejectedSignals [3]uint64 // pressure, unavailable, concurrency limit
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 QueueState ¶ added in v0.10.0
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 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 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 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.