keypool

package
v0.11.9 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: Apache-2.0 Imports: 13 Imported by: 1 module, 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 keypool implements per-key circuit-breaker state and configurable Pool selection over healthy keys. State is persisted in pkg/kv under "secret_health:{secret:<keyHash>}" (circuit records), "pool_rr:{pool:<scope>}" (round-robin counters), and "{pool_lru:<scope>}:<keyHash>" (LRU timestamps); the scope is the caller's policy id.

Supported selection strategies (KeySelection):

  • "prioritized" (default) — always pick the first healthy key in declaration order.
  • "round-robin" — distribute traffic evenly using a counter.
  • "least-recently-used" — pick the key with the oldest last-used timestamp.

Expected kv ops per request:

  • Pick: one kv.Batch round trip with a GET of each candidate's breaker record and, for round-robin, the counter's INCR and EXPIRE NX. Prioritized reads only the first candidate in the batch; the ones behind it cost a GET each, and only while the keys ahead are open. Promoting an expired open key to half-open adds a SET; least-recently-used adds a GET per healthy candidate and a SET. PreparePick queues the same reads on a caller's batch (policy admission sends them with the rate-limit reserve).
  • RecordSuccess: one script; PrepareRecordSuccess queues it on a caller's batch. A key's record exists only once it has failed: post-flight writes a success only for a half-open probe, a record with a backoff step, or a failure count (Candidate.SuccessNeedsWrite). RecordFailure: one script; PrepareRecordFailure queues it on a caller's batch. Claiming a half-open probe in Pick: one script.

The KeySelection enum lives in this package (not policy) so policy can import keypool without creating a cycle when its Service composes Selector + Limiter at runtime.

Index

Constants

View Source
const (

	// DefaultFailureThreshold and DefaultFailureWindow apply when WithBreaker is not given positive values: a closed key opens on this many server or network errors within the window, with no success between them.
	DefaultFailureThreshold = 5
	DefaultFailureWindow    = 30 * time.Second
)

Variables

View Source
var ErrNoHealthyKeys = errors.New("keypool: no healthy keys in pool")

Functions

func ClearCircuit

func ClearCircuit(ctx context.Context, store kv.Store, keyHash string) error

ClearCircuit deletes the circuit-breaker record for a key from the KV store. This is best-effort: if the DEL fails the error is returned to the caller, who should log a warning but not fail the outer operation.

Use this when a key is permanently deleted from the catalog so that orphaned secret_health:* keys do not accumulate in Redis indefinitely (R-8).

func PickOps added in v0.11.8

func PickOps(algo KeySelection, n int) int

PickOps is the most commands PreparePick queues for n keys under algo.

func RegisterScripts added in v0.9.8

func RegisterScripts(m *kv.Mem)

RegisterScripts installs the Go emulators for keypool's Lua scripts on a MemStore, mirroring the Redis-side behaviour exactly. New registers them automatically when the store IS a *kv.Mem; test doubles that merely embed one must call this on the inner Mem themselves (same convention as pkgratelimit.RegisterScripts).

Types

type Candidate added in v0.11.7

type Candidate struct {
	Key    *hostkey.HostKey
	Record CircuitRecord
	// Stored is false when the store held no record for the key (or the read failed) and Record is the closed default.
	Stored bool
}

Candidate is a key fit for traffic and the breaker record it was judged on.

func (Candidate) SuccessNeedsWrite added in v0.11.7

func (c Candidate) SuccessNeedsWrite() bool

SuccessNeedsWrite reports whether a success on c changes its record: a half-open probe, a backoff step to decay, or a failure count to clear. A clean closed record, or none, already reads as healthy and gets no write.

type CircuitRecord

type CircuitRecord struct {
	State          CircuitState
	OpenUntil      time.Time
	BackoffStep    int
	LastTransition time.Time
	// Indefinite marks a record written before auth cooldowns were bounded; it reads as an expired open record.
	Indefinite bool
	Reason     CooldownReason
	// Failures counts the server errors since WindowStart that did not open the key yet.
	Failures    int
	WindowStart time.Time
	// ProbeUntil is when a half-open key's probe lease ends; until then other picks skip the key.
	ProbeUntil time.Time
}

CircuitRecord is the per-key circuit-breaker state stored under "secret_health:<keyHash>" in pkg/state.

type CircuitState

type CircuitState int

CircuitState describes the current health of a key.

const (
	CircuitClosed   CircuitState = iota // healthy, accepting traffic
	CircuitOpen                         // unhealthy, skip
	CircuitHalfOpen                     // single probe allowed
)

func (CircuitState) String

func (s CircuitState) String() string

String returns a stable lower-snake label for the circuit state, suitable for logs and API responses.

type CooldownReason

type CooldownReason string

CooldownReason describes why a key was placed into cooldown (circuit open). The empty string means unknown / legacy record written before this field existed.

const (
	ReasonUpstreamAuthFailed   CooldownReason = "upstream_auth_failed"
	ReasonUpstreamForbidden    CooldownReason = "upstream_forbidden"
	ReasonUpstreamRateLimited  CooldownReason = "upstream_rate_limited"
	ReasonUpstreamServerError  CooldownReason = "upstream_server_error"
	ReasonUpstreamNetworkError CooldownReason = "upstream_network_error"
)

type FailureKind

type FailureKind int

FailureKind classifies the upstream failure for circuit-breaker transitions.

const (
	FailureAuth           FailureKind = iota // 401 → open on the auth cooldown ladder
	FailureRateLimitShort                    // 429 with Retry-After ≤ 5s → stay closed
	FailureRateLimitLong                     // 429 with Retry-After > 5s → open for that duration
	FailureServerError                       // 5xx → exponential backoff
	FailureNetwork                           // net/timeout (post-connect) → treat as 5xx
	// FailureUpstreamUnreachable is a dial-phase failure (connection refused,
	// no route, DNS, TLS handshake): the connection was never established, so
	// it is a property of the host/baseURL, not the key. It NEVER trips a key
	// breaker — the pipeline retries the same host with backoff and reports an
	// unreachable status. Distinguishes a misconfigured baseURL from a bad key.
	FailureUpstreamUnreachable
	// FailureForbidden is a 403: the credential authenticated but the request
	// was refused, often for what it asked (a model or feature the account
	// lacks), so it backs off like a 5xx rather than condemning the key.
	FailureForbidden
)

type KeySelection

type KeySelection string

KeySelection is the algorithm a Selector uses to pick from healthy candidates. Persisted as a string in Policy.Spec.KeySelection.

const (
	// KeySelectionPrioritized drains keys in declaration order — the
	// first healthy key in the candidate set wins. Default.
	KeySelectionPrioritized KeySelection = "prioritized"
	// KeySelectionRoundRobin rotates evenly across healthy keys via a
	// per-scope counter.
	KeySelectionRoundRobin KeySelection = "round-robin"
	// KeySelectionLeastRecentlyUsed prefers the key whose last successful
	// use was furthest in the past.
	KeySelectionLeastRecentlyUsed KeySelection = "least-recently-used"
)

type PreparedFailure added in v0.11.7

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

PreparedFailure is a RecordFailure queued on a kv batch; Finish logs the transition once the batch has run.

func (*PreparedFailure) Finish added in v0.11.7

func (p *PreparedFailure) Finish(ctx context.Context)

Finish logs the failure write's outcome.

type PreparedPick added in v0.11.7

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

PreparedPick is a Pick whose reads are queued on a kv batch; Finish chooses the key once the batch has run.

func (*PreparedPick) Finish added in v0.11.7

func (p *PreparedPick) Finish(ctx context.Context) (Candidate, error)

Finish chooses the key from the batch's results, reading on its own only the prioritized candidates the batch skipped.

type PreparedSuccess added in v0.11.7

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

PreparedSuccess is a RecordSuccess queued on a kv batch; Finish logs the transition once the batch has run.

func (*PreparedSuccess) Err added in v0.11.7

func (p *PreparedSuccess) Err() error

Err is the success write's outcome as the batch left it, before Finish logs it.

func (*PreparedSuccess) Finish added in v0.11.7

func (p *PreparedSuccess) Finish(ctx context.Context)

Finish logs the success write's outcome.

type Selector

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

Selector picks HostKeys from Pools and tracks per-key circuit-breaker state.

func New

func New(s kv.Store, log *slog.Logger, clock func() time.Time, rng *rand.Rand) *Selector

New constructs a Selector. clock and rng may be nil. When rng is nil, a new rand seeded from time.Now().UnixNano() is used.

func (*Selector) NewBatch added in v0.11.7

func (s *Selector) NewBatch(size int) *kv.Batch

NewBatch returns a kv batch on the selector's store with room for size commands, so a caller can send PreparePick's reads in the same round trip as its own commands.

func (*Selector) Pick

func (s *Selector) Pick(ctx context.Context, scope string, algo KeySelection, keys []*hostkey.HostKey, exclude ...[]*hostkey.HostKey) (*hostkey.HostKey, error)

Pick returns a healthy HostKey from the candidate set. scope is the kv key tag (the owning Policy's Meta.ID) used for the round-robin counter and LRU timestamps. algo is the selection strategy; empty falls back to KeySelectionPrioritized.

exclude is an optional list of keys to skip even if healthy (e.g. for retry-with-exclusion in future callers). Pass nil to skip the check.

An open key past its OpenUntil goes half-open and serves one probe at a time: the pick that claims the probe lease gets it, concurrent picks skip it, and the probe's RecordSuccess/RecordFailure settles the key.

The reads go out in one kv batch; see PreparePick to share it.

func (*Selector) PickCandidate added in v0.11.7

func (s *Selector) PickCandidate(ctx context.Context, scope string, algo KeySelection, keys, exclude []*hostkey.HostKey) (Candidate, error)

PickCandidate is Pick returning the record the key was picked on, so the caller can tell whether its success needs writing.

func (*Selector) PickWithExclude

func (s *Selector) PickWithExclude(ctx context.Context, scope string, algo KeySelection, keys []*hostkey.HostKey, exclude []*hostkey.HostKey) (*hostkey.HostKey, error)

PickWithExclude is a convenience wrapper around Pick that accepts an explicit exclude list. Callers that always have an exclude slice can use this to avoid the variadic syntax.

func (*Selector) PreparePick added in v0.11.7

func (s *Selector) PreparePick(b *kv.Batch, scope string, algo KeySelection, keys, exclude []*hostkey.HostKey) *PreparedPick

PreparePick queues Pick's reads for keys on b: each candidate's breaker record (prioritized: the first candidate's only) and, for round-robin, the rotation counter. The caller runs b, then calls Finish.

func (*Selector) PrepareRecordFailure added in v0.11.7

func (s *Selector) PrepareRecordFailure(b *kv.Batch, keyHash string, kind FailureKind, retryAfter time.Duration) *PreparedFailure

PrepareRecordFailure queues RecordFailure's script for keyHash on b. It returns nil when there is no script to queue (the store runs none, or kind writes nothing); the caller then calls RecordFailure on its own.

func (*Selector) PrepareRecordSuccess added in v0.11.7

func (s *Selector) PrepareRecordSuccess(b *kv.Batch, keyHash string) *PreparedSuccess

PrepareRecordSuccess queues RecordSuccess's script for keyHash on b. It returns nil when the store runs no scripts; the caller then calls RecordSuccess on its own.

func (*Selector) ReadCircuit

func (s *Selector) ReadCircuit(ctx context.Context, keyHash string) (CircuitRecord, bool)

ReadCircuit returns the stored circuit-breaker record for a key and whether a record actually exists in the state store. A missing or undecodable record yields a default-closed record with found=false — the key has not failed within the record's TTL and is assumed healthy (a success writes a record only to close a half-open probe or reset a backoff). This is a read-only accessor for the admin plane; it does not auto-transition expired-open records the way Pick does.

func (*Selector) RecordFailure

func (s *Selector) RecordFailure(ctx context.Context, keyHash string, kind FailureKind, retryAfter time.Duration)

RecordFailure transitions according to kind, in one script. Server and network errors open a closed key only once the threshold is reached within the window; 401 and 403 open it at once. retryAfter is honoured only for FailureRateLimitLong.

func (*Selector) RecordSuccess

func (s *Selector) RecordSuccess(ctx context.Context, keyHash string)

RecordSuccess closes a closed or half-open key one backoff step down and clears its failure count, in one script. An open key is left alone.

func (*Selector) WithBreaker added in v0.11.7

func (s *Selector) WithBreaker(threshold int, window time.Duration) *Selector

WithBreaker sets how many server or network errors within window open a closed key. Values below 1 keep the defaults.

Jump to

Keyboard shortcuts

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