Files
Jason Xu 260211cd9e 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.
2026-10-17 03:30:25 +08:00

134 lines
3.4 KiB
Go

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...)
if cfg.ProxyFile != "" {
resolved := cfg.ProxyFile
if !filepath.IsAbs(resolved) {
resolved = filepath.Join(filepath.Dir(configPath), resolved)
}
proxies, err := readProxyFile(resolved)
if err != nil {
return fmt.Errorf("load proxy file %s: %w", resolved, err)
}
effective = append(effective, proxies...)
}
effective = uniqueProxyEntries(effective)
if len(effective) == 0 {
effective = []string{"direct"}
}
cfg.effectiveProxies = effective
return nil
}
func readProxyFile(path string) ([]string, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
var proxies []string
scanner := bufio.NewScanner(file)
scanner.Buffer(make([]byte, 4096), 1024*1024)
for scanner.Scan() {
value := strings.TrimSpace(strings.TrimPrefix(scanner.Text(), "\ufeff"))
value = strings.TrimSpace(stripProxyLineComment(value))
if value != "" {
proxies = append(proxies, value)
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
return proxies, nil
}
func stripProxyLineComment(line string) string {
for i := 0; i < len(line); i++ {
if i > 0 && line[i-1] != ' ' && line[i-1] != '\t' {
continue
}
if line[i] == '#' || line[i] == ';' || (line[i] == '/' && i+1 < len(line) && line[i+1] == '/') {
return line[:i]
}
}
return line
}
// 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 {
key, pool := ParseProxyEntry(item)
if key == "" {
continue
}
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
}
func trimList(items *[]string) {
out := (*items)[:0]
for _, item := range *items {
if value := strings.TrimSpace(item); value != "" {
out = append(out, value)
}
}
*items = out
}