Documentation
¶
Overview ¶
Package keypool implements per-key circuit-breaker state and configurable Pool selection over healthy keys. State is persisted in pkg/state under "secret_health:<keyHash>" (circuit records), "pool_rr:<poolName>" (round-robin counters), and "pool_lru:<poolName>:<keyHash>" (LRU timestamps).
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
- Variables
- func ClearCircuit(ctx context.Context, store kv.Store, keyHash string) error
- func RegisterScripts(m *kv.Mem)
- type Candidate
- type CircuitRecord
- type CircuitState
- type CooldownReason
- type FailureKind
- type KeySelection
- type PreparedFailure
- type PreparedPick
- type PreparedSuccess
- type Selector
- func (s *Selector) NewBatch() *kv.Batch
- func (s *Selector) Pick(ctx context.Context, scope string, algo KeySelection, keys []*hostkey.HostKey, ...) (*hostkey.HostKey, error)
- func (s *Selector) PickCandidate(ctx context.Context, scope string, algo KeySelection, ...) (Candidate, error)
- func (s *Selector) PickWithExclude(ctx context.Context, scope string, algo KeySelection, keys []*hostkey.HostKey, ...) (*hostkey.HostKey, error)
- func (s *Selector) PreparePick(b *kv.Batch, scope string, algo KeySelection, keys, exclude []*hostkey.HostKey) *PreparedPick
- func (s *Selector) PrepareRecordFailure(b *kv.Batch, keyHash string, kind FailureKind, retryAfter time.Duration) *PreparedFailure
- func (s *Selector) PrepareRecordSuccess(b *kv.Batch, keyHash string) *PreparedSuccess
- func (s *Selector) ReadCircuit(ctx context.Context, keyHash string) (CircuitRecord, bool)
- func (s *Selector) RecordFailure(ctx context.Context, keyHash string, kind FailureKind, ...)
- func (s *Selector) RecordSuccess(ctx context.Context, keyHash string)
- func (s *Selector) WithBreaker(threshold int, window time.Duration) *Selector
Constants ¶
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 ¶
var ErrNoHealthyKeys = errors.New("keypool: no healthy keys in pool")
Functions ¶
func ClearCircuit ¶
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 RegisterScripts ¶ added in v0.9.8
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
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.
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 ¶
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
NewBatch returns a kv batch on the selector's store, 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 (typically the owning Policy's Meta.Name) 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 ¶
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 ¶
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.