Documentation
¶
Overview ¶
Package middleware provides HTTP admission control for Go services. A shared Service applies one total limit and critical reservation across its handlers. It does not start servers, read environment files, or install global handlers.
Index ¶
- Variables
- type AdaptiveConfig
- type ControllerState
- type DecisionState
- type HandlerOption
- type OutcomeStatistics
- type Priority
- type PriorityStatistics
- type ResolutionStatistics
- type Service
- func (s *Service) ControllerSnapshot() ControllerState
- func (s *Service) DecisionSnapshot() DecisionState
- func (s *Service) Middleware(priority Priority, next http.Handler, options ...HandlerOption) http.Handler
- func (s *Service) Snapshot() ServiceState
- func (s *Service) Statistics() Statistics
- func (s *Service) TenantSnapshot() TenantState
- type ServiceConfig
- type ServiceState
- type Statistics
- type TenantConfig
- type TenantPolicy
- type TenantResolver
- type TenantSharingConfig
- type TenantState
Constants ¶
This section is empty.
Variables ¶
var ErrInvalidTenantIdentity = errors.New("gatewise: invalid tenant identity")
var ErrUntrustedTenantSource = errors.New("gatewise: untrusted tenant source")
Functions ¶
This section is empty.
Types ¶
type AdaptiveConfig ¶
type AdaptiveConfig struct {
MinConcurrent int
InitialConcurrent int
Interval time.Duration
MinSamples int
TargetLatency time.Duration
}
AdaptiveConfig enables request-driven adjustment when attached to ServiceConfig. Zero fields select conservative defaults. MaxConcurrent remains the ceiling.
type ControllerState ¶ added in v0.2.0
type ControllerState struct {
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 both interval and sample requirements are met. Decision is one of not_evaluated, hold, increase or decrease. These are observations, not controls.
type DecisionState ¶ added in v0.6.0
type DecisionState struct {
Enabled bool
Mode decision.Mode
Last decision.Result
Proposals [3]uint64 // allow, limit, reject; includes only evaluated signals.
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 HandlerOption ¶
type HandlerOption func(*handlerOptions)
func WithLatencyTarget ¶
func WithLatencyTarget(target time.Duration) HandlerOption
WithLatencyTarget gives this handler its own budget so naturally slower work is not compared directly to fast handlers sharing the same service capacity.
func WithResource ¶ added in v0.6.0
func WithResource(name string) HandlerOption
WithResource selects a server-controlled resource scope, never a caller header. Scoped ceilings still compare the shared Service in-flight count.
type OutcomeStatistics ¶
type PriorityStatistics ¶
type PriorityStatistics struct {
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 ResolutionStatistics ¶ added in v0.4.0
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service must be constructed with NewService; its zero value is not usable. It is safe for concurrent use. Reuse one instance for handlers sharing capacity; construct separate instances for independent service budgets.
func NewService ¶
func NewService(c ServiceConfig) (*Service, error)
func (*Service) ControllerSnapshot ¶ added in v0.2.0
func (s *Service) ControllerSnapshot() ControllerState
func (*Service) DecisionSnapshot ¶ added in v0.6.0
func (s *Service) DecisionSnapshot() DecisionState
func (*Service) Middleware ¶
func (s *Service) Middleware(priority Priority, next http.Handler, options ...HandlerOption) http.Handler
Middleware wraps next with a route-configured priority. Invalid priorities or nil handlers panic at registration time. Without Priorities, caller headers cannot change priority. Explicit tier policies resolve trusted metadata first. The slot is held until next returns (or panics); work outliving the handler is outside that lifetime. Cancellation is forwarded through the request context. There is no waiting queue, preemption, automatic retry, or process-wide budget.
func (*Service) Snapshot ¶
func (s *Service) Snapshot() ServiceState
func (*Service) Statistics ¶
func (s *Service) Statistics() Statistics
Statistics returns coherent histogram buckets/counts/sums and a live capacity snapshot. Scraping this method does not count as service traffic.
func (*Service) TenantSnapshot ¶ added in v0.3.0
func (s *Service) TenantSnapshot() TenantState
type ServiceConfig ¶
type ServiceConfig struct {
// Decisions is optional. The caller owns observation collection and lifecycle.
Decisions *decisionpkg.Engine
// 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 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 {
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
}
Statistics is a bounded snapshot independent of any metrics backend. Histograms contain admitted work only. Rejected requests do not pollute handler latency.
type TenantConfig ¶ added in v0.3.0
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.
Resolver TenantResolver
}
type TenantPolicy ¶ added in v0.3.0
type TenantPolicy string
const ( TenantReject TenantPolicy = "reject" )
type TenantResolver ¶ added in v0.3.0
TenantResolver must use an authenticated identity or explicitly trusted metadata. Empty identity invokes MissingPolicy. Errors reject without exposing their text. Keep resolvers local and fast; Gatewise does not authenticate identities.
func TrustedTenantHeader ¶ added in v0.3.0
func TrustedTenantHeader(header string, cidrs []string) (TenantResolver, error)
TrustedTenantHeader trusts only the immediate peer's address, never Forwarded or X-Forwarded-For. Trusted ingress must authenticate and overwrite the header. Requests without the header invoke MissingPolicy; supplied untrusted headers reject.
type TenantSharingConfig ¶ added in v0.5.0
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.