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 ConfigureProxyLogWriter(async bool, batchSize int, flushIntervalMs int)
- func DeleteProxyVideoTaskByPublicID(publicID string)
- func DetectClientContext(downstreamPath string, headers map[string]string, body any) proxy.DownstreamClientContext
- func EnqueueGatewayRequest(ctx context.Context, entry store.GatewayRequest) error
- func EnqueueProxyLog(ctx context.Context, entry proxy.ProxyLogEntry) error
- func EnsureResponsesWebsocketTransport(srv *http.Server, cfg WebSocketConfig)
- func GetProxyAuth(r *http.Request) *auth.ProxyAuthContext
- func HandleAlphaSearch(w http.ResponseWriter, r *http.Request)
- func HandleAudioSpeech(w http.ResponseWriter, r *http.Request)
- func HandleAudioTranscriptions(w http.ResponseWriter, r *http.Request)
- func HandleAudioTranslations(w http.ResponseWriter, r *http.Request)
- 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 HandleModerations(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 HandleSystemOne(w http.ResponseWriter, r *http.Request)
- func HandleVideosContent(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 HandleVideosRemix(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 RequestLifecycle(next http.Handler) http.Handler
- func ResetCodexSessionResponseStoreForTest()
- func ResetResponsesWebsocketTransportForTest()
- func ResponsesWSError(status int, message string) map[string]any
- func ResponsesWebsocketTransportRegistered() bool
- func RoutingPolicyFromAuth(policy auth.DownstreamRoutingPolicy) routing.DownstreamRoutingPolicy
- func SaveProxyVideoTask(task *ProxyVideoTask)
- func SelectedChannelSupportsCodexWebsocketTransport(platform string, accountExtraConfig *string, requestModel string) bool
- func SetMediaTargetAllowPrivateForTest(allow bool) func()
- func SetUpstreamConfig(cfg *UpstreamConfig)
- func ShutdownProxyLogBatchWriter(ctx context.Context) error
- 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/internal/responses-websocket-residual.md" )
Responses WebSocket uses native Codex wss when enabled and supported by the selected channel, otherwise bridging HTTP SSE. Sessions and response IDs are process-local. Each message enforces model policy and managed-key request quota.
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 ConfigureProxyLogWriter ¶ added in v0.13.0
ConfigureProxyLogWriter sets up the global proxy log writer. When async is true a batch writer is started; when false any existing writer is shut down (drained) and the system reverts to synchronous writes. Idempotent: calling again first drains the previous writer so reconfigure does not leak a goroutine or lose in-flight entries.
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 EnqueueGatewayRequest ¶ added in v0.25.0
func EnqueueGatewayRequest(ctx context.Context, entry store.GatewayRequest) error
EnqueueGatewayRequest follows PROXY_LOG_ASYNC and is drained before DB close.
func EnqueueProxyLog ¶ added in v0.13.0
func EnqueueProxyLog(ctx context.Context, entry proxy.ProxyLogEntry) error
EnqueueProxyLog writes a proxy_logs entry, either via the async batch writer (when configured) or synchronously (sync mode / tests). This is the production write path wired into UpstreamConfig.LogProxy by app.ConfigureProxyUpstream. Backpressure (channel full) falls back to a synchronous InsertProxyLog so logs are never dropped.
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 HandleAlphaSearch ¶ added in v0.24.0
func HandleAlphaSearch(w http.ResponseWriter, r *http.Request)
func HandleAudioSpeech ¶ added in v0.24.0
func HandleAudioSpeech(w http.ResponseWriter, r *http.Request)
func HandleAudioTranscriptions ¶ added in v0.24.0
func HandleAudioTranscriptions(w http.ResponseWriter, r *http.Request)
func HandleAudioTranslations ¶ added in v0.24.0
func HandleAudioTranslations(w http.ResponseWriter, r *http.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 and filters the successful response to the calling key's files (see processManagedProxyResponse). 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. Preserves JSON or multipart fields for the explicitly selected endpoint.
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 HandleModerations ¶ added in v0.24.0
func HandleModerations(w http.ResponseWriter, r *http.Request)
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 HandleSystemOne ¶ added in v0.24.0
func HandleSystemOne(w http.ResponseWriter, r *http.Request)
func HandleVideosContent ¶ added in v0.24.0
func HandleVideosContent(w http.ResponseWriter, r *http.Request)
HandleVideosContent downloads content under the same task identity as polling.
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 HandleVideosRemix ¶ added in v0.24.0
func HandleVideosRemix(w http.ResponseWriter, r *http.Request)
HandleVideosRemix creates a separate owned task on the source task's grant.
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 non-null "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 RequestLifecycle ¶ added in v0.25.0
RequestLifecycle runs before recovery, body limits and authentication, but records only known proxy surfaces. Successful WS upgrades have turn owners; an unsuccessful upgrade is still an ordinary HTTP rejection.
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 RoutingPolicyFromAuth ¶ added in v0.24.0
func RoutingPolicyFromAuth(policy auth.DownstreamRoutingPolicy) routing.DownstreamRoutingPolicy
RoutingPolicyFromAuth converts the auth-layer downstream policy into the routing-layer policy. Single owner of the field mapping; both the proxy admission path and the admin key-context explainer use it.
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. Both copies carry the same timestamp and both are bounded by PROXY_VIDEO_TASK_RETENTION_DAYS (cache: lazy sweep; DB: retention scheduler).
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 SetMediaTargetAllowPrivateForTest ¶ added in v0.26.0
func SetMediaTargetAllowPrivateForTest(allow bool) func()
SetMediaTargetAllowPrivateForTest lets tests in other packages that stand up a loopback CDN exercise the media path. It returns a restore function and is never called from production code.
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 ShutdownProxyLogBatchWriter ¶ added in v0.13.0
ShutdownProxyLogBatchWriter drains and stops the global batch writer if one is running. Called from app graceful shutdown BEFORE store.CloseDatabase so the writer can flush its last batch against a still-open DB. No-op when the writer is nil (sync mode).
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.
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 {
// ObserveAttempt records each actual socket attempt, including retries and
// zero-event dial fallback. It does not decide the downstream turn result.
ObserveAttempt func([]map[string]any, error, time.Duration)
SessionID string
RequestURL string
Headers map[string]string
Body map[string]any
// ResinAccount carries the Resin business identity for the native wss
// reverse-proxy rewrite. When non-empty (and ResinPlatform is set) and
// Resin is enabled, the dial URL is rewritten to
// ws://{host}/{token}/{Platform}/{protocol}/{target} and X-Resin-Account
// is set on the dial headers.
ResinAccount string
// ResinPlatform is the Platform segment for the resin reverse-proxy path.
// The caller (which has the site in scope) resolves it from
// cfg.ResinPlatformName (falling back to site.Platform).
ResinPlatform string
}
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
// (video mapping, tester selection, or Messages bridge continuation).
// When non-nil and >0, SelectProxyChannelForAttempt uses SelectPreferredChannel
// and does not fall back to other channels on retry.
ForcedChannelID *int64
// contains filtered or unexported fields
}
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 {
UpstreamReportedModel *string
FirstOutputLatencyMs *int64
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
// contains filtered or unexported fields
}
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"`
// Owner is an internal opaque identity hash; it is never serialized.
Owner string `json:"-"`
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. Owner is the downstream key identity (store.DirectVideoTaskOwner); GET/DELETE require a mapping whose owner matches the caller, so a missing or ownerless row is a 404 rather than a pass-through of a client-supplied upstream id.
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. A cache line past the retention TTL counts as a miss even before the next (throttled) sweep deletes it; the durable table then decides exactly as it would for a cold process, so a row the scheduler has not pruned yet re-warms the line with a fresh storedAt.
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
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
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
// DirectAccountLimiter caps concurrent dispatches per direct upstream
// account (upstream_credentials.id), since direct channels have no site
// row to carry MaxConcurrency. The limit comes from
// PROXY_DIRECT_ACCOUNT_MAX_CONCURRENCY; 0 leaves direct dispatch
// unlimited. When nil, proxy.DefaultDirectAccountConcurrencyLimiter is
// used.
DirectAccountLimiter *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
ResolveDirectCredential func(context.Context, int64, *string, bool) (*oauth.DirectCredentialResult, 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
- direct_bailian_stream.go
- direct_bedrock.go
- direct_bedrock_stream.go
- direct_cline_stream.go
- direct_codex_images_request.go
- direct_codex_images_stream.go
- direct_endpoints.go
- direct_fallback.go
- direct_media_profiles.go
- direct_media_profiles_response.go
- direct_media_request.go
- direct_nanogpt.go
- direct_nanogpt_stream.go
- direct_nanogpt_xml.go
- direct_ollama.go
- direct_opencode.go
- direct_openrouter_image.go
- direct_openrouter_image_response.go
- direct_protocol_bridge.go
- direct_provider_session.go
- direct_provider_stream.go
- direct_provider_wire.go
- direct_relaykit.go
- direct_router_chat_stream.go
- direct_upstream.go
- direct_video.go
- direct_video_accounting.go
- direct_video_native.go
- direct_video_native_response.go
- doc.go
- domestic_chat_request.go
- downstream_response_model.go
- embeddings.go
- files.go
- files_ownership.go
- gemini.go
- headers.go
- images.go
- managed_objects.go
- max_tokens.go
- media.go
- media_stream.go
- media_target_guard.go
- messages.go
- messages_replay.go
- models.go
- models_list_cache.go
- multipart.go
- native_json.go
- prompt_filter.go
- proxy_log.go
- proxy_log_batch.go
- proxy_path_guard.go
- reasoning_suffix.go
- request_lifecycle.go
- rerank.go
- responses.go
- responses_ws.go
- router.go
- search.go
- sse_output.go
- sse_parser.go
- surface.go
- upstream.go
- upstream_body_rewrite.go
- upstream_encoding.go
- upstream_messages_bridge.go
- upstream_responses.go
- upstream_sanitize.go
- upstream_stream.go
- upstream_terminal.go
- usage.go
- user_budget.go
- videos.go