mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-05 16:04:01 +00:00
Preserve request parameters, tool-call completion reasons and retry session affinity. Bound upstream header waits, stop expired-context scans and add opt-in redacted request-body diagnostics. Isolate Playground diagnostics from production pools, report stream failures accurately, align readiness with discoverable models and honor Docker listen configuration. Split Go and WebUI modules by responsibility, add regression tests and CI, standardize formatting and rewrite the English and Chinese READMEs. Refs: #6, #18, #19, #20, #21, #22, #23, #24, #25
318 lines
11 KiB
Go
318 lines
11 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"crypto/subtle"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"log/slog"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
const maxRequestBody = 32 << 20
|
|
|
|
const anonymousZenKey = "public"
|
|
|
|
type Gateway struct {
|
|
cfg Config
|
|
logger *slog.Logger
|
|
transports *transportPool
|
|
zenNodes *nodePool
|
|
goNodes *nodePool
|
|
anonymous *anonymousPool
|
|
catalog *modelCatalog
|
|
monitor *Monitor
|
|
}
|
|
|
|
func NewGateway(cfg Config, logger *slog.Logger, monitor *Monitor) (*Gateway, error) {
|
|
transports, err := newTransportPool(cfg.RuntimeProxies(), cfg.Performance, cfg.Performance.AttemptTimeout(time.Duration(cfg.Retry.TimeoutSeconds)*time.Second))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
cooldown := time.Duration(cfg.Performance.FailureCooldownSeconds) * time.Second
|
|
zenNodes, err := newNodePool(cfg.ZenKeys, transports, cooldown)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("zen node pool: %w", err)
|
|
}
|
|
goNodes, err := newNodePool(cfg.GoKeys, transports, cooldown)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("go node pool: %w", err)
|
|
}
|
|
catalog := newModelCatalog(cfg.Prefer, cfg.Models.Protocols)
|
|
catalog.SetRefreshInterval(time.Duration(cfg.Models.RefreshSeconds) * time.Second)
|
|
return &Gateway{
|
|
cfg: cfg,
|
|
logger: logger,
|
|
transports: transports,
|
|
zenNodes: zenNodes,
|
|
goNodes: goNodes,
|
|
anonymous: newAnonymousPool(cfg.Anonymous, transports, cooldown),
|
|
catalog: catalog,
|
|
monitor: monitor,
|
|
}, nil
|
|
}
|
|
|
|
func (g *Gateway) Handler() http.Handler {
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("GET /v1/models", g.authenticate(g.handleModels))
|
|
mux.HandleFunc("POST /v1/chat/completions", g.authenticate(g.handleInference(ProtocolChat)))
|
|
mux.HandleFunc("POST /v1/responses", g.authenticate(g.handleInference(ProtocolResponses)))
|
|
mux.HandleFunc("POST /v1/messages", g.authenticate(g.handleInference(ProtocolAnthropic)))
|
|
mux.HandleFunc("GET /healthz", g.handleHealth)
|
|
return recoveryMiddleware(g.logger, mux)
|
|
}
|
|
|
|
func (g *Gateway) authenticate(next http.HandlerFunc) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
candidates := []string{strings.TrimSpace(r.Header.Get("x-api-key"))}
|
|
if auth := r.Header.Get("Authorization"); strings.HasPrefix(strings.ToLower(auth), "bearer ") {
|
|
candidates = append(candidates, strings.TrimSpace(auth[7:]))
|
|
}
|
|
valid := false
|
|
for _, key := range g.cfg.ServerKeys {
|
|
for _, candidate := range candidates {
|
|
if len(candidate) == len(key) && subtle.ConstantTimeCompare([]byte(candidate), []byte(key)) == 1 {
|
|
valid = true
|
|
}
|
|
}
|
|
}
|
|
if !valid {
|
|
protocol := ProtocolChat
|
|
if r.URL.Path == "/v1/messages" {
|
|
protocol = ProtocolAnthropic
|
|
}
|
|
writeAPIError(w, protocol, http.StatusUnauthorized, "invalid local API key", "authentication_error", "")
|
|
return
|
|
}
|
|
next(w, r)
|
|
}
|
|
}
|
|
|
|
func (g *Gateway) handleInference(external Protocol) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxRequestBody))
|
|
if err != nil {
|
|
writeAPIError(w, external, http.StatusBadRequest, "request body is too large or unreadable", "invalid_request_error", "")
|
|
return
|
|
}
|
|
var payload map[string]any
|
|
if err := json.Unmarshal(body, &payload); err != nil {
|
|
writeAPIError(w, external, http.StatusBadRequest, "request body must be a JSON object", "invalid_request_error", "")
|
|
return
|
|
}
|
|
model := stringAt(payload, "model")
|
|
meta := metaFromRequest(r)
|
|
if meta != nil {
|
|
meta.Model = model
|
|
}
|
|
if model == "" {
|
|
writeAPIError(w, external, http.StatusBadRequest, "model is required", "invalid_request_error", "model")
|
|
return
|
|
}
|
|
if !g.catalog.Supported(model) {
|
|
writeAPIError(w, external, http.StatusBadRequest, "the model uses an upstream protocol that opencode2api does not expose", "invalid_request_error", "model")
|
|
return
|
|
}
|
|
route, err := g.catalog.Route(model, len(g.cfg.ZenKeys) > 0, len(g.cfg.GoKeys) > 0, g.cfg.Anonymous)
|
|
if override, selected := debugKeyOverrideFrom(r.Context()); selected {
|
|
// A per-key diagnostic must not silently be served by another key,
|
|
// another tier or the anonymous lane.
|
|
route, err = g.catalog.RouteForTier(model, override.Tier, len(g.cfg.ZenKeys) > 0, len(g.cfg.GoKeys) > 0)
|
|
}
|
|
if err != nil {
|
|
writeAPIError(w, external, http.StatusBadRequest, err.Error(), "invalid_request_error", "model")
|
|
return
|
|
}
|
|
if meta != nil {
|
|
meta.Tier = string(route.Tier)
|
|
meta.Protocol = route.Protocol
|
|
}
|
|
bodies, err := g.prepareRouteBodies(external, route, payload)
|
|
if err != nil {
|
|
writeAPIError(w, external, http.StatusBadRequest, err.Error(), "invalid_request_error", "")
|
|
return
|
|
}
|
|
ids := deriveRequestIDs(r, payload)
|
|
if meta != nil {
|
|
meta.Request = ids.Request
|
|
}
|
|
stream := boolAt(payload, "stream")
|
|
requestCtx, cancel := context.WithTimeout(r.Context(), time.Duration(g.cfg.Retry.TimeoutSeconds)*time.Second)
|
|
defer cancel()
|
|
resp, upstreamRoute, err := g.doUpstream(requestCtx, route, bodies, ids)
|
|
if err != nil {
|
|
finalTier := route.Tier
|
|
if meta != nil && meta.Tier != "" {
|
|
finalTier = Tier(meta.Tier)
|
|
}
|
|
keyID, channel, anonymous := requestCredential(requestCtx)
|
|
g.logger.Warn("all upstream attempts failed", "component", "upstream", "event", "request_failed", "request_id", ids.Request, "tier", finalTier, "key_id", keyID, "channel", channel, "anonymous", anonymous, "error", err)
|
|
// An exhausted request budget is a timeout, not a bad gateway: the
|
|
// distinction matters to clients that retry on 502.
|
|
if errors.Is(err, context.DeadlineExceeded) {
|
|
writeAPIError(w, external, http.StatusGatewayTimeout, "upstream request timed out", "upstream_timeout", ids.Request)
|
|
return
|
|
}
|
|
writeAPIError(w, external, http.StatusBadGateway, "all upstream attempts failed", "upstream_error", ids.Request)
|
|
return
|
|
}
|
|
defer resp.Body.Close()
|
|
if meta != nil {
|
|
meta.Tier = string(upstreamRoute.Tier)
|
|
meta.Protocol = upstreamRoute.Protocol
|
|
}
|
|
w.Header().Set("x-request-id", ids.Request)
|
|
if resp.StatusCode/100 != 2 {
|
|
copyErrorResponse(w, external, resp, ids.Request)
|
|
return
|
|
}
|
|
if stream {
|
|
if meta != nil {
|
|
meta.Stream = true
|
|
}
|
|
if g.monitor != nil {
|
|
g.monitor.activeStreams.Add(1)
|
|
defer g.monitor.activeStreams.Add(-1)
|
|
}
|
|
w.Header().Set("Content-Type", "text/event-stream; charset=utf-8")
|
|
w.Header().Set("Cache-Control", "no-cache")
|
|
w.Header().Set("X-Accel-Buffering", "no")
|
|
w.WriteHeader(resp.StatusCode)
|
|
var usage bridgeUsage
|
|
var usageReported bool
|
|
if external == upstreamRoute.Protocol {
|
|
usage, usageReported, err = forwardSSEWithUsageContext(r.Context(), w, resp.Body, upstreamRoute.Protocol, model)
|
|
} else {
|
|
usage, usageReported, err = transcodeStreamWithUsageContext(r.Context(), w, resp.Body, upstreamRoute.Protocol, external, model)
|
|
}
|
|
if meta != nil {
|
|
meta.Usage, meta.UsageReported = usage, usageReported
|
|
if err != nil {
|
|
meta.Outcome = "stream_error"
|
|
if streamClientCancelled(r.Context(), err) {
|
|
meta.Outcome = "client_canceled"
|
|
}
|
|
}
|
|
}
|
|
if err != nil && !errors.Is(err, context.Canceled) {
|
|
g.logger.Warn("downstream stream ended with an error", "component", "stream", "event", "stream_failed", "request_id", ids.Request, "model", model, "tier", upstreamRoute.Tier, "error", err)
|
|
}
|
|
return
|
|
}
|
|
responseBody, err := io.ReadAll(io.LimitReader(resp.Body, 64<<20))
|
|
if err != nil {
|
|
writeAPIError(w, external, http.StatusBadGateway, "failed to read upstream response", "upstream_error", ids.Request)
|
|
return
|
|
}
|
|
if usage, reported := extractResponseUsage(upstreamRoute.Protocol, responseBody); meta != nil {
|
|
meta.Usage, meta.UsageReported = usage, reported
|
|
}
|
|
if external != upstreamRoute.Protocol {
|
|
responseBody, err = convertResponse(upstreamRoute.Protocol, external, responseBody)
|
|
if err != nil {
|
|
g.logger.Warn("response protocol conversion failed", "component", "conversion", "event", "response_conversion_failed", "request_id", ids.Request, "model", model, "source_protocol", upstreamRoute.Protocol, "target_protocol", external, "error", err)
|
|
writeAPIError(w, external, http.StatusBadGateway, "unsupported upstream response", "upstream_error", ids.Request)
|
|
return
|
|
}
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(resp.StatusCode)
|
|
_, _ = w.Write(responseBody)
|
|
}
|
|
}
|
|
|
|
func (g *Gateway) prepareRouteBodies(from Protocol, route modelRoute, input map[string]any) (map[Tier][]byte, error) {
|
|
tiers := make([]Tier, 0, len(route.KeyTiers)+1)
|
|
seen := make(map[Tier]bool, len(route.KeyTiers)+1)
|
|
addTier := func(tier Tier) {
|
|
if tier != TierZen && tier != TierGo || seen[tier] {
|
|
return
|
|
}
|
|
seen[tier] = true
|
|
tiers = append(tiers, tier)
|
|
}
|
|
addTier(route.Tier)
|
|
for _, tier := range route.KeyTiers {
|
|
addTier(tier)
|
|
}
|
|
if len(tiers) == 0 {
|
|
return nil, errors.New("no usable upstream tier")
|
|
}
|
|
bodies := make(map[Tier][]byte, len(tiers))
|
|
for _, tier := range tiers {
|
|
protocol := route.ProtocolFor(tier)
|
|
baseURL := g.cfg.Upstream.Zen
|
|
if tier == TierGo {
|
|
baseURL = g.cfg.Upstream.Go
|
|
}
|
|
upstreamPayload, err := prepareUpstreamRequest(from, protocol, input, baseURL)
|
|
if err != nil {
|
|
if tier != route.Tier {
|
|
// A fallback tier may use a stricter wire format than the
|
|
// preferred tier. Do not reject a request before the preferred
|
|
// upstream has even been tried; that tier is attempted only if
|
|
// the request actually falls back.
|
|
continue
|
|
}
|
|
return nil, fmt.Errorf("prepare %s upstream request: %w", tier, err)
|
|
}
|
|
encoded, err := json.Marshal(upstreamPayload)
|
|
if err != nil {
|
|
return nil, errors.New("request contains unsupported JSON values")
|
|
}
|
|
bodies[tier] = encoded
|
|
}
|
|
return bodies, nil
|
|
}
|
|
|
|
func copyErrorResponse(w http.ResponseWriter, protocol Protocol, resp *http.Response, requestID string) {
|
|
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
|
|
if retryAfter := resp.Header.Get("Retry-After"); retryAfter != "" {
|
|
w.Header().Set("Retry-After", retryAfter)
|
|
}
|
|
message := http.StatusText(resp.StatusCode)
|
|
var value map[string]any
|
|
if json.Unmarshal(body, &value) == nil {
|
|
message = firstString(stringAt(value, "error", "message"), stringAt(value, "message"), message)
|
|
}
|
|
writeAPIError(w, protocol, resp.StatusCode, message, "upstream_error", requestID)
|
|
}
|
|
|
|
func writeAPIError(w http.ResponseWriter, protocol Protocol, status int, message, kind, requestID string) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
if requestID != "" {
|
|
w.Header().Set("x-request-id", requestID)
|
|
}
|
|
if protocol == ProtocolAnthropic {
|
|
writeJSONStatus(w, status, map[string]any{"type": "error", "error": map[string]any{"type": kind, "message": message}})
|
|
return
|
|
}
|
|
writeJSONStatus(w, status, map[string]any{"error": map[string]any{"message": message, "type": kind, "param": nil, "code": nil}})
|
|
}
|
|
|
|
func writeJSON(w http.ResponseWriter, status int, value any) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
writeJSONStatus(w, status, value)
|
|
}
|
|
|
|
func writeJSONStatus(w http.ResponseWriter, status int, value any) {
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(value)
|
|
}
|
|
|
|
func recoveryMiddleware(logger *slog.Logger, next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
defer func() {
|
|
if value := recover(); value != nil {
|
|
logger.Error("request handler panicked", "component", "http", "event", "request_panic", "error", value)
|
|
writeAPIError(w, ProtocolChat, http.StatusInternalServerError, "internal server error", "server_error", "")
|
|
}
|
|
}()
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|