Documentation
¶
Overview ¶
Package proxyhandler implements the OpenAI-compatible proxy endpoint handlers.
Package proxyhandler implements proxy route handlers. Thin HTTP handlers that delegate to endpoint flow + transform.
Index ¶
- Constants
- Variables
- func BuildCodexSessionResponseStoreKey(sessionID string, siteID, accountID, channelID int64) string
- func BuildCodexWebsocketHandshakeHeaders(headers map[string]string) map[string]string
- func BuildCodexWebsocketRequestBody(body map[string]any) map[string]any
- func CloneMultipartBody(r *http.Request, overrides map[string]string) (io.Reader, string, error)
- func CloseCodexWebsocketSession(sessionID string)
- func DeleteProxyVideoTaskByPublicID(publicID string)
- func DetectClientContext(downstreamPath string, headers map[string]string, body any) proxy.DownstreamClientContext
- func EnsureResponsesWebsocketTransport(srv *http.Server, cfg WebSocketConfig)
- func GetProxyAuth(r *http.Request) *auth.ProxyAuthContext
- func HandleChatCompletions(w http.ResponseWriter, r *http.Request)
- func HandleClaudeCountTokens(w http.ResponseWriter, r *http.Request)
- func HandleClaudeMessages(w http.ResponseWriter, r *http.Request)
- func HandleCompletions(w http.ResponseWriter, r *http.Request)
- func HandleEmbeddings(w http.ResponseWriter, r *http.Request)
- func HandleFilesDelete(w http.ResponseWriter, r *http.Request)
- func HandleFilesDownload(w http.ResponseWriter, r *http.Request)
- func HandleFilesInfo(w http.ResponseWriter, r *http.Request)
- func HandleFilesList(w http.ResponseWriter, r *http.Request)
- func HandleFilesUpload(w http.ResponseWriter, r *http.Request)
- func HandleGeminiCLICountTokens(w http.ResponseWriter, r *http.Request)
- func HandleGeminiCLIGenerateContent(w http.ResponseWriter, r *http.Request)
- func HandleGeminiCLIStreamGenerateContent(w http.ResponseWriter, r *http.Request)
- func HandleGeminiGenerateContent(w http.ResponseWriter, r *http.Request)
- func HandleGeminiGenerateContentDynamic(w http.ResponseWriter, r *http.Request)
- func HandleGeminiModelsList(w http.ResponseWriter, r *http.Request)
- func HandleGeminiModelsListDynamic(w http.ResponseWriter, r *http.Request)
- func HandleImagesEdits(w http.ResponseWriter, r *http.Request)
- func HandleImagesGenerations(w http.ResponseWriter, r *http.Request)
- func HandleImagesVariations(w http.ResponseWriter, r *http.Request)
- func HandleModels(w http.ResponseWriter, r *http.Request)
- func HandleRerank(w http.ResponseWriter, r *http.Request)
- func HandleResponses(w http.ResponseWriter, r *http.Request, downstreamPath string)
- func HandleResponsesAliasGet426(w http.ResponseWriter, r *http.Request)
- func HandleResponsesAliasPost(w http.ResponseWriter, r *http.Request)
- func HandleResponsesGet426(w http.ResponseWriter, r *http.Request)
- func HandleResponsesWebsocket(w http.ResponseWriter, r *http.Request)
- func HandleResponsesWebsocketUpgradeResidual(w http.ResponseWriter, r *http.Request)
- func HandleSearch(w http.ResponseWriter, r *http.Request)
- func HandleVideosCreate(w http.ResponseWriter, r *http.Request)
- func HandleVideosDelete(w http.ResponseWriter, r *http.Request)
- func HandleVideosGet(w http.ResponseWriter, r *http.Request)
- func HeaderMapFromRequest(headers map[string][]string) map[string]string
- func InsertProxyLog(ctx context.Context, db *store.DB, entry proxy.ProxyLogEntry) error
- func IsModelAllowedByPolicy(requestedModel string, policy auth.DownstreamRoutingPolicy) bool
- func IsMultipartRequest(r *http.Request) bool
- func IsSseDoneMarker(ev SseEvent) bool
- func IsSseErrorEvent(ev SseEvent) bool
- func IsWebsocketUpgradeRequest(r *http.Request) bool
- func LogCodexWebsocketDialFallback(sessionID string, err error)
- func LogSseErrorEvents(events []SseEvent)
- func ParseGeminiPath(path string) (apiVersion, model, action string)
- func ParseReasoningSuffix(model string) (base string, effort string)
- func PrepareCtx(r *http.Request, cfg SurfConfig) (*Ctx, *SurfResult)
- func RegisterFilesRoutes(r chi.Router)
- func RegisterGeminiRoutes(r chi.Router)
- func RegisterNonV1ProxyRoutes(r chi.Router)
- func RegisterProxyRoutes(r chi.Router)
- func ResetCodexSessionResponseStoreForTest()
- func ResetResponsesWebsocketTransportForTest()
- func ResponsesWSError(status int, message string) map[string]any
- func ResponsesWebsocketTransportRegistered() bool
- func SaveProxyVideoTask(task *ProxyVideoTask)
- func SelectedChannelSupportsCodexWebsocketTransport(platform string, accountExtraConfig *string, requestModel string) bool
- func SetUpstreamConfig(cfg *UpstreamConfig)
- func SynthesizePrewarmResponsePayloads(model string, responseID string) []map[string]any
- func ToCodexWebsocketURL(requestURL string) string
- type AvailableModelContextLengthsSource
- type AvailableModelsSource
- type BillingCostResult
- type ChannelHealthProbeExecutor
- type CodexWebsocketRuntimeError
- type CodexWebsocketRuntimeResult
- type CodexWebsocketSendInput
- type Ctx
- type MultipartFormData
- type ParsedUsage
- type ProxyVideoTask
- type ResponsesWSMessage
- type SseEvent
- type SseParseResult
- type SurfConfig
- type SurfResult
- type UpstreamConfig
- type WebSocketConfig
Constants ¶
const ( ResponsesWebsocketResidualStatus = "c3_codex_upstream_wss" ResponsesWebsocketResidualDoc = "docs/responses-websocket-residual.md" )
Forbidden always: Hijack-silent-close · invent terminal frames for failed bridges.
Variables ¶
var ErrMultipartLimitExceeded = errors.New("multipart form exceeded configured limit")
Functions ¶
func BuildCodexSessionResponseStoreKey ¶
BuildCodexSessionResponseStoreKey scopes a WS client session to site/account/channel. Empty sessionID → empty key.
func BuildCodexWebsocketHandshakeHeaders ¶
BuildCodexWebsocketHandshakeHeaders ensures OpenAI-Beta includes responses_websockets.
func BuildCodexWebsocketRequestBody ¶
BuildCodexWebsocketRequestBody wraps a responses body as type=response.create.
func CloneMultipartBody ¶
CloneMultipartBody clones the request body for forwarding to upstream. If overrides is non-nil, field values matching override keys are replaced (e.g., replacing "model" with the resolved upstream model). Returns the body reader, content type, and error.
func CloseCodexWebsocketSession ¶
func CloseCodexWebsocketSession(sessionID string)
CloseCodexWebsocketSession closes the upstream socket for a session key. Intentionally preserves remembered previous_response_id (TS parity).
func DeleteProxyVideoTaskByPublicID ¶
func DeleteProxyVideoTaskByPublicID(publicID string)
DeleteProxyVideoTaskByPublicID deletes a video task by publicId (memory + DB).
func DetectClientContext ¶
func DetectClientContext(downstreamPath string, headers map[string]string, body any) proxy.DownstreamClientContext
DetectClientContext is a thin wrapper around proxy.DetectClientContext. It converts http.Header to a map[string]string suitable for detection.
func EnsureResponsesWebsocketTransport ¶
func EnsureResponsesWebsocketTransport(srv *http.Server, cfg WebSocketConfig)
EnsureResponsesWebsocketTransport marks the Responses WS transport as registered. C1 does not install a separate ConnState hook — upgrade is handled on the GET /v1/responses (and alias) route handlers after ProxyAuth middleware.
func GetProxyAuth ¶
func GetProxyAuth(r *http.Request) *auth.ProxyAuthContext
GetProxyAuth extracts the proxy auth context from the request.
func HandleChatCompletions ¶
func HandleChatCompletions(w http.ResponseWriter, r *http.Request)
HandleChatCompletions handles POST /v1/chat/completions and POST /chat/completions. Surface format: "openai".
func HandleClaudeCountTokens ¶
func HandleClaudeCountTokens(w http.ResponseWriter, r *http.Request)
HandleClaudeCountTokens handles POST /v1/messages/count_tokens.
func HandleClaudeMessages ¶
func HandleClaudeMessages(w http.ResponseWriter, r *http.Request)
HandleClaudeMessages handles POST /v1/messages. Surface format: "claude".
func HandleCompletions ¶
func HandleCompletions(w http.ResponseWriter, r *http.Request)
HandleCompletions handles POST /v1/completions (legacy non-chat completions).
func HandleEmbeddings ¶
func HandleEmbeddings(w http.ResponseWriter, r *http.Request)
HandleEmbeddings handles POST /v1/embeddings.
func HandleFilesDelete ¶
func HandleFilesDelete(w http.ResponseWriter, r *http.Request)
HandleFilesDelete handles DELETE /v1/files/{fileId}.
func HandleFilesDownload ¶
func HandleFilesDownload(w http.ResponseWriter, r *http.Request)
HandleFilesDownload handles GET /v1/files/{fileId}/content. Relays binary/content responses via the standard buffered upstream path.
func HandleFilesInfo ¶
func HandleFilesInfo(w http.ResponseWriter, r *http.Request)
HandleFilesInfo handles GET /v1/files/{fileId}.
func HandleFilesList ¶
func HandleFilesList(w http.ResponseWriter, r *http.Request)
HandleFilesList handles GET /v1/files. Forwards to upstream GET /v1/files. When no channel can be selected and the proxy stub is enabled (tests), returns an empty OpenAI-shaped list.
func HandleFilesUpload ¶
func HandleFilesUpload(w http.ResponseWriter, r *http.Request)
HandleFilesUpload handles POST /v1/files (multipart file upload). Forwards to upstream POST /v1/files after auth + channel selection.
func HandleGeminiCLICountTokens ¶
func HandleGeminiCLICountTokens(w http.ResponseWriter, r *http.Request)
HandleGeminiCLICountTokens handles POST /v1internal::countTokens.
func HandleGeminiCLIGenerateContent ¶
func HandleGeminiCLIGenerateContent(w http.ResponseWriter, r *http.Request)
HandleGeminiCLIGenerateContent handles POST /v1internal::generateContent. Gemini CLI internal protocol. downstreamProtocol: "gemini-cli", action: "generateContent".
func HandleGeminiCLIStreamGenerateContent ¶
func HandleGeminiCLIStreamGenerateContent(w http.ResponseWriter, r *http.Request)
HandleGeminiCLIStreamGenerateContent handles POST /v1internal::streamGenerateContent. Path action forces stream even when body omits stream:true ().
func HandleGeminiGenerateContent ¶
func HandleGeminiGenerateContent(w http.ResponseWriter, r *http.Request)
HandleGeminiGenerateContent handles POST /v1beta/models/*. Parses {apiVersion}/models/{model}:{action} from the path. Official Gemini clients put the model in the path (not body) and imply streaming via the :streamGenerateContent action ().
func HandleGeminiGenerateContentDynamic ¶
func HandleGeminiGenerateContentDynamic(w http.ResponseWriter, r *http.Request)
HandleGeminiGenerateContentDynamic handles POST /gemini/:geminiApiVersion/models/*.
func HandleGeminiModelsList ¶
func HandleGeminiModelsList(w http.ResponseWriter, r *http.Request)
HandleGeminiModelsList handles GET /v1beta/models. Returns a Gemini-shaped models list built from the MetAPI-owned catalog (resolveOwnedModelCatalog / AvailableModelsSource), not a hard-coded stub and not a live upstream Generative Language models scrape. See
func HandleGeminiModelsListDynamic ¶
func HandleGeminiModelsListDynamic(w http.ResponseWriter, r *http.Request)
HandleGeminiModelsListDynamic handles GET /gemini/:geminiApiVersion/models.
func HandleImagesEdits ¶
func HandleImagesEdits(w http.ResponseWriter, r *http.Request)
HandleImagesEdits handles POST /v1/images/edits. Supports multipart/form-data and JSON body. Model defaults to "gpt-image-1". Multipart is parsed in PrepareCtx and forwarded via CloneMultipartBody in dispatchUpstream.
func HandleImagesGenerations ¶
func HandleImagesGenerations(w http.ResponseWriter, r *http.Request)
HandleImagesGenerations handles POST /v1/images/generations. Model defaults to "gpt-image-1".
func HandleImagesVariations ¶
func HandleImagesVariations(w http.ResponseWriter, r *http.Request)
HandleImagesVariations handles POST /v1/images/variations. Always returns 400 — not supported.
func HandleModels ¶
func HandleModels(w http.ResponseWriter, r *http.Request)
HandleModels handles GET /v1/models. Returns model list in OpenAI or Claude format based on request headers.
func HandleRerank ¶
func HandleRerank(w http.ResponseWriter, r *http.Request)
HandleRerank handles POST /v1/rerank.
OpenAI-compatible / Cohere-style rerank surface. Request body is passed through to upstream /v1/rerank after standard PrepareCtx model swap. Expected body fields (validated only for model; rest is passthrough):
{
"model": "rerank-...",
"query": "...",
"documents": ["...",...] // or array of objects
}
Streaming is not supported.
func HandleResponses ¶
func HandleResponses(w http.ResponseWriter, r *http.Request, downstreamPath string)
HandleResponses handles POST /v1/responses and /v1/responses/compact.
func HandleResponsesAliasGet426 ¶
func HandleResponsesAliasGet426(w http.ResponseWriter, r *http.Request)
HandleResponsesAliasGet426 handles GET /responses and /responses/*. Unknown alias → 404. Upgrade attempt → C1 WS transport. Plain GET → 426.
func HandleResponsesAliasPost ¶
func HandleResponsesAliasPost(w http.ResponseWriter, r *http.Request)
HandleResponsesAliasPost handles POST /responses and /responses/* (alias paths).
func HandleResponsesGet426 ¶
func HandleResponsesGet426(w http.ResponseWriter, r *http.Request)
HandleResponsesGet426 handles GET /v1/responses. Plain GET → 426 Upgrade Required. WebSocket upgrade attempt → C1 transport (coder/websocket + HTTP SSE bridge; see EnsureResponsesWebsocketTransport).
func HandleResponsesWebsocket ¶
func HandleResponsesWebsocket(w http.ResponseWriter, r *http.Request)
HandleResponsesWebsocket serves a Responses WebSocket connection (C1). Caller must only invoke this when IsWebsocketUpgradeRequest(r) is true. Auth is expected from ProxyAuth middleware (GetProxyAuth); if missing, upgrade is refused with 401 before Accept.
func HandleResponsesWebsocketUpgradeResidual ¶
func HandleResponsesWebsocketUpgradeResidual(w http.ResponseWriter, r *http.Request)
HandleResponsesWebsocketUpgradeResidual is the legacy entrypoint. C1: with auth context → real transport; without auth → clear HTTP 401 (unit tests without middleware; never Hijack-silent-close).
func HandleSearch ¶
func HandleSearch(w http.ResponseWriter, r *http.Request)
HandleSearch handles POST /v1/search. Validates: query required, stream=false required, max_results in [1,20].
func HandleVideosCreate ¶
func HandleVideosCreate(w http.ResponseWriter, r *http.Request)
On successful non-stream upstream 2xx, dispatch rewrites response `id` to a generated publicId and SaveProxyVideoTask (process-local).
func HandleVideosDelete ¶
func HandleVideosDelete(w http.ResponseWriter, r *http.Request)
Sticky pin: resolve mapping before delete so channel preference and path rewrite still apply for this request.
func HandleVideosGet ¶
func HandleVideosGet(w http.ResponseWriter, r *http.Request)
Sticky pin: when the mapping has ChannelID > 0, force preferred channel selection so the request hits the same upstream account/site as create.
func HeaderMapFromRequest ¶
HeaderMapFromRequest extracts relevant headers as a string map for client detection.
func InsertProxyLog ¶
InsertProxyLog writes one proxy_logs row. Columns match store.ProxyLog / DDL. Fields present only on ProxyLogEntry (usage_source, upstream_path) are not persisted until the schema grows those columns; they remain on the entry for in-process consumers and tests.
func IsModelAllowedByPolicy ¶
func IsModelAllowedByPolicy(requestedModel string, policy auth.DownstreamRoutingPolicy) bool
IsModelAllowedByPolicy checks if a model is allowed by the downstream policy.
func IsMultipartRequest ¶
IsMultipartRequest checks if the request is multipart/form-data.
func IsSseDoneMarker ¶
IsSseDoneMarker checks if an SSE event is a [DONE] marker.
func IsSseErrorEvent ¶
IsSseErrorEvent checks if an SSE event's data payload represents an error. Detects JSON objects containing "error" keys at the top level, or error event types like "response.failed", "error".
func IsWebsocketUpgradeRequest ¶
IsWebsocketUpgradeRequest reports whether r is a WebSocket upgrade attempt.
func LogCodexWebsocketDialFallback ¶
LogCodexWebsocketDialFallback records honest dial→HTTP fallback.
func LogSseErrorEvents ¶
func LogSseErrorEvents(events []SseEvent)
LogSseErrorEvents logs each SSE error event at WARN level.
func ParseGeminiPath ¶
ParseGeminiPath parses a Gemini path into apiVersion, model, action. E.g., "/v1beta/models/gemini-2.5-pro:generateContent" -> apiVersion="v1beta", model="gemini-2.5-pro", action="generateContent" Also accepts the dynamic surface "/gemini/{apiVersion}/models/{model}:{action}".
func ParseReasoningSuffix ¶
Injection is OpenAI-surface only (reasoning_effort is an OpenAI field); Anthropic (thinking) / Gemini (thinkingConfig) dialects strip for routing but do not inject here — cross-dialect injection is a documented follow-up.
func PrepareCtx ¶
func PrepareCtx(r *http.Request, cfg SurfConfig) (*Ctx, *SurfResult)
PrepareCtx extracts all context needed for proxy request handling.
func RegisterFilesRoutes ¶
RegisterFilesRoutes registers OpenAI-compatible /v1/files proxy routes. Mounted under /v1, so paths omit the /v1 prefix.
func RegisterGeminiRoutes ¶
RegisterGeminiRoutes registers all Gemini surface routes. 7 routes total: models list (2), generateContent (2), CLI internal (3).
func RegisterNonV1ProxyRoutes ¶
RegisterNonV1ProxyRoutes registers proxy routes that are NOT under /v1. This includes: /chat/completions, /responses aliases, and Gemini routes. The router must have proxy auth middleware applied.
func RegisterProxyRoutes ¶
RegisterProxyRoutes registers all /v1/* proxy surfaces on the given chi router. The router is expected to be mounted under /v1 with proxy auth middleware applied.
func ResetCodexSessionResponseStoreForTest ¶
func ResetCodexSessionResponseStoreForTest()
ResetCodexSessionResponseStoreForTest clears process-local state (tests only).
func ResetResponsesWebsocketTransportForTest ¶
func ResetResponsesWebsocketTransportForTest()
ResetResponsesWebsocketTransportForTest clears registration state (tests only).
func ResponsesWSError ¶
ResponsesWSError builds a WebSocket-shaped error object.
func ResponsesWebsocketTransportRegistered ¶
func ResponsesWebsocketTransportRegistered() bool
ResponsesWebsocketTransportRegistered reports whether the transport registration entrypoint has been called in this process.
func SaveProxyVideoTask ¶
func SaveProxyVideoTask(task *ProxyVideoTask)
SaveProxyVideoTask saves a video task mapping to the process-local cache and dual-writes to proxy_video_tasks when a runtime DB is available. Known limitation: durable rows have no TTL/GC currently
func SelectedChannelSupportsCodexWebsocketTransport ¶
func SelectedChannelSupportsCodexWebsocketTransport(platform string, accountExtraConfig *string, requestModel string) bool
SelectedChannelSupportsCodexWebsocketTransport reports whether an upstream Codex wss dial should be attempted (TS selectedChannelSupportsCodexWebsocketTransport). Platform must be codex; global flag CodexUpstreamWebsocketEnabled must be on; optional account extraConfig websockets false disables.
func SetUpstreamConfig ¶
func SetUpstreamConfig(cfg *UpstreamConfig)
SetUpstreamConfig sets the package-level upstream forwarding dependencies. Called during server startup to wire in the routing engine and HTTP executor.
func SynthesizePrewarmResponsePayloads ¶
SynthesizePrewarmResponsePayloads generates pre-warm response.created + response.completed for Codex file-search pre-warm mode (generate=false without incremental input).
func ToCodexWebsocketURL ¶
ToCodexWebsocketURL converts an https/http responses URL to wss/ws.
Types ¶
type AvailableModelContextLengthsSource ¶
type AvailableModelContextLengthsSource interface {
GetAvailableModelContextLengths(ctx context.Context) (map[string]int64, error)
}
AvailableModelContextLengthsSource is an optional router capability that maps exposed model ids to token_routes.context_length when set. Production routing.TokenRouter implements this; unit mocks may omit it so listing keeps knownModelContextLength heuristics only. Values are metadata for /v1/models — they do not enforce max tokens on the proxy path.
type AvailableModelsSource ¶
AvailableModelsSource is implemented by routers that can list MetAPI-owned models from enabled token_routes (notably routing.TokenRouter.GetAvailableModels). Channel-selection-only mocks may omit this method; listing then uses the documented last-resort catalog (see resolveOwnedModelCatalog).
type BillingCostResult ¶
BillingCostResult is the cost estimate attached to a successful proxy log.
func EstimateBillingCostFromUsage ¶
func EstimateBillingCostFromUsage(modelName, platform string, usage ParsedUsage) BillingCostResult
EstimateBillingCostFromUsage builds estimated_cost + billing_details for proxy_logs.
type ChannelHealthProbeExecutor ¶
type ChannelHealthProbeExecutor struct {
// contains filtered or unexported fields
}
ChannelHealthProbeExecutor is a thin boot-wired probe that hits live upstream for ModelProbeScheduler / admin probe-now paths.
It prefers a lightweight GET /v1/models check. Platforms without a models catalog endpoint may return non-2xx; those outcomes are recorded as failure (not credential expiry). See known limitation.
func NewChannelHealthProbeExecutor ¶
func NewChannelHealthProbeExecutor(cfg *config.Config) *ChannelHealthProbeExecutor
NewChannelHealthProbeExecutor builds the production probe executor.
func (*ChannelHealthProbeExecutor) ProbeChannel ¶
func (p *ChannelHealthProbeExecutor) ProbeChannel(ctx context.Context, target scheduler.ProbeTarget) (scheduler.ProbeOutcome, error)
ProbeChannel implements scheduler.ChannelHealthProbe.
func (*ChannelHealthProbeExecutor) SetDB ¶
func (p *ChannelHealthProbeExecutor) SetDB(db *store.DB)
SetDB injects a database handle (tests). Production leaves this nil.
func (*ChannelHealthProbeExecutor) SetTransport ¶
func (p *ChannelHealthProbeExecutor) SetTransport(rt http.RoundTripper)
SetTransport injects a RoundTripper (tests).
type CodexWebsocketRuntimeError ¶
type CodexWebsocketRuntimeError struct {
Message string
Status int
Events []map[string]any
Payload any
}
CodexWebsocketRuntimeError is returned when an upstream Codex wss turn fails. When Events is empty and Status is set, the caller should prefer HTTP bridge fallback.
func (*CodexWebsocketRuntimeError) Error ¶
func (e *CodexWebsocketRuntimeError) Error() string
type CodexWebsocketRuntimeResult ¶
CodexWebsocketRuntimeResult is a successful terminal turn.
func SendCodexWebsocketRequest ¶
func SendCodexWebsocketRequest(ctx context.Context, input CodexWebsocketSendInput) (*CodexWebsocketRuntimeResult, error)
SendCodexWebsocketRequest dials (or reuses) an upstream Codex wss session and waits for a terminal event. previous_response_id not-found recovers once by strip.
type CodexWebsocketSendInput ¶
type CodexWebsocketSendInput struct {
SessionID string
RequestURL string
Headers map[string]string
Body map[string]any
}
CodexWebsocketSendInput is one upstream wss turn.
type Ctx ¶
type Ctx struct {
Auth *auth.ProxyAuthContext
Policy auth.DownstreamRoutingPolicy
Body map[string]any
RawBody []byte // raw request body bytes for zero-copy model swap in upstream
Headers map[string]string
ClientCtx proxy.DownstreamClientContext
DownstreamPath string
RequestedModel string
SurfaceFormat string
IsStream bool
Multipart bool
Retries int
MaxRetries int
// ForcedChannelID pins channel selection to a specific route channel when set
// (videos sticky pin from mapping; tester forced channel paths).
// When non-nil and >0, SelectProxyChannelForAttempt uses SelectPreferredChannel
// and does not fall back to other channels on retry.
ForcedChannelID *int64
}
Ctx holds all context needed for a proxy request.
type MultipartFormData ¶
type MultipartFormData struct {
Values map[string][]string
Files map[string][]*multipart.FileHeader
}
MultipartFormData holds parsed multipart form data with file entries.
func ParseMultipartFormData ¶
func ParseMultipartFormData(r *http.Request) (*MultipartFormData, error)
ParseMultipartFormData parses multipart/form-data from a request. Returns nil if the request is not multipart (caller should fall back to JSON).
type ParsedUsage ¶
type ParsedUsage struct {
PromptTokens int64
CompletionTokens int64
TotalTokens int64
CacheReadTokens int64
CacheCreationTokens int64
// ReasoningTokens captures Gemini thoughtsTokenCount / OpenAI reasoning_tokens
// when reported separately. Not persisted as its own proxy_logs column; it is
// folded into CompletionTokens / TotalTokens when total is missing.
ReasoningTokens int64
// Source is "upstream" when any token field was present, otherwise "unknown".
Source string
Found bool
}
ParsedUsage is a normalized token usage snapshot extracted from an upstream body/SSE.
func ParseUsageFromBody ¶
func ParseUsageFromBody(body []byte) ParsedUsage
Does not invent usage when upstream omitted token fields.
func ParseUsageFromSSEEvents ¶
func ParseUsageFromSSEEvents(events []SseEvent) ParsedUsage
ParseUsageFromSSEEvents extracts the best-effort final usage from SSE data events. Later events win when they carry usage so stream-end payloads (message_delta, response.completed, final chat.completion.chunk) override partial early values.
func (ParsedUsage) ToUsageSummary ¶
func (u ParsedUsage) ToUsageSummary() *proxy.UsageSummary
ToUsageSummary converts ParsedUsage into the lightweight failure-detection summary.
type ProxyVideoTask ¶
type ProxyVideoTask struct {
PublicID string `json:"publicId"`
UpstreamVideoID string `json:"upstreamVideoId"`
SiteURL string `json:"siteUrl"`
TokenValue string `json:"tokenValue"`
RequestedModel string `json:"requestedModel"`
ActualModel string `json:"actualModel"`
ChannelID int64 `json:"channelId"`
AccountID int64 `json:"accountId"`
}
Create saves a process-local cache entry and dual-writes to `proxy_video_tasks` when store.GetDB() is available so multi-instance / restart can resolve publicId. GET/DELETE treat the store as an optional rewrite aid, not a hard gate — missing entries still pass the client id through to upstream. Sticky site/token pin remains a known limitation. See limitation.md.
func GetProxyVideoTaskByPublicID ¶
func GetProxyVideoTaskByPublicID(publicID string) *ProxyVideoTask
GetProxyVideoTaskByPublicID retrieves a video task by publicId. Memory cache first; cold miss falls back to proxy_video_tasks.
type ResponsesWSMessage ¶
type ResponsesWSMessage struct {
Type string `json:"type"`
Model string `json:"model,omitempty"`
Generate *bool `json:"generate,omitempty"`
Input []any `json:"input,omitempty"`
Instructions any `json:"instructions,omitempty"`
PreviousResponseID string `json:"previous_response_id,omitempty"`
Raw map[string]any `json:"-"`
}
ResponsesWSMessage is a WebSocket message from the downstream client.
func ParseResponsesWSMessage ¶
func ParseResponsesWSMessage(raw []byte) (*ResponsesWSMessage, error)
ParseResponsesWSMessage parses a WebSocket JSON message.
type SseEvent ¶
type SseEvent struct {
Data string // joined multi-line data content
Event string // event type (default: "message")
ID string // event ID
Retry int64 // retry interval in milliseconds (0 = not set)
}
SseEvent represents a parsed SSE event with its fields.
func ParseSseStream ¶
ParseSseStream parses a raw SSE byte stream into structured events.
SSE protocol (text/event-stream): - Events are separated by double newlines (\n\n) - Lines starting with "data:" contain event data - Lines starting with "event:" set the event type - Lines starting with "id:" set the event ID - Lines starting with "retry:" set the reconnection time in ms - Lines starting with ":" are comments (ignored) - Multi-line data: consecutive "data:" lines are joined with "\n"
Returns the remaining incomplete buffer (partial event) for the next call.
type SseParseResult ¶
type SseParseResult struct {
Events []SseEvent
HasDataEvent bool // at least one event with non-empty data
HasErrorEvent bool // at least one event with error-type data
HasDoneMarker bool // at least one [DONE] event
}
SseParseResult contains the parsed events and aggregate state.
func BuildSseParseResult ¶
func BuildSseParseResult(events []SseEvent) SseParseResult
BuildSseParseResult aggregates parse state from parsed events.
func ParseAndAnalyzeSseStream ¶
func ParseAndAnalyzeSseStream(raw string) SseParseResult
ParseAndAnalyzeSseStream parses an SSE stream and returns the aggregate result. Convenience wrapper around ParseSseStream + BuildSseParseResult.
type SurfConfig ¶
type SurfConfig struct {
Endpoint string
DownstreamPath string
RequireModel bool
DefaultModel string
// ForceStream forces IsStream=true even when the body omits stream:true.
// Used by Gemini path action streamGenerateContent and CLI
// /v1internal::streamGenerateContent where streaming is path-implied.
ForceStream bool
Method string
ExtraHeaders map[string]string
MaxRetries int
SurfaceFormat string // "openai", "claude", or empty
}
SurfConfig is the configuration for a proxy surface handler.
type SurfResult ¶
type SurfResult struct {
OK bool
Status int
Body []byte
Error string
ErrorType string
Stream bool
StreamBody io.ReadCloser
Usage *proxy.UsageSummary
LatencyMs int64
// Selected *prouting.SelectedChannel // populated after channel selection
ClientCtx proxy.DownstreamClientContext
}
SurfResult is the result of processing a proxy surface request.
type UpstreamConfig ¶
type UpstreamConfig struct {
Router proxy.TokenRouterInterface
RouteRefresher proxy.RouteRefreshWorkflow
Coordinator *proxy.ProxyChannelCoordinator
Executor *proxy.RuntimeExecutor
// SiteLimiter caps concurrent dispatches per site (sites.max_concurrency).
// When nil, proxy.DefaultSiteConcurrencyLimiter is used.
// Orthogonal to Coordinator channel leases.
SiteLimiter *proxy.SiteConcurrencyLimiter
// LogProxy persists successful/failed proxy attempts into proxy_logs.
// When nil, defaultLogProxyWriter uses store.GetDB() (no-op if DB unset).
LogProxy func(ctx context.Context, entry proxy.ProxyLogEntry) error
}
UpstreamConfig holds the dependencies needed for upstream forwarding.
type WebSocketConfig ¶
type WebSocketConfig struct {
// AuthTokenValidation is reserved for non-middleware upgrade paths.
// Unused while upgrade runs under ProxyAuth middleware (preferred).
AuthTokenValidation func(token string) (*auth.ProxyAuthContext, error)
}
WebSocketConfig holds optional hooks for Responses WebSocket transport. Registration accepts the config so boot wiring stays stable.
Source Files
¶
- billing_cost.go
- channel_health_probe.go
- chat.go
- client_detect.go
- codex_ws_runtime.go
- completions.go
- doc.go
- embeddings.go
- files.go
- gemini.go
- images.go
- max_tokens.go
- messages.go
- models.go
- multipart.go
- proxy_log.go
- reasoning_suffix.go
- rerank.go
- responses.go
- responses_ws.go
- router.go
- search.go
- sse_parser.go
- surface.go
- upstream.go
- upstream_responses.go
- upstream_sanitize.go
- upstream_stream.go
- usage.go
- videos.go