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.
A Selector with a PickState picks from the process's memory instead: breaker records are copies, every one reread once per refresh interval, and the round-robin counters and LRU stamps live there alone, so rotation is per process rather than fleet-wide. Its own transitions apply to the copy at once, also when the store failed to run them; another process's reach it within one interval and a round trip, so it may send up to that long of requests to a key another process has just seen fail. A success served on a copy that does not yet show another process's failures skips the success write (Candidate.SuccessNeedsWrite reads the copy), so it may leave that failure count standing. Only when refreshes fail does a copy age, up to two intervals, before picks read through. The probe claim stays a store script: it needs fleet-wide exclusion.
Expected kv ops per request:
- Pick with a PickState: none while the records it reads are fresh (read or written within two intervals). A record not yet held, or stale, is read through: a GET queued on the pick's batch for the candidates PreparePick reads, and under prioritized, a GET each for the keys behind the first, one at a time and only while the keys ahead are open.
- Pick without one: 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. Least-recently-used adds a GET per healthy candidate and a SET. PreparePick queues the same reads on a caller's batch (the pipeline sends them with the caller's hold).
- Either way, claiming the probe of a key whose cooldown ended: one script.
- PickState refresh, per interval and off the request path: one pipelined round trip with a GET per record held; a record nobody picked for five minutes is dropped, as are idle rotation counters and LRU stamps.
- 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 BreakerCellKey(valueHash string) cell.Key
- func ClearCircuit(ctx context.Context, store kv.Store, keyHash string) error
- func CooldownCellKey(accountID string) cell.Key
- func PickOps(algo KeySelection, n int) int
- func RegisterScripts(m *kv.Mem)
- func RotationKey(poolID string) cell.Key
- type BreakerCell
- type Candidate
- type CircuitRecord
- type CircuitState
- type CooldownCell
- type CooldownReason
- type FailureKind
- type KeySelection
- type PickState
- type PreparedFailure
- type PreparedPick
- type PreparedSuccess
- type Rotation
- type Selector
- func (s *Selector) NewBatch(size int) *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
- func (s *Selector) WithPickState(ps *PickState) *Selector
- type Verdict
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 )
const DefaultRefreshInterval = time.Second
DefaultRefreshInterval is how often a PickState rereads every breaker record it holds. It bounds how late another pod's breaker transition reaches this one.
Variables ¶
var ErrNoHealthyKeys = errors.New("keypool: no healthy keys in pool")
Functions ¶
func BreakerCellKey ¶ added in v0.20.0
BreakerCellKey keys a breaker by the credential's value hash: a rotated value gets a fresh, closed breaker and the old one expires unlinked.
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 CooldownCellKey ¶ added in v0.20.0
CooldownCellKey keys a cooldown by account id: every credential of the account shares the provider's ceiling, so they cool together.
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
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).
func RotationKey ¶ added in v0.20.0
RotationKey keys a pool's rotation by pool id, so reordering the pool keeps its round-robin phase and every policy drawing on the pool shares one rotation.
Types ¶
type BreakerCell ¶ added in v0.20.0
type BreakerCell struct {
// contains filtered or unexported fields
}
BreakerCell holds the latest circuit record known for one credential value.
func NewBreakerCell ¶ added in v0.20.0
func NewBreakerCell() *BreakerCell
NewBreakerCell returns a closed breaker.
func (*BreakerCell) Load ¶ added in v0.20.0
func (c *BreakerCell) Load() *CircuitRecord
Load returns the record, nil while the breaker has never failed.
func (*BreakerCell) Store ¶ added in v0.20.0
func (c *BreakerCell) Store(r *CircuitRecord)
Store replaces the record; r must not be modified afterwards.
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 CooldownCell ¶ added in v0.20.0
type CooldownCell struct {
// contains filtered or unexported fields
}
CooldownCell is the time, in unix milliseconds, until which an account is skipped: as a whole, or for one model, since providers limit each model separately within an account.
func NewCooldownCell ¶ added in v0.20.0
func NewCooldownCell() *CooldownCell
NewCooldownCell returns a cooldown that is not set.
func (*CooldownCell) Cooled ¶ added in v0.20.0
func (c *CooldownCell) Cooled(nowMs int64, modelID string) bool
Cooled reports whether the account is cooling for modelID at nowMs.
func (*CooldownCell) Extend ¶ added in v0.20.0
func (c *CooldownCell) Extend(untilMs int64)
Extend moves the whole account's end to untilMs unless it already lies later, so a short local cooldown never cuts a longer one another pod reported.
func (*CooldownCell) ExtendModel ¶ added in v0.20.0
func (c *CooldownCell) ExtendModel(modelID string, untilMs, nowMs int64)
ExtendModel moves modelID's end to untilMs unless it already lies later. Entries already over at nowMs are dropped from the copy it writes.
func (*CooldownCell) Until ¶ added in v0.20.0
func (c *CooldownCell) Until(modelID string) int64
Until returns when the account frees up for modelID in unix milliseconds, the later of its whole and its model cooldown; 0 when neither was set.
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 PickState ¶ added in v0.20.0
type PickState struct {
// contains filtered or unexported fields
}
PickState is the pick state a pod keeps in memory instead of reading the store per request: a copy of the breaker records of the keys it picks, all reread off the request path once per interval, and the round-robin rotation and least-recently-used stamps of each pick scope, which are this pod's own. Selectors sharing one PickState (the request path's and the post-flight one) see each other's transitions at once.
A record not yet read, or last read more than two intervals ago (refreshes failing), is read through by the pick that needs it. A transition the store failed to run is applied here alone and holds against older store reads: an open until its OpenUntil, a success until the store shows a transition after it.
func NewPickState ¶ added in v0.20.0
NewPickState returns a PickState rereading on store every interval (0 means DefaultRefreshInterval). Call Start to run the refresh loop.
func (*PickState) Close ¶ added in v0.20.0
func (ps *PickState) Close()
Close stops the refresh loop.
func (*PickState) Refresh ¶ added in v0.20.0
Refresh rereads every record held, in one pipelined round trip, and forgets the records, rotation counters and LRU stamps nobody picked for pickStateIdle. A read that fails leaves its record as it was, to age into a read-through.
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 Rotation ¶ added in v0.20.0
type Rotation struct {
// contains filtered or unexported fields
}
Rotation is one pool's per-process selection state: the round-robin counter and the last use of each credential value.
func NewRotation ¶ added in v0.20.0
func NewRotation() *Rotation
NewRotation returns a rotation starting at the pool's first credential.
func (*Rotation) LastUsed ¶ added in v0.20.0
LastUsed returns when the credential last served, 0 if never.
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 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) that the PickState does not hold fresh and, for round-robin without a PickState, 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.
func (*Selector) WithBreaker ¶ added in v0.11.7
WithBreaker sets how many server or network errors within window open a closed key. Values below 1 keep the defaults.
func (*Selector) WithPickState ¶ added in v0.20.0
WithPickState makes s pick from ps instead of reading the store per pick, and write its own transitions through to ps. Give every selector of the process the same ps. Call before serving.
type Verdict ¶ added in v0.20.0
type Verdict int
Verdict is what a key agent tells the request to do after a key failed. It lives here, beside FailureKind, so the agent and the request loop share it without importing each other.
const ( // VerdictNext: give up on this key, fail over to the next candidate. VerdictNext Verdict = iota // VerdictRetry: retry the SAME key with the returned fresh secret value // (the agent re-resolved it — e.g. the key had rotated upstream). VerdictRetry // VerdictFail: stop; return the upstream error to the caller. VerdictFail )