Merge branch 'jasonxu114514:main' into main

This commit is contained in:
hanlap0503 authored and GitHub committed 2026-10-16 08:08:41 +07:00
commit d15aec3d2e
3 files changed
+55 -3

No files matched your search

+35
View File
@@ -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.
+14
View File
@@ -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
+6 -3
View File
@@ -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 {