Files
coder/aibridge/keypool/failover.go
T
Susana Ferreira 01ec5e4577 feat: add key pool failover metrics to aibridge (#25901)
## Description

This PR adds Prometheus metrics for aibridge's API-key failover, giving visibility into key pool health and failover behavior per provider.

The following metrics are introduced:

- **`key_pool_state`** (gauge): number of keys currently in each state (`valid`, `temporary`, `permanent`) per provider, sampled at scrape time.
- **`key_pool_state_transitions_total`** (counter): key state transitions during failover, labeled by `reason` (`rate_limited`, `unauthorized`, `forbidden`).
- **`key_pool_exhaustions_total`** (counter): times a pool ran out of usable keys, labeled by `outcome` (`rate_limited`, `auth_failed`).
- **`key_pool_failover_attempts`** (histogram): keys attempted before success or exhaustion (per interception for bridged requests, per request for passthrough).

## Changes

- Moves `MarkKeyOnStatus` and key-pool error handling onto `*keypool.Pool`.
- Attaches metrics to each provider's key pool at install time, on construction and on provider reload.
- Adds a scrape-time state collector and a `KeyPools()` accessor on the bridge pool to feed it.
- Tracks per-request key attempts in the bridged and passthrough failover paths.
- Adds test coverage for the new metrics across the keypool unit tests, the bridged intercept failover tests, and the passthrough failover test.

Closes https://github.com/coder/internal/issues/1447
Closes https://linear.app/codercom/issue/AIGOV-198/aibridge-key-failover-observability

> [!NOTE]
> Initially generated by Claude Opus 4.7, modified and reviewed by @ssncferreira
2026-06-09 10:49:47 +01:00

118 lines
3.3 KiB
Go

package keypool
import (
"bytes"
"io"
"net/http"
"cdr.dev/slog/v3"
"github.com/coder/coder/v2/aibridge/utils"
)
// KeyFailoverConfig is the per-provider configuration consumed by
// NewKeyFailoverTransport.
type KeyFailoverConfig struct {
// Pool is the key pool to walk. Nil disables key failover.
Pool *Pool
Logger slog.Logger
// IsBYOK returns true when the request already carries
// user-supplied auth. BYOK requests skip key failover.
IsBYOK func(*http.Request) bool
// InjectAuthKey writes the key value into the outbound headers
// in the format the provider expects.
InjectAuthKey func(*http.Header, string)
// BuildKeyPoolResponse renders the response sent to the client
// when the walker has no more keys to try.
BuildKeyPoolResponse func(*Error) *http.Response
}
// keyFailoverTransport retries inner across the key pool on
// key-specific failures.
type keyFailoverTransport struct {
inner http.RoundTripper
config KeyFailoverConfig
}
// NewKeyFailoverTransport returns an http.RoundTripper backed by
// keyFailoverTransport. If config.Pool is nil, inner is returned
// unchanged.
func NewKeyFailoverTransport(inner http.RoundTripper, config KeyFailoverConfig) http.RoundTripper {
if config.Pool == nil {
return inner
}
return &keyFailoverTransport{
inner: inner,
config: config,
}
}
// RoundTrip is invoked by the proxy once per outer client request,
// after Rewrite has applied proxy headers.
//
// For centralized requests it walks the key pool, retrying on
// key-specific failures until one key succeeds or the pool is
// exhausted. BYOK requests skip the failover loop.
func (t *keyFailoverTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if t.config.IsBYOK(req) {
return t.inner.RoundTrip(req)
}
// Buffer once so retries can replay the body.
body, err := bufferBody(req)
if err != nil {
return nil, err
}
// Fresh walker per request, independent of other inflight requests.
walker := t.config.Pool.Walker()
defer func() { t.config.Pool.RecordAttempts(walker.Attempts()) }()
for {
key, keyPoolErr := walker.Next()
if keyPoolErr != nil {
resp := t.config.BuildKeyPoolResponse(keyPoolErr)
if resp == nil {
// Fallback if BuildKeyPoolResponse returns nil.
body := []byte(`{"error":"key pool unavailable"}`)
resp = utils.NewJSONErrorResponse(http.StatusBadGateway, 0, body)
}
return resp, nil
}
// Clone per attempt so the original request isn't mutated.
outReq := req.Clone(req.Context())
if body != nil {
outReq.Body = io.NopCloser(bytes.NewReader(body))
}
t.config.InjectAuthKey(&outReq.Header, key.Value())
resp, rtErr := t.inner.RoundTrip(outReq)
if rtErr != nil {
// Transport-level error, not a key issue.
return resp, rtErr
}
// MarkKeyOnStatus returns true on key-specific failures (e.g. 401/403/429).
if t.config.Pool.MarkKeyOnStatus(req.Context(), key, resp, t.config.Logger) {
// Drain and retry with the next key.
_, _ = io.Copy(io.Discard, resp.Body)
_ = resp.Body.Close()
continue
}
// Success or non-key error, forward as-is.
return resp, nil
}
}
// bufferBody reads the request body fully so it can be replayed
// across key-failover retries. Returns nil for a nil body.
func bufferBody(req *http.Request) ([]byte, error) {
if req.Body == nil {
return nil, nil
}
defer req.Body.Close()
return io.ReadAll(req.Body)
}