mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-05 08:02:53 +00:00
feat: add automatic proxy failover and health checks
This commit is contained in:
1 parent
f32c4a0e61
commit
1f603c35a6
4 files changed
+270
-43
No files matched your search
@@ -11,9 +11,10 @@
|
||||
- 分离配置 Zen key 池与 Zen Go key 池
|
||||
- 模型同时存在于两个上游时优先使用 Zen
|
||||
- 支持直连、HTTP、HTTPS、SOCKS5 和 SOCKS5H 代理
|
||||
- 将 key 平均固定分配给代理,保持连接亲和性
|
||||
- 将 key 自动均衡绑定到代理,保持连接亲和性
|
||||
- 使用无锁轮询分配并发请求
|
||||
- 节点失败后立即切换,并对故障节点进行短时冷却
|
||||
- 代理失败后自动迁移绑定,key 失败后进行短时冷却
|
||||
- 启动时及每 60 秒通过 Cloudflare trace 并行检查代理可用性
|
||||
- 为不同会话生成不同的 OpenCode 会话 ID
|
||||
|
||||
## API 路径
|
||||
|
||||
+115
-16
@@ -17,12 +17,19 @@ import (
|
||||
|
||||
const maxRequestBody = 32 << 20
|
||||
|
||||
const (
|
||||
proxyHealthCheckURL = "https://cloudflare.com/cdn-cgi/trace"
|
||||
proxyHealthCheckInterval = 60 * time.Second
|
||||
proxyHealthCheckTimeout = 10 * time.Second
|
||||
)
|
||||
|
||||
type Gateway struct {
|
||||
cfg Config
|
||||
logger *slog.Logger
|
||||
zenNodes *nodePool
|
||||
goNodes *nodePool
|
||||
catalog *modelCatalog
|
||||
cfg Config
|
||||
logger *slog.Logger
|
||||
transports *transportPool
|
||||
zenNodes *nodePool
|
||||
goNodes *nodePool
|
||||
catalog *modelCatalog
|
||||
}
|
||||
|
||||
func NewGateway(cfg Config, logger *slog.Logger) (*Gateway, error) {
|
||||
@@ -40,11 +47,12 @@ func NewGateway(cfg Config, logger *slog.Logger) (*Gateway, error) {
|
||||
return nil, fmt.Errorf("go node pool: %w", err)
|
||||
}
|
||||
return &Gateway{
|
||||
cfg: cfg,
|
||||
logger: logger,
|
||||
zenNodes: zenNodes,
|
||||
goNodes: goNodes,
|
||||
catalog: newModelCatalog(cfg.Models.Protocols),
|
||||
cfg: cfg,
|
||||
logger: logger,
|
||||
transports: transports,
|
||||
zenNodes: zenNodes,
|
||||
goNodes: goNodes,
|
||||
catalog: newModelCatalog(cfg.Models.Protocols),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -215,6 +223,11 @@ func (g *Gateway) doUpstream(ctx context.Context, route modelRoute, body []byte,
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
proxy := nodes.Proxy(node)
|
||||
if proxy == nil {
|
||||
lastErr = errors.New("upstream key has no proxy binding")
|
||||
break
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Accept", "application/json, text/event-stream")
|
||||
req.Header.Set("User-Agent", opencodeUserAgent())
|
||||
@@ -228,19 +241,27 @@ func (g *Gateway) doUpstream(ctx context.Context, route modelRoute, body []byte,
|
||||
} else {
|
||||
req.Header.Set("Authorization", "Bearer "+node.key)
|
||||
}
|
||||
resp, err := node.client.Do(req)
|
||||
resp, err := proxy.client.Do(req)
|
||||
if err == nil && resp.StatusCode/100 == 2 {
|
||||
nodes.MarkSuccess(node)
|
||||
g.logger.Debug("upstream accepted request", "request_id", ids.Request, "attempt", attempt, "tier", route.Tier, "proxy", redactURL(node.proxy))
|
||||
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
|
||||
}
|
||||
nodes.MarkFailure(node, resp, err)
|
||||
if isProxyFailure(resp, err) {
|
||||
g.rebindFailedProxy(proxy)
|
||||
if nodes.Proxy(node) == proxy {
|
||||
nodes.MarkFailure(node, resp, err)
|
||||
}
|
||||
} else {
|
||||
nodes.MarkFailure(node, resp, err)
|
||||
}
|
||||
lastResponse = resp
|
||||
lastErr = err
|
||||
if err != nil {
|
||||
g.logger.Debug("upstream transport error", "request_id", ids.Request, "attempt", attempt, "proxy", redactURL(node.proxy), "error", err)
|
||||
g.logger.Debug("upstream transport error", "request_id", ids.Request, "attempt", attempt, "proxy", redactURL(proxy.name), "error", err)
|
||||
} else {
|
||||
g.logger.Debug("upstream rejected request", "request_id", ids.Request, "attempt", attempt, "status", resp.StatusCode, "proxy", redactURL(node.proxy))
|
||||
g.logger.Debug("upstream rejected request", "request_id", ids.Request, "attempt", attempt, "status", resp.StatusCode, "proxy", redactURL(proxy.name))
|
||||
}
|
||||
}
|
||||
if lastResponse != nil {
|
||||
@@ -249,6 +270,78 @@ func (g *Gateway) doUpstream(ctx context.Context, route modelRoute, body []byte,
|
||||
return nil, lastErr
|
||||
}
|
||||
|
||||
func isProxyFailure(resp *http.Response, err error) bool {
|
||||
if err != nil {
|
||||
return true
|
||||
}
|
||||
if resp == nil {
|
||||
return false
|
||||
}
|
||||
switch resp.StatusCode {
|
||||
case http.StatusProxyAuthRequired, http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (g *Gateway) rebindFailedProxy(proxy *proxyTransport) (zenMoved, goMoved int) {
|
||||
if proxy == nil {
|
||||
return 0, 0
|
||||
}
|
||||
wasHealthy := proxy.healthy.Swap(false)
|
||||
zenMoved = g.zenNodes.RebindProxy(proxy.index)
|
||||
goMoved = g.goNodes.RebindProxy(proxy.index)
|
||||
if wasHealthy || zenMoved+goMoved > 0 {
|
||||
g.logger.Warn("proxy unavailable", "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))
|
||||
}
|
||||
}
|
||||
go func() {
|
||||
check()
|
||||
ticker := time.NewTicker(proxyHealthCheckInterval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
check()
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func protocolPath(protocol Protocol) string {
|
||||
switch protocol {
|
||||
case ProtocolResponses:
|
||||
@@ -296,10 +389,16 @@ func (g *Gateway) refreshTier(ctx context.Context, base string, nodes *nodePool)
|
||||
return nil
|
||||
}
|
||||
refreshCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
models, err := fetchModels(refreshCtx, node.client, base, node.key)
|
||||
proxy := nodes.Proxy(node)
|
||||
if proxy == nil {
|
||||
cancel()
|
||||
return nil
|
||||
}
|
||||
models, err := fetchModels(refreshCtx, proxy.client, base, node.key)
|
||||
cancel()
|
||||
if err == nil {
|
||||
nodes.MarkSuccess(node)
|
||||
proxy.healthy.Store(true)
|
||||
return models
|
||||
}
|
||||
nodes.MarkFailure(node, nil, err)
|
||||
|
||||
@@ -35,6 +35,7 @@ func main() {
|
||||
|
||||
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer cancel()
|
||||
gateway.StartProxyHealthChecks(ctx)
|
||||
gateway.StartModelRefresh(ctx)
|
||||
|
||||
server := &http.Server{
|
||||
|
||||
@@ -1,28 +1,33 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand/v2"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
type proxyTransport struct {
|
||||
name string
|
||||
client *http.Client
|
||||
index int
|
||||
name string
|
||||
client *http.Client
|
||||
healthy atomic.Bool
|
||||
}
|
||||
|
||||
type transportPool struct {
|
||||
items []proxyTransport
|
||||
items []*proxyTransport
|
||||
}
|
||||
|
||||
func newTransportPool(proxies []string, cfg PerformanceConfig, responseHeaderTimeout time.Duration) (*transportPool, error) {
|
||||
p := &transportPool{items: make([]proxyTransport, 0, len(proxies))}
|
||||
p := &transportPool{items: make([]*proxyTransport, 0, len(proxies))}
|
||||
for _, raw := range proxies {
|
||||
transport := http.DefaultTransport.(*http.Transport).Clone()
|
||||
transport.MaxIdleConns = cfg.MaxIdleConns
|
||||
@@ -44,51 +49,172 @@ func newTransportPool(proxies []string, cfg PerformanceConfig, responseHeaderTim
|
||||
}
|
||||
transport.Proxy = http.ProxyURL(u)
|
||||
}
|
||||
p.items = append(p.items, proxyTransport{name: raw, client: &http.Client{Transport: transport}})
|
||||
proxy := &proxyTransport{index: len(p.items), name: raw, client: &http.Client{Transport: transport}}
|
||||
proxy.healthy.Store(true)
|
||||
p.items = append(p.items, proxy)
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// upstreamNode is immutable except for health counters. A key is permanently
|
||||
// assigned to one proxy, so the request hot path never parses URLs or builds a
|
||||
// key/proxy combination.
|
||||
type proxyHealthResult struct {
|
||||
proxy *proxyTransport
|
||||
err error
|
||||
wasHealthy bool
|
||||
}
|
||||
|
||||
// CheckHealth checks every route concurrently. A proxy is considered healthy
|
||||
// only when the request reaches the target and returns a successful response.
|
||||
func (p *transportPool) CheckHealth(ctx context.Context, target string, timeout time.Duration) []proxyHealthResult {
|
||||
results := make(chan proxyHealthResult, len(p.items))
|
||||
for _, proxy := range p.items {
|
||||
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}
|
||||
}()
|
||||
}
|
||||
out := make([]proxyHealthResult, 0, len(p.items))
|
||||
for range p.items {
|
||||
out = append(out, <-results)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// upstreamNode keeps a key stable while allowing its proxy binding to change
|
||||
// atomically when a proxy becomes unavailable.
|
||||
type upstreamNode struct {
|
||||
key string
|
||||
proxy string
|
||||
client *http.Client
|
||||
index int
|
||||
proxyIndex atomic.Int64
|
||||
failures atomic.Uint32
|
||||
cooldownUntil atomic.Int64
|
||||
}
|
||||
|
||||
type nodePool struct {
|
||||
nodes []*upstreamNode
|
||||
next atomic.Uint64
|
||||
cooldown time.Duration
|
||||
nodes []*upstreamNode
|
||||
transports *transportPool
|
||||
next atomic.Uint64
|
||||
cooldown time.Duration
|
||||
bindingsMu sync.Mutex
|
||||
bindingCount []int
|
||||
}
|
||||
|
||||
// newNodePool distributes N keys over M proxies in round-robin order. N/M must
|
||||
// be a positive integer, so every proxy receives exactly the same key count.
|
||||
// newNodePool distributes keys over proxies in round-robin order. When there
|
||||
// are fewer keys than proxies, the remaining proxies are intentionally idle and
|
||||
// can take over a key immediately if an active proxy fails.
|
||||
func newNodePool(keys []string, transports *transportPool, cooldown time.Duration) (*nodePool, error) {
|
||||
if transports == nil || len(transports.items) == 0 {
|
||||
return nil, fmt.Errorf("at least one proxy transport is required")
|
||||
}
|
||||
pool := &nodePool{
|
||||
nodes: make([]*upstreamNode, 0, len(keys)),
|
||||
transports: transports,
|
||||
cooldown: cooldown,
|
||||
bindingCount: make([]int, len(transports.items)),
|
||||
}
|
||||
if len(keys) == 0 {
|
||||
return &nodePool{cooldown: cooldown}, nil
|
||||
return pool, nil
|
||||
}
|
||||
if len(transports.items) > len(keys) {
|
||||
return nil, fmt.Errorf("cannot evenly assign %d keys to %d proxies: every proxy must receive at least one key", len(keys), len(transports.items))
|
||||
}
|
||||
if len(keys)%len(transports.items) != 0 {
|
||||
return nil, fmt.Errorf("cannot evenly assign %d keys to %d proxies: key count must be divisible by proxy count", len(keys), len(transports.items))
|
||||
}
|
||||
pool := &nodePool{nodes: make([]*upstreamNode, 0, len(keys)), cooldown: cooldown}
|
||||
for i, key := range keys {
|
||||
proxy := transports.items[i%len(transports.items)]
|
||||
pool.nodes = append(pool.nodes, &upstreamNode{key: key, proxy: proxy.name, client: proxy.client, index: i})
|
||||
proxyIndex := i % len(transports.items)
|
||||
node := &upstreamNode{key: key, index: i}
|
||||
node.proxyIndex.Store(int64(proxyIndex))
|
||||
pool.nodes = append(pool.nodes, node)
|
||||
pool.bindingCount[proxyIndex]++
|
||||
}
|
||||
return pool, nil
|
||||
}
|
||||
|
||||
func (p *nodePool) Len() int { return len(p.nodes) }
|
||||
|
||||
func (p *nodePool) Proxy(node *upstreamNode) *proxyTransport {
|
||||
if p == nil || node == nil || p.transports == nil {
|
||||
return nil
|
||||
}
|
||||
index := int(node.proxyIndex.Load())
|
||||
if index < 0 || index >= len(p.transports.items) {
|
||||
return nil
|
||||
}
|
||||
return p.transports.items[index]
|
||||
}
|
||||
|
||||
// RebindProxy moves every key currently using failedProxy to the least-loaded
|
||||
// healthy proxy. Empty proxies are selected in configuration order; otherwise
|
||||
// one of the least-loaded proxies is chosen at random. If every alternative is
|
||||
// currently unhealthy, it still attempts the least-loaded alternative.
|
||||
func (p *nodePool) RebindProxy(failedProxy int) int {
|
||||
if p == nil || p.transports == nil || len(p.transports.items) < 2 || failedProxy < 0 || failedProxy >= len(p.transports.items) {
|
||||
return 0
|
||||
}
|
||||
p.bindingsMu.Lock()
|
||||
defer p.bindingsMu.Unlock()
|
||||
|
||||
moved := 0
|
||||
for _, node := range p.nodes {
|
||||
if int(node.proxyIndex.Load()) != failedProxy {
|
||||
continue
|
||||
}
|
||||
target := p.replacementLocked(failedProxy, true)
|
||||
if target < 0 {
|
||||
target = p.replacementLocked(failedProxy, false)
|
||||
}
|
||||
if target < 0 {
|
||||
continue
|
||||
}
|
||||
p.bindingCount[failedProxy]--
|
||||
p.bindingCount[target]++
|
||||
node.proxyIndex.Store(int64(target))
|
||||
node.failures.Store(0)
|
||||
node.cooldownUntil.Store(0)
|
||||
moved++
|
||||
}
|
||||
return moved
|
||||
}
|
||||
|
||||
func (p *nodePool) replacementLocked(failedProxy int, healthyOnly bool) int {
|
||||
minimum := int(^uint(0) >> 1)
|
||||
candidates := make([]int, 0, len(p.transports.items)-1)
|
||||
for i := range p.transports.items {
|
||||
if i == failedProxy || healthyOnly && !p.transports.items[i].healthy.Load() {
|
||||
continue
|
||||
}
|
||||
count := p.bindingCount[i]
|
||||
if count == 0 {
|
||||
return i
|
||||
}
|
||||
if count < minimum {
|
||||
minimum = count
|
||||
candidates = candidates[:0]
|
||||
candidates = append(candidates, i)
|
||||
} else if count == minimum {
|
||||
candidates = append(candidates, i)
|
||||
}
|
||||
}
|
||||
if len(candidates) == 0 {
|
||||
return -1
|
||||
}
|
||||
return candidates[rand.IntN(len(candidates))]
|
||||
}
|
||||
|
||||
type nodeCursor struct {
|
||||
pool *nodePool
|
||||
next int
|
||||
|
||||
Reference in new issue
Block a user