From ee0fb53e5d6baf81017b46b41388d044dd965778 Mon Sep 17 00:00:00 2001 From: Jason Xu Date: Sat, 17 Oct 2026 04:04:07 +0800 Subject: [PATCH] fix(proxy): force fresh tunnels for #pool and stop failing over cooling exits Three defects kept the anonymous lane returning 502 "all upstream attempts failed" and kept rotating endpoints pinned to one exit IP: - Cloning http.DefaultTransport after its first dial inherits the configured HTTP/2 ALPN and TLSNextProto map, which ignore DisableKeepAlives and Request.Close and multiplex every request over a single CONNECT tunnel. A pool transport now installs an explicit empty TLSNextProto map and pins ALPN to http/1.1, so each attempt opens a new tunnel and draws a new exit. - anonymousCursor.Next returned nil as soon as every static proxy was cooling or unhealthy, which turned a transient 429 into an immediate "no healthy anonymous proxies available" and a 502 for the client. It now tracks the nodes this cursor already tried and falls back to the earliest-expiring remaining node, mirroring the key pool's earliest-expiry behavior. - An upstream HTTP response proves the proxy route is reachable, so a 4xx/5xx (or a 2xx) now clears an unhealthy flag left by an earlier transient timeout instead of leaving the route evicted for up to 15 minutes. The tier-outer loop also keeps the last upstream response when a later key tier dies on transport: the previous code dropped it, so a real 429 from the anonymous lane was replaced by a generic 502. --- internal/gateway/pool.go | 66 ++++++++++++++++++++---- internal/gateway/pool_test.go | 96 +++++++++++++++++++++++++++++++++++ internal/gateway/refresh.go | 19 +++++-- internal/gateway/upstream.go | 17 +++++-- 4 files changed, 177 insertions(+), 21 deletions(-) create mode 100644 internal/gateway/pool_test.go diff --git a/internal/gateway/pool.go b/internal/gateway/pool.go index a208c53..b794368 100644 --- a/internal/gateway/pool.go +++ b/internal/gateway/pool.go @@ -2,6 +2,7 @@ package gateway import ( "context" + "crypto/tls" "errors" "fmt" "hash/fnv" @@ -54,6 +55,7 @@ type anonymousCursor struct { pool *anonymousPool start int offset int + used []bool } func newAnonymousPool(enabled bool, transports *transportPool, cooldown time.Duration) *anonymousPool { @@ -100,30 +102,57 @@ func (p *anonymousPool) CursorFor(affinity string) anonymousCursor { // Next visits each healthy, non-cooling static proxy at most once per cursor. // When the pool contains rotating proxy-pool transports (#pool), it continues // cycling through them after the first pass so retry.max_attempts can draw a -// fresh upstream connection (and new exit IP) on every attempt. +// fresh upstream connection (and new exit IP) on every attempt. If all static +// proxies are currently cooling or marked unhealthy, Next falls back to the +// earliest-expiring node not yet tried by this cursor instead of returning nil +// immediately. func (c *anonymousCursor) Next() *anonymousNode { if c.pool == nil || len(c.pool.nodes) == 0 { return nil } n := len(c.pool.nodes) + if c.used == nil { + c.used = make([]bool, n) + } now := time.Now().UnixNano() for c.offset < n { - node := c.pool.nodes[(c.start+c.offset)%n] + idx := (c.start + c.offset) % n c.offset++ - if node.proxy.pool || (node.proxy.healthy.Load() && node.cooldownUntil.Load() <= now) { + node := c.pool.nodes[idx] + if node.proxy.pool || (!c.used[idx] && node.proxy.healthy.Load() && node.cooldownUntil.Load() <= now) { + c.used[idx] = true return node } } - if !c.pool.hasPool { - return nil - } - for range n { - node := c.pool.nodes[(c.start+c.offset)%n] - c.offset++ - if node.proxy.pool { - return node + if c.pool.hasPool { + for range n { + idx := (c.start + c.offset) % n + c.offset++ + node := c.pool.nodes[idx] + if node.proxy.pool { + return node + } } } + choice := -1 + var earliest int64 + choiceHealthy := false + for step := range n { + idx := (c.start + step) % n + if c.used[idx] { + continue + } + node := c.pool.nodes[idx] + healthy := node.proxy.healthy.Load() + until := node.cooldownUntil.Load() + if choice < 0 || (healthy && !choiceHealthy) || (healthy == choiceHealthy && until < earliest) { + choice, earliest, choiceHealthy = idx, until, healthy + } + } + if choice >= 0 { + c.used[choice] = true + return c.pool.nodes[choice] + } return nil } @@ -217,6 +246,21 @@ func newTransportPool(proxies []string, cfg config.PerformanceConfig, responseHe transport.ResponseHeaderTimeout = responseHeaderTimeout transport.ForceAttemptHTTP2 = !isPool transport.DisableKeepAlives = isPool + if isPool { + // Cloning DefaultTransport after its first dial inherits the + // already-configured HTTP/2 ALPN and TLSNextProto map, which ignores + // DisableKeepAlives and req.Close and multiplexes every request over + // one CONNECT tunnel. An explicit empty TLSNextProto map and HTTP/1.1 + // ALPN force a brand-new TCP + CONNECT tunnel per attempt. + transport.TLSNextProto = make(map[string]func(authority string, c *tls.Conn) http.RoundTripper) + if transport.TLSClientConfig == nil { + transport.TLSClientConfig = &tls.Config{NextProtos: []string{"http/1.1"}} + } else { + tlsCfg := transport.TLSClientConfig.Clone() + tlsCfg.NextProtos = []string{"http/1.1"} + transport.TLSClientConfig = tlsCfg + } + } transport.DialContext = (&net.Dialer{ Timeout: time.Duration(cfg.ConnectTimeoutSeconds) * time.Second, KeepAlive: 30 * time.Second, diff --git a/internal/gateway/pool_test.go b/internal/gateway/pool_test.go new file mode 100644 index 0000000..a7b352c --- /dev/null +++ b/internal/gateway/pool_test.go @@ -0,0 +1,96 @@ +package gateway + +import ( + "net/http" + "testing" + "time" + + "opencode2api/internal/config" +) + +func testPerformanceConfig() config.PerformanceConfig { + return config.PerformanceConfig{MaxIdleConns: 8, MaxIdleConnsPerHost: 8, IdleConnTimeoutSeconds: 30, ConnectTimeoutSeconds: 5, FailureCooldownSeconds: 15} +} + +// A #pool entry must dial like a rotating endpoint: no HTTP/2, no keep-alive +// idle pool, and an explicit empty TLSNextProto so a cloned DefaultTransport +// cannot reuse the tunnel it configured before the first dial. +func TestPoolTransportForcesFreshConnection(t *testing.T) { + transports, err := newTransportPool([]string{"http://127.0.0.1:7890#pool", "direct"}, testPerformanceConfig(), 0) + if err != nil { + t.Fatalf("newTransportPool failed: %v", err) + } + pool := transports.items[0] + if !pool.pool { + t.Fatal("the #pool entry was not marked as a rotating pool") + } + transport := pool.client.Transport.(*http.Transport) + if transport.DisableKeepAlives != true || transport.ForceAttemptHTTP2 != false { + t.Fatalf("pool transport keeps connections alive: DisableKeepAlives=%v ForceAttemptHTTP2=%v", transport.DisableKeepAlives, transport.ForceAttemptHTTP2) + } + if transport.TLSNextProto == nil || len(transport.TLSNextProto) != 0 { + t.Fatalf("pool transport still negotiates HTTP/2: TLSNextProto=%v", transport.TLSNextProto) + } + if transport.TLSClientConfig == nil || len(transport.TLSClientConfig.NextProtos) != 1 || transport.TLSClientConfig.NextProtos[0] != "http/1.1" { + t.Fatalf("pool transport TLS ALPN = %v, want [http/1.1]", transport.TLSClientConfig) + } + static := transports.items[1] + if static.pool || static.client.Transport.(*http.Transport).ForceAttemptHTTP2 != true { + t.Fatal("the static entry must keep the default pooling behavior") + } +} + +// When every static proxy is cooling, Next must fall back to the node that +// recovers first instead of returning nil, which used to turn a rate-limited +// exit into an immediate "503/502 no healthy anonymous proxies" failure. +func TestAnonymousCursorFallsBackToCoolingNodes(t *testing.T) { + transports, err := newTransportPool([]string{"http://127.0.0.1:7890", "http://127.0.0.1:7891"}, testPerformanceConfig(), 0) + if err != nil { + t.Fatalf("newTransportPool failed: %v", err) + } + pool := newAnonymousPool(true, transports, 15*time.Second) + now := time.Now().UnixNano() + pool.nodes[0].cooldownUntil.Store(now + int64(90*time.Second)) + pool.nodes[1].cooldownUntil.Store(now + int64(30*time.Second)) + + cursor := pool.CursorFor("") + visited := map[int]int{} + for range 2 { + node := cursor.Next() + if node == nil { + t.Fatal("cursor returned nil while cooling nodes were still available") + } + visited[node.proxy.index]++ + } + if len(visited) != 2 { + t.Fatalf("cursor fell back to %d distinct nodes, want both cooling nodes", len(visited)) + } + if node := cursor.Next(); node != nil { + t.Fatalf("cursor revisited proxies after exhausting the pool: index=%d", node.proxy.index) + } + + // The earliest-expiring node must be offered first. + stats := pool.CursorFor("") + if node := stats.Next(); node == nil || node.proxy.index != 1 { + t.Fatalf("fallback did not prefer the earliest-expiring node: %v", node) + } +} + +// A #pool entry keeps being offered after one pass so retry.max_attempts can +// draw a fresh upstream connection (and exit IP) on every attempt. +func TestAnonymousCursorCyclesPoolEntries(t *testing.T) { + transports, err := newTransportPool([]string{"http://127.0.0.1:7890#pool"}, testPerformanceConfig(), 0) + if err != nil { + t.Fatalf("newTransportPool failed: %v", err) + } + pool := newAnonymousPool(true, transports, 15*time.Second) + pool.nodes[0].cooldownUntil.Store(time.Now().Add(time.Minute).UnixNano()) + + cursor := pool.CursorFor("") + for attempt := 1; attempt <= 3; attempt++ { + node := cursor.Next() + if node == nil { + t.Fatalf("pool entry was not offered on attempt %d", attempt) + } + } +} diff --git a/internal/gateway/refresh.go b/internal/gateway/refresh.go index ff77917..54d5021 100644 --- a/internal/gateway/refresh.go +++ b/internal/gateway/refresh.go @@ -18,8 +18,10 @@ const ( ) // 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. +// connection refusals mark a proxy unavailable. Any HTTP response — including +// 4xx/5xx — proves the route is reachable and restores a proxy evicted by an +// earlier transient failure, so a rate-limited exit is never blamed on the +// proxy route itself. func (g *Gateway) syncProxyResult(ctx context.Context, proxy *proxyTransport, status int, err error) bool { if proxy == nil || proxy.pool { return false @@ -36,13 +38,20 @@ func (g *Gateway) syncProxyResult(ctx context.Context, proxy *proxyTransport, st } return false } + if err == nil && status >= 400 && status < 600 { + // Receiving an HTTP status from the upstream proves the proxy route + // itself is reachable; restore an unhealthy flag left by an earlier + // transient timeout instead of keeping the route evicted. + 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 } diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index f2d211d..2e42c68 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -230,10 +230,6 @@ func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodie keyTiers = []config.Tier{route.Tier} } for _, tier := range keyTiers { - if lastResponse != nil { - httpx.DrainAndClose(lastResponse.Body) - lastResponse = nil - } keyRoute := route keyRoute.Tier = tier keyRoute.Anonymous = false @@ -242,9 +238,20 @@ func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodie resp, err, used := g.doKeyUpstream(ctx, keyRoute, bodies, ids, attempts) attempts += used if err == nil && resp != nil && resp.StatusCode/100 == 2 { + if lastResponse != nil { + httpx.DrainAndClose(lastResponse.Body) + } return resp, keyRoute, attempts, nil } - lastResponse, lastErr = resp, err + if resp != nil { + if lastResponse != nil { + httpx.DrainAndClose(lastResponse.Body) + } + lastResponse = resp + } + if err != nil { + lastErr = err + } } if lastResponse != nil { return lastResponse, effectiveRoute, attempts, nil