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
258 lines
8.8 KiB
Go
258 lines
8.8 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net/http"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
const (
|
|
proxyHealthCheckURL = "https://cloudflare.com/cdn-cgi/trace"
|
|
proxyHealthCheckInterval = 15 * time.Minute
|
|
proxyHealthCheckTimeout = 10 * time.Second
|
|
)
|
|
|
|
// syncProxyResult updates proxy health from real traffic. Only timeouts and
|
|
// connection refusals mark a proxy unavailable. Other errors and 4xx/5xx
|
|
// responses trigger a neutral URL check without being treated as proxy failure.
|
|
func (g *Gateway) syncProxyResult(ctx context.Context, proxy *proxyTransport, status int, err error) bool {
|
|
if proxy == nil {
|
|
return false
|
|
}
|
|
if isProxyFailure(err) {
|
|
g.rebindFailedProxy(proxy)
|
|
g.verifyProxyAfterError(ctx, proxy, status)
|
|
return true
|
|
}
|
|
if status >= 200 && status < 400 {
|
|
wasHealthy := proxy.healthy.Swap(true)
|
|
if !wasHealthy {
|
|
g.restoreProxy(proxy)
|
|
}
|
|
return false
|
|
}
|
|
if err != nil {
|
|
g.verifyProxyAfterError(ctx, proxy, status)
|
|
return false
|
|
}
|
|
if status >= 400 && status < 600 {
|
|
g.verifyProxyAfterError(ctx, proxy, status)
|
|
}
|
|
return false
|
|
}
|
|
|
|
func (g *Gateway) verifyProxyAfterError(ctx context.Context, proxy *proxyTransport, status int) {
|
|
if !proxy.checking.CompareAndSwap(false, true) {
|
|
return
|
|
}
|
|
// The client request may finish or be cancelled while the verification is
|
|
// running. Keep its values but give the proxy check an independent timeout.
|
|
checkCtx := context.WithoutCancel(ctx)
|
|
go func() {
|
|
result := g.transports.checkClaimedProxy(checkCtx, proxy, proxyHealthCheckURL, proxyHealthCheckTimeout)
|
|
g.applyProxyHealthResult(result, "upstream HTTP response", status)
|
|
}()
|
|
}
|
|
|
|
func (g *Gateway) rebindFailedProxy(proxy *proxyTransport) (zenMoved, goMoved int) {
|
|
if proxy == nil {
|
|
return 0, 0
|
|
}
|
|
wasHealthy := proxy.healthy.Swap(false)
|
|
return g.rebindUnavailableProxy(proxy, wasHealthy)
|
|
}
|
|
|
|
func (g *Gateway) rebindUnavailableProxy(proxy *proxyTransport, wasHealthy bool) (zenMoved, goMoved int) {
|
|
zenMoved = g.zenNodes.RebindProxy(proxy.index)
|
|
goMoved = g.goNodes.RebindProxy(proxy.index)
|
|
if wasHealthy || zenMoved+goMoved > 0 {
|
|
g.logger.Warn("proxy became unavailable", "component", "proxy", "event", "proxy_unavailable", "proxy", redactURL(proxy.name), "zen_keys_moved", zenMoved, "go_keys_moved", goMoved)
|
|
}
|
|
return zenMoved, goMoved
|
|
}
|
|
|
|
func (g *Gateway) restoreProxy(proxy *proxyTransport) (zenMoved, goMoved int) {
|
|
if proxy == nil {
|
|
return 0, 0
|
|
}
|
|
zenMoved = g.zenNodes.RestoreProxy(proxy.index)
|
|
goMoved = g.goNodes.RestoreProxy(proxy.index)
|
|
if zenMoved+goMoved > 0 {
|
|
g.logger.Info("proxy connectivity restored", "component", "proxy", "event", "proxy_restored", "proxy", redactURL(proxy.name), "zen_keys_moved", zenMoved, "go_keys_moved", goMoved)
|
|
}
|
|
return zenMoved, goMoved
|
|
}
|
|
|
|
func (g *Gateway) StartProxyHealthChecks(ctx context.Context) {
|
|
check := func() {
|
|
results := g.transports.CheckHealth(ctx, proxyHealthCheckURL, proxyHealthCheckTimeout)
|
|
for _, result := range results {
|
|
g.applyProxyHealthResult(result, "scheduled health check", 0)
|
|
}
|
|
}
|
|
go func() {
|
|
ticker := time.NewTicker(proxyHealthCheckInterval)
|
|
defer ticker.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-ticker.C:
|
|
check()
|
|
}
|
|
}
|
|
}()
|
|
}
|
|
|
|
func (g *Gateway) applyProxyHealthResult(result proxyHealthResult, source string, upstreamStatus int) {
|
|
if result.err == nil {
|
|
if !result.wasHealthy {
|
|
g.restoreProxy(result.proxy)
|
|
}
|
|
g.logger.Debug("proxy health check passed", "component", "proxy", "event", "health_check_passed", "source", source, "upstream_status", upstreamStatus, "proxy", redactURL(result.proxy.name))
|
|
return
|
|
}
|
|
if !result.failed {
|
|
g.logger.Debug("proxy health check was inconclusive", "component", "proxy", "event", "health_check_inconclusive", "source", source, "upstream_status", upstreamStatus, "proxy", redactURL(result.proxy.name), "error", result.err)
|
|
return
|
|
}
|
|
if g.transports.hasHealthy() {
|
|
zenMoved, goMoved := g.rebindUnavailableProxy(result.proxy, result.wasHealthy)
|
|
if result.wasHealthy || zenMoved+goMoved > 0 {
|
|
g.logger.Warn("proxy health check failed", "component", "proxy", "event", "health_check_failed", "source", source, "upstream_status", upstreamStatus, "proxy", redactURL(result.proxy.name), "zen_keys_moved", zenMoved, "go_keys_moved", goMoved, "error", result.err)
|
|
return
|
|
}
|
|
}
|
|
g.logger.Debug("proxy health check is still failing", "component", "proxy", "event", "health_check_still_failing", "source", source, "upstream_status", upstreamStatus, "proxy", redactURL(result.proxy.name), "error", result.err)
|
|
}
|
|
|
|
func (g *Gateway) StartModelRefresh(ctx context.Context) {
|
|
refresh := func() {
|
|
var zen, goModels []string
|
|
var capabilities protocolCapabilities
|
|
var capabilitiesErr error
|
|
var wg sync.WaitGroup
|
|
wg.Add(3)
|
|
go func() { defer wg.Done(); zen = g.refreshZen(ctx) }()
|
|
go func() { defer wg.Done(); goModels = g.refreshTier(ctx, g.cfg.Upstream.Go, g.goNodes) }()
|
|
go func() {
|
|
defer wg.Done()
|
|
capabilityCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
|
defer cancel()
|
|
capabilities, capabilitiesErr = g.refreshProtocolCapabilities(capabilityCtx)
|
|
}()
|
|
wg.Wait()
|
|
if ctx.Err() != nil {
|
|
return
|
|
}
|
|
if capabilitiesErr != nil {
|
|
g.logger.Warn("OpenCode capability catalog refresh failed", "component", "models", "event", "capability_refresh_failed", "error", capabilitiesErr)
|
|
}
|
|
if zen != nil || goModels != nil {
|
|
g.catalog.ReplaceWithCapabilities(zen, goModels, capabilities.Protocols, capabilities.Unsupported, capabilities.Metadata)
|
|
if ctx.Err() == nil {
|
|
if err := g.catalog.SaveCache(); err != nil {
|
|
g.logger.Warn("model catalog cache write failed", "component", "models", "event", "catalog_cache_write_failed", "error", err)
|
|
}
|
|
}
|
|
g.logger.Info("model catalog refreshed", "component", "models", "event", "catalog_refreshed", "models", len(g.catalog.List()))
|
|
}
|
|
}
|
|
go func() {
|
|
refresh()
|
|
ticker := time.NewTicker(time.Duration(g.cfg.Models.RefreshSeconds) * time.Second)
|
|
defer ticker.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-ticker.C:
|
|
refresh()
|
|
}
|
|
}
|
|
}()
|
|
}
|
|
|
|
func (g *Gateway) refreshProtocolCapabilities(ctx context.Context) (protocolCapabilities, error) {
|
|
if g.transports == nil || len(g.transports.items) == 0 {
|
|
return fetchProtocolCapabilities(ctx, &http.Client{Timeout: 30 * time.Second}, openCodeCapabilitiesURL)
|
|
}
|
|
var lastErr error
|
|
for _, proxy := range g.transports.items {
|
|
if proxy == nil || !proxy.healthy.Load() {
|
|
continue
|
|
}
|
|
capabilities, err := fetchProtocolCapabilities(ctx, proxy.client, openCodeCapabilitiesURL)
|
|
if err == nil {
|
|
return capabilities, nil
|
|
}
|
|
lastErr = err
|
|
}
|
|
if lastErr == nil {
|
|
lastErr = errors.New("no healthy proxy available for OpenCode capability catalog")
|
|
}
|
|
return protocolCapabilities{}, lastErr
|
|
}
|
|
|
|
func (g *Gateway) refreshZen(ctx context.Context) []string {
|
|
if models := g.refreshTier(ctx, g.cfg.Upstream.Zen, g.zenNodes); models != nil {
|
|
return models
|
|
}
|
|
if !g.cfg.Anonymous {
|
|
return nil
|
|
}
|
|
return g.refreshAnonymousTier(ctx, g.cfg.Upstream.Zen)
|
|
}
|
|
|
|
func (g *Gateway) refreshAnonymousTier(ctx context.Context, base string) []string {
|
|
cursor := g.anonymous.CursorFor("")
|
|
limit := g.anonymous.Len()
|
|
for attempt := 1; attempt <= limit; attempt++ {
|
|
node := cursor.Next()
|
|
if node == nil {
|
|
break
|
|
}
|
|
refreshCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
|
models, status, err := fetchModels(refreshCtx, node.proxy.client, base, anonymousZenKey)
|
|
g.syncProxyResult(refreshCtx, node.proxy, status, err)
|
|
cancel()
|
|
if err == nil {
|
|
g.anonymous.MarkSuccess(node)
|
|
return models
|
|
}
|
|
g.anonymous.MarkFailure(node, nil, err)
|
|
g.logger.Debug("anonymous model catalog refresh attempt failed", "component", "models", "event", "anonymous_refresh_attempt_failed", "upstream", redactURL(base), "attempt", attempt, "proxy", redactURL(node.proxy.name), "error", err)
|
|
}
|
|
g.logger.Warn("anonymous model catalog refresh failed", "component", "models", "event", "anonymous_refresh_failed", "upstream", redactURL(base))
|
|
return nil
|
|
}
|
|
|
|
func (g *Gateway) refreshTier(ctx context.Context, base string, nodes *nodePool) []string {
|
|
cursor := nodes.Cursor()
|
|
for attempt := 0; attempt < g.cfg.Retry.MaxAttempts; attempt++ {
|
|
node := cursor.Next()
|
|
if node == nil {
|
|
return nil
|
|
}
|
|
refreshCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
|
proxy := nodes.Proxy(node)
|
|
if proxy == nil {
|
|
cancel()
|
|
return nil
|
|
}
|
|
models, status, err := fetchModels(refreshCtx, proxy.client, base, node.key)
|
|
g.syncProxyResult(refreshCtx, proxy, status, err)
|
|
cancel()
|
|
if err == nil {
|
|
nodes.MarkSuccess(node)
|
|
return models
|
|
}
|
|
nodes.MarkFailure(node, nil, err)
|
|
g.logger.Debug("model catalog refresh attempt failed", "component", "models", "event", "refresh_attempt_failed", "upstream", redactURL(base), "attempt", attempt+1, "error", err)
|
|
}
|
|
g.logger.Warn("model catalog refresh failed", "component", "models", "event", "refresh_failed", "upstream", redactURL(base))
|
|
return nil
|
|
}
|