limits

package
v1.261119.1 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: MPL-2.0 Imports: 7 Imported by: 0 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 limits implements the state behind routing limits: live in-flight counters per upstream account/service, sliding usage windows, and the all-or-nothing permits that tie both to a request's lifetime. It knows nothing about routing, gin or the database; see .design/routing-limits.md.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Lease

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

Lease owns the permits of one client request. It lives in the request context; a middleware calls ReleaseAll when the handler returns, which covers streaming completion, client cancellation and panics. Failover swaps the permit of the failed attempt for the next one.

func NewLease

func NewLease() *Lease

NewLease creates an empty lease.

func (*Lease) Hold

func (l *Lease) Hold(serviceID string, p *Permit)

Hold registers an attempt's permit under its service ID. If the lease is already closed the permit is released immediately (a late arrival must not leak).

func (*Lease) Release

func (l *Lease) Release(serviceID string)

Release frees the permits held for one service (a failed failover attempt).

func (*Lease) ReleaseAll

func (l *Lease) ReleaseAll()

ReleaseAll frees everything and closes the lease.

type Permit

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

Permit is one attempt's hold on a set of subjects.

func (*Permit) Release

func (p *Permit) Release()

Release frees the in-flight slots. Safe to call more than once and on nil.

type QuotaFunc

type QuotaFunc func(providerUUID string) (pct float64, ok bool)

QuotaFunc returns the upstream quota used percentage (0-100) for a provider; ok=false means unknown, which never blocks.

type Reason

type Reason uint8

Reason is a bit set of the limits that blocked a candidate.

const (
	ReasonConcurrency Reason = 1 << iota
	ReasonUsage
	ReasonQuota
)

func (Reason) String

func (r Reason) String() string

type Registry

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

Registry holds all counters. The zero value is not usable; use NewRegistry.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates an empty registry.

func (*Registry) Assess

func (r *Registry) Assess(subjects []Subject) Verdict

Assess classifies the subjects without consuming anything.

func (*Registry) Changed

func (r *Registry) Changed() <-chan struct{}

Changed returns a channel closed on the next release; waiters re-assess then.

func (*Registry) Keys

func (r *Registry) Keys(prefix string) []string

Keys lists the keys of all live counters starting with prefix.

func (*Registry) Reap

func (r *Registry) Reap() int

Reap force-releases permits held longer than the leak-guard hold time and drops idle counters. Returns the number of permits reaped.

func (*Registry) Record

func (r *Registry) Record(subjects []Subject, tokens int64)

Record adds completed-request tokens to the subjects' usage windows.

func (*Registry) Seed

func (r *Registry) Seed(key string, l ai.Limits, events []UsageEvent)

Seed adds historical usage (warm start after a restart) to a key's window.

func (*Registry) SetMaxHold

func (r *Registry) SetMaxHold(d time.Duration)

SetMaxHold overrides the leak-guard hold time (tests).

func (*Registry) SetQuotaFunc

func (r *Registry) SetQuotaFunc(fn QuotaFunc)

SetQuotaFunc wires upstream quota lookups (optional). Lookups are cached for a few seconds so the request path never pays a store read per candidate.

func (*Registry) StartSweeper

func (r *Registry) StartSweeper(ctx context.Context)

StartSweeper runs Reap periodically until ctx is done.

func (*Registry) Stat

func (r *Registry) Stat(key string) Stat

Stat returns the live counters for a key (zero value when unknown).

func (*Registry) TryAcquire

func (r *Registry) TryAcquire(subjects []Subject, force bool) (*Permit, Verdict)

TryAcquire atomically re-checks the subjects and, if none is blocked (or force is set), counts the request: it takes one in-flight slot on every subject and one request in every usage window. The returned Permit must be released exactly once per attempt (Release is idempotent).

func (*Registry) Utilization

func (r *Registry) Utilization(subjects []Subject) Utilization

Utilization reports the tightest (highest) load per dimension across subjects.

func (*Registry) WindowEmpty

func (r *Registry) WindowEmpty(key string, l ai.Limits) bool

WindowEmpty reports whether the key has no usage recorded in a window of the limit's current length, i.e. whether warm-starting it would not double count.

type Scope

type Scope uint8

Scope says which kind of entity a Subject is, so a blocked verdict can name who is exhausted (the person, the team, the upstream).

const (
	ScopeAcct Scope = 1 << iota
	ScopeSvc
	ScopeModel
	ScopeUser
	ScopeTeam
)

func (Scope) String

func (s Scope) String() string

type Stat

type Stat struct {
	Inflight int
	Requests int64
	Tokens   int64
}

Stat is the live state of one key, for status APIs.

type State

type State int

State classifies how loaded a candidate is.

const (
	StateOK      State = iota // below every limit and every soft threshold
	StateHot                  // at/above a soft threshold, below every hard limit
	StateBlocked              // at/above a hard limit
)

func (State) String

func (s State) String() string

type Subject

type Subject struct {
	Key    string
	Scope  Scope
	Limits ai.Limits
	// Quota is the provider UUID whose upstream quota Limits.QuotaPercent is
	// checked against. Empty = no quota check.
	Quota string
}

Subject is one counted entity (an account, one rule's share of it, a model, a person or a team) and the limits that apply to it.

type UsageEvent

type UsageEvent struct {
	At       time.Time
	Requests int64
	Tokens   int64
}

UsageEvent is a historical usage sample used by Seed.

type Utilization

type Utilization struct {
	Concurrency    float64
	HasConcurrency bool
	Usage          float64
	HasUsage       bool
}

Utilization is the per-dimension load of a set of subjects in percent (not capped: 100 = at the hard limit). Has* is false when no subject configures that dimension, so callers can tell "unlimited" from "idle".

type Verdict

type Verdict struct {
	State   State
	Reasons Reason
	// Scopes is the set of subject scopes that are blocked (hard limit hit).
	Scopes Scope
	// Pressure is the largest used/limit ratio across all dimensions
	// (1.0 = at the hard limit; 0 when nothing is limited).
	Pressure float64
	// RetryAfter is a hint for how long until a blocked usage budget frees up
	// (or a short default for pure concurrency).
	RetryAfter time.Duration
}

Verdict is the result of assessing a set of subjects.

func (Verdict) ConcurrencyOnly

func (v Verdict) ConcurrencyOnly() bool

ConcurrencyOnly reports a blocked verdict that waiting could resolve within seconds: only in-flight caps are hit.

Jump to

Keyboard shortcuts

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