mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-05 08:02:53 +00:00
295 lines
8.2 KiB
Go
295 lines
8.2 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"io"
|
|
"math/rand/v2"
|
|
"net"
|
|
"net/http"
|
|
"net/url"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
)
|
|
|
|
type proxyTransport struct {
|
|
index int
|
|
name string
|
|
client *http.Client
|
|
healthy atomic.Bool
|
|
}
|
|
|
|
type transportPool struct {
|
|
items []*proxyTransport
|
|
}
|
|
|
|
func newTransportPool(proxies []string, cfg PerformanceConfig, responseHeaderTimeout time.Duration) (*transportPool, error) {
|
|
p := &transportPool{items: make([]*proxyTransport, 0, len(proxies))}
|
|
for _, raw := range proxies {
|
|
transport := http.DefaultTransport.(*http.Transport).Clone()
|
|
transport.MaxIdleConns = cfg.MaxIdleConns
|
|
transport.MaxIdleConnsPerHost = cfg.MaxIdleConnsPerHost
|
|
transport.MaxConnsPerHost = cfg.MaxConnsPerHost
|
|
transport.IdleConnTimeout = time.Duration(cfg.IdleConnTimeoutSeconds) * time.Second
|
|
transport.ResponseHeaderTimeout = responseHeaderTimeout
|
|
transport.ForceAttemptHTTP2 = true
|
|
transport.DialContext = (&net.Dialer{
|
|
Timeout: time.Duration(cfg.ConnectTimeoutSeconds) * time.Second,
|
|
KeepAlive: 30 * time.Second,
|
|
}).DialContext
|
|
if raw == "direct" {
|
|
transport.Proxy = nil
|
|
} else {
|
|
u, err := url.Parse(raw)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("parse proxy %s: %w", redactURL(raw), err)
|
|
}
|
|
transport.Proxy = http.ProxyURL(u)
|
|
}
|
|
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
|
|
}
|
|
|
|
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
|
|
index int
|
|
proxyIndex atomic.Int64
|
|
failures atomic.Uint32
|
|
cooldownUntil atomic.Int64
|
|
}
|
|
|
|
type nodePool struct {
|
|
nodes []*upstreamNode
|
|
transports *transportPool
|
|
next atomic.Uint64
|
|
cooldown time.Duration
|
|
bindingsMu sync.Mutex
|
|
bindingCount []int
|
|
}
|
|
|
|
// 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 pool, nil
|
|
}
|
|
for i, key := range keys {
|
|
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
|
|
}
|
|
|
|
// Cursor reserves a different starting node for each concurrent request.
|
|
// Selection is delayed until Next, so a node marked failed by the preceding
|
|
// attempt is immediately skipped. Both Cursor and Next allocate no memory.
|
|
func (p *nodePool) Cursor() nodeCursor {
|
|
if len(p.nodes) == 0 {
|
|
return nodeCursor{pool: p}
|
|
}
|
|
return nodeCursor{pool: p, next: int((p.next.Add(1) - 1) % uint64(len(p.nodes)))}
|
|
}
|
|
|
|
func (c *nodeCursor) Next() *upstreamNode {
|
|
if c.pool == nil || len(c.pool.nodes) == 0 {
|
|
return nil
|
|
}
|
|
now := time.Now().UnixNano()
|
|
choice := -1
|
|
var earliest int64
|
|
for offset := 0; offset < len(c.pool.nodes); offset++ {
|
|
i := (c.next + offset) % len(c.pool.nodes)
|
|
until := c.pool.nodes[i].cooldownUntil.Load()
|
|
if until <= now {
|
|
choice = i
|
|
break
|
|
}
|
|
if choice == -1 || until < earliest {
|
|
choice, earliest = i, until
|
|
}
|
|
}
|
|
if choice < 0 {
|
|
return nil
|
|
}
|
|
c.next = (choice + 1) % len(c.pool.nodes)
|
|
return c.pool.nodes[choice]
|
|
}
|
|
|
|
func (p *nodePool) MarkSuccess(node *upstreamNode) {
|
|
node.failures.Store(0)
|
|
node.cooldownUntil.Store(0)
|
|
}
|
|
|
|
func (p *nodePool) MarkFailure(node *upstreamNode, resp *http.Response, err error) {
|
|
if err == nil && resp != nil && resp.StatusCode != http.StatusUnauthorized && resp.StatusCode != http.StatusForbidden && resp.StatusCode != http.StatusTooManyRequests && resp.StatusCode < 500 {
|
|
return
|
|
}
|
|
failures := node.failures.Add(1)
|
|
multiplier := time.Duration(1 << min(failures-1, 3))
|
|
delay := p.cooldown * multiplier
|
|
if resp != nil {
|
|
if retryAfter := parseRetryAfter(resp.Header.Get("Retry-After")); retryAfter > delay {
|
|
delay = retryAfter
|
|
}
|
|
}
|
|
node.cooldownUntil.Store(time.Now().Add(delay).UnixNano())
|
|
}
|
|
|
|
func parseRetryAfter(value string) time.Duration {
|
|
if seconds, err := strconv.Atoi(strings.TrimSpace(value)); err == nil && seconds > 0 {
|
|
return time.Duration(seconds) * time.Second
|
|
}
|
|
if when, err := http.ParseTime(value); err == nil {
|
|
return max(time.Until(when), 0)
|
|
}
|
|
return 0
|
|
}
|
|
|
|
func drainAndClose(body io.ReadCloser) {
|
|
if body == nil {
|
|
return
|
|
}
|
|
_, _ = io.Copy(io.Discard, io.LimitReader(body, 64<<10))
|
|
_ = body.Close()
|
|
}
|