diff --git a/CHANGELOG.md b/CHANGELOG.md index 3b76173b..7af4343a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ ### Added -- `http-framework-test` 新增可选代理池:支持代理列表与供应商接口、失败冷却及有界切换;仅自动重放 GET/HEAD/OPTIONS,遵守 429 Retry-After,切换失败时返回响应或错误且不回退直连。附中英文指南与本地 HTTP/HTTPS/SOCKS5 回归测试(#357)。 +- `http-framework-test` 新增可选代理池:支持静态/结构化代理列表与供应商接口、粘性/轮询策略、供应商故障静态回退、失败冷却及有界切换;仅自动重放 GET/HEAD/OPTIONS,遵守 429 Retry-After,切换失败时返回响应或错误且不回退直连。附中英文指南与本地 HTTP/HTTPS/SOCKS5 回归测试(#357)。 - 支持通过 `agent.task_timeout_minutes` 配置单代理、多代理、工作流及异步任务执行超时:未配置默认 600 分钟,`0` 表示不限时,负数拒绝加载;续跑保留重新计时行为,单次工具超时仍独立生效。 diff --git a/docs/en-US/http-proxy-pool.md b/docs/en-US/http-proxy-pool.md index 194676af..35478104 100644 --- a/docs/en-US/http-proxy-pool.md +++ b/docs/en-US/http-proxy-pool.md @@ -39,19 +39,20 @@ The endpoint must return UTF-8 newline-separated endpoints, a JSON array of endp {"proxies": ["http://127.0.0.1:8081", "127.0.0.1:8082"]} ``` -Other provider formats require an adapter. No public free-proxy sources are built in. The source is fetched at startup and at most once more per request/redirect hop when available candidates run out. New endpoints are deduplicated and merged without clearing cooldowns. Fetches have a 10-second timeout, do not follow redirects, accept at most 1 MiB, and the pool holds at most 256 endpoints. An initial fetch failure stops the call. A refresh failure preserves the last HTTP failure response, or reports an error if no response exists. +Entries may also be objects such as `{"host":"127.0.0.1","port":8081,"scheme":"http","username":"user","password":"pass"}` (`ip` aliases `host`) or `{"url":"http://127.0.0.1:8081"}`. Scheme defaults to HTTP, credentials are optional and automatically URL-encoded. Other provider formats require an adapter. No public free-proxy sources are built in. The source is fetched at startup and at most once more per request/redirect hop when available candidates run out. New endpoints are deduplicated and merged without clearing cooldowns. Fetches have 10-second connect/read timeouts, do not follow redirects, accept at most 1 MiB, and the pool holds at most 256 endpoints. An initial fetch failure warns and uses static endpoints when available; source-only calls fail. A refresh failure preserves the last HTTP failure response, or reports an error if no response exists. ## Behavior | Parameter | Default | Meaning | | --- | --- | --- | | `proxy_pool` | Empty | JSON string array or newline-separated list | +| `proxy_strategy` | `"sticky"` | `sticky` reuses successful proxies; `round_robin` rotates and skips cooldowns | | `proxy_source` | Empty | User-configured HTTP(S) provider endpoint, optionally combined with a list | | `proxy_max_attempts` | `3` | 1–10 distinct proxy attempts per request/redirect hop | | `proxy_cooldown` | `"60"` | 0–86400 seconds before a failed proxy is eligible again | | `proxy_fail_status` | `"403,429"` | Comma-separated status codes from 400–599; `"none"` disables status-based switching | -- Successful proxies stay selected. Failed proxies enter cooldown. Each proxy is tried at most once per request/redirect hop. +- Successful proxies stay selected by default. With `proxy_strategy="round_robin"`, each request/redirect hop rotates through eligible proxies. Failed proxies enter cooldown. Each proxy is tried at most once per request/redirect hop. - Only GET, HEAD and OPTIONS are replayed automatically. POST, PUT, DELETE and other methods retain the first result. An explicit `repeat` still requests additional executions. - Transport failures before response headers can trigger switching. Failures while reading a response body are reported without replaying a partial response. - A 429 with a valid future `Retry-After` stops automatic replay and reports that the caller should retry later. Further requests to that origin within the same tool invocation are blocked until the wait expires; waits are recorded for at most 24 hours. diff --git a/docs/zh-CN/http-proxy-pool.md b/docs/zh-CN/http-proxy-pool.md index 06b0d265..73b135fc 100644 --- a/docs/zh-CN/http-proxy-pool.md +++ b/docs/zh-CN/http-proxy-pool.md @@ -43,15 +43,16 @@ {"proxies": ["http://127.0.0.1:8081"]} ``` -也支持 `{"data": ["http://127.0.0.1:8081"]}`。需要其他供应商字段格式时,应由供应商或自建适配接口转换为上述格式。项目不内置公共免费代理来源。 +也支持 `{"data": ["http://127.0.0.1:8081"]}`。列表元素还可为 `{"host":"127.0.0.1","port":8081,"scheme":"http","username":"user","password":"pass"}`(`ip` 可代替 `host`),或 `{"url":"http://127.0.0.1:8081"}`。`scheme` 默认 HTTP,认证字段可省略;结构化凭证自动做 URL 编码。需要其他供应商字段格式时,应由供应商或自建适配接口转换为上述格式。项目不内置公共免费代理来源。 -供应商接口在调用开始时拉取一次;每个请求或重定向跳的可用代理耗尽时,最多再拉取一次。新地址与现有地址去重合并,已有冷却记录保留。接口超时固定 10 秒,不跟随重定向,响应上限 1 MiB,代理总数上限 256。首次拉取失败直接结束调用;切换过程中拉取失败则保留最后的 HTTP 失败响应,若还未收到响应则报错。 +供应商接口在调用开始时拉取一次;每个请求或重定向跳的可用代理耗尽时,最多再拉取一次。新地址与现有地址去重合并,已有冷却记录保留。连接/读取超时为 10 秒,不跟随重定向,响应上限 1 MiB,代理总数上限 256。首次拉取失败时,有静态列表则发出提示并继续使用静态代理;仅配置供应商时结束调用;切换过程中拉取失败则保留最后的 HTTP 失败响应,若还未收到响应则报错。 ## 切换与结果 | 参数 | 默认值 | 行为 | | --- | --- | --- | | `proxy_pool` | 空 | JSON 字符串数组或换行列表 | +| `proxy_strategy` | `"sticky"` | `sticky` 成功后复用,`round_robin` 轮询并跳过冷却代理 | | `proxy_source` | 空 | 用户配置的 HTTP(S) 供应商接口,可与列表合用 | | `proxy_max_attempts` | `3` | 每个请求/重定向跳最多尝试 1–10 个不同代理 | | `proxy_cooldown` | `"60"` | 失败代理冷却 0–86400 秒 | @@ -59,7 +60,7 @@ 具体规则: -- 池内成功代理保持粘性复用;失败后冷却,在剩余可用代理中切换。每个请求或重定向跳内,同一代理最多尝试一次。 +- 默认保持成功代理;设置 `proxy_strategy="round_robin"` 后,每个请求/重定向跳轮询可用代理;失败后冷却,在剩余可用代理中切换。每个请求或重定向跳内,同一代理最多尝试一次。 - 仅 GET、HEAD、OPTIONS 自动重放。POST、PUT、DELETE 等方法发生错误或命中状态码时保留首次结果;用户显式设置的 `repeat` 仍表示额外执行次数。 - 连接、代理、超时等传输错误可触发上述切换;响应体开始读取后的中断直接报错,不重放部分响应。 - 429 若包含有效且尚未到期的 `Retry-After`,停止自动重放并提示稍后重试。同一工具调用中,对该目标源的后续请求也会被阻止至等待期结束,等待值最多记为 24 小时。 diff --git a/internal/security/http_proxy_pool_test.go b/internal/security/http_proxy_pool_test.go index 096d177f..224c99a7 100644 --- a/internal/security/http_proxy_pool_test.go +++ b/internal/security/http_proxy_pool_test.go @@ -20,12 +20,12 @@ func TestHTTPProxyPoolToolArguments(t *testing.T) { pool := "http://user:p%40ss@localhost:8081\nhttp://localhost:8082" args := executor.buildCommandArgs(tool.Name, tool, map[string]interface{}{ "url": "https://target.invalid/a/../b", "proxy_pool": pool, - "proxy_source": "https://provider.invalid/?key=placeholder", - "proxy_max_attempts": float64(2), "proxy_cooldown": "0", "proxy_fail_status": "none", + "proxy_source": "https://provider.invalid/?key=placeholder", + "proxy_strategy": "round_robin", "proxy_max_attempts": float64(2), "proxy_cooldown": "0", "proxy_fail_status": "none", }) want := map[string]string{ "--proxy-pool": pool, "--proxy-source": "https://provider.invalid/?key=placeholder", - "--proxy-max-attempts": "2", "--proxy-cooldown": "0", "--proxy-fail-status": "none", + "--proxy-strategy": "round_robin", "--proxy-max-attempts": "2", "--proxy-cooldown": "0", "--proxy-fail-status": "none", } for flag, value := range want { found := false diff --git a/scripts/test_http_proxy_pool.py b/scripts/test_http_proxy_pool.py index 49a4810b..b3790198 100644 --- a/scripts/test_http_proxy_pool.py +++ b/scripts/test_http_proxy_pool.py @@ -208,6 +208,40 @@ class ProxyPoolTests(unittest.TestCase): with self.subTest(kwargs=kwargs), self.assertRaises(ValueError): Pool("localhost:8080", **kwargs) + def test_structured_provider_entries(self): + raw = {"data": [{"ip": "::1", "port": 1080, "scheme": "socks5", + "username": "u@", "password": "p:/"}, + {"url": "http://localhost:8080"}]} + self.assertEqual(NS["parse_proxy_list"](raw), + ["socks5://u%40:p%3A%2F@[::1]:1080", "http://localhost:8080"]) + for row in [{"host": "evil@host", "port": 80}, {"host": "host", "port": True}, + {"host": "host", "port": 80, "password": "secret"}]: + with self.assertRaises(ValueError) as caught: + NS["parse_proxy_list"]([row]) + self.assertNotIn("secret", str(caught.exception)) + + def test_round_robin_rotates_without_skipping_failover_candidate(self): + with server(403) as bad, server() as second, server() as third: + pool = Pool(json.dumps([bad.url, second.url, third.url]), strategy="round_robin") + with httpx.Client(transport=pool, trust_env=False) as client: + for expected in [2, 3, 2]: + response, *_ = send(client) + with contextlib.closing(response): + self.assertEqual(response.read(), b"ok") + self.assertEqual(response.extensions["proxy_pool"]["proxy"], expected) + self.assertEqual(len(bad.requests), 1) + + def test_provider_outage_keeps_static_pool_and_source_only_fails(self): + with server() as proxy, server(503) as provider: + pool = Pool(proxy.url, source=provider.url + "/?key=secret") + with httpx.Client(transport=pool, trust_env=False) as client: + response, *_ = send(client) + with contextlib.closing(response): + self.assertEqual(response.read(), b"ok") + with self.assertRaisesRegex(ValueError, "HTTP 503"): + Pool("", source=provider.url) + self.assertNotIn("secret", self.diagnostics.getvalue()) + def test_failover_and_sticky_connection_preserve_raw_path(self): with server(403, b"blocked") as blocked, server() as good: pool = Pool(json.dumps([blocked.url, good.url]), cooldown=60) @@ -476,6 +510,17 @@ class ProxyPoolTests(unittest.TestCase): "--proxy-fail-status", "none") self.assertEqual(result.returncode, 0, result.stderr) + def test_cli_round_robin_repeats_use_different_proxies(self): + with server(body=b"first-proxy") as first, server(body=b"second-proxy") as second: + result = self.run_cli("--url", "http://target.invalid/", "--proxy-pool", + json.dumps([first.url, second.url]), "--repeat", "2", + "--proxy-strategy", "round_robin") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("first-proxy", result.stdout) + self.assertIn("second-proxy", result.stdout) + self.assertEqual(len(first.requests), 1) + self.assertEqual(len(second.requests), 1) + if __name__ == "__main__": unittest.main() diff --git a/tools/http-framework-test.yaml b/tools/http-framework-test.yaml index 92feab68..41ef7db2 100644 --- a/tools/http-framework-test.yaml +++ b/tools/http-framework-test.yaml @@ -301,6 +301,26 @@ args: raise ValueError("Proxy list must contain at most 256 entries") proxies = [] for value in raw: + if isinstance(value, dict): + if "url" in value: + value = value["url"] + else: + host = value.get("host", value.get("ip")) + port = value.get("port") + scheme = value.get("scheme", "http") + username = value.get("username", "") + password = value.get("password", "") + if (not isinstance(host, str) or not host or + not isinstance(port, (str, int)) or isinstance(port, bool) or + not str(port).isascii() or not str(port).isdigit() or + not all(isinstance(v, str) for v in (scheme, username, password)) or + any(c in host for c in "@/?#") or (password and not username)): + raise ValueError("Invalid structured proxy entry") + if ":" in host and not host.startswith("["): + host = "[" + host + "]" + auth = (urllib.parse.quote(username, safe="") + ":" + + urllib.parse.quote(password, safe="") + "@") if username else "" + value = f"{scheme}://{auth}{host}:{port}" if not isinstance(value, str): raise ValueError("Proxy entries must be URL strings or host:port strings") value = value.strip() @@ -384,7 +404,11 @@ args: RETRY_METHODS = {"GET", "HEAD", "OPTIONS"} def __init__(self, proxies, source="", max_attempts=3, cooldown=60.0, - fail_status="403,429", transport_kwargs=None): + fail_status="403,429", transport_kwargs=None, strategy="sticky"): + if strategy not in {"sticky", "round_robin"}: + raise ValueError("proxy_strategy must be sticky or round_robin") + self.strategy = strategy + self.cursor = 0 if not 1 <= max_attempts <= 10: raise ValueError("proxy_max_attempts must be between 1 and 10") if not math.isfinite(cooldown) or not 0 <= cooldown <= 86400: @@ -410,7 +434,12 @@ args: self.target_wait = {} self.current = None if self.source: - self.refresh() + try: + self.refresh() + except ValueError as exc: + if not self.proxies: + raise + print(f"[proxy pool] {exc}; using configured static endpoints", file=sys.stderr) if not self.proxies: raise ValueError("Proxy pool has no endpoints") @@ -421,12 +450,17 @@ args: raise ValueError("Proxy pool exceeds 256 endpoints") self.proxies = merged - def select(self, attempted): + def select(self, attempted, advance=True): now = time.monotonic() - candidates = ([self.current] if self.current else []) + self.proxies + if self.strategy == "round_robin": + candidates = self.proxies[self.cursor:] + self.proxies[:self.cursor] + else: + candidates = ([self.current] if self.current else []) + self.proxies for proxy in candidates: if proxy not in attempted and self.cooling.get(proxy, 0) <= now: - self.current = proxy + if advance: + self.current = proxy + self.cursor = (self.proxies.index(proxy) + 1) % len(self.proxies) return proxy return None @@ -481,14 +515,14 @@ args: if not retryable or wait > 0 or attempt == self.max_attempts: return response # Keep the last response observable if no replacement is available. - available = self.select(attempted) + available = self.select(attempted, advance=False) if available is None and self.source and not refreshed: refreshed = True try: self.refresh() except ValueError as exc: print(f"[proxy pool] {exc}; preserving last response", file=sys.stderr) - available = self.select(attempted) + available = self.select(attempted, advance=False) if available is None: print("[proxy pool] no replacement available; preserving last response", file=sys.stderr) return response @@ -1192,6 +1226,7 @@ args: parser.add_argument("--proxy", default="") parser.add_argument("--proxy-pool", default="") parser.add_argument("--proxy-source", default="") + parser.add_argument("--proxy-strategy", choices=["sticky", "round_robin"], default="sticky") parser.add_argument("--proxy-max-attempts", type=int, default=3) parser.add_argument("--proxy-cooldown", type=float, default=60.0) parser.add_argument("--proxy-fail-status", default="403,429") @@ -1373,6 +1408,7 @@ args: args.proxy_pool, source=args.proxy_source, max_attempts=args.proxy_max_attempts, cooldown=args.proxy_cooldown, fail_status=args.proxy_fail_status, transport_kwargs=transport_kwargs, + strategy=args.proxy_strategy, ) except ValueError as exc: parser.error(str(exc)) @@ -1662,9 +1698,15 @@ parameters: flag: "--proxy-pool" - name: "proxy_source" type: "string" - description: "用户配置的代理供应商 HTTP(S) 接口;返回换行列表、JSON 数组或 {proxies:[...]} / {data:[...]};开始及耗尽时有界拉取;与 proxy 互斥" + description: "用户配置的代理供应商 HTTP(S) 接口;返回换行列表、JSON 数组或 {proxies:[...]} / {data:[...]},元素可为 URL 或 host/ip+port 对象;开始及耗尽时有界拉取;与 proxy 互斥" required: false flag: "--proxy-source" + - name: "proxy_strategy" + type: "string" + description: "代理选择策略:sticky(默认,成功后复用),round_robin(每次请求/重定向跳轮询可用代理);均跳过冷却代理" + required: false + default: "sticky" + flag: "--proxy-strategy" - name: "proxy_max_attempts" type: "int" description: "每个请求/重定向跳的代理尝试上限(1-10);每个代理最多尝试一次;仅 GET/HEAD/OPTIONS 自动重放"