Documentation
¶
Overview ¶
Package proxy implements the dual-loop proxy orchestration core with channel retry, session leasing, and failure classification.
Package proxy implements the proxy orchestration core (). Dual loops: outer channel retry + inner endpoint iteration. Session lease with sticky bindings and concurrency limiting.
Index ¶
- Constants
- Variables
- func ApplyKeyProxyOverride(base *platform.ProxyConfig, keyProxyURL *string) *platform.ProxyConfig
- func BuildForcedChannelUnavailableMessage(forcedChannelID *int64) string
- func BuildUpstreamURL(siteURL, path string) string
- func CanRetryChannelSelection(retryCount int, maxRetries int, forcedChannelID *int64) bool
- func ContainsPathTraversal(path string) bool
- func DetectCliProfile(input types.DetectInput) types.DetectedProfile
- func DirectProtocolForPath(path string) int
- func DirectProtocolMaskForPath(path string) int
- func EnsureRequestID(ctx context.Context, fallback string) (context.Context, string)
- func ExplainNoChannel(ctx context.Context, router TokenRouterInterface, requestedModel string, ...) string
- func FirstByteTimeoutMs(proxyFirstByteTimeoutSec int) int64
- func GetProxyMaxChannelAttempts(cfgMaxChannelAttempts int) int
- func GetProxyMaxChannelRetries(maxChannelAttempts int) int
- func GetTesterForcedChannelID(headers map[string]string, clientIP string) *int64
- func IsDirectMediaPath(path string) bool
- func IsLoopbackClientIP(ip string) bool
- func IsMetapiControlHeader(name string) bool
- func IsObservedFirstByteTimeoutError(err error) bool
- func IsSessionScopedChannel(extraConfig *string, oauthProvider *string) bool
- func IsTrustedTesterRequest(headers map[string]string, clientIP string) bool
- func MaxBufferedResponseBodyBytes() int64
- func NewStreamTransport() *http.Transport
- func PathForEndpoint(endpoint UpstreamEndpoint) string
- func ReadBufferedResponseBody(r io.Reader) ([]byte, error)
- func RegisterDetectionProfile(p *types.CliProfileDefinition)
- func RegisterFallbackProfile(p *types.CliProfileDefinition)
- func RequestCeiling(firstByteTimeoutSec int) time.Duration
- func RequestIDFromContext(ctx context.Context) string
- func ResponsesOnlyChatUnsupportedMessage(downstreamPath string) string
- func RoutingProtocolForPath(path string) (required int, allowConversion bool)
- func SelectProxyChannelForAttempt(ctx context.Context, router TokenRouterInterface, ...) (*routing.SelectedChannel, error)
- func ShouldAbortSameSiteEndpointFallback(status int, upstreamErrorText string) bool
- func ShouldDowngradeToNextEndpoint(status int, rawErrText string) bool
- func ShouldForceUpstreamStream(pref SiteProtocolPreference, upstreamPath string, isCompact bool) bool
- func ShouldRecordChannelFailure(status int, upstreamErrorText string) bool
- func ShouldRetryProxyRequest(status int, upstreamErrorText string) bool
- func WithRequestID(ctx context.Context, requestID string) context.Context
- func WriteBudget(firstByteTimeoutSec int) time.Duration
- type ChannelLoadSnapshot
- type ChannelSelectionInput
- type CliProfileCapabilities
- type CliProfileDefinition
- type CliProfileID
- type DetectInput
- type DetectedProfile
- type DownstreamClientContext
- type EndpointCandidateOptions
- type ExecutorDispatchInput
- type ExecutorDispatchResult
- type FailureCode
- type ProxyChannelCoordinator
- type ProxyLogEntry
- type RuntimeExecutor
- func (e *RuntimeExecutor) Dispatch(ctx context.Context, input ExecutorDispatchInput) (*ExecutorDispatchResult, error)
- func (e *RuntimeExecutor) DoStreamWithObservedFirstByte(ctx context.Context, req *http.Request, firstByteTimeoutMs int64) (*http.Response, error)
- func (e *RuntimeExecutor) DoWithObservedFirstByte(ctx context.Context, req *http.Request, firstByteTimeoutMs int64) (*http.Response, error)
- func (e *RuntimeExecutor) WithObservedFirstByte(ctx context.Context, input ExecutorDispatchInput, firstByteTimeoutMs int64) (*ExecutorDispatchResult, int64, error)
- type SelectionExplainer
- type SiteConcurrencyLimiter
- type SiteProtocolPreference
- type SiteSlot
- type TokenRouterInterface
- type UpstreamBufferedBody
- type UpstreamContentFacts
- type UpstreamEncoding
- type UpstreamEncodingKind
- type UpstreamEndpoint
- type UpstreamStreamBody
- type UpstreamVerdict
- type UsageSummary
Constants ¶
const ( TesterRequestHeader = "x-metapi-tester-request" TesterForcedChannelHeader = "x-metapi-tester-forced-channel-id" )
Tester header constants.
const ( ProfileGeneric = types.ProfileGeneric ProfileCodex = types.ProfileCodex ProfileClaudeCode = types.ProfileClaudeCode ProfileGeminiCli = types.ProfileGeminiCli )
const DefaultRequestCeiling = httpclient.DefaultRequestCeiling
DefaultRequestCeiling is the whole-request timeout ceiling for buffered (non-stream) upstream dispatch. It is a safety net for a hung upstream, not the primary liveness control: the header phase is observed separately via PROXY_FIRST_BYTE_TIMEOUT_SEC, and streams are governed per chunk by the relay's idle guard (PROXY_STREAM_IDLE_TIMEOUT_SEC) instead of total elapsed time. The shared value also bounds the default stream header wait.
const UpstreamEncodingSkippedMessage = "upstream response uses a content encoding metapi does not decode; usage accounting and content-failure judgement were skipped"
UpstreamEncodingSkippedMessage is the STABLE warn text the data plane emits whenever it holds upstream body bytes it cannot decode. Stability matters: operators alert on it, and it is the only surface that makes the resulting account/reality gap ("we recorded a success but no tokens") visible instead of silent. Never reword it without treating that as an operator-facing contract change.
Variables ¶
var DefaultDirectAccountConcurrencyLimiter = NewSiteConcurrencyLimiter()
DefaultDirectAccountConcurrencyLimiter caps concurrent dispatches per direct upstream account. Direct channels bypass Site.MaxConcurrency because they have no site row, so the data plane keys a separate limiter by credential ID to retain per-account isolation.
var DefaultSiteConcurrencyLimiter = NewSiteConcurrencyLimiter()
DefaultSiteConcurrencyLimiter is the process-global site limiter used by the proxy data plane when UpstreamConfig does not inject a custom instance.
var ErrBufferedResponseBodyTooLarge = errors.New("upstream response body exceeded buffered limit")
var ErrObservedFirstByteTimeout = httpclient.ErrResponseHeaderTimeout
ErrObservedFirstByteTimeout is returned by DoWithObservedFirstByte when the first-byte / response-header deadline fires before headers arrive.
Unit note: firstByteTimeoutMs is milliseconds. Config field PROXY_FIRST_BYTE_TIMEOUT_SEC is seconds; convert with FirstByteTimeoutMs.
Functions ¶
func ApplyKeyProxyOverride ¶
func ApplyKeyProxyOverride(base *platform.ProxyConfig, keyProxyURL *string) *platform.ProxyConfig
Empty / whitespace keyProxyURL returns base unchanged (inherit).
func BuildForcedChannelUnavailableMessage ¶
BuildForcedChannelUnavailableMessage builds a human-readable message for forced channel unavailability.
func BuildUpstreamURL ¶
BuildUpstreamURL constructs an upstream URL from a site URL and path.
func CanRetryChannelSelection ¶
CanRetryChannelSelection checks if a channel retry is possible. Returns false if a forced channel is set (no fallback), or if max retries reached.
func ContainsPathTraversal ¶ added in v0.16.7
ContainsPathTraversal reports whether a request path contains a ".." segment. Callers pass percent-decoded paths (net/http decodes the request target into r.URL.Path before handlers run, so %2e%2e arrives as ".."), which makes a plain segment scan sufficient for both literal and encoded traversal. Single-dot segments are not traversal on their own and are left alone so legitimate paths are never altered.
func DetectCliProfile ¶
func DetectCliProfile(input types.DetectInput) types.DetectedProfile
DetectCliProfile detects the CLI profile from the input. Returns the first matching profile, or generic as fallback.
func DirectProtocolForPath ¶ added in v0.24.0
DirectProtocolForPath also recognizes non-generation surfaces. Keep them out of EndpointFromPath: media permissions must never enable protocol fallback.
func DirectProtocolMaskForPath ¶ added in v0.24.0
These wire-compatible operations retain distinct stored grants/endpoints. The selected adapter, not the inbound path, owns their provider differences.
func EnsureRequestID ¶
EnsureRequestID returns ctx carrying a non-empty request id when possible. Prefer the existing chi/Metapi id; only copies an explicit fallback when neither context source already has a value.
func ExplainNoChannel ¶ added in v0.18.0
func ExplainNoChannel( ctx context.Context, router TokenRouterInterface, requestedModel string, excludeChannelIDs []int64, policy routing.DownstreamRoutingPolicy, ) string
ExplainNoChannel renders one compact line describing why no channel could serve requestedModel, for the 503 body, the server log and the operator-facing all-failed event. It returns "" when the router cannot explain or the explanation itself fails: a missing reason must never become a harder failure.
The route decision panel already reads ExplainSelection; this is the same source, asked at the moment an operator actually needs it (#1179 — a bare "No available channels" plus `channel selection failed err=<nil>` gave no way to tell an unmatched route from unbound tokens, cooldown or a downstream policy).
func FirstByteTimeoutMs ¶
FirstByteTimeoutMs converts ProxyFirstByteTimeoutSec (seconds) to the internal first-byte observation unit (milliseconds). Values <= 0 disable first-byte observation (returns 0).
Matches original TS: firstByteTimeoutMs = proxyFirstByteTimeoutSec * 1000.
func GetProxyMaxChannelAttempts ¶
GetProxyMaxChannelAttempts returns the configured max channel attempts (min 1).
func GetProxyMaxChannelRetries ¶
GetProxyMaxChannelRetries returns max channel retries (attempts - 1, min 0).
func GetTesterForcedChannelID ¶
GetTesterForcedChannelID extracts the forced channel ID from tester headers.
func IsDirectMediaPath ¶ added in v0.24.0
func IsLoopbackClientIP ¶
IsLoopbackClientIP checks if a client IP is loopback.
func IsMetapiControlHeader ¶
IsMetapiControlHeader reports whether a custom header is a Metapi control signal that must not be forwarded upstream (responses-only / stream preference marks).
func IsObservedFirstByteTimeoutError ¶
IsObservedFirstByteTimeoutError reports whether err is a first-byte timeout.
func IsSessionScopedChannel ¶
IsSessionScopedChannel checks if a channel uses session-scoped credentials.
func IsTrustedTesterRequest ¶
IsTrustedTesterRequest checks if the request is from a trusted tester (loopback + header).
func MaxBufferedResponseBodyBytes ¶
func MaxBufferedResponseBodyBytes() int64
MaxBufferedResponseBodyBytes returns the configured max non-streaming upstream response size in bytes from the startup-loaded config singleton. Falls back to DefaultProxyMaxBufferedResponseBytes when config is not yet loaded (e.g. tests that bypass TestMain) or when the operator left the value at zero/negative (Load already clamps, but GetSafe guards anyway). Reading a struct field per request is materially cheaper than re-parsing os.Getenv + strconv.ParseInt on every proxied request — this function is on the hot path called from upstream.go, upstream_stream.go, executor.go.
func NewStreamTransport ¶ added in v0.16.18
NewStreamTransport builds a reusable stream transport whose header budget is owned by httpclient.DoWithHeaderBudget, not a competing fixed transport timer. Callers must dispatch through that helper (as RuntimeExecutor does), including when first-byte observation is disabled. Dial/TLS/idle limits remain intact.
func PathForEndpoint ¶
func PathForEndpoint(endpoint UpstreamEndpoint) string
PathForEndpoint returns the canonical upstream path for a known endpoint type. Unknown endpoints return "".
func RegisterDetectionProfile ¶
func RegisterDetectionProfile(p *types.CliProfileDefinition)
RegisterDetectionProfile adds a profile to the detection chain. Profiles must be registered in priority order: claude_code -> codex -> gemini_cli.
func RegisterFallbackProfile ¶
func RegisterFallbackProfile(p *types.CliProfileDefinition)
RegisterFallbackProfile registers a profile for map lookup only (not in detection chain).
func RequestCeiling ¶ added in v0.16.22
RequestCeiling returns the whole-request timeout for buffered upstream dispatch: max(DefaultRequestCeiling, firstByteTimeout*2). The doubling keeps multi-endpoint fallback able to complete when an operator raises the first-byte window above the default ceiling.
This is the single source of truth shared by the executor wiring (app.WireProxyUpstream) and the server-side write budget below, so the two can never drift apart again.
func RequestIDFromContext ¶
RequestIDFromContext returns the Metapi request/trace id when present. Falls back to chi's middleware.GetReqID so ingress middleware and attempt loops share the same correlation value without extra wiring.
func ResponsesOnlyChatUnsupportedMessage ¶
ResponsesOnlyChatUnsupportedMessage is the clear client error when a chat/completions (or messages) client hits a responses-only site and transform is not available. Used when DISABLE_CROSS_PROTOCOL_FALLBACK is true and body cannot be rewritten.
func RoutingProtocolForPath ¶ added in v0.24.0
RoutingProtocolForPath supplies the request context used by both execution and administrator previews. Only generation surfaces allow conversion; count_tokens retains native-protocol authorization.
func SelectProxyChannelForAttempt ¶
func SelectProxyChannelForAttempt( ctx context.Context, router TokenRouterInterface, coord *ProxyChannelCoordinator, input ChannelSelectionInput, ) (*routing.SelectedChannel, error)
SelectProxyChannelForAttempt selects a channel for the current attempt. Paths: tester forced -> normal selection (first attempt may retry selection once when the store returned no channels).
func ShouldAbortSameSiteEndpointFallback ¶
ShouldAbortSameSiteEndpointFallback decides whether to abort endpoint fallback within the same site. Used by the endpoint flow to stop trying other endpoints when the failure looks systemic (rate limit, gateway error, etc.).
Scope note : this aborts *endpoint-list* fallback on one selected channel/site attempt — it does NOT mark sibling channels failed and does NOT expand request-local excludeChannelIDs. Channel failover remains channel-scoped via SelectNextChannel / conductor exclude lists.
func ShouldDowngradeToNextEndpoint ¶
ShouldDowngradeToNextEndpoint reports whether an upstream error indicates the current protocol/path is wrong and a different endpoint candidate should be tried.
func ShouldForceUpstreamStream ¶
func ShouldForceUpstreamStream(pref SiteProtocolPreference, upstreamPath string, isCompact bool) bool
Forces stream when: - site PreferStream / ResponsesOnly and path is responses (non-compact) - platform-level ShouldForceResponsesUpstreamStream (codex/sub2api) — callers may combine with transform/openai/responses helpers
func ShouldRecordChannelFailure ¶ added in v0.27.0
ShouldRecordChannelFailure separates upstream faults from client request errors for channel health. A 4xx response that the retry policy classifies as non-retryable is a request validation failure, not evidence that the channel is unhealthy; recording it would put a healthy channel into cooldown after a malformed client request. Transport failures and 5xx responses are always channel failures.
func ShouldRetryProxyRequest ¶
ShouldRetryProxyRequest classifies an upstream failure for channel-level retry decisions. Returns true if the proxy should retry with a different channel or the same channel.
Decision matrix:
- Status inside the operator-tunable retry ranges: retryable. The default ranges (routing.DefaultRetryStatusRangesSpec) reproduce exactly the historical hardcoded verdicts: >= 500, 408/409/425/429, and 401/403 (auth faults an OAuth token refresh may resolve). Operators can narrow or widen the set at runtime (proxy_retry_status_ranges setting).
- Error text matches model-unsupported patterns: retryable (try another channel)
- Error text matches non-retryable request patterns: non-retryable (bad request)
- Error text matches retryable channel-local patterns: retryable
- 400/404/422: non-retryable (unless error text overrides)
- Other: non-retryable
func WithRequestID ¶
WithRequestID stores requestID on ctx. Empty ids are ignored.
func WriteBudget ¶ added in v0.16.22
WriteBudget returns the write-deadline budget for a proxy surface response.
net/http arms the connection write deadline with Server.WriteTimeout (60s in app.newHTTPServer) right after the request header is read, so that deadline also covers the time the handler spends waiting for the upstream. With the executor ceiling at 90s the two inverted: a buffered response that arrived between 61s and 90s was killed while writing it back to the client. The proxy surface therefore re-arms its own deadline (router.ProxyWriteDeadline) from this budget, which is always >= RequestCeiling.
Types ¶
type ChannelLoadSnapshot ¶
type ChannelLoadSnapshot struct {
ChannelID int64
SessionScoped bool
ConcurrencyLimit int
ActiveLeaseCount int
WaitingCount int
LoadRatio float64
Saturated bool
}
ChannelLoadSnapshot is a snapshot of channel load.
type ChannelSelectionInput ¶
type ChannelSelectionInput struct {
RequestedModel string
DownstreamPolicy routing.DownstreamRoutingPolicy
// ExcludeChannelIDs is a request-local list of already-tried channel IDs.
// Scope is channel-only: callers must not expand this to all channels of a
// site. Same-site siblings stay eligible unless routing policy (cooldown /
// site breaker / credential-scoped usage-limit) independently filters them.
//
ExcludeChannelIDs []int64
RetryCount int
ForcedChannelID *int64
}
ChannelSelectionInput is the input for SelectProxyChannelForAttempt.
type CliProfileCapabilities ¶
type CliProfileCapabilities = types.CliProfileCapabilities
Re-export types for convenience so callers don't need to import proxy/types.
type CliProfileDefinition ¶
type CliProfileDefinition = types.CliProfileDefinition
Re-export types for convenience so callers don't need to import proxy/types.
type CliProfileID ¶
type CliProfileID = types.CliProfileID
Re-export types for convenience so callers don't need to import proxy/types.
type DetectInput ¶
type DetectInput = types.DetectInput
Re-export types for convenience so callers don't need to import proxy/types.
type DetectedProfile ¶
type DetectedProfile = types.DetectedProfile
Re-export types for convenience so callers don't need to import proxy/types.
type DownstreamClientContext ¶
type DownstreamClientContext struct {
ClientKind string
ClientAppID string
ClientAppName string
ClientConfidence string
SessionID string
TraceHint string
Capabilities CliProfileCapabilities
}
DownstreamClientContext holds the detected downstream client context.
func DetectClientContext ¶
func DetectClientContext(downstreamPath string, headers map[string]string, body any) DownstreamClientContext
DetectClientContext detects the downstream client context from request metadata.
type EndpointCandidateOptions ¶
type EndpointCandidateOptions struct {
// DisableCrossProtocolFallback limits candidates to the primary endpoint only.
// When ResponsesOnly is set, primary is forced to responses regardless of
// downstream path (chat/messages clients are rewritten to responses).
DisableCrossProtocolFallback bool
// Preference is the site protocol preference (responses-only / stream).
Preference SiteProtocolPreference
}
EndpointCandidateOptions controls multi-protocol candidate ordering.
type ExecutorDispatchInput ¶
type ExecutorDispatchInput struct {
SiteURL string
TargetURL string
Method string
Headers map[string]string
Body []byte
Signal <-chan struct{}
}
ExecutorDispatchInput is the input for dispatching an HTTP request.
type ExecutorDispatchResult ¶
type ExecutorDispatchResult struct {
Status int
Headers map[string]string
Body []byte
BodyReader io.ReadCloser
}
ExecutorDispatchResult is the result of dispatching an HTTP request.
type FailureCode ¶ added in v0.17.0
type FailureCode string
FailureCode names why the single content judge declared a failure. A code keeps the same meaning wherever it is logged, stored or alerted on; explicit protocol-error evidence is currently supplied by the streaming path.
const ( // FailureCodeNone means the content judgement found no failure. FailureCodeNone FailureCode = "" // FailureCodeErrorEvent means the upstream explicitly reported a protocol // error, independent of optional keyword and empty-content heuristics. FailureCodeErrorEvent FailureCode = "upstream_error_event" // FailureCodeErrorKeyword means the upstream content matched an operator // configured PROXY_ERROR_KEYWORDS entry. FailureCodeErrorKeyword FailureCode = "upstream_error_keyword" // FailureCodeEmptyContent means PROXY_EMPTY_CONTENT_FAIL is enabled and the // upstream produced neither completion output nor completion tokens. FailureCodeEmptyContent FailureCode = "upstream_empty_content" )
type ProxyChannelCoordinator ¶
type ProxyChannelCoordinator struct{}
ProxyChannelCoordinator tracks per-channel session load for routing.
Sticky-session leases (AcquireChannelLease / BindStickyChannel, the waiter queue, and lease keepalive/expiry goroutines) are DEFERRED: no caller in the proxy acquires leases today, so that machinery was removed in chore/rm-dead-proxy-routing and can be reintroduced from git history when sticky sessions are wired up. Until then every load snapshot reports zero active leases and zero waiters.
func NewProxyChannelCoordinator ¶
func NewProxyChannelCoordinator() *ProxyChannelCoordinator
NewProxyChannelCoordinator creates a new coordinator. The session-channel concurrency limit is read from the runtime-settings snapshot on every acquire so a settings change hot-applies without a restart.
func (*ProxyChannelCoordinator) GetActiveChannelIDs ¶
func (c *ProxyChannelCoordinator) GetActiveChannelIDs() []int64
GetActiveChannelIDs returns channel IDs with active leases. Leases are deferred (see ProxyChannelCoordinator), so this is always empty.
func (*ProxyChannelCoordinator) GetChannelLoadSnapshot ¶
func (c *ProxyChannelCoordinator) GetChannelLoadSnapshot( channelID int64, extraConfig *string, oauthProvider *string, ) ChannelLoadSnapshot
GetChannelLoadSnapshot returns a snapshot of a channel's load. Leases are deferred (see ProxyChannelCoordinator), so active and waiting counts are always zero.
func (*ProxyChannelCoordinator) Reset ¶
func (c *ProxyChannelCoordinator) Reset()
Reset resets all state (for testing).
type ProxyLogEntry ¶
type ProxyLogEntry struct {
OwnerUserID *int64
UserGroupID *int64
GatewayRequestID string
DownstreamPath *string
UpstreamReportedModel *string
RouteID *int64
ChannelID *int64
UpstreamChannelID *int64
UpstreamGrantID *int64
AccountID *int64
DownstreamAPIKeyID *int64
ModelRequested string
ModelActual *string
Status string
HTTPStatus int
IsStream *bool
FirstByteLatencyMs *int64
FirstOutputLatencyMs *int64
LatencyMs int64
PromptTokens *int64
CompletionTokens *int64
TotalTokens *int64
EstimatedCost float64
BillingDetails any
ClientFamily string
ClientAppID string
ClientAppName string
ClientConfidence string
ErrorMessage *string
RetryCount int
// RequestID correlates multi-channel retry/failover attempts for one client call.
// Same value as chi X-Request-Id / middleware.GetReqID for the ingress request.
RequestID string
UpstreamPath *string
UsageSource string
}
ProxyLogEntry is a single proxy log row.
type RuntimeExecutor ¶
type RuntimeExecutor struct {
// contains filtered or unexported fields
}
RuntimeExecutor dispatches upstream HTTP requests.
func NewRuntimeExecutor ¶
func NewRuntimeExecutor(requestTimeout time.Duration) *RuntimeExecutor
NewRuntimeExecutor creates a new RuntimeExecutor with the given timeout. The client refuses cross-origin redirects (and https→http) to block SSRF via 302 to a different host / private / metadata endpoint.
func (*RuntimeExecutor) Dispatch ¶
func (e *RuntimeExecutor) Dispatch(ctx context.Context, input ExecutorDispatchInput) (*ExecutorDispatchResult, error)
Dispatch sends an HTTP request to the upstream.
func (*RuntimeExecutor) DoStreamWithObservedFirstByte ¶ added in v0.16.18
func (e *RuntimeExecutor) DoStreamWithObservedFirstByte( ctx context.Context, req *http.Request, firstByteTimeoutMs int64, ) (*http.Response, error)
DoStreamWithObservedFirstByte dispatches through the stream client without a whole-request timeout. The shared header-budget owner uses the explicit first-byte timeout, or DefaultRequestCeiling when observation is disabled. Once headers arrive, only the caller and relay body-idle guard may cancel a healthy stream; callers must close resp.Body to release the request context.
func (*RuntimeExecutor) DoWithObservedFirstByte ¶
func (e *RuntimeExecutor) DoWithObservedFirstByte( ctx context.Context, req *http.Request, firstByteTimeoutMs int64, ) (*http.Response, error)
DoWithObservedFirstByte sends req and observes first-byte (response header) latency. Unlike WithObservedFirstByte it does NOT buffer the body, so callers (including streaming handlers) must close resp.Body themselves.
When firstByteTimeoutMs > 0 and the deadline fires before headers arrive, it returns (nil, ErrObservedFirstByteTimeout). firstByteTimeoutMs is milliseconds (see FirstByteTimeoutMs).
After headers arrive the first-byte timer is stopped so the body stream is not cancelled by the observation deadline.
func (*RuntimeExecutor) WithObservedFirstByte ¶
func (e *RuntimeExecutor) WithObservedFirstByte( ctx context.Context, input ExecutorDispatchInput, firstByteTimeoutMs int64, ) (*ExecutorDispatchResult, int64, error)
WithObservedFirstByte dispatches a request and observes the first-byte latency. Returns a special result with status=0 if the first-byte timeout fires. firstByteTimeoutMs is milliseconds (see FirstByteTimeoutMs).
type SelectionExplainer ¶ added in v0.18.0
type SelectionExplainer interface {
ExplainSelection(ctx context.Context, requestedModel string, excludeChannelIDs []int64, policy routing.DownstreamRoutingPolicy) (routing.RouteDecisionExplanation, error)
}
SelectionExplainer is the optional capability routing.TokenRouter brings to a failed selection: why nothing was selectable. Unit stubs may omit it, and then the failure is reported without a reason instead of failing harder — the same optional-interface idiom AvailableModelsSource uses for model listing.
type SiteConcurrencyLimiter ¶
type SiteConcurrencyLimiter struct {
// contains filtered or unexported fields
}
SiteConcurrencyLimiter caps concurrent upstream dispatches per scope. It is orthogonal to ProxyChannelCoordinator channel leases: a request may hold both a site slot and a channel lease independently.
The scope key is a site ID for regular channels and an upstream credential ID for direct channels (see DefaultDirectAccountConcurrencyLimiter); the two populations use separate limiter instances so their ID spaces never collide.
Semantics: - limit <= 0 → unlimited (always acquire; no tracking) - limit > 0 → at most that many concurrent held slots per scope key
On saturation callers must skip to the next channel/site and must NOT mark the channel expired or record a routing failure cascade.
func NewSiteConcurrencyLimiter ¶
func NewSiteConcurrencyLimiter() *SiteConcurrencyLimiter
NewSiteConcurrencyLimiter creates an empty site-scoped limiter.
func (*SiteConcurrencyLimiter) ActiveCount ¶
func (l *SiteConcurrencyLimiter) ActiveCount(siteID int64) int
ActiveCount returns the number of currently held slots for siteID. Unlimited / unknown sites report 0.
func (*SiteConcurrencyLimiter) TryAcquire ¶
func (l *SiteConcurrencyLimiter) TryAcquire(siteID int64, maxConcurrency int64) (*SiteSlot, bool)
TryAcquire attempts to take one concurrency slot for siteID.
Returns (slot, true) when the call may proceed. slot is never nil on success; for unlimited sites the slot is a no-op (Release is still safe). Returns (nil, false) when the site is saturated — caller should skip this site/channel without recording failure.
type SiteProtocolPreference ¶
type SiteProtocolPreference = profiles.SiteProtocolPreference
SiteProtocolPreference re-exports profiles.SiteProtocolPreference for callers that already depend on proxy (handler layer).
func DetectSiteProtocolPreferenceFromSite ¶
func DetectSiteProtocolPreferenceFromSite(platform, siteURL string, customHeadersJSON *string) SiteProtocolPreference
DetectSiteProtocolPreferenceFromSite is a convenience for store.Site-like fields.
type SiteSlot ¶
type SiteSlot struct {
// contains filtered or unexported fields
}
SiteSlot is a held (or no-op) concurrency permit for one attempt scope (site or direct credential). Always call Release exactly once when the upstream attempt finishes.
type TokenRouterInterface ¶
type TokenRouterInterface interface {
SelectChannel(ctx context.Context, requestedModel string, policy routing.DownstreamRoutingPolicy) (*routing.SelectedChannel, error)
SelectNextChannel(ctx context.Context, requestedModel string, excludeChannelIDs []int64, policy routing.DownstreamRoutingPolicy) (*routing.SelectedChannel, error)
SelectPreferredChannel(ctx context.Context, requestedModel string, preferredChannelID int64, policy routing.DownstreamRoutingPolicy, excludeChannelIDs []int64) (*routing.SelectedChannel, error)
RecordSuccess(ctx context.Context, channelID int64, latencyMs float64, cost float64, modelName *string, actualAccountID *int64) error
RecordFailure(ctx context.Context, channelID int64, failureCtx routing.SiteRuntimeFailureContext, actualAccountID *int64) error
}
TokenRouterInterface is the interface for channel selection. This allows the proxy layer to depend on routing without circular imports.
type UpstreamBufferedBody ¶ added in v0.17.0
type UpstreamBufferedBody struct {
// Bytes is what the caller must parse AND relay. Identity or freshly
// decoded bytes when Readable; the untouched encoded bytes otherwise.
Bytes []byte
// Readable reports whether Bytes is actual content. When false the caller
// MUST skip usage extraction and content judgement, record usage as
// unknown, and relay Bytes together with the upstream Content-Encoding.
Readable bool
// Encoding is the classification, for logging.
Encoding UpstreamEncoding
// DecodeErr carries the stdlib failure when a codec we do implement could
// not actually decode the body (corrupt, truncated, or the decoded size
// exceeded the buffered limit). Logging only — the honesty contract is the
// same as for an unsupported codec.
DecodeErr error
}
UpstreamBufferedBody is the buffered-body view the data plane parses and relays. It is the single answer to "what do the bytes I just read mean?".
func NormalizeUpstreamBufferedBody ¶ added in v0.17.0
func NormalizeUpstreamBufferedBody(h http.Header, body []byte) UpstreamBufferedBody
NormalizeUpstreamBufferedBody applies the encoding decision to a buffered upstream body. resp.Header is mutated exactly when the body was decoded: the Content-Encoding is deleted so the existing relay whitelist cannot forward a header that no longer describes the bytes we are about to write.
type UpstreamContentFacts ¶ added in v0.17.0
type UpstreamContentFacts struct {
// StatusCode is the HTTP status the upstream answered with. The judgement
// itself stays status-agnostic (callers only judge 2xx answers); it is
// carried so a verdict can be traced back to its attempt.
StatusCode int
// Streaming marks the SSE path, which has no raw body to inspect.
Streaming bool
// RawText is the content to keyword-scan. Buffered: the full response body.
// Streaming: the concatenated SSE error-event payloads, the only content
// signal the bounded analyzer keeps.
RawText string
// HasOutput reports whether the upstream produced completion content.
// Streaming callers set it from output-bearing events; the buffered
// path leaves it false and the judge derives it from RawText.
HasOutput bool
// HasErrorEvent reports a parsed protocol error, not output mentioning an
// error. Streaming callers set it from the SSE analyzer.
HasErrorEvent bool
// Usage is the parsed usage summary (nil when the upstream sent none).
Usage *UsageSummary
// Unreadable reports that the bytes behind these facts could not be read at
// all — an upstream Content-Encoding we do not decode (br/zstd/a stacked
// list), or a codec we do implement that failed on this body. It is the
// caller's honest admission that it has NO content evidence, and it short-
// circuits the whole judgement: a body we cannot parse must never be turned
// into a failure, because that records a 502 against a channel whose answer
// may have been perfectly good (see proxy/upstream_encoding.go).
Unreadable bool
}
UpstreamContentFacts is the protocol-agnostic description of what an upstream actually returned. Each call path fills it from data it already has: the buffered path from the raw response body, the streaming path from the bounded incremental SSE analyzer (which never retains the raw body).
type UpstreamEncoding ¶ added in v0.17.0
type UpstreamEncoding struct {
// Value is the raw Content-Encoding header value ("" when absent).
Value string
// Kind is the readability classification of Value.
Kind UpstreamEncodingKind
}
UpstreamEncoding is the classification of one upstream response body.
func ClassifyUpstreamEncoding ¶ added in v0.17.0
func ClassifyUpstreamEncoding(h http.Header) UpstreamEncoding
ClassifyUpstreamEncoding is the ONE owner of "can we read this upstream body?". Both the buffered and the streaming dispatch path classify through it, so the two can never disagree about what an encoding means.
net/http already handles the dominant case before we get here: when the outbound request carried no explicit Accept-Encoding, the transport adds "gzip" itself, transparently decompresses a gzip answer and deletes Content-Encoding / Content-Length from resp.Header — which lands here as identity. This function therefore only ever sees an encoding the transport refused to touch: a codec it does not implement (deflate/br/zstd), a multi-layer stack, or a gzip answer that arrived on a transport which did not negotiate it.
func (UpstreamEncoding) Decodable ¶ added in v0.17.0
func (e UpstreamEncoding) Decodable() bool
Decodable reports whether a stdlib codec can turn the body into identity.
func (UpstreamEncoding) Readable ¶ added in v0.17.0
func (e UpstreamEncoding) Readable() bool
Readable reports whether the bytes the caller holds (after Decode for a decodable encoding) may be parsed as content. When false, usage extraction and content judgement must both be skipped: unreadable bytes carry no evidence, and inventing a failure from them is what poisons channel health with perfectly healthy upstream answers.
func (UpstreamEncoding) RelayHeader ¶ added in v0.17.0
func (e UpstreamEncoding) RelayHeader() bool
RelayHeader reports whether the upstream Content-Encoding must stay on the response relayed to the downstream client. True exactly when the bytes are relayed verbatim and therefore still encoded; false once we decoded them (we re-frame the body ourselves, so keeping the header would be a lie) and false when there is no header to relay.
func (UpstreamEncoding) String ¶ added in v0.17.0
func (e UpstreamEncoding) String() string
String keeps log lines readable.
type UpstreamEncodingKind ¶ added in v0.17.0
type UpstreamEncodingKind int
UpstreamEncodingKind classifies an upstream Content-Encoding by what it means for our ability to READ the body. That ability — not the header itself — is what decides whether usage may be accounted and whether the content judge may run at all.
const ( // UpstreamEncodingIdentity means the bytes we hold are the content: no // Content-Encoding, or the explicit "identity" token. Everything downstream // (usage extraction, keyword scan, empty-content rule) may run. UpstreamEncodingIdentity UpstreamEncodingKind = iota // UpstreamEncodingDecodable means a stdlib codec can turn the bytes back // into identity (gzip / deflate). The caller decodes, parses the decoded // bytes and re-frames the response WITHOUT Content-Encoding. UpstreamEncodingDecodable // UpstreamEncodingUndecodable means we cannot read the bytes at all (br, // zstd, a multi-layer stack, or a codec that failed mid-decode). The caller // MUST NOT parse, judge or account them, and MUST relay them verbatim // together with their Content-Encoding so the client — which may well be // able to decode them — still gets an intact response. UpstreamEncodingUndecodable )
type UpstreamEndpoint ¶
type UpstreamEndpoint string
UpstreamEndpoint represents an upstream API endpoint type.
const ( EndpointChat UpstreamEndpoint = "chat" // /v1/chat/completions EndpointMessages UpstreamEndpoint = "messages" // /v1/messages (Anthropic) EndpointResponses UpstreamEndpoint = "responses" // /v1/responses (Codex) EndpointGemini UpstreamEndpoint = "gemini" // native generateContent EndpointOllama UpstreamEndpoint = "ollama" // native /api/chat )
func EndpointFromPath ¶
func EndpointFromPath(path string) (UpstreamEndpoint, bool)
EndpointFromPath maps a downstream path to a known chat-family endpoint. Non chat-family paths return ("", false).
func ResolveEndpointCandidates ¶
func ResolveEndpointCandidates(downstreamPath string, disableCrossProtocolFallback bool) []UpstreamEndpoint
For responses-only sites, prefer ResolveEndpointCandidatesWithOptions.
func ResolveEndpointCandidatesWithOptions ¶
func ResolveEndpointCandidatesWithOptions(downstreamPath string, opts EndpointCandidateOptions) []UpstreamEndpoint
Policy: - responses-only site → only EndpointResponses (even if client called chat/messages) - prefer-responses → responses first, then remaining chat-family endpoints - disableCrossProtocolFallback → single primary (responses when responses-only) - non chat-family path → nil (caller uses original path)
type UpstreamStreamBody ¶ added in v0.17.0
type UpstreamStreamBody struct {
// Reader replaces the upstream body when the stream must be decoded. Nil
// means "keep the body you already have" (identity, or undecodable).
Reader io.ReadCloser
// Readable reports whether the relayed chunks are actual SSE content. When
// false the SSE analyzer must not be fed and the content judge must not
// run; the chunks are relayed verbatim with the upstream Content-Encoding.
Readable bool
// Encoding is the classification, for logging.
Encoding UpstreamEncoding
}
UpstreamStreamBody is the streaming counterpart of UpstreamBufferedBody: the same classification, plus a replacement reader when the codec is one we implement.
func WrapUpstreamStreamBody ¶ added in v0.17.0
func WrapUpstreamStreamBody(h http.Header, body io.ReadCloser) UpstreamStreamBody
WrapUpstreamStreamBody applies the encoding decision to a streaming upstream body. Decoding is lazy: the codec header is read on the first Read so this call never blocks before the downstream SSE headers go out.
type UpstreamVerdict ¶ added in v0.17.0
type UpstreamVerdict struct {
Failed bool
Code FailureCode
Status int
Reason string
}
UpstreamVerdict is the single content judgement result.
func JudgeUpstreamContent ¶ added in v0.17.0
func JudgeUpstreamContent(facts UpstreamContentFacts) UpstreamVerdict
JudgeUpstreamContent is the ONE owner of content-level failure judgement. Both the buffered and the streaming dispatch path call it, so the two can no longer drift apart in judgement strength — the historical split (buffered judged, stream only logged) is what let a failed upstream answer be recorded as a success.
Pure: no I/O, no *http.Response, no protocol plumbing. Same facts in, same verdict out.
Detection: 0. Unreadable body: no judgement at all (see UpstreamContentFacts.Unreadable) 1. Keyword matching: if config.ProxyErrorKeywords is non-empty, case-insensitive 2. Explicit protocol error events: always fail, even with output or usage 3. Empty content check: if ProxyEmptyContentFailEnabled and no completion tokens + no output
type UsageSummary ¶
UsageSummary is a lightweight usage summary for failure detection.