mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-05 08:02:53 +00:00
feat(proxy): support rotating proxy pools via #pool marker
An endpoint that already rotates exit IPs (Resin and similar gateways) was handled like a static proxy, which defeated the rotation in three ways: - the cloned transport kept HTTP/2 and keep-alive enabled, so every request reused one CONNECT tunnel and therefore one exit IP, drawing 429s; - a single slow exit marked the whole entry unhealthy and keys were rebound, with scheduled recovery only every 15 minutes; - any 429/5xx put the anonymous node into a 15s-120s cooldown, and that lane has no earliest-expiry fallback, so the request failed with "no healthy anonymous proxies available" (HTTP 502). Mark an entry with a "#pool" fragment (or a "pool+" scheme prefix) to declare it a rotating pool. Pool entries then open a fresh connection per attempt (DisableKeepAlives, no HTTP/2, plus Connection: close on the request), are excluded from cooldown, health eviction, and proxy rebinding, and may be retried up to retry.max_attempts on the anonymous lane instead of once. Config validation and redaction work on the clean URL, the marker stays visible in the operator UI, and deduplication keeps a pool entry next to a static proxy that dials the same endpoint since they are different routes.
This commit is contained in:
1 parent
6d83806939
commit
260211cd9e
12 files changed
+273
-21
No files matched your search
@@ -316,6 +316,27 @@ direct
|
||||
|
||||
Comment markers are `#`, `;`, and `//` at the start of a line or after whitespace.
|
||||
|
||||
#### Rotating proxy pools
|
||||
|
||||
Suffix an entry with `#pool` (or prefix it with `pool+`) to declare that the endpoint is a rotating proxy pool such as [Resin](https://github.com/Resinat/Resin), where every new TCP connection exits from a different IP:
|
||||
|
||||
```text
|
||||
http://127.0.0.1:7890#pool
|
||||
socks5://127.0.0.1:1080#pool
|
||||
pool+http://127.0.0.1:7891
|
||||
```
|
||||
|
||||
A pool entry is handled differently from a static proxy:
|
||||
|
||||
| Behavior | Static proxy | `#pool` entry |
|
||||
| ------------------------- | ------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
|
||||
| Connection reuse | Keep-alive plus HTTP/2 multiplexing (`performance.*` pool settings) | A fresh TCP + CONNECT tunnel per request (`DisableKeepAlives`, no HTTP/2) |
|
||||
| Failure cooldown | 15s–120s exponential backoff, inflated by `Retry-After` | None: the next request simply draws a new exit IP |
|
||||
| Health eviction | Marked unhealthy, keys rebound, rechecked every 15 minutes | Never evicted; the health check is skipped entirely |
|
||||
| Anonymous lane retries | At most one attempt per configured proxy | Up to `retry.max_attempts`, cycling the pool entry |
|
||||
|
||||
Use it when the endpoint behind the URL already performs the rotation and the pool's own exit IPs are individually rate-limited or flaky; the gateway then treats each attempt as a fresh endpoint instead of pinning the conversation to one exit. A single `#pool` entry is enough — you no longer need to list dozens of exits. Static entries keep the pooling behavior described below.
|
||||
|
||||
### Timeouts and connection pools
|
||||
|
||||
| Field | Default | Meaning |
|
||||
|
||||
@@ -306,6 +306,27 @@ direct
|
||||
|
||||
Dấu bắt đầu chú thích là `#`, `;` và `//`, ở đầu dòng hoặc sau khoảng trắng.
|
||||
|
||||
#### Proxy pool luân chuyển
|
||||
|
||||
Thêm hậu tố `#pool` (hoặc tiền tố `pool+`) vào một mục để khai báo rằng endpoint đó là proxy pool luân chuyển như [Resin](https://github.com/Resinat/Resin), nơi mỗi kết nối TCP mới đi ra từ một IP khác:
|
||||
|
||||
```text
|
||||
http://127.0.0.1:7890#pool
|
||||
socks5://127.0.0.1:1080#pool
|
||||
pool+http://127.0.0.1:7891
|
||||
```
|
||||
|
||||
Mục `#pool` được xử lý khác hoàn toàn so với proxy tĩnh:
|
||||
|
||||
| Hành vi | Proxy tĩnh | Mục `#pool` |
|
||||
| --------------------- | -------------------------------------------------------------- | ------------------------------------------------------------------------ |
|
||||
| Tái sử dụng kết nối | Keep-alive và ghép kênh HTTP/2 (tham số `performance.*`) | Một tunnel TCP + CONNECT mới cho mỗi request (`DisableKeepAlives`, không HTTP/2) |
|
||||
| Cooldown khi lỗi | 15s–120s lùi theo cấp số nhân, cộng thêm `Retry-After` | Không: request kế tiếp lấy luôn exit IP mới |
|
||||
| Loại bỏ theo sức khoẻ | Đánh dấu không khoẻ, chuyển key, kiểm tra lại mỗi 15 phút | Không bao giờ bị loại bỏ; bỏ qua hoàn toàn health check |
|
||||
| Số lần thử kênh ẩn danh | Tối đa một lần cho mỗi proxy đã cấu hình | Tối đa `retry.max_attempts` lần, quay vòng mục pool |
|
||||
|
||||
Dùng khi bản thân endpoint sau URL đã tự luân chuyển, còn từng exit IP trong pool bị giới hạn riêng hoặc chập chờn: gateway sẽ coi mỗi lần thử là một endpoint mới thay vì ghim cả phiên vào một exit. Chỉ cần một mục `#pool` là đủ, không cần liệt kê hàng chục exit. Các mục tĩnh vẫn giữ hành vi pooling mô tả bên dưới.
|
||||
|
||||
### Timeout và connection pool
|
||||
|
||||
| Trường | Mặc định | Ý nghĩa |
|
||||
|
||||
@@ -311,6 +311,27 @@ direct
|
||||
|
||||
支持 `#`、`;`、`//` 注释标记,标记需要位于行首或空白字符之后。
|
||||
|
||||
#### 轮换代理池
|
||||
|
||||
在条目末尾追加 `#pool`(或在开头加 `pool+`)即可声明该地址是轮换代理池(例如 [Resin](https://github.com/Resinat/Resin)),每次新建 TCP 连接都会从不同出口 IP 发出:
|
||||
|
||||
```text
|
||||
http://127.0.0.1:7890#pool
|
||||
socks5://127.0.0.1:1080#pool
|
||||
pool+http://127.0.0.1:7891
|
||||
```
|
||||
|
||||
代理池条目的处理方式与静态代理完全不同:
|
||||
|
||||
| 行为 | 静态代理 | `#pool` 条目 |
|
||||
| ------------ | ------------------------------------------- | --------------------------------------------------------- |
|
||||
| 连接复用 | Keep-alive + HTTP/2 多路复用(`performance.*` 连接池参数) | 每次请求新建 TCP + CONNECT 隧道(`DisableKeepAlives`,禁用 HTTP/2) |
|
||||
| 失败冷却 | 15s–120s 指数退避,并受 `Retry-After` 影响 | 无冷却:下一次请求直接换一个新出口 IP |
|
||||
| 可用性剔除 | 标记不可用、迁移 Key、每 15 分钟复检 | 永不剔除,完全跳过健康检查 |
|
||||
| 匿名通道重试 | 每个配置的代理最多尝试一次 | 最多尝试 `retry.max_attempts` 次,循环该池条目 |
|
||||
|
||||
当 URL 背后的服务本身就在做轮换、而池内出口 IP 会被单独限流或不稳定时使用它:网关会把每次尝试都当作新出口,而不是把整个会话固定在某个出口上。只要一条 `#pool` 条目即可,无需再罗列几十个出口。静态条目仍然保留下文的连接池行为。
|
||||
|
||||
### 超时与连接池
|
||||
|
||||
| 字段 | 默认值 | 含义 |
|
||||
|
||||
@@ -244,7 +244,8 @@ func Normalize(path string, cfg Config) (Config, error) {
|
||||
if raw == "direct" {
|
||||
continue
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
clean, _ := ParseProxyEntry(raw)
|
||||
u, err := url.Parse(clean)
|
||||
if err != nil || u.Host == "" {
|
||||
return Config{}, fmt.Errorf("invalid proxy URL %q", RedactURL(raw))
|
||||
}
|
||||
|
||||
@@ -3,11 +3,38 @@ package config
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ParseProxyEntry splits an optional dynamic-pool marker ("pool+" scheme prefix
|
||||
// or "#pool" URL fragment) from a configured proxy string and returns the clean
|
||||
// dial URL alongside whether the entry is a rotating proxy pool (such as Resin).
|
||||
func ParseProxyEntry(raw string) (clean string, pool bool) {
|
||||
trimmed := strings.TrimSpace(raw)
|
||||
if trimmed == "" || trimmed == "direct" {
|
||||
return trimmed, false
|
||||
}
|
||||
lower := strings.ToLower(trimmed)
|
||||
if strings.HasPrefix(lower, "pool+") {
|
||||
trimmed = strings.TrimSpace(trimmed[len("pool+"):])
|
||||
pool = true
|
||||
}
|
||||
if u, err := url.Parse(trimmed); err == nil && u.Host != "" {
|
||||
if strings.EqualFold(strings.TrimSpace(u.Fragment), "pool") {
|
||||
pool = true
|
||||
u.Fragment = ""
|
||||
trimmed = u.String()
|
||||
}
|
||||
} else if idx := strings.LastIndex(trimmed, "#"); idx >= 0 && strings.EqualFold(strings.TrimSpace(trimmed[idx+1:]), "pool") {
|
||||
pool = true
|
||||
trimmed = strings.TrimSpace(trimmed[:idx])
|
||||
}
|
||||
return trimmed, pool
|
||||
}
|
||||
|
||||
func resolveProxyFiles(configPath string, cfg *Config) error {
|
||||
trimList(&cfg.Proxies)
|
||||
effective := append([]string(nil), cfg.Proxies...)
|
||||
@@ -23,7 +50,7 @@ func resolveProxyFiles(configPath string, cfg *Config) error {
|
||||
effective = append(effective, proxies...)
|
||||
}
|
||||
|
||||
effective = uniqueStrings(effective)
|
||||
effective = uniqueProxyEntries(effective)
|
||||
if len(effective) == 0 {
|
||||
effective = []string{"direct"}
|
||||
}
|
||||
@@ -66,14 +93,30 @@ func stripProxyLineComment(line string) string {
|
||||
return line
|
||||
}
|
||||
|
||||
func uniqueStrings(items []string) []string {
|
||||
// uniqueProxyEntries drops exact repeats while keeping a #pool entry next to a
|
||||
// static proxy that dials the same endpoint: they are different routes (fresh
|
||||
// connection, no cooldown, no health eviction), not two spellings of one.
|
||||
func uniqueProxyEntries(items []string) []string {
|
||||
out := items[:0]
|
||||
seen := make(map[string]struct{}, len(items))
|
||||
pools := make(map[string]struct{}, len(items))
|
||||
for _, item := range items {
|
||||
if _, exists := seen[item]; exists {
|
||||
key, pool := ParseProxyEntry(item)
|
||||
if key == "" {
|
||||
continue
|
||||
}
|
||||
seen[item] = struct{}{}
|
||||
if pool {
|
||||
if _, exists := pools[key]; exists {
|
||||
continue
|
||||
}
|
||||
pools[key] = struct{}{}
|
||||
out = append(out, item)
|
||||
continue
|
||||
}
|
||||
if _, exists := seen[key]; exists {
|
||||
continue
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
out = append(out, item)
|
||||
}
|
||||
return out
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
package config
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestParseProxyEntry(t *testing.T) {
|
||||
cases := []struct {
|
||||
raw string
|
||||
want string
|
||||
pool bool
|
||||
}{
|
||||
{"direct", "direct", false},
|
||||
{"", "", false},
|
||||
{" http://127.0.0.1:7890 ", "http://127.0.0.1:7890", false},
|
||||
{"http://127.0.0.1:7890", "http://127.0.0.1:7890", false},
|
||||
{"http://127.0.0.1:7890#pool", "http://127.0.0.1:7890", true},
|
||||
{"http://127.0.0.1:7890#POOL", "http://127.0.0.1:7890", true},
|
||||
{"http://user:pass@127.0.0.1:7890#pool", "http://user:pass@127.0.0.1:7890", true},
|
||||
{"socks5://127.0.0.1:1080#pool", "socks5://127.0.0.1:1080", true},
|
||||
{"socks5h://127.0.0.1:1080#pool", "socks5h://127.0.0.1:1080", true},
|
||||
{"pool+http://127.0.0.1:7890", "http://127.0.0.1:7890", true},
|
||||
{"pool+socks5://127.0.0.1:1080", "socks5://127.0.0.1:1080", true},
|
||||
// A fragment that is not the pool marker belongs to the proxy URL.
|
||||
{"http://127.0.0.1:7890#other", "http://127.0.0.1:7890#other", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
clean, pool := ParseProxyEntry(tc.raw)
|
||||
if clean != tc.want || pool != tc.pool {
|
||||
t.Errorf("ParseProxyEntry(%q) = (%q, %v), want (%q, %v)", tc.raw, clean, pool, tc.want, tc.pool)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedactURLKeepsPoolMarker(t *testing.T) {
|
||||
// url.User("***") percent-escapes the asterisks; that is the existing
|
||||
// RedactURL shape for every proxy, so the expectation mirrors it.
|
||||
const masked = "http://%2A%2A%2A@127.0.0.1:7890#pool"
|
||||
if got := RedactURL("http://user:pass@127.0.0.1:7890#pool"); got != masked {
|
||||
t.Errorf("pool URL redacted as %q, want %q", got, masked)
|
||||
}
|
||||
if got := RedactURL("pool+http://user:pass@127.0.0.1:7890"); got != masked {
|
||||
t.Errorf("pool+ URL redacted as %q, want %q", got, masked)
|
||||
}
|
||||
if got := RedactURL("http://127.0.0.1:7890"); got != "http://127.0.0.1:7890" {
|
||||
t.Errorf("static URL redacted as %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The same endpoint listed statically and as a pool is two distinct routes and
|
||||
// must survive deduplication; an exact repeat must not.
|
||||
func TestResolveProxyFilesKeepsPoolVariantOfSameEndpoint(t *testing.T) {
|
||||
cfg := Config{Proxies: []string{
|
||||
"http://127.0.0.1:7890",
|
||||
"http://127.0.0.1:7890#pool",
|
||||
"http://127.0.0.1:7890",
|
||||
}}
|
||||
if err := resolveProxyFiles("config.json", &cfg); err != nil {
|
||||
t.Fatalf("resolveProxyFiles failed: %v", err)
|
||||
}
|
||||
got := cfg.RuntimeProxies()
|
||||
want := []string{"http://127.0.0.1:7890", "http://127.0.0.1:7890#pool"}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("resolved proxies = %q, want %q", got, want)
|
||||
}
|
||||
for i := range want {
|
||||
if got[i] != want[i] {
|
||||
t.Fatalf("resolved proxies = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A pool entry must validate against the clean URL, and its credentials must
|
||||
// stay redactable after the marker is stripped.
|
||||
func TestNormalizeAcceptsPoolProxy(t *testing.T) {
|
||||
cfg := Config{
|
||||
Listen: "127.0.0.1:8080",
|
||||
ServerKeys: []string{"local-key"},
|
||||
Anonymous: true,
|
||||
Proxies: []string{"http://user:secret@127.0.0.1:7890#pool", "direct"},
|
||||
Upstream: UpstreamConfig{Zen: "https://opencode.ai/zen", Go: "https://opencode.ai/zen/go", Anonymous: "https://opencode.ai/inference"},
|
||||
Retry: RetryConfig{MaxAttempts: 3, TimeoutSeconds: 300},
|
||||
Models: ModelsConfig{RefreshSeconds: 300, Protocols: map[string]string{}},
|
||||
Performance: PerformanceConfig{MaxIdleConns: 10, MaxIdleConnsPerHost: 10, IdleConnTimeoutSeconds: 30, ConnectTimeoutSeconds: 5, FailureCooldownSeconds: 15},
|
||||
Logging: LoggingConfig{Level: "info", RingSize: 100},
|
||||
Prefer: TierGo,
|
||||
}
|
||||
normalized, err := Normalize("config.json", cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("Normalize rejected a pool proxy: %v", err)
|
||||
}
|
||||
redactor := NewSecretRedactor()
|
||||
redactor.Replace(normalized)
|
||||
if got := redactor.String("dial http://user:secret@127.0.0.1:7890 failed"); got != "dial *** failed" {
|
||||
t.Errorf("pool proxy credentials survived redaction: %q", got)
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,10 @@ func MaskValue(value string) string {
|
||||
}
|
||||
|
||||
func RedactURL(raw string) string {
|
||||
clean, pool := ParseProxyEntry(raw)
|
||||
if clean != "" {
|
||||
raw = clean
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
return "<invalid>"
|
||||
@@ -25,6 +29,9 @@ func RedactURL(raw string) string {
|
||||
if u.User != nil {
|
||||
u.User = url.User("***")
|
||||
}
|
||||
if pool && u.Fragment == "" {
|
||||
u.Fragment = "pool"
|
||||
}
|
||||
return u.String()
|
||||
}
|
||||
|
||||
@@ -56,8 +63,9 @@ func (r *SecretRedactor) Replace(cfg Config) {
|
||||
}
|
||||
for _, value := range cfg.RuntimeProxies() {
|
||||
if value != "direct" {
|
||||
values = append(values, value)
|
||||
if parsed, err := url.Parse(value); err == nil && parsed.User != nil {
|
||||
clean, _ := ParseProxyEntry(value)
|
||||
values = append(values, value, clean)
|
||||
if parsed, err := url.Parse(clean); err == nil && parsed.User != nil {
|
||||
values = append(values, parsed.User.Username())
|
||||
if password, ok := parsed.User.Password(); ok {
|
||||
values = append(values, password)
|
||||
|
||||
+35
-10
@@ -24,6 +24,7 @@ import (
|
||||
type proxyTransport struct {
|
||||
index int
|
||||
name string
|
||||
pool bool
|
||||
client *http.Client
|
||||
healthy atomic.Bool
|
||||
checking atomic.Bool
|
||||
@@ -40,6 +41,7 @@ type anonymousPool struct {
|
||||
nodes []*anonymousNode
|
||||
next atomic.Uint64
|
||||
cooldown time.Duration
|
||||
hasPool bool
|
||||
}
|
||||
|
||||
type anonymousNode struct {
|
||||
@@ -61,6 +63,9 @@ func newAnonymousPool(enabled bool, transports *transportPool, cooldown time.Dur
|
||||
}
|
||||
pool.nodes = make([]*anonymousNode, 0, len(transports.items))
|
||||
for _, proxy := range transports.items {
|
||||
if proxy.pool {
|
||||
pool.hasPool = true
|
||||
}
|
||||
pool.nodes = append(pool.nodes, &anonymousNode{proxy: proxy})
|
||||
}
|
||||
return pool
|
||||
@@ -73,6 +78,10 @@ func (p *anonymousPool) Len() int {
|
||||
return len(p.nodes)
|
||||
}
|
||||
|
||||
func (p *anonymousPool) HasPool() bool {
|
||||
return p != nil && p.hasPool
|
||||
}
|
||||
|
||||
func (p *anonymousPool) CursorFor(affinity string) anonymousCursor {
|
||||
if p == nil || len(p.nodes) == 0 {
|
||||
return anonymousCursor{pool: p}
|
||||
@@ -88,16 +97,30 @@ func (p *anonymousPool) CursorFor(affinity string) anonymousCursor {
|
||||
return anonymousCursor{pool: p, start: start}
|
||||
}
|
||||
|
||||
// Next visits each healthy, non-cooling proxy at most once per cursor.
|
||||
// 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.
|
||||
func (c *anonymousCursor) Next() *anonymousNode {
|
||||
if c.pool == nil || len(c.pool.nodes) == 0 {
|
||||
return nil
|
||||
}
|
||||
n := len(c.pool.nodes)
|
||||
now := time.Now().UnixNano()
|
||||
for c.offset < len(c.pool.nodes) {
|
||||
node := c.pool.nodes[(c.start+c.offset)%len(c.pool.nodes)]
|
||||
for c.offset < n {
|
||||
node := c.pool.nodes[(c.start+c.offset)%n]
|
||||
c.offset++
|
||||
if node.proxy.healthy.Load() && node.cooldownUntil.Load() <= now {
|
||||
if node.proxy.pool || (node.proxy.healthy.Load() && node.cooldownUntil.Load() <= now) {
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -145,7 +168,7 @@ func (p *anonymousPool) RestoreProxy(proxy *proxyTransport) int {
|
||||
const maxAnonymousRetryAfterMultiplier = 8
|
||||
|
||||
func (p *anonymousPool) MarkFailure(node *anonymousNode, resp *http.Response, err error) {
|
||||
if node == nil {
|
||||
if node == nil || (node.proxy != nil && node.proxy.pool) {
|
||||
return
|
||||
}
|
||||
if err == nil && resp != nil && resp.StatusCode != http.StatusUnauthorized && resp.StatusCode != http.StatusForbidden && resp.StatusCode != http.StatusTooManyRequests && resp.StatusCode < 500 {
|
||||
@@ -185,27 +208,29 @@ func (p *transportPool) healthCounts() (total, healthy int) {
|
||||
func newTransportPool(proxies []string, cfg config.PerformanceConfig, responseHeaderTimeout time.Duration) (*transportPool, error) {
|
||||
p := &transportPool{items: make([]*proxyTransport, 0, len(proxies))}
|
||||
for _, raw := range proxies {
|
||||
clean, isPool := config.ParseProxyEntry(raw)
|
||||
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.ForceAttemptHTTP2 = !isPool
|
||||
transport.DisableKeepAlives = isPool
|
||||
transport.DialContext = (&net.Dialer{
|
||||
Timeout: time.Duration(cfg.ConnectTimeoutSeconds) * time.Second,
|
||||
KeepAlive: 30 * time.Second,
|
||||
}).DialContext
|
||||
if raw == "direct" {
|
||||
if clean == "direct" {
|
||||
transport.Proxy = nil
|
||||
} else {
|
||||
u, err := url.Parse(raw)
|
||||
u, err := url.Parse(clean)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse proxy %s: %w", config.RedactURL(raw), err)
|
||||
}
|
||||
transport.Proxy = http.ProxyURL(u)
|
||||
}
|
||||
proxy := &proxyTransport{index: len(p.items), name: raw, client: &http.Client{Transport: transport}}
|
||||
proxy := &proxyTransport{index: len(p.items), name: raw, pool: isPool, client: &http.Client{Transport: transport}}
|
||||
proxy.healthy.Store(true)
|
||||
p.items = append(p.items, proxy)
|
||||
}
|
||||
@@ -227,7 +252,7 @@ func (p *transportPool) CheckHealth(ctx context.Context, target string, timeout
|
||||
results := make(chan proxyHealthResult, len(p.items))
|
||||
checks := 0
|
||||
for _, proxy := range p.items {
|
||||
if proxy.healthy.Load() || !proxy.checking.CompareAndSwap(false, true) {
|
||||
if proxy.pool || proxy.healthy.Load() || !proxy.checking.CompareAndSwap(false, true) {
|
||||
continue
|
||||
}
|
||||
// A real request may have restored the proxy between the first health
|
||||
|
||||
@@ -21,7 +21,7 @@ const (
|
||||
// connection refusals mark a proxy unavailable. Other errors and 4xx/5xx
|
||||
// responses trigger a neutral URL check without being treated as proxy failure.
|
||||
func (g *Gateway) syncProxyResult(ctx context.Context, proxy *proxyTransport, status int, err error) bool {
|
||||
if proxy == nil {
|
||||
if proxy == nil || proxy.pool {
|
||||
return false
|
||||
}
|
||||
if isProxyFailure(err) {
|
||||
@@ -216,6 +216,9 @@ func (g *Gateway) refreshZen(ctx context.Context) []string {
|
||||
func (g *Gateway) refreshAnonymousTier(ctx context.Context, base string) []string {
|
||||
cursor := g.anonymous.CursorFor("")
|
||||
limit := g.anonymous.Len()
|
||||
if g.anonymous.HasPool() && g.cfg.Retry.MaxAttempts > limit {
|
||||
limit = g.cfg.Retry.MaxAttempts
|
||||
}
|
||||
for attempt := 1; attempt <= limit; attempt++ {
|
||||
node := cursor.Next()
|
||||
if node == nil {
|
||||
|
||||
@@ -266,6 +266,9 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
|
||||
var lastErr error
|
||||
cursor := g.anonymous.CursorFor(ids.Session)
|
||||
limit := g.anonymous.Len()
|
||||
if g.anonymous.HasPool() && g.cfg.Retry.MaxAttempts > limit {
|
||||
limit = g.cfg.Retry.MaxAttempts
|
||||
}
|
||||
proxies := 0
|
||||
attempts := 0
|
||||
rawBody := bodies[config.TierZen]
|
||||
@@ -320,6 +323,9 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
|
||||
if err != nil {
|
||||
return nil, err, attempts
|
||||
}
|
||||
if node.proxy.pool {
|
||||
req.Close = true
|
||||
}
|
||||
setRequestCredential(ctx, config.TierZen, "anonymous", "anonymous", true, node.proxy)
|
||||
started := time.Now()
|
||||
resp, err := doInferenceAttempt(node.proxy.client, req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second, g.attemptTimeout)
|
||||
@@ -721,6 +727,9 @@ func (g *Gateway) doSelectedKeyUpstream(ctx context.Context, route models.Route,
|
||||
if err != nil {
|
||||
return nil, err, 0
|
||||
}
|
||||
if proxy.pool {
|
||||
req.Close = true
|
||||
}
|
||||
started := time.Now()
|
||||
resp, err := doInferenceAttempt(proxy.client, req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second, g.attemptTimeout)
|
||||
duration := time.Since(started)
|
||||
@@ -788,6 +797,9 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies
|
||||
lastErr = errors.New("upstream key has no proxy binding")
|
||||
break
|
||||
}
|
||||
if proxy.pool {
|
||||
req.Close = true
|
||||
}
|
||||
keyID := config.KeyDisplayID(node.key)
|
||||
setRequestCredential(ctx, route.Tier, keyID, "key", false, proxy)
|
||||
attemptStarted := time.Now()
|
||||
|
||||
+1
-1
@@ -844,7 +844,7 @@
|
||||
<label for="proxies-new" data-i18n="config.proxy.add">新增 Proxy(每行一个)</label>
|
||||
<textarea
|
||||
id="proxies-new"
|
||||
placeholder="direct http://user:pass@host:port"
|
||||
placeholder="direct http://user:pass@host:port http://127.0.0.1:7890#pool"
|
||||
></textarea>
|
||||
</div>
|
||||
<div class="field">
|
||||
|
||||
+4
-2
@@ -256,7 +256,8 @@ const DICTIONARY = {
|
||||
"config.secrets.anonymous": "Enable the Zen anonymous channel",
|
||||
"config.secrets.add": "One key per line",
|
||||
"config.proxy.title": "Proxy nodes",
|
||||
"config.proxy.caption": "Supports direct, HTTP(S), and SOCKS URLs.",
|
||||
"config.proxy.caption":
|
||||
"Supports direct, HTTP(S), and SOCKS URLs. Suffix an entry with #pool to mark it as a rotating proxy pool: the gateway then opens a fresh connection per attempt, skips its cooldown and health eviction, and retries it up to retry.max_attempts times.",
|
||||
"config.proxy.add": "Add proxies (one per line)",
|
||||
"config.upstream.title": "Upstream and protocol routing",
|
||||
"config.upstream.caption":
|
||||
@@ -801,7 +802,8 @@ const DICTIONARY = {
|
||||
"config.secrets.anonymous": "Bật kênh ẩn danh Zen",
|
||||
"config.secrets.add": "Mỗi dòng thêm một key",
|
||||
"config.proxy.title": "Nút Proxy",
|
||||
"config.proxy.caption": "Hỗ trợ direct, HTTP(S) và URL SOCKS.",
|
||||
"config.proxy.caption":
|
||||
"Hỗ trợ direct, HTTP(S) và URL SOCKS. Thêm hậu tố #pool để đánh dấu mục đó là proxy pool luân chuyển: gateway sẽ mở kết nối mới cho mỗi lần thử, bỏ qua cooldown và loại bỏ theo sức khoẻ, và thử lại tối đa retry.max_attempts lần.",
|
||||
"config.proxy.add": "Thêm Proxy (mỗi dòng một cái)",
|
||||
"config.upstream.title": "Upstream và định tuyến giao thức",
|
||||
"config.upstream.caption":
|
||||
|
||||
Reference in new issue
Block a user