diff --git a/gateway.go b/gateway.go index 77eca6a..8f313da 100644 --- a/gateway.go +++ b/gateway.go @@ -19,7 +19,7 @@ const maxRequestBody = 32 << 20 const ( proxyHealthCheckURL = "https://cloudflare.com/cdn-cgi/trace" - proxyHealthCheckInterval = 60 * time.Second + proxyHealthCheckInterval = 15 * time.Minute proxyHealthCheckTimeout = 10 * time.Second ) @@ -242,14 +242,17 @@ func (g *Gateway) doUpstream(ctx context.Context, route modelRoute, body []byte, req.Header.Set("Authorization", "Bearer "+node.key) } resp, err := proxy.client.Do(req) + status := 0 + if resp != nil { + status = resp.StatusCode + } + proxyFailed := g.syncProxyResult(ctx, proxy, status, err) if err == nil && resp.StatusCode/100 == 2 { nodes.MarkSuccess(node) - proxy.healthy.Store(true) g.logger.Debug("upstream accepted request", "request_id", ids.Request, "attempt", attempt, "tier", route.Tier, "proxy", redactURL(proxy.name)) return resp, nil } - if isProxyFailure(resp, err) { - g.rebindFailedProxy(proxy) + if proxyFailed { if nodes.Proxy(node) == proxy { nodes.MarkFailure(node, resp, err) } @@ -270,19 +273,46 @@ func (g *Gateway) doUpstream(ctx context.Context, route modelRoute, body []byte, return nil, lastErr } -func isProxyFailure(resp *http.Response, err error) bool { +// 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 { - return true - } - if resp == nil { + g.verifyProxyAfterError(ctx, proxy, status) return false } - switch resp.StatusCode { - case http.StatusProxyAuthRequired, http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout: - return true - default: - 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) { @@ -290,6 +320,10 @@ func (g *Gateway) rebindFailedProxy(proxy *proxyTransport) (zenMoved, goMoved in 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 { @@ -298,37 +332,26 @@ func (g *Gateway) rebindFailedProxy(proxy *proxyTransport) (zenMoved, goMoved in 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 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) - healthy := 0 for _, result := range results { - if result.err == nil { - healthy++ - } - } - for _, result := range results { - if result.err != nil { - if ctx.Err() != nil { - return - } - zenMoved, goMoved := 0, 0 - if healthy > 0 { - zenMoved = g.zenNodes.RebindProxy(result.proxy.index) - goMoved = g.goNodes.RebindProxy(result.proxy.index) - } - if result.wasHealthy || zenMoved+goMoved > 0 { - g.logger.Warn("proxy health check failed", "proxy", redactURL(result.proxy.name), "zen_keys_moved", zenMoved, "go_keys_moved", goMoved, "error", result.err) - } else { - g.logger.Debug("proxy health check still failing", "proxy", redactURL(result.proxy.name), "error", result.err) - } - continue - } - g.logger.Debug("proxy health check passed", "proxy", redactURL(result.proxy.name)) + g.applyProxyHealthResult(result, "scheduled health check", 0) } } go func() { - check() ticker := time.NewTicker(proxyHealthCheckInterval) defer ticker.Stop() for { @@ -342,6 +365,28 @@ func (g *Gateway) StartProxyHealthChecks(ctx context.Context) { }() } +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", "source", source, "upstream_status", upstreamStatus, "proxy", redactURL(result.proxy.name)) + return + } + if !result.failed { + g.logger.Debug("proxy 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", "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 still failing", "source", source, "upstream_status", upstreamStatus, "proxy", redactURL(result.proxy.name), "error", result.err) +} + func protocolPath(protocol Protocol) string { switch protocol { case ProtocolResponses: @@ -394,11 +439,11 @@ func (g *Gateway) refreshTier(ctx context.Context, base string, nodes *nodePool) cancel() return nil } - models, err := fetchModels(refreshCtx, proxy.client, base, node.key) + models, status, err := fetchModels(refreshCtx, proxy.client, base, node.key) + g.syncProxyResult(refreshCtx, proxy, status, err) cancel() if err == nil { nodes.MarkSuccess(node) - proxy.healthy.Store(true) return models } nodes.MarkFailure(node, nil, err) diff --git a/models.go b/models.go index 840b3c3..034cbb7 100644 --- a/models.go +++ b/models.go @@ -143,26 +143,26 @@ type modelsResponse struct { } `json:"data"` } -func fetchModels(ctx context.Context, client *http.Client, baseURL, key string) ([]string, error) { +func fetchModels(ctx context.Context, client *http.Client, baseURL, key string) ([]string, int, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(baseURL, "/")+"/v1/models", nil) if err != nil { - return nil, err + return nil, 0, err } req.Header.Set("Authorization", "Bearer "+key) req.Header.Set("User-Agent", opencodeUserAgent()) req.Header.Set("x-opencode-client", "cli") resp, err := client.Do(req) if err != nil { - return nil, err + return nil, 0, err } defer resp.Body.Close() if resp.StatusCode/100 != 2 { - return nil, fmt.Errorf("models endpoint returned HTTP %d", resp.StatusCode) + return nil, resp.StatusCode, fmt.Errorf("models endpoint returned HTTP %d", resp.StatusCode) } var payload modelsResponse dec := json.NewDecoder(io.LimitReader(resp.Body, 8<<20)) if err := dec.Decode(&payload); err != nil { - return nil, err + return nil, resp.StatusCode, err } models := make([]string, 0, len(payload.Data)) for _, item := range payload.Data { @@ -171,7 +171,7 @@ func fetchModels(ctx context.Context, client *http.Client, baseURL, key string) } } if len(models) == 0 { - return nil, errors.New("models endpoint returned an empty list") + return nil, resp.StatusCode, errors.New("models endpoint returned an empty list") } - return models, nil + return models, resp.StatusCode, nil } diff --git a/pool.go b/pool.go index f6e102b..2d71220 100644 --- a/pool.go +++ b/pool.go @@ -2,6 +2,7 @@ package main import ( "context" + "errors" "fmt" "io" "math/rand/v2" @@ -12,20 +13,31 @@ import ( "strings" "sync" "sync/atomic" + "syscall" "time" ) type proxyTransport struct { - index int - name string - client *http.Client - healthy atomic.Bool + index int + name string + client *http.Client + healthy atomic.Bool + checking atomic.Bool } type transportPool struct { items []*proxyTransport } +func (p *transportPool) hasHealthy() bool { + for _, proxy := range p.items { + if proxy.healthy.Load() { + return true + } + } + return false +} + func newTransportPool(proxies []string, cfg PerformanceConfig, responseHeaderTimeout time.Duration) (*transportPool, error) { p := &transportPool{items: make([]*proxyTransport, 0, len(proxies))} for _, raw := range proxies { @@ -59,54 +71,87 @@ func newTransportPool(proxies []string, cfg PerformanceConfig, responseHeaderTim type proxyHealthResult struct { proxy *proxyTransport err error + failed bool wasHealthy bool } -// CheckHealth checks every route concurrently. A proxy is considered healthy -// only when the request reaches the target and returns a successful response. +// CheckHealth concurrently rechecks only proxies already marked unhealthy. +// Healthy proxies are skipped before a check is claimed. Any HTTP response +// from the test URL proves that the route is reachable; only a timeout or +// connection refusal keeps the proxy unhealthy. func (p *transportPool) CheckHealth(ctx context.Context, target string, timeout time.Duration) []proxyHealthResult { results := make(chan proxyHealthResult, len(p.items)) + checks := 0 for _, proxy := range p.items { + if proxy.healthy.Load() || !proxy.checking.CompareAndSwap(false, true) { + continue + } + // A real request may have restored the proxy between the first health + // read and claiming this check. + if proxy.healthy.Load() { + proxy.checking.Store(false) + continue + } + checks++ go func() { - checkCtx, cancel := context.WithTimeout(ctx, timeout) - defer cancel() - req, err := http.NewRequestWithContext(checkCtx, http.MethodGet, target, nil) - if err == nil { - req.Header.Set("User-Agent", opencodeUserAgent()) - resp, requestErr := proxy.client.Do(req) - err = requestErr - if resp != nil { - _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 64<<10)) - _ = resp.Body.Close() - if err == nil && resp.StatusCode/100 != 2 { - err = fmt.Errorf("health endpoint returned HTTP %d", resp.StatusCode) - } - } - } - wasHealthy := true - if err == nil { - proxy.healthy.Store(true) - } else { - wasHealthy = proxy.healthy.Swap(false) - } - results <- proxyHealthResult{proxy: proxy, err: err, wasHealthy: wasHealthy} + results <- p.checkClaimedProxy(ctx, proxy, target, timeout) }() } - out := make([]proxyHealthResult, 0, len(p.items)) - for range p.items { + out := make([]proxyHealthResult, 0, checks) + for range checks { out = append(out, <-results) } return out } +// checkClaimedProxy performs a check after the caller has acquired checking. +func (p *transportPool) checkClaimedProxy(ctx context.Context, proxy *proxyTransport, target string, timeout time.Duration) proxyHealthResult { + defer proxy.checking.Store(false) + checkCtx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + req, err := http.NewRequestWithContext(checkCtx, http.MethodGet, target, nil) + if err == nil { + req.Header.Set("User-Agent", opencodeUserAgent()) + resp, requestErr := proxy.client.Do(req) + err = requestErr + if resp != nil { + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 64<<10)) + _ = resp.Body.Close() + } + } + result := proxyHealthResult{proxy: proxy, err: err, wasHealthy: proxy.healthy.Load()} + if err == nil { + result.wasHealthy = proxy.healthy.Swap(true) + } else if isProxyFailure(err) { + result.failed = true + result.wasHealthy = proxy.healthy.Swap(false) + } + return result +} + +// isProxyFailure deliberately recognizes only failures that say the proxy +// route is unavailable. HTTP responses and unrelated transport/protocol errors +// must not evict a proxy. +func isProxyFailure(err error) bool { + if err == nil { + return false + } + if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, syscall.ECONNREFUSED) { + return true + } + var timeout interface{ Timeout() bool } + return errors.As(err, &timeout) && timeout.Timeout() +} + // upstreamNode keeps a key stable while allowing its proxy binding to change // atomically when a proxy becomes unavailable. type upstreamNode struct { - key string - index int - proxyIndex atomic.Int64 - failures atomic.Uint32 - cooldownUntil atomic.Int64 + key string + index int + preferredProxy int + proxyIndex atomic.Int64 + failures atomic.Uint32 + cooldownUntil atomic.Int64 } type nodePool struct { @@ -136,7 +181,7 @@ func newNodePool(keys []string, transports *transportPool, cooldown time.Duratio } for i, key := range keys { proxyIndex := i % len(transports.items) - node := &upstreamNode{key: key, index: i} + node := &upstreamNode{key: key, index: i, preferredProxy: proxyIndex} node.proxyIndex.Store(int64(proxyIndex)) pool.nodes = append(pool.nodes, node) pool.bindingCount[proxyIndex]++ @@ -144,6 +189,34 @@ func newNodePool(keys []string, transports *transportPool, cooldown time.Duratio return pool, nil } +// RestoreProxy moves keys that were originally assigned to a recovered proxy +// back to it. Proxies without an original key simply become healthy failover +// candidates again. +func (p *nodePool) RestoreProxy(recoveredProxy int) int { + if p == nil || p.transports == nil || recoveredProxy < 0 || recoveredProxy >= len(p.transports.items) { + return 0 + } + p.bindingsMu.Lock() + defer p.bindingsMu.Unlock() + + moved := 0 + for _, node := range p.nodes { + current := int(node.proxyIndex.Load()) + if node.preferredProxy != recoveredProxy || current == recoveredProxy { + continue + } + if current >= 0 && current < len(p.bindingCount) { + p.bindingCount[current]-- + } + p.bindingCount[recoveredProxy]++ + node.proxyIndex.Store(int64(recoveredProxy)) + node.failures.Store(0) + node.cooldownUntil.Store(0) + moved++ + } + return moved +} + func (p *nodePool) Len() int { return len(p.nodes) } func (p *nodePool) Proxy(node *upstreamNode) *proxyTransport {