mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-05 08:02:53 +00:00
A quota response with a multi-hour Retry-After cooled anonymous exits for hours, so after a network change gave them a fresh allowance traffic kept falling through to key lanes until restart. Cap Retry-After on the anonymous lane at the 8x backoff ceiling, and clear anonymous cooldowns when their proxy recovers. Key lanes keep honoring Retry-After in full. Co-authored-by: CheerC <cheerc@gmail.com>
270 lines
9.6 KiB
Go
270 lines
9.6 KiB
Go
package gateway
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net/http"
|
|
"sync"
|
|
"time"
|
|
|
|
"opencode2api/internal/config"
|
|
modelcatalog "opencode2api/internal/models"
|
|
)
|
|
|
|
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", config.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)
|
|
// The anonymous lane carries its own per-proxy cooldowns; key recovery
|
|
// alone would leave it skipped after an outage-era failure.
|
|
anonCleared := g.anonymous.RestoreProxy(proxy)
|
|
if zenMoved+goMoved > 0 || anonCleared > 0 {
|
|
g.logger.Info("proxy connectivity restored", "component", "proxy", "event", "proxy_restored", "proxy", config.RedactURL(proxy.name), "zen_keys_moved", zenMoved, "go_keys_moved", goMoved, "anonymous_cleared", anonCleared)
|
|
}
|
|
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", config.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", config.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", config.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", config.RedactURL(result.proxy.name), "error", result.err)
|
|
}
|
|
|
|
func (g *Gateway) StartModelRefresh(ctx context.Context) {
|
|
refresh := func() {
|
|
var zen, goModels []string
|
|
var capabilities modelcatalog.Capabilities
|
|
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)
|
|
g.syncRotation()
|
|
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) (modelcatalog.Capabilities, error) {
|
|
if g.transports == nil || len(g.transports.items) == 0 {
|
|
return modelcatalog.FetchCapabilities(ctx, &http.Client{Timeout: 30 * time.Second}, modelcatalog.CapabilitiesURL)
|
|
}
|
|
var lastErr error
|
|
for _, proxy := range g.transports.items {
|
|
if proxy == nil || !proxy.healthy.Load() {
|
|
continue
|
|
}
|
|
capabilities, err := modelcatalog.FetchCapabilities(ctx, proxy.client, modelcatalog.CapabilitiesURL)
|
|
if err == nil {
|
|
return capabilities, nil
|
|
}
|
|
lastErr = err
|
|
}
|
|
if lastErr == nil {
|
|
lastErr = errors.New("no healthy proxy available for OpenCode capability catalog")
|
|
}
|
|
return modelcatalog.Capabilities{}, 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.Anonymous)
|
|
}
|
|
|
|
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 := modelcatalog.FetchModels(refreshCtx, node.proxy.client, base, anonymousZenKey)
|
|
if err != nil && status == 404 {
|
|
// The new inference backend does not expose a models listing;
|
|
// probe the legacy Zen console origin once before giving up.
|
|
models, status, err = modelcatalog.FetchModels(refreshCtx, node.proxy.client, modelcatalog.LegacyZenBase, 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", config.RedactURL(base), "attempt", attempt, "proxy", config.RedactURL(node.proxy.name), "error", err)
|
|
}
|
|
g.logger.Warn("anonymous model catalog refresh failed", "component", "models", "event", "anonymous_refresh_failed", "upstream", config.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 := modelcatalog.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", config.RedactURL(base), "attempt", attempt+1, "error", err)
|
|
}
|
|
g.logger.Warn("model catalog refresh failed", "component", "models", "event", "refresh_failed", "upstream", config.RedactURL(base))
|
|
return nil
|
|
}
|