From a6601da673c03832bf78ce04b100dee8c8a92385 Mon Sep 17 00:00:00 2001 From: Jason Xu Date: Thu, 15 Oct 2026 20:40:50 +0800 Subject: [PATCH] fix: report a proxy error when every proxy is down When every attempt died on the proxy route itself, the gateway answered with a generic 502 "all upstream attempts failed", pointing operators at the upstream instead of their proxies. Attempt errors that fail before a connection to the upstream exists (proxy dial, CONNECT/SOCKS handshake, tunnelled TLS) are now tagged as proxy failures on real proxies; direct transports are left untouched. The anonymous lane also reports a proxy failure when no proxy is healthy. When the final error is such a failure, the inference and System One handlers return 503 with type "proxy_error". Any upstream HTTP response is still forwarded as before, so genuine upstream errors are not mislabelled. --- internal/gateway/first_event.go | 35 +++++++++++++++++++++++++++++++++ internal/gateway/gateway.go | 14 +++++++++++++ internal/gateway/upstream.go | 9 ++++++--- 3 files changed, 55 insertions(+), 3 deletions(-) diff --git a/internal/gateway/first_event.go b/internal/gateway/first_event.go index 77947e9..e003a58 100644 --- a/internal/gateway/first_event.go +++ b/internal/gateway/first_event.go @@ -7,12 +7,15 @@ import ( "errors" "fmt" "io" + "net" "net/http" "net/http/httptrace" "strings" "sync" "sync/atomic" "time" + + "opencode2api/internal/config" ) var ( @@ -69,6 +72,38 @@ type phasedError struct { func (e *phasedError) Error() string { return fmt.Sprintf("%s [phase=%s]", e.err.Error(), e.phase) } func (e *phasedError) Unwrap() error { return e.err } +// errProxyUnavailable marks an attempt that never reached the upstream because +// the proxy route itself failed. When it is the final error of a request, the +// client gets a proxy error instead of a generic bad gateway. +var errProxyUnavailable = errors.New("proxy unavailable") + +type proxyUnavailableError struct { + proxy string + err error +} + +func (e *proxyUnavailableError) Error() string { + return fmt.Sprintf("proxy %s unavailable: %s", e.proxy, e.err.Error()) +} +func (e *proxyUnavailableError) Unwrap() []error { return []error{errProxyUnavailable, e.err} } + +// asProxyUnavailable tags an attempt error that died before a connection to the +// upstream existed. Through a real proxy that phase covers the proxy dial, the +// CONNECT/SOCKS handshake and the TLS handshake tunnelled through it, so the +// failure belongs to the proxy rather than the upstream. Direct transports are +// left untouched: there a dial failure is an upstream reachability problem. +func asProxyUnavailable(proxy *proxyTransport, err error) error { + if err == nil || proxy == nil || proxy.name == "direct" { + return err + } + var pe *phasedError + var op *net.OpError + if errors.As(err, &pe) && pe.phase == "dial" || errors.As(err, &op) && (op.Op == "proxyconnect" || strings.HasPrefix(op.Op, "socks")) { + return &proxyUnavailableError{proxy: config.RedactURL(proxy.name), err: err} + } + return err +} + // classifyAttemptError renders a leg token for the request log. The phase is // appended for the attempt-deadline and transport cases so a hung exit can be // attributed without grepping logs. diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index ff6a002..ccf87e0 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -41,6 +41,10 @@ func attemptDeadline(cfg config.Config) time.Duration { // gateway could answer, so the failure is neither upstream nor ours. const statusClientClosedRequest = 499 +// proxyUnavailableMessage is returned when every attempt died on the proxy +// route itself, so operators look at their proxies instead of the upstream. +const proxyUnavailableMessage = "all proxies are unavailable; the upstream could not be reached" + type Gateway struct { rotation *rotation.Manager cfg config.Config @@ -228,6 +232,12 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc { return } g.logger.Warn("all upstream attempts failed", "component", "upstream", "event", "request_failed", "request_id", ids.Request, "tier", finalTier, "key_id", keyID, "channel", channel, "anonymous", anonymous, "error", err) + // The request never reached the upstream because the proxy route + // failed; report that instead of blaming the upstream with a 502. + if errors.Is(err, errProxyUnavailable) { + wire.WriteError(w, external, http.StatusServiceUnavailable, proxyUnavailableMessage, "proxy_error", ids.Request) + return + } // An exhausted request budget is a timeout, not a bad gateway: the // distinction matters to clients that retry on 502. if errors.Is(err, context.DeadlineExceeded) { @@ -397,6 +407,10 @@ func (g *Gateway) forwardSystemOne(w http.ResponseWriter, r *http.Request, body return } g.logger.Warn("all upstream attempts failed", "component", "upstream", "event", "request_failed", "request_id", ids.Request, "tier", finalTier, "key_id", keyID, "channel", channel, "anonymous", anonymous, "error", err) + if errors.Is(err, errProxyUnavailable) { + wire.WriteError(w, wire.SystemOne, http.StatusServiceUnavailable, proxyUnavailableMessage, "proxy_error", ids.Request) + return + } if errors.Is(err, context.DeadlineExceeded) { wire.WriteError(w, wire.SystemOne, http.StatusGatewayTimeout, "upstream request timed out", "upstream_timeout", ids.Request) return diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index 86116af..d12d1da 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -323,7 +323,7 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b return resp, nil, attempts } lastResponse = resp - lastErr = err + lastErr = asProxyUnavailable(node.proxy, err) if err != nil { g.logger.Debug("anonymous transport attempt failed", "component", "upstream", "event", "anonymous_attempt_transport_failed", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", config.RedactURL(node.proxy.name), "duration_ms", duration.Milliseconds(), "error", err) } else { @@ -335,6 +335,9 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b } if lastErr == nil { lastErr = errors.New("no healthy anonymous proxies available") + if !g.transports.hasHealthy() { + lastErr = fmt.Errorf("no healthy anonymous proxies available: %w", errProxyUnavailable) + } } return nil, lastErr, attempts } @@ -654,7 +657,7 @@ func (g *Gateway) doSelectedKeyUpstream(ctx context.Context, route models.Route, duration := time.Since(started) g.recordUpstreamAttempt(ctx, route, ids, attemptOffset+1, keyID, "key", false, proxy, resp, err, duration) if err != nil { - return nil, err, 1 + return nil, asProxyUnavailable(proxy, err), 1 } return resp, nil, 1 } @@ -747,7 +750,7 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies return resp, nil, attempts } lastResponse = resp - lastErr = err + lastErr = asProxyUnavailable(proxy, err) if err != nil { g.logger.Debug("upstream transport attempt failed", "component", "upstream", "event", "attempt_transport_failed", "request_id", ids.Request, "attempt", attempts, "tier", route.Tier, "key_id", keyID, "proxy", config.RedactURL(proxy.name), "duration_ms", attemptDuration.Milliseconds(), "error", err) } else {