proxy

package
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Aug 13, 2026 License: MIT Imports: 22 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 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

View Source
const (
	TesterRequestHeader       = "x-metapi-tester-request"
	TesterForcedChannelHeader = "x-metapi-tester-forced-channel-id"
)

Tester header constants.

View Source
const (
	ProfileGeneric    = types.ProfileGeneric
	ProfileCodex      = types.ProfileCodex
	ProfileClaudeCode = types.ProfileClaudeCode
	ProfileGeminiCli  = types.ProfileGeminiCli
)
View Source
const DefaultMaxBufferedResponseBodyBytes int64 = 20 << 20
View Source
const DefaultMaxRefreshAuthSuccesses = 1

DefaultMaxRefreshAuthSuccesses caps successful RefreshAuth calls per channel before the conductor fails over with a channel-scoped exclude.

View Source
const KeyProxyPrecedence = "key > account > site > system > direct"

Product intent: multi-tenant downstream keys may need distinct egress even when they share the same upstream site/account channel. A non-empty key proxy therefore wins over site and account proxies. NULL / empty key proxy preserves pre-SC2 behavior (inherit site/account/system).

Variables

View Source
var DefaultSiteConcurrencyLimiter = NewSiteConcurrencyLimiter()

DefaultSiteConcurrencyLimiter is the process-global site limiter used by the proxy data plane when UpstreamConfig does not inject a custom instance.

View Source
var ErrBufferedResponseBodyTooLarge = errors.New("upstream response body exceeded buffered limit")
View Source
var ErrObservedFirstByteTimeout = errors.New("first byte timeout")

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 ApplyStreamPreference

func ApplyStreamPreference(body map[string]any, pref SiteProtocolPreference, upstreamPath string, isCompact bool) (map[string]any, bool)

ApplyStreamPreference mutates a shallow copy of body to set stream=true when ShouldForceUpstreamStream is true. Returns the (possibly same) body map and whether stream was forced.

func BindSurfaceStickyChannel

func BindSurfaceStickyChannel(
	coord *ProxyChannelCoordinator,
	key string,
	channelID int64,
	extraConfig *string,
	oauthProvider *string,
)

BindSurfaceStickyChannel binds a surface request to a sticky channel.

func BuildForcedChannelUnavailableMessage

func BuildForcedChannelUnavailableMessage(forcedChannelID *int64) string

BuildForcedChannelUnavailableMessage builds a human-readable message for forced channel unavailability.

func BuildSurfaceChannelBusyMessage

func BuildSurfaceChannelBusyMessage(waitMs int64) string

BuildSurfaceChannelBusyMessage builds a human-readable channel busy message.

func BuildSurfaceStickySessionKey

func BuildSurfaceStickySessionKey(
	coord *ProxyChannelCoordinator,
	clientKind string,
	sessionID string,
	requestedModel string,
	downstreamPath string,
	downstreamAPIKeyID *int64,
) string

BuildSurfaceStickySessionKey builds a sticky session key for a surface request.

func BuildUpstreamURL

func BuildUpstreamURL(siteURL, path string) string

BuildUpstreamURL constructs an upstream URL from a site URL and path.

func CanRetryChannelSelection

func CanRetryChannelSelection(retryCount int, maxRetries int, forcedChannelID *int64) bool

CanRetryChannelSelection checks if a channel retry is possible. Returns false if a forced channel is set (no fallback), or if max retries reached.

func ClearSurfaceStickyChannel

func ClearSurfaceStickyChannel(coord *ProxyChannelCoordinator, key string, channelID int64)

ClearSurfaceStickyChannel clears the sticky channel binding.

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 EnsureRequestID

func EnsureRequestID(ctx context.Context, fallback string) (context.Context, string)

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 FirstByteTimeoutMs

func FirstByteTimeoutMs(proxyFirstByteTimeoutSec int) int64

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 GetProfileDefinition

func GetProfileDefinition(id types.CliProfileID) *types.CliProfileDefinition

GetProfileDefinition returns a profile by ID.

func GetProxyMaxChannelAttempts

func GetProxyMaxChannelAttempts(cfgMaxChannelAttempts int) int

GetProxyMaxChannelAttempts returns the configured max channel attempts (min 1).

func GetProxyMaxChannelRetries

func GetProxyMaxChannelRetries(maxChannelAttempts int) int

GetProxyMaxChannelRetries returns max channel retries (attempts - 1, min 0).

func GetSurfaceStickyPreferredChannelID

func GetSurfaceStickyPreferredChannelID(coord *ProxyChannelCoordinator, key string) *int64

GetSurfaceStickyPreferredChannelID returns the preferred channel ID from the sticky session.

func GetTesterForcedChannelID

func GetTesterForcedChannelID(headers map[string]string, clientIP string) *int64

GetTesterForcedChannelID extracts the forced channel ID from tester headers.

func IsLoopbackClientIP

func IsLoopbackClientIP(ip string) bool

IsLoopbackClientIP checks if a client IP is loopback.

func IsMetapiControlHeader

func IsMetapiControlHeader(name string) bool

IsMetapiControlHeader reports whether a custom header is a MetAPI control signal that must not be forwarded upstream (responses-only / stream preference marks).

func IsObservedFirstByteTimeout

func IsObservedFirstByteTimeout(result *ExecutorDispatchResult) bool

IsObservedFirstByteTimeout checks if a result represents a first-byte timeout.

func IsObservedFirstByteTimeoutError

func IsObservedFirstByteTimeoutError(err error) bool

IsObservedFirstByteTimeoutError reports whether err is a first-byte timeout.

func IsResponsesOnlySite

func IsResponsesOnlySite(platform, siteURL string, customHeaders map[string]string) bool

IsResponsesOnlySite reports whether the site is responses-only.

func IsSessionScopedChannel

func IsSessionScopedChannel(extraConfig *string, oauthProvider *string) bool

IsSessionScopedChannel checks if a channel uses session-scoped credentials.

func IsTrustedTesterRequest

func IsTrustedTesterRequest(headers map[string]string, clientIP string) bool

IsTrustedTesterRequest checks if the request is from a trusted tester (loopback + header).

func MaxBufferedResponseBodyBytes

func MaxBufferedResponseBodyBytes() int64

func PathForEndpoint

func PathForEndpoint(endpoint UpstreamEndpoint) string

PathForEndpoint returns the canonical upstream path for a known endpoint type. Unknown endpoints return "".

func ReadBufferedResponseBody

func ReadBufferedResponseBody(r io.Reader) ([]byte, error)

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 RequestIDFromContext

func RequestIDFromContext(ctx context.Context) string

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 ResolveKeyProxyURL

func ResolveKeyProxyURL(proxyURL *string) *string

ResolveKeyProxyURL normalizes a nullable proxy URL pointer. Whitespace-only and empty values become nil (inherit).

func ResponsesOnlyChatUnsupportedMessage

func ResponsesOnlyChatUnsupportedMessage(downstreamPath string) string

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 SelectProxyChannelForAttempt

func SelectProxyChannelForAttempt(
	ctx context.Context,
	router TokenRouterInterface,
	coord *ProxyChannelCoordinator,
	routeRefresher RouteRefreshWorkflow,
	input ChannelSelectionInput,
) (*routing.SelectedChannel, error)

SelectProxyChannelForAttempt selects a channel for the current attempt. Implements the dual-path selection: tester forced -> sticky preference -> normal -> route refresh.

func ShouldAbortSameSiteEndpointFallback

func ShouldAbortSameSiteEndpointFallback(status int, upstreamErrorText string) bool

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

func ShouldDowngradeToNextEndpoint(status int, rawErrText string) bool

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 ShouldRetryProxyRequest

func ShouldRetryProxyRequest(status int, upstreamErrorText string) bool

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: - >= 500: always retryable - 408/409/425/429: always retryable - 401/403: retryable (may be resolved by OAuth token refresh) - 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 SummarizeUpstreamError

func SummarizeUpstreamError(status int, rawErrText string) string

SummarizeUpstreamError creates a human-readable upstream error summary.

func WithRequestID

func WithRequestID(ctx context.Context, requestID string) context.Context

WithRequestID stores requestID on ctx. Empty ids are ignored.

func WithUpstreamPath

func WithUpstreamPath(path, message string) string

WithUpstreamPath prefixes a message with the upstream path context.

Types

type AcquireResult

type AcquireResult struct {
	Status string        // "acquired" or "timeout"
	Lease  *ChannelLease // non-nil only for "acquired"
	WaitMs int64         // wait duration before timeout (0 for instant)
}

AcquireResult is the result of acquiring a channel lease.

func AcquireSurfaceChannelLease

func AcquireSurfaceChannelLease(
	coord *ProxyChannelCoordinator,
	stickySessionKey string,
	channelID int64,
	extraConfig *string,
	oauthProvider *string,
) AcquireResult

AcquireSurfaceChannelLease acquires a channel lease for a surface request. Uses channelId=0 (noop) when no sticky session key is present.

type AttemptFailureAction

type AttemptFailureAction string

AttemptFailureAction indicates what the conductor should do after a failed attempt.

const (
	ActionRetrySameChannel AttemptFailureAction = "retry_same_channel"
	ActionRefreshAuth      AttemptFailureAction = "refresh_auth"
	ActionFailover         AttemptFailureAction = "failover"
	ActionTerminal         AttemptFailureAction = "terminal"
	ActionStop             AttemptFailureAction = "stop"
)

type AttemptInput

type AttemptInput struct {
	Selected          *routing.SelectedChannel
	AttemptIndex      int
	ExcludeChannelIDs []int64
}

AttemptInput is the input for an attempt callback.

type AttemptResult

type AttemptResult struct {
	OK           bool
	Response     any
	Status       int
	RawErrorText string
	LatencyMs    int64
	Cost         float64
}

AttemptResult is the result of an attempt callback.

type BuiltEndpointRequest

type BuiltEndpointRequest struct {
	Endpoint UpstreamEndpoint
	Path     string
	Headers  map[string]string
	Body     map[string]any
	Runtime  *EndpointRuntime
}

BuiltEndpointRequest is a built upstream request for a specific endpoint.

type ChannelLease

type ChannelLease struct {
	ChannelID int64
	// contains filtered or unexported fields
}

ChannelLease is a lease on a session-scoped channel.

func (*ChannelLease) IsActive

func (l *ChannelLease) IsActive() bool

IsActive returns whether the lease is still active.

func (*ChannelLease) Release

func (l *ChannelLease) Release()

Release releases the lease, freeing the channel slot.

func (*ChannelLease) Touch

func (l *ChannelLease) Touch()

Touch extends the lease TTL.

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
	StickySessionKey  string
	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 ConductorDependencies

type ConductorDependencies struct {
	SelectChannel          func(ctx context.Context, requestedModel string, policy routing.DownstreamRoutingPolicy) (*routing.SelectedChannel, error)
	SelectNextChannel      func(ctx context.Context, requestedModel string, excludeChannelIDs []int64, policy routing.DownstreamRoutingPolicy) (*routing.SelectedChannel, error)
	PreviewSelectedChannel func(ctx context.Context, requestedModel string, policy routing.DownstreamRoutingPolicy) (*routing.SelectedChannel, error)
	RefreshAuth            func(ctx context.Context, selected *routing.SelectedChannel, failureCtx struct {
		Status       int
		RawErrorText string
	}) (*routing.SelectedChannel, error)
	// MaxAttempts is the hard total attempt budget covering same-channel retries,
	// auth refresh retries, and cross-channel failover. Values <= 0 resolve via
	// GetProxyMaxChannelAttempts (minimum 1). Prefer wiring config.ProxyMaxChannelAttempts.
	MaxAttempts int
	// MaxRefreshAuthSuccesses caps successful RefreshAuth calls per selected channel
	// before failover. Values <= 0 use DefaultMaxRefreshAuthSuccesses.
	MaxRefreshAuthSuccesses int
}

ConductorDependencies are the injected dependencies for DefaultProxyConductor.

type DefaultProxyConductor

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

DefaultProxyConductor implements action-based retry for non-surface flows.

func NewDefaultProxyConductor

func NewDefaultProxyConductor(deps ConductorDependencies) *DefaultProxyConductor

NewDefaultProxyConductor creates a new conductor.

func (*DefaultProxyConductor) Execute

Execute runs the action-based retry conductor loop.

Hard budget: attempts never exceed maxAttempts (same-channel + refresh + failover). RefreshAuth successes are capped per channel; nil/error RefreshAuth fails over.

func (*DefaultProxyConductor) PreviewSelectedChannel

func (c *DefaultProxyConductor) PreviewSelectedChannel(
	ctx context.Context,
	requestedModel string,
	downstreamPolicy routing.DownstreamRoutingPolicy,
) (*routing.SelectedChannel, error)

PreviewSelectedChannel returns the selected channel without executing a request.

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 Dispatcher

type Dispatcher func(request BuiltEndpointRequest, targetURL string, firstByteTimeoutMs int64) (*ExecutorDispatchResult, error)

Dispatcher is a function that dispatches an HTTP request. If firstByteTimeoutMs > 0, the dispatcher should observe first-byte latency and return a status-0 response on timeout.

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 EndpointAttemptContext

type EndpointAttemptContext struct {
	EndpointIndex  int
	EndpointCount  int
	Request        BuiltEndpointRequest
	TargetURL      string
	Response       *ExecutorDispatchResult
	RawErrText     string
	ErrText        string
	RecoverApplied bool
}

EndpointAttemptContext holds context for an endpoint attempt.

type EndpointAttemptSuccessContext

type EndpointAttemptSuccessContext struct {
	EndpointIndex  int
	EndpointCount  int
	Request        BuiltEndpointRequest
	TargetURL      string
	Response       *ExecutorDispatchResult
	RecoverApplied bool
}

EndpointAttemptSuccessContext holds context for a successful endpoint attempt.

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
	// DownstreamClient may influence preference when Codex profile is detected.
	DownstreamClient *types.DetectedProfile
}

EndpointCandidateOptions controls multi-protocol candidate ordering.

type EndpointFlowResult

type EndpointFlowResult struct {
	OK           bool
	Response     *ExecutorDispatchResult
	UpstreamPath string
	Status       int
	ErrText      string
	RawErrText   string
}

EndpointFlowResult is the result of ExecuteEndpointFlow.

func ExecuteEndpointFlow

func ExecuteEndpointFlow(input ExecuteEndpointFlowInput) EndpointFlowResult

ExecuteEndpointFlow runs the endpoint-level iteration loop. Iterates over endpointCandidates until success or exhaustion.

type EndpointRuntime

type EndpointRuntime struct {
	Executor       string // "default", "codex", "gemini-cli", "antigravity", "claude"
	ModelName      string
	Stream         bool
	OAuthProjectID string
	Action         string // "generateContent", "streamGenerateContent", "countTokens"
}

EndpointRuntime holds runtime metadata for a request.

type ExecuteEndpointFlowInput

type ExecuteEndpointFlowInput struct {
	SiteURL                       string
	ProxyURL                      string
	DisableCrossProtocolFallback  bool
	EndpointCandidates            []UpstreamEndpoint
	BuildRequest                  func(endpoint UpstreamEndpoint, endpointIndex int) BuiltEndpointRequest
	DispatchRequest               func(request BuiltEndpointRequest, targetURL string, firstByteTimeoutMs int64) (*ExecutorDispatchResult, error)
	FirstByteTimeoutMs            int64
	TryRecover                    func(ctx *EndpointAttemptContext) *RecoverResult
	ShouldDowngrade               func(ctx EndpointAttemptContext) bool
	ShouldAbortRemainingEndpoints func(ctx EndpointAttemptContext) bool
	OnDowngrade                   func(ctx EndpointAttemptContext)
	OnAttemptFailure              func(ctx EndpointAttemptContext)
	OnAttemptSuccess              func(ctx EndpointAttemptSuccessContext)
}

ExecuteEndpointFlowInput is the input for ExecuteEndpointFlow.

type ExecuteInput

type ExecuteInput struct {
	RequestedModel    string
	DownstreamPolicy  routing.DownstreamRoutingPolicy
	Attempt           func(ctx context.Context, input AttemptInput) (AttemptResult, error)
	OnTerminalFailure func(ctx context.Context, selected *routing.SelectedChannel, failureCtx struct {
		Status       int
		RawErrorText string
	}) error
}

ExecuteInput is the input for the Execute method.

type ExecuteResult

type ExecuteResult struct {
	OK           bool
	Reason       string // "no_channel", "terminal", "failed"
	Selected     *routing.SelectedChannel
	Response     any
	Status       int
	RawErrorText string
	Attempts     int
}

ExecuteResult is the result of the Execute method.

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 FailureResult

type FailureResult struct {
	Status int
	Reason string
}

FailureResult is a content-based failure detection result.

func DetectProxyFailure

func DetectProxyFailure(rawText string, usage *UsageSummary) *FailureResult

DetectProxyFailure detects proxy failures from response content. This is PURELY content-based — it does NOT look at HTTP status codes. Called AFTER a non-stream response body is received.

Detection: 1. Keyword matching: if config.ProxyErrorKeywords is non-empty, checks case-insensitive 2. Empty content check: if ProxyEmptyContentFailEnabled and no completion tokens + no output

type ProxyChannelCoordinator

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

ProxyChannelCoordinator manages sticky session bindings and channel concurrency leases. Both are conditional: only activate when the downstream request has a valid sticky session key AND the channel's account uses session-scoped credentials.

func NewProxyChannelCoordinator

func NewProxyChannelCoordinator(cfg *config.Config) *ProxyChannelCoordinator

NewProxyChannelCoordinator creates a new coordinator.

func (*ProxyChannelCoordinator) AcquireChannelLease

func (c *ProxyChannelCoordinator) AcquireChannelLease(
	channelID int64,
	extraConfig *string,
	oauthProvider *string,
) AcquireResult

AcquireChannelLease acquires a lease for a channel. Returns noop if channelID <= 0 or concurrency limit is 0.

func (*ProxyChannelCoordinator) BindStickyChannel

func (c *ProxyChannelCoordinator) BindStickyChannel(key string, channelID int64, extraConfig *string, oauthProvider *string)

BindStickyChannel binds a session key to a channel.

func (*ProxyChannelCoordinator) BuildStickySessionKey

func (c *ProxyChannelCoordinator) BuildStickySessionKey(
	clientKind string,
	sessionID string,
	requestedModel string,
	downstreamPath string,
	downstreamAPIKeyID *int64,
) string

BuildStickySessionKey constructs a sticky session key from client context. Returns empty string if sticky sessions are disabled or sessionId/model are missing.

func (*ProxyChannelCoordinator) ClearStickyChannel

func (c *ProxyChannelCoordinator) ClearStickyChannel(key string, channelID int64)

ClearStickyChannel clears a sticky binding. If channelID is provided (>0), only clears if it matches.

func (*ProxyChannelCoordinator) GetActiveChannelIDs

func (c *ProxyChannelCoordinator) GetActiveChannelIDs() []int64

GetActiveChannelIDs returns channel IDs with active leases.

func (*ProxyChannelCoordinator) GetChannelLoadSnapshot

func (c *ProxyChannelCoordinator) GetChannelLoadSnapshot(
	channelID int64,
	extraConfig *string,
	oauthProvider *string,
) ChannelLoadSnapshot

GetChannelLoadSnapshot returns a snapshot of a channel's load.

func (*ProxyChannelCoordinator) GetStickyChannelID

func (c *ProxyChannelCoordinator) GetStickyChannelID(key string) int64

GetStickyChannelID returns the sticky channel ID for a session key, or 0 if none/expired.

func (*ProxyChannelCoordinator) Reset

func (c *ProxyChannelCoordinator) Reset()

ResetProxyChannelCoordinator resets all state (for testing).

type ProxyLogEntry

type ProxyLogEntry struct {
	RouteID            *int64
	ChannelID          *int64
	AccountID          *int64
	DownstreamAPIKeyID *int64
	ModelRequested     string
	ModelActual        *string
	Status             string
	HTTPStatus         int
	IsStream           *bool
	FirstByteLatencyMs *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 RecoverResult

type RecoverResult struct {
	Response     *ExecutorDispatchResult
	UpstreamPath string
	Request      *BuiltEndpointRequest
	TargetURL    string
}

RecoverResult is the result of a recovery attempt.

type RouteRefreshWorkflow

type RouteRefreshWorkflow interface {
	RefreshModelsAndRebuildRoutes(ctx context.Context) error
}

RouteRefreshWorkflow is the interface for route refresh.

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

Dispatch sends an HTTP request to the upstream.

func (*RuntimeExecutor) Do

func (e *RuntimeExecutor) Do(req *http.Request) (*http.Response, error)

Do sends an HTTP request through the executor's client, returning the raw *http.Response. Unlike Dispatch, this does NOT read the body — callers (especially streaming handlers) must close resp.Body themselves.

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 SiteConcurrencyLimiter

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

SiteConcurrencyLimiter caps concurrent upstream dispatches per site. It is orthogonal to ProxyChannelCoordinator channel leases: a request may hold both a site slot and a channel lease independently.

Semantics (sites.max_concurrency / Site.MaxConcurrency): - limit <= 0 → unlimited (always acquire; no tracking) - limit > 0 → at most that many concurrent held slots per siteID

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 DetectSiteProtocolPreference

func DetectSiteProtocolPreference(platform, siteURL string, customHeaders map[string]string) SiteProtocolPreference

DetectSiteProtocolPreference resolves responses-only / stream preference for a site.

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) site concurrency permit. Always call Release exactly once when the upstream attempt finishes.

func (*SiteSlot) Release

func (s *SiteSlot) Release()

Release frees the slot. Idempotent and safe on no-op / nil slots.

type StickyEntry

type StickyEntry struct {
	ChannelID   int64
	ExpiresAtMs int64
}

StickyEntry is a sticky session binding entry.

type SurfaceAccountRef

type SurfaceAccountRef struct {
	ID            int64
	Username      *string
	ExtraConfig   *string
	OAuthProvider *string
}

SurfaceAccountRef is a lightweight account reference.

type SurfaceChannelRef

type SurfaceChannelRef struct {
	RouteID *int64
	ID      int64
}

SurfaceChannelRef is a lightweight channel reference.

type SurfaceFailureResponse

type SurfaceFailureResponse struct {
	Action  string // "respond" or "retry"
	Status  int
	Payload map[string]any
}

SurfaceFailureResponse is a terminal failure response.

type SurfaceFailureToolkit

type SurfaceFailureToolkit struct {
	WarningScope       SurfaceWarningScope
	DownstreamPath     string
	MaxRetries         int
	Router             TokenRouterInterface
	Coord              *ProxyChannelCoordinator
	LogProxy           func(ctx context.Context, entry ProxyLogEntry) error
	ReportAllFailed    func(model string, reason string)
	ReportTokenExpired func(accountID int64, username *string, siteName *string, detail string)
}

SurfaceFailureToolkit provides common failure handling methods for surfaces.

func NewSurfaceFailureToolkit

func NewSurfaceFailureToolkit(
	scope SurfaceWarningScope,
	downstreamPath string,
	maxRetries int,
	router TokenRouterInterface,
	coord *ProxyChannelCoordinator,
	logProxy func(ctx context.Context, entry ProxyLogEntry) error,
	reportAllFailed func(model string, reason string),
	reportTokenExpired func(accountID int64, username *string, siteName *string, detail string),
) *SurfaceFailureToolkit

NewSurfaceFailureToolkit creates a new failure toolkit.

func (*SurfaceFailureToolkit) HandleDetectedFailure

func (ft *SurfaceFailureToolkit) HandleDetectedFailure(
	ctx context.Context,
	selected SurfaceSelectedChannel,
	requestedModel string,
	modelName string,
	failure *FailureResult,
	latencyMs int64,
	retryCount int,
	promptTokens int64,
	completionTokens int64,
	totalTokens int64,
	upstreamPath string,
) SurfaceFailureResponse

HandleDetectedFailure handles a content-based failure detection.

func (*SurfaceFailureToolkit) HandleExecutionError

func (ft *SurfaceFailureToolkit) HandleExecutionError(
	ctx context.Context,
	selected SurfaceSelectedChannel,
	requestedModel string,
	modelName string,
	errorMessage string,
	latencyMs int64,
	retryCount int,
) SurfaceFailureResponse

HandleExecutionError handles a non-HTTP execution error (network failure, etc.).

func (*SurfaceFailureToolkit) HandleUpstreamFailure

func (ft *SurfaceFailureToolkit) HandleUpstreamFailure(
	ctx context.Context,
	selected SurfaceSelectedChannel,
	requestedModel string,
	modelName string,
	status int,
	errText string,
	rawErrText string,
	isStream bool,
	latencyMs int64,
	retryCount int,
) SurfaceFailureResponse

HandleUpstreamFailure handles an upstream endpoint failure. Records failure, writes proxy log, and decides retry vs respond.

func (*SurfaceFailureToolkit) RecordStreamFailure

func (ft *SurfaceFailureToolkit) RecordStreamFailure(
	ctx context.Context,
	selected SurfaceSelectedChannel,
	requestedModel string,
	modelName string,
	errorMessage string,
	latencyMs int64,
	retryCount int,
	promptTokens int64,
	completionTokens int64,
	totalTokens int64,
	upstreamPath string,
	httpStatus int,
	runtimeFailureStatus *int,
)

RecordStreamFailure records a stream-level failure.

type SurfaceSelectedChannel

type SurfaceSelectedChannel struct {
	Channel     SurfaceChannelRef
	Account     SurfaceAccountRef
	Site        SurfaceSiteRef
	ActualModel string
}

SurfaceSelectedChannel is a lightweight selected channel for surface operations.

func ConvertToSurfaceSelectedChannel

func ConvertToSurfaceSelectedChannel(sel *routing.SelectedChannel) SurfaceSelectedChannel

ConvertToSurfaceSelectedChannel converts a routing.SelectedChannel to a SurfaceSelectedChannel.

type SurfaceSiteRef

type SurfaceSiteRef struct {
	Name     *string
	ID       int64
	URL      string
	Platform string
}

SurfaceSiteRef is a lightweight site reference.

type SurfaceUsageSummary

type SurfaceUsageSummary struct {
	PromptTokens             int64
	CompletionTokens         int64
	TotalTokens              int64
	CacheReadTokens          int64
	CacheCreationTokens      int64
	PromptTokensIncludeCache *bool
}

SurfaceUsageSummary is a usage summary for surface operations.

type SurfaceWarningScope

type SurfaceWarningScope string

SurfaceWarningScope is the warning scope for surface operations.

const (
	ScopeChat      SurfaceWarningScope = "chat"
	ScopeResponses SurfaceWarningScope = "responses"
)

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 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)
)

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 UsageSummary

type UsageSummary struct {
	PromptTokens     int
	CompletionTokens int
	TotalTokens      int
}

UsageSummary is a lightweight usage summary for failure detection.

Directories

Path Synopsis
Package types holds shared type definitions for the proxy module.
Package types holds shared type definitions for the proxy module.

Jump to

Keyboard shortcuts

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