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 ¶
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 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.
type OutcomeStatistics ¶
type PriorityStatistics ¶
type PriorityStatistics struct {
Priority Priority
Admitted, RejectedConcurrency, RejectedReservation uint64
RejectedTenant, RejectedTenantRegistry, RejectedTenantMissing, RejectedTenantInvalid, RejectedTenantUntrusted uint64
Outcomes [3]OutcomeStatistics // completed, canceled, panicked
}
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) 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. Caller headers cannot change priority. 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 {
// 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
}
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 {
Name string
State ServiceState
Controller ControllerState
Tenants TenantState
Priorities [2]PriorityStatistics
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 {
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.