mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-05 16:04:01 +00:00
OpenCode's 2026-10-14 gate rejects the gateway on every lane again (403 FreeTierError) while the official CLI keeps working. Probing byte-identical CLI v2.0.29 replays against the live endpoint isolated the deltas this changeset fixes on top of #83: - identity: derive the session from the new x-opencode-session-id signal too, and stop forwarding the legacy x-opencode-request header and canonical prj_* project ids upstream — both are instant 403s. - upstream: the x-opencode-project header keeps one conversation pinned to one upstream project but is now hashed into the bare 40-hex shape the client sends (a prj_* value 403s). - refresh: when the configured anonymous upstream has no models route (404), fall back to the legacy Zen console listing so the anonymous catalog still populates. The endpoint move, genuine tool definitions, and UA shape came in with #83; the definitions embedded there were re-verified byte-for-byte against a fresh CLI v2.0.29 capture, including the smallest passing toolset (shell + read) and per-tool definition checks. Validation: live end-to-end against opencode.ai — anonymous lane serves streaming and plain JSON chat completions on big-pickle and step-5-preview-free, tool calls pass through, all nine exposed free models probe available, go vet/build/gofmt clean.
267 lines
9.3 KiB
Go
267 lines
9.3 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)
|
|
if zenMoved+goMoved > 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)
|
|
}
|
|
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
|
|
}
|