middleware

package
v0.5.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: 16 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 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

View Source
var ErrInvalidTenantIdentity = errors.New("gatewise: invalid tenant identity")
View Source
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 OutcomeStatistics struct {
	Outcome         string
	StatusClasses   [7]uint64 // 1xx, 2xx, 3xx, 4xx, 5xx, other, none
	Count           uint64
	DurationSum     float64
	DurationBuckets [11]uint64 // cumulative, seconds
}

type Priority

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

type PriorityStatistics

type PriorityStatistics struct {
	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 ResolutionStatistics added in v0.4.0

type ResolutionStatistics struct {
	Priority Priority
	Source   string
	Count    uint64
}

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. 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 {
	// 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 {
	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"
	TenantShared TenantPolicy = "shared"
)

type TenantResolver added in v0.3.0

type TenantResolver func(*http.Request) (string, error)

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.

type TenantState added in v0.3.0

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

Jump to

Keyboard shortcuts

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