mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-05 08:02:53 +00:00
fix(upstream): stop retrying request-level rejections and cap anonymous exits
The anonymous walk now ends on a deterministic 4xx instead of replaying the same context-length rejection through every exit and tier. Static exits are capped by performance.max_anonymous_exits, and an IP-level abuse block marks only its exit; the lane breaker opens only when every exit is blocked, so a single 403 no longer pauses the lane. The Zen key tier is skipped after an IP block while the authenticated Go tier remains available. Add performance.free_tier_block_seconds, make the breaker half-open probe single-flight, and coordinate refreshes and availability probes with the breaker. Update the shipped example to start on the anonymous lane.
This commit is contained in:
1 parent
ddb5c14b3f
commit
0bb23c7a7f
11 files changed
+265
-85
No files matched your search
@@ -36,7 +36,7 @@ go build -o opencode2api ./cmd/opencode2api
|
||||
Before starting, edit `config.json`:
|
||||
|
||||
1. Replace `server_keys` with your own local API key.
|
||||
2. Supply Zen or Go keys. Alternatively, set `anonymous: true` and empty both upstream key arrays.
|
||||
2. Optionally supply Zen or Go keys. The example enables the anonymous free lane and leaves both upstream key arrays empty.
|
||||
3. Replace `webui.password`. The example enables the WebUI with username `admin`.
|
||||
|
||||
```bash
|
||||
@@ -211,13 +211,13 @@ Eligibility is a routing decision; the upstream can still reject or rate-limit t
|
||||
|
||||
The routing sequence is:
|
||||
|
||||
1. For an eligible model, try each available anonymous proxy once.
|
||||
1. For an eligible model, try up to `performance.max_anonymous_exits` available anonymous proxies once each. Every proxy tries the v2 `/inference` lane first, then the v1 `/zen` lane.
|
||||
2. Try authenticated tiers in `prefer` order, using only tiers with a configured key and a route for that model.
|
||||
3. Apply `retry.max_attempts` separately to each authenticated tier.
|
||||
|
||||
Anonymous attempts are not cut short by `retry.max_attempts`, but all attempts share the request timeout. Network errors, authentication failures, rate limits, and server errors can rotate keys. Other 4xx responses end the current tier; another available tier may still be tried.
|
||||
Anonymous attempts are not cut short by `retry.max_attempts`, but all attempts share the request timeout. Network errors, authentication failures, rate limits, and server errors can rotate exits. A request-level `400`/`413`/`422` (for example `context_length_exceeded`) ends the request immediately: another exit or tier cannot change the request. An IP-level abuse `403` blocks only that exit; if every exit is blocked, the gateway stops walking them, and an authenticated Go key can still serve the request.
|
||||
|
||||
When the free tier is blocked for the whole deployment (an IP-level `403` abuse response), retrying only extends the penalty, so an optional lane-level circuit breaker can stop the probing. With `models.anonymous_backoff` configured, `threshold` consecutive failed anonymous attempts, or a single `403`/`429` (an explicit block signal), pause the whole anonymous lane for `base_hours`, doubling on every further trip up to `max_hours`. While paused, requests skip the lane entirely: no proxy is drawn, no upstream request is made, and routing goes straight to the authenticated tiers. The first attempt after the window expires probes once; success closes the breaker and restores the free lane, failure opens the next, longer window. The block is absent, and so the breaker is off, by default.
|
||||
When the free tier is blocked for the whole deployment (an IP-level `403` abuse response), retrying only extends the penalty, so an optional lane-level circuit breaker can stop the probing. With `models.anonymous_backoff` configured, `threshold` consecutive failed anonymous attempts or an all-exits IP block pause the whole anonymous lane for `base_hours`, doubling on every further trip up to `max_hours`. A single non-abuse `403` or `429` does not open the breaker; it counts toward the threshold. While paused, requests skip the lane entirely: no proxy is drawn, no upstream request is made, and routing goes straight to the authenticated tiers. Catalog refreshes and availability probes honour the pause as well. When the window expires one request wins the half-open probe; success closes the breaker and restores the free lane, failure opens the next, longer window. The block is absent, and so the breaker stays off, by default.
|
||||
|
||||
Requests are encoded for each tier's own protocol. With `performance.first_event_timeout_seconds` enabled, a successful SSE response is held until the first complete data event. A timeout or disconnect before that event uses the existing key/proxy retry budget; comments do not satisfy the timeout. Once released downstream, the stream is never replayed. The default is `0` (disabled); try `15` seconds for upstreams that accept requests but send no events. This bounds the first event, not the first text token, and does not apply to System One. Rotation aliases use their separate `rotation.first_output_seconds` timeout. A recognized stale Responses reasoning reference can trigger one repair pass; selected-key diagnostics never use that replay.
|
||||
|
||||
@@ -337,7 +337,7 @@ A pool entry is handled differently from a static proxy:
|
||||
| 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 |
|
||||
| Anonymous lane retries | One visit per exit, up to `performance.max_anonymous_exits` exits | 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.
|
||||
|
||||
@@ -348,6 +348,8 @@ Use it when the endpoint behind the URL already performs the rotation and the po
|
||||
| `retry.max_attempts` | `3` | Attempts per authenticated tier, including the first. |
|
||||
| `retry.timeout_seconds` | `300` | Total inference timeout, including stream consumption. |
|
||||
| `performance.attempt_timeout_seconds` | `0` | Whole-attempt bound; 0 uses the request timeout. |
|
||||
| `performance.max_anonymous_exits` | `8` | Distinct static proxy exits per anonymous request. |
|
||||
| `performance.free_tier_block_seconds` | `900` | Cool-down for an exit the free tier flagged. |
|
||||
| `performance.connect_timeout_seconds` | `5` | Connection establishment timeout. |
|
||||
| `performance.failure_cooldown_seconds` | `15` | Base failure cooldown. |
|
||||
| `performance.max_idle_conns` | `2048` | Idle connection limit per proxy transport. |
|
||||
|
||||
+9
-4
@@ -38,7 +38,7 @@ go build -o opencode2api ./cmd/opencode2api
|
||||
Trước khi khởi động, hãy sửa `config.json`:
|
||||
|
||||
1. Thay `server_keys` bằng API key cục bộ của bạn.
|
||||
2. Cung cấp key Zen hoặc Go. Nếu không, đặt `anonymous: true` và để cả hai mảng key upstream rỗng.
|
||||
2. Tùy chọn: thêm key Zen hoặc Go; ví dụ đã bật làn ẩn danh và để trống cả hai mảng key thượng nguồn.
|
||||
3. Thay `webui.password`. File mẫu bật WebUI với tài khoản `admin`.
|
||||
|
||||
```bash
|
||||
@@ -215,11 +215,13 @@ Khi `anonymous: true`, chỉ cần một trong hai điều kiện sau là mô h
|
||||
|
||||
Trình tự định tuyến là:
|
||||
|
||||
1. Với mô hình đủ điều kiện, thử lần lượt mỗi proxy ẩn danh khả dụng.
|
||||
1. Với mô hình đủ điều kiện, thử tối đa `performance.max_anonymous_exits` proxy ẩn danh khả dụng, mỗi proxy một lần; mỗi proxy thử làn v2 `/inference` trước, rồi làn v1 `/zen`.
|
||||
2. Thử các tier có xác thực theo thứ tự `prefer`, chỉ dùng những tier có key được cấu hình và có route cho mô hình đó.
|
||||
3. Áp dụng `retry.max_attempts` riêng cho từng tier có xác thực.
|
||||
|
||||
Các lần thử ẩn danh không bị `retry.max_attempts` cắt ngắn, nhưng mọi lần thử đều dùng chung timeout của request. Lỗi mạng, xác thực thất bại, giới hạn tần suất và lỗi máy chủ có thể làm luân chuyển key. Các phản hồi 4xx khác kết thúc tier hiện tại; một tier khác còn khả dụng vẫn có thể được thử.
|
||||
Các lần thử ẩn danh không bị `retry.max_attempts` cắt ngắn, nhưng mọi lần thử đều dùng chung timeout của request. Lỗi mạng, xác thực thất bại, giới hạn tần suất và lỗi máy chủ có thể làm luân chuyển exit. Request-level `400`/`413`/`422` (ví dụ `context_length_exceeded`) kết thúc request ngay: đổi exit hay tier không thể thay đổi bản thân request. Abuse `403` ở mức IP chỉ loại bỏ exit hiện tại; khi mọi exit đều bị chặn, gateway ngừng quét và key Go đã cấu hình vẫn có thể phục vụ.
|
||||
|
||||
Khi bật `models.anonymous_backoff`, `threshold` lần lỗi ẩn danh liên tiếp hoặc việc mọi exit bị chặn IP sẽ tạm dừng toàn bộ làn ẩn danh trong `base_hours`, tăng gấp đôi sau mỗi lần kích hoạt cho tới `max_hours`. Một `403` không phải lạm dụng hoặc `429` đơn lẻ không mở cầu dao mà chỉ tính vào ngưỡng. Trong thời gian tạm dừng, không rút proxy và không gửi request thượng nguồn (kể cả làm mới catalog và probe), định tuyến chuyển thẳng sang tier có xác thực. Khi hết cửa sổ, chỉ một request thắng probe bán mở: thành công sẽ đóng cầu dao và khôi phục làn ẩn danh, thất bại sẽ mở cửa sổ dài hơn tiếp theo. Bỏ khối cấu hình này thì cầu dao tắt.
|
||||
|
||||
Request được mã hoá theo giao thức riêng của từng tier. Khi bật `performance.first_event_timeout_seconds`, một phản hồi SSE thành công sẽ được giữ lại cho tới sự kiện dữ liệu hoàn chỉnh đầu tiên. Timeout hoặc mất kết nối trước sự kiện đó sẽ dùng ngân sách retry key/proxy hiện có; comment không tính là thoát timeout. Sau khi được giải phóng xuống phía dưới, luồng không bao giờ được phát lại. Mặc định là `0` (tắt); hãy thử `15` giây cho các upstream nhận request nhưng không gửi sự kiện nào. Giới hạn này áp dụng cho sự kiện đầu tiên, không phải token văn bản đầu tiên, và không áp dụng cho System One. Bí danh luân chuyển dùng timeout riêng `rotation.first_output_seconds`. Một tham chiếu reasoning Responses bị lỗi thời đã nhận diện có thể kích hoạt một lượt sửa; chẩn đoán chọn key cụ thể không bao giờ dùng lượt phát lại đó.
|
||||
|
||||
@@ -272,6 +274,7 @@ Xem [config.example.json](config.example.json) để có một cấu hình khở
|
||||
| `models.refresh_seconds` | `300`; tối thiểu 1. |
|
||||
| `models.protocols` | `{}`; ghi đè giao thức gốc theo từng mô hình. |
|
||||
| `models.free_only` | `false`; chỉ công khai và định tuyến mô hình miễn phí, kể cả khi có key Zen hoặc Go. |
|
||||
| `models.anonymous_backoff` | Tắt khi vắng mặt; `{threshold, base_hours, max_hours}`, mặc định 6, 1, 24. |
|
||||
| `reasoning.effort` | Rỗng (tắt); `minimal`, `low`, `medium`, `high`, `xhigh`, `max` hoặc `none`. |
|
||||
| `reasoning.effort_by_model`| `{}`; ghi đè `reasoning.effort` theo từng mô hình. |
|
||||
|
||||
@@ -324,7 +327,7 @@ Mục `#pool` được xử lý khác hoàn toàn so với proxy tĩnh:
|
||||
| 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 |
|
||||
| Số lần thử kênh ẩn danh | Một lần ghé mỗi exit, tối đa `performance.max_anonymous_exits` exit | 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.
|
||||
|
||||
@@ -335,6 +338,8 @@ Dùng khi bản thân endpoint sau URL đã tự luân chuyển, còn từng exi
|
||||
| `retry.max_attempts` | `3` | Số lần thử cho mỗi tier có xác thực, kể cả lần đầu. |
|
||||
| `retry.timeout_seconds` | `300` | Timeout suy luận tổng, gồm cả thời gian đọc luồng. |
|
||||
| `performance.attempt_timeout_seconds` | `0` | Giới hạn cho một lần thử; 0 dùng timeout của request. |
|
||||
| `performance.max_anonymous_exits` | `8` | Số exit proxy tĩnh tối đa cho mỗi request ẩn danh. |
|
||||
| `performance.free_tier_block_seconds` | `900` | Thời gian cooldown cho exit bị tầng miễn phí đánh dấu. |
|
||||
| `performance.connect_timeout_seconds` | `5` | Timeout thiết lập kết nối. |
|
||||
| `performance.failure_cooldown_seconds` | `15` | Cooldown lỗi cơ sở. |
|
||||
| `performance.max_idle_conns` | `2048` | Giới hạn kết nối rảnh cho mỗi transport proxy. |
|
||||
|
||||
+9
-4
@@ -36,7 +36,7 @@ go build -o opencode2api ./cmd/opencode2api
|
||||
启动前编辑 `config.json`:
|
||||
|
||||
1. 将 `server_keys` 替换为自己的本地 API Key。
|
||||
2. 填入 Zen 或 Go Key;也可以设置 `anonymous: true`,并清空两个上游 Key 数组。
|
||||
2. 可选:填入 Zen 或 Go Key;示例已启用匿名通道,并清空两个上游 Key 数组。
|
||||
3. 替换 `webui.password`。示例配置启用了 WebUI,用户名为 `admin`。
|
||||
|
||||
```bash
|
||||
@@ -211,11 +211,13 @@ System One 将自由文本状态与类型化问题配对,并返回类型化答
|
||||
|
||||
路由顺序:
|
||||
|
||||
1. 符合条件的模型先尝试匿名通道,每个可用代理最多一次。
|
||||
1. 符合条件的模型最多尝试 `performance.max_anonymous_exits` 个可用匿名代理,每个代理一次;每个代理先走 v2 `/inference`,再走 v1 `/zen`。
|
||||
2. 按 `prefer` 顺序尝试认证通道,仅包含已配置 Key 且可以提供该模型的 Tier。
|
||||
3. 每个认证 Tier 分别使用 `retry.max_attempts` 预算。
|
||||
|
||||
匿名阶段不受 `retry.max_attempts` 截断,但所有阶段共享请求总超时。网络错误、认证失败、限流和服务端错误可以触发 Key 轮换;其他 4xx 会结束当前 Tier,仍可继续尝试另一个可用 Tier。
|
||||
匿名阶段不受 `retry.max_attempts` 截断,但所有阶段共享请求总超时。网络错误、认证失败、限流和服务端错误可以触发出口轮换。请求级 `400`/`413`/`422`(例如 `context_length_exceeded`)会立即结束请求:换出口或换 Tier 都无法改变请求本身。IP 级 abuse `403` 只淘汰当前出口;所有出口都被封时停止扫描,已配置的 Go Key 仍可继续服务。
|
||||
|
||||
配置 `models.anonymous_backoff` 后,连续 `threshold` 次匿名失败或所有出口都被 IP 封禁会暂停整条匿名通道 `base_hours`,之后每次再触发翻倍,直到 `max_hours`。单个非滥用 `403` 或 `429` 不会立即熔断,只计入连续失败。暂停期间不取代理、不发任何上游请求(包括模型目录刷新和可用性探测),路由直接落到认证通道。窗口到期后只允许一个请求做半开探测:成功关闭熔断并恢复匿名通道,失败则开启下一个更长的窗口。省略该配置块时熔断关闭。
|
||||
|
||||
每个 Tier 使用自己的原生协议编码请求。启用 `performance.first_event_timeout_seconds` 后,会先等待完整的 SSE data 事件再向客户端交付响应;注释心跳不算首事件。首事件前超时或断开会沿用现有 Key / 代理重试预算,交付后不再重放。默认 `0` 关闭,可对接受请求后无事件的上游尝试设置为 `15` 秒。它限制首事件而非首个文本 token,不适用于 System One;轮转别名使用独立的 `rotation.first_output_seconds`。识别到过期的 Responses reasoning 引用时,可执行一次修复重试;指定 Key 的诊断不会执行该重试。
|
||||
|
||||
@@ -268,6 +270,7 @@ Key 初始化时均衡分配到代理。真实流量可以触发代理检查、K
|
||||
| `models.refresh_seconds` | `300`;最小为 1。 |
|
||||
| `models.protocols` | `{}`;按模型 ID 覆盖原生协议。 |
|
||||
| `models.free_only` | `false`;即使配置了 Zen / Go Key,也只暴露和路由免费模型。 |
|
||||
| `models.anonymous_backoff` | 缺省关闭;`{threshold, base_hours, max_hours}`,默认 6、1、24。 |
|
||||
| `reasoning.effort` | 空(关闭);可选 `auto`、`minimal`、`low`、`medium`、`high`、`xhigh`、`max`、`none`。 |
|
||||
| `reasoning.effort_by_model` | `{}`;按模型 ID 覆盖 `reasoning.effort`。 |
|
||||
|
||||
@@ -329,7 +332,7 @@ pool+http://127.0.0.1:7891
|
||||
| 连接复用 | Keep-alive + HTTP/2 多路复用(`performance.*` 连接池参数) | 每次请求新建 TCP + CONNECT 隧道(`DisableKeepAlives`,禁用 HTTP/2) |
|
||||
| 失败冷却 | 15s–120s 指数退避,并受 `Retry-After` 影响 | 无冷却:下一次请求直接换一个新出口 IP |
|
||||
| 可用性剔除 | 标记不可用、迁移 Key、每 15 分钟复检 | 永不剔除,完全跳过健康检查 |
|
||||
| 匿名通道重试 | 每个配置的代理最多尝试一次 | 最多尝试 `retry.max_attempts` 次,循环该池条目 |
|
||||
| 匿名通道重试 | 每个出口最多访问一次,最多 `performance.max_anonymous_exits` 个出口 | 最多尝试 `retry.max_attempts` 次,循环该池条目 |
|
||||
|
||||
当 URL 背后的服务本身就在做轮换、而池内出口 IP 会被单独限流或不稳定时使用它:网关会把每次尝试都当作新出口,而不是把整个会话固定在某个出口上。只要一条 `#pool` 条目即可,无需再罗列几十个出口。静态条目仍然保留下文的连接池行为。
|
||||
|
||||
@@ -340,6 +343,8 @@ pool+http://127.0.0.1:7891
|
||||
| `retry.max_attempts` | `3` | 每个认证 Tier 的尝试次数,包含首次请求。 |
|
||||
| `retry.timeout_seconds` | `300` | 推理请求总超时,包含流式响应读取。 |
|
||||
| `performance.attempt_timeout_seconds` | `0` | 单次尝试的总超时;0 表示使用请求总超时。 |
|
||||
| `performance.max_anonymous_exits` | `8` | 每个匿名请求最多尝试的静态代理出口数。 |
|
||||
| `performance.free_tier_block_seconds` | `900` | 被免费层标记的出口冷却时长。 |
|
||||
| `performance.connect_timeout_seconds` | `5` | 建立连接的超时。 |
|
||||
| `performance.failure_cooldown_seconds` | `15` | 失败冷却基数。 |
|
||||
| `performance.max_idle_conns` | `2048` | 每个代理 Transport 的空闲连接上限。 |
|
||||
|
||||
+5
-3
@@ -1,9 +1,9 @@
|
||||
{
|
||||
"listen": "127.0.0.1:8080",
|
||||
"server_keys": ["change-this-local-key"],
|
||||
"zen_keys": ["sk-your-zen-key"],
|
||||
"zen_keys": [],
|
||||
"go_keys": [],
|
||||
"anonymous": false,
|
||||
"anonymous": true,
|
||||
"proxies": ["direct"],
|
||||
"proxyfile": "",
|
||||
"upstream": {
|
||||
@@ -28,7 +28,9 @@
|
||||
"connect_timeout_seconds": 5,
|
||||
"failure_cooldown_seconds": 15,
|
||||
"attempt_timeout_seconds": 0,
|
||||
"first_event_timeout_seconds": 0
|
||||
"first_event_timeout_seconds": 0,
|
||||
"max_anonymous_exits": 8,
|
||||
"free_tier_block_seconds": 900
|
||||
},
|
||||
"logging": {
|
||||
"level": "info",
|
||||
|
||||
@@ -100,11 +100,11 @@ type ModelsConfig struct {
|
||||
// FreeOnly limits discovery and routing to free models, even when Zen or
|
||||
// Go keys could serve paid ones. Free models may still fall back to keys.
|
||||
FreeOnly bool `json:"free_only"`
|
||||
// AnonymousBackoff configures a circuit breaker for the keyless lane: after
|
||||
// Threshold consecutive failed attempts, or immediately on a 403 or 429,
|
||||
// the lane pauses for BaseHours, doubling on every further trip up to
|
||||
// MaxHours. An absent block leaves the lane unpaused, which is the previous
|
||||
// behavior.
|
||||
// AnonymousBackoff configures a circuit breaker for the keyless lane:
|
||||
// after Threshold consecutive failed attempts, or when every exit is under
|
||||
// the free tier's IP block, the lane pauses for BaseHours, doubling on
|
||||
// every further trip up to MaxHours. An absent block leaves the lane
|
||||
// unpaused, which is the previous behavior.
|
||||
AnonymousBackoff *AnonymousBackoffConfig `json:"anonymous_backoff,omitempty"`
|
||||
}
|
||||
|
||||
@@ -171,8 +171,10 @@ type WebUIConfig struct {
|
||||
// handling: the connection pool limits (MaxConnsPerHost 0 means unlimited),
|
||||
// the dial timeout, the base cooldown after an upstream key or anonymous
|
||||
// proxy fails, and the per-attempt and first-event timeouts.
|
||||
// AttemptTimeoutSeconds 0 leaves only the request-level timeout in place, and
|
||||
// FirstEventTimeoutSeconds 0 disables the first-event wait.
|
||||
// AttemptTimeoutSeconds 0 leaves only the request-level timeout in place,
|
||||
// FirstEventTimeoutSeconds 0 disables the first-event wait, MaxAnonymousExits
|
||||
// 0 uses the built-in cap, and FreeTierBlockSeconds 0 uses the built-in
|
||||
// cool-down for an exit the free tier flagged.
|
||||
type PerformanceConfig struct {
|
||||
MaxIdleConns int `json:"max_idle_conns"`
|
||||
MaxIdleConnsPerHost int `json:"max_idle_conns_per_host"`
|
||||
@@ -182,6 +184,16 @@ type PerformanceConfig struct {
|
||||
FailureCooldownSeconds int `json:"failure_cooldown_seconds"`
|
||||
AttemptTimeoutSeconds int `json:"attempt_timeout_seconds"`
|
||||
FirstEventTimeoutSeconds int `json:"first_event_timeout_seconds"`
|
||||
// MaxAnonymousExits bounds how many distinct static proxy exits one
|
||||
// anonymous request may walk. Each exit may still try the v2 /inference
|
||||
// lane and the v1 /zen lane, so the upstream request count can be twice
|
||||
// this value; a rotating #pool entry is drawn once per retry.max_attempts
|
||||
// instead.
|
||||
MaxAnonymousExits int `json:"max_anonymous_exits"`
|
||||
// FreeTierBlockSeconds is how long an exit the free tier flagged as
|
||||
// abusive stays out of the anonymous cursor. Upstream does not publish
|
||||
// the block duration, so the default is a conservative 15 minutes.
|
||||
FreeTierBlockSeconds int `json:"free_tier_block_seconds"`
|
||||
}
|
||||
|
||||
// AttemptTimeout returns the bound for a single upstream attempt. When
|
||||
@@ -309,6 +321,12 @@ func Normalize(path string, cfg Config) (Config, error) {
|
||||
if cfg.Performance.FirstEventTimeoutSeconds < 0 || cfg.Performance.FirstEventTimeoutSeconds > 86400 {
|
||||
return Config{}, errors.New("performance.first_event_timeout_seconds must be between 0 and 86400 (0 disables the first-event timeout)")
|
||||
}
|
||||
if cfg.Performance.MaxAnonymousExits < 0 {
|
||||
return Config{}, errors.New("performance.max_anonymous_exits must not be negative (0 uses the built-in cap)")
|
||||
}
|
||||
if cfg.Performance.FreeTierBlockSeconds < 0 {
|
||||
return Config{}, errors.New("performance.free_tier_block_seconds must not be negative (0 uses the built-in cool-down)")
|
||||
}
|
||||
if cfg.Logging.Level != "debug" && cfg.Logging.Level != "info" && cfg.Logging.Level != "warn" && cfg.Logging.Level != "error" {
|
||||
return Config{}, errors.New("logging.level must be debug, info, warn, or error")
|
||||
}
|
||||
|
||||
@@ -23,6 +23,17 @@ var errFreeTierIPBlocked = errors.New("free tier blocked the egress IP")
|
||||
// two ways out.
|
||||
const freeTierBlockedMessage = "OpenCode is blocking free-model traffic from the IP this gateway leaves from, so retrying now cannot succeed. Route the request through another exit or wait for the block to expire."
|
||||
|
||||
// errAnonymousLanePaused reports that the anonymous lane's circuit breaker has
|
||||
// paused the whole lane. Unlike an upstream rejection, another exit or a retry
|
||||
// cannot succeed while the lane is paused; the caller should use an
|
||||
// authenticated tier or report the pause itself.
|
||||
var errAnonymousLanePaused = errors.New("anonymous lane paused by its circuit breaker")
|
||||
|
||||
// anonymousLanePausedMessage is what a client receives while the circuit
|
||||
// breaker holds the anonymous lane shut. It names the cause so the operator is
|
||||
// not sent looking for a credential or model problem.
|
||||
const anonymousLanePausedMessage = "The anonymous free tier is paused after repeated upstream failures. Configure an authenticated key, wait for the pause to expire, or restart the gateway after confirming the upstream block has lifted."
|
||||
|
||||
// freeTierBlockTTL keeps a blocked exit out of the anonymous cursor. Upstream
|
||||
// does not publish the block duration, so this is a conservative backoff: long
|
||||
// enough to stop the retry storm, short enough that an unblocked IP recovers
|
||||
|
||||
@@ -26,6 +26,7 @@ import (
|
||||
"time"
|
||||
|
||||
"opencode2api/internal/config"
|
||||
"opencode2api/internal/httpx"
|
||||
"opencode2api/internal/identity"
|
||||
"opencode2api/internal/jsonutil"
|
||||
"opencode2api/internal/models"
|
||||
@@ -126,6 +127,7 @@ func New(cfg config.Config, logger *slog.Logger, monitor *telemetry.Metrics) (*G
|
||||
catalog: catalog,
|
||||
monitor: monitor,
|
||||
attemptTimeout: attemptDeadline(cfg),
|
||||
freeTierBlock: time.Duration(cfg.Performance.FreeTierBlockSeconds) * time.Second,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -306,6 +308,12 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc {
|
||||
defer cancel()
|
||||
resp, upstreamRoute, err := g.doUpstream(requestCtx, route, bodies, ids)
|
||||
if err != nil {
|
||||
// The error branch never forwards the last response body, so close
|
||||
// it here; otherwise a block or a paused lane leaks one upstream
|
||||
// connection on every request.
|
||||
if resp != nil && resp.Body != nil {
|
||||
httpx.DrainAndClose(resp.Body)
|
||||
}
|
||||
finalTier := route.Tier
|
||||
if meta != nil && meta.Tier != "" {
|
||||
finalTier = config.Tier(meta.Tier)
|
||||
@@ -343,6 +351,13 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc {
|
||||
wire.WriteError(w, external, http.StatusServiceUnavailable, freeTierBlockedMessage, "free_tier_ip_blocked", ids.Request)
|
||||
return
|
||||
}
|
||||
// The anonymous lane's circuit breaker is open. Report the pause
|
||||
// distinctly so the operator does not look for a credential or a
|
||||
// model problem in the upstream error.
|
||||
if errors.Is(err, errAnonymousLanePaused) {
|
||||
wire.WriteError(w, external, http.StatusServiceUnavailable, anonymousLanePausedMessage, "free_tier_lane_paused", ids.Request)
|
||||
return
|
||||
}
|
||||
wire.WriteError(w, external, http.StatusBadGateway, "all upstream attempts failed", "upstream_error", ids.Request)
|
||||
return
|
||||
}
|
||||
|
||||
+66
-13
@@ -72,14 +72,16 @@ type anonymousNodes struct {
|
||||
next atomic.Uint64
|
||||
cooldown time.Duration
|
||||
hasPool bool
|
||||
// breaker stops the whole lane after repeated failures instead of poking
|
||||
// a flagged upstream forever: after backoff.threshold consecutive failed
|
||||
// attempts the lane pauses for backoff.base, doubling every further trip
|
||||
// (one strike per trip) up to backoff.max. A success closes the breaker.
|
||||
// breaker stops the whole lane after repeated failures or when every
|
||||
// exit is under the free tier's IP block: the lane then pauses for
|
||||
// backoff.base, doubling every further trip (one strike per trip) up to
|
||||
// backoff.max. A success closes the breaker. probing marks the single
|
||||
// half-open attempt allowed after the window expires.
|
||||
backoff anonymousBackoff
|
||||
breakerUntil atomic.Int64
|
||||
breakerStrikes atomic.Int32
|
||||
consecutive atomic.Int32
|
||||
probing atomic.Bool
|
||||
}
|
||||
|
||||
type anonymousBackoff struct {
|
||||
@@ -128,8 +130,8 @@ func (p *anonymousNodes) Len() int {
|
||||
return len(p.nodes)
|
||||
}
|
||||
|
||||
// blockedExits reports whether any exit is currently under the free tier's IP
|
||||
// block, and no exit at all is available to serve the request.
|
||||
// blockedExits reports whether every configured exit is currently under the
|
||||
// free tier's IP block, so no exit can serve the request.
|
||||
func (p *anonymousNodes) blockedExits(now time.Time) bool {
|
||||
if p == nil || len(p.nodes) == 0 {
|
||||
return false
|
||||
@@ -166,8 +168,28 @@ func (p *anonymousNodes) CursorFor(affinity string) anonymousCursor {
|
||||
return anonymousCursor{pool: p, start: start}
|
||||
}
|
||||
|
||||
// Paused reports whether the breaker currently holds the lane shut.
|
||||
func (p *anonymousNodes) Paused() bool {
|
||||
// AllowAttempt reports whether an anonymous attempt may run. An open breaker
|
||||
// refuses every attempt. Once its window expires, exactly one caller wins the
|
||||
// half-open probe, so the lane is not flooded before it is known to work
|
||||
// again; every winner must release the probe through NoteSuccess, NoteFailure,
|
||||
// NoteNeutral or ReleaseProbe.
|
||||
func (p *anonymousNodes) AllowAttempt() bool {
|
||||
if p == nil || p.backoff.threshold < 1 {
|
||||
return true
|
||||
}
|
||||
until := p.breakerUntil.Load()
|
||||
if until == 0 {
|
||||
return true
|
||||
}
|
||||
if time.Now().UnixNano() < until {
|
||||
return false
|
||||
}
|
||||
return p.probing.CompareAndSwap(false, true)
|
||||
}
|
||||
|
||||
// Open reports whether the breaker currently holds the lane shut. A half-open
|
||||
// breaker whose window has expired reports false: the lane is being probed.
|
||||
func (p *anonymousNodes) Open() bool {
|
||||
if p == nil {
|
||||
return false
|
||||
}
|
||||
@@ -175,6 +197,15 @@ func (p *anonymousNodes) Paused() bool {
|
||||
return until != 0 && time.Now().UnixNano() < until
|
||||
}
|
||||
|
||||
// ReleaseProbe returns an unused half-open probe slot. It is safe to call
|
||||
// after any outcome has already closed or reopened the breaker.
|
||||
func (p *anonymousNodes) ReleaseProbe() {
|
||||
if p == nil {
|
||||
return
|
||||
}
|
||||
p.probing.Store(false)
|
||||
}
|
||||
|
||||
// NoteSuccess closes the breaker and forgets the strikes.
|
||||
func (p *anonymousNodes) NoteSuccess() {
|
||||
if p == nil {
|
||||
@@ -183,24 +214,45 @@ func (p *anonymousNodes) NoteSuccess() {
|
||||
p.consecutive.Store(0)
|
||||
p.breakerStrikes.Store(0)
|
||||
p.breakerUntil.Store(0)
|
||||
p.probing.Store(false)
|
||||
}
|
||||
|
||||
// NoteNeutral releases a half-open probe and closes the breaker without
|
||||
// counting a strike. It is used when the upstream answered the lane but
|
||||
// rejected the request itself (for example a context-length 400): the lane is
|
||||
// reachable, so it should not stay paused, and the request is not evidence of
|
||||
// an upstream outage.
|
||||
func (p *anonymousNodes) NoteNeutral() {
|
||||
if p == nil {
|
||||
return
|
||||
}
|
||||
p.consecutive.Store(0)
|
||||
p.breakerUntil.Store(0)
|
||||
p.probing.Store(false)
|
||||
}
|
||||
|
||||
// NoteFailure records one failed attempt. It reports the pause window when the
|
||||
// consecutive-failure threshold trips the breaker.
|
||||
// consecutive-failure threshold trips the breaker. A failure during the
|
||||
// half-open probe reopens the breaker immediately with the next, longer window
|
||||
// instead of waiting for another threshold's worth of traffic.
|
||||
func (p *anonymousNodes) NoteFailure() (time.Duration, bool) {
|
||||
if p == nil || p.backoff.threshold < 1 {
|
||||
return 0, false
|
||||
}
|
||||
now := time.Now().UnixNano()
|
||||
until := p.breakerUntil.Load()
|
||||
if p.probing.Load() || (until != 0 && now >= until) {
|
||||
return p.trip()
|
||||
}
|
||||
if p.consecutive.Add(1) < p.backoff.threshold {
|
||||
return 0, false
|
||||
}
|
||||
return p.trip()
|
||||
}
|
||||
|
||||
// ForceOpen trips the breaker immediately. A 403 or 429 from the anonymous
|
||||
// upstream is a clear "blocked" signal (abuse detection, fingerprint gate or
|
||||
// region lock), and continuing to probe only extends the block, so it does
|
||||
// not wait for the consecutive-failure threshold.
|
||||
// ForceOpen trips the breaker immediately. The anonymous walk calls it when
|
||||
// every exit is under the free tier's IP block: another request cannot reach a
|
||||
// working exit, and probing would only extend the penalty.
|
||||
func (p *anonymousNodes) ForceOpen() (time.Duration, bool) {
|
||||
if p == nil || p.backoff.threshold < 1 {
|
||||
return 0, false
|
||||
@@ -217,6 +269,7 @@ func (p *anonymousNodes) trip() (time.Duration, bool) {
|
||||
pause = p.backoff.max
|
||||
}
|
||||
p.breakerUntil.Store(time.Now().Add(pause).UnixNano())
|
||||
p.probing.Store(false)
|
||||
return pause, true
|
||||
}
|
||||
|
||||
|
||||
+23
-11
@@ -88,11 +88,6 @@ func probePayload(model string, protocol wire.Protocol, effort string, v1 bool)
|
||||
// when every lane reported it; any other failure keeps the result
|
||||
// inconclusive.
|
||||
func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult {
|
||||
if g.anonymous.Paused() {
|
||||
// The breaker is open; probing now would just refresh the upstream's
|
||||
// abuse window.
|
||||
return probeResult{reason: "anonymous_paused", attempted: false}
|
||||
}
|
||||
if !g.catalog.IsFreeModel(model) {
|
||||
return probeResult{reason: "not_free"}
|
||||
}
|
||||
@@ -107,14 +102,23 @@ func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult
|
||||
client *http.Client
|
||||
}
|
||||
var lanes []lane
|
||||
anonymousPaused := false
|
||||
if g.cfg.Anonymous {
|
||||
cursor := g.anonymous.CursorFor(ids.Session)
|
||||
if node := cursor.Next(); node != nil {
|
||||
// Try the anonymous upstreams in preference order: the v2
|
||||
// /inference origin before the v1 fallback.
|
||||
for _, baseURL := range g.anonymousUpstreams() {
|
||||
lanes = append(lanes, lane{anonymousZenKey, "anonymous", baseURL, g.inferenceClient(node.proxy, baseURL, model)})
|
||||
if g.anonymous.AllowAttempt() {
|
||||
defer g.anonymous.ReleaseProbe()
|
||||
cursor := g.anonymous.CursorFor(ids.Session)
|
||||
if node := cursor.Next(); node != nil {
|
||||
// Try the anonymous upstreams in preference order: the v2
|
||||
// /inference origin before the v1 fallback.
|
||||
for _, baseURL := range g.anonymousUpstreams() {
|
||||
lanes = append(lanes, lane{anonymousZenKey, "anonymous", baseURL, g.inferenceClient(node.proxy, baseURL, model)})
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// The breaker is open, or another half-open probe is already
|
||||
// running. Skip only the anonymous lane: a configured Zen key
|
||||
// still provides an independent probe channel.
|
||||
anonymousPaused = true
|
||||
}
|
||||
}
|
||||
cursor := g.zenNodes.CursorFor(ids.Session)
|
||||
@@ -124,6 +128,9 @@ func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult
|
||||
}
|
||||
}
|
||||
result := probeResult{reason: "no_probe_channel"}
|
||||
if anonymousPaused && len(lanes) == 0 {
|
||||
result.reason = "anonymous_paused"
|
||||
}
|
||||
inconclusive := ""
|
||||
for _, lane := range lanes {
|
||||
if ctx.Err() != nil {
|
||||
@@ -134,6 +141,11 @@ func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult
|
||||
}
|
||||
result = run("")
|
||||
result.channel = lane.name
|
||||
if result.success && lane.name == "anonymous" {
|
||||
// A successful anonymous probe proves the lane answers again;
|
||||
// close the breaker so user traffic resumes immediately.
|
||||
g.anonymous.NoteSuccess()
|
||||
}
|
||||
if result.success {
|
||||
if g.cfg.ForcedEffort(model) == "auto" && protocol != wire.SystemOne {
|
||||
if !g.catalog.MetadataForTier(model, config.TierZen).Reasoning {
|
||||
|
||||
@@ -251,8 +251,16 @@ func (g *Gateway) refreshZen(ctx context.Context) []string {
|
||||
// node per attempt: one pass over the nodes, or up to retry.max_attempts
|
||||
// attempts when #pool transports exist. base only labels the logs.
|
||||
func (g *Gateway) refreshAnonymousTier(ctx context.Context, base string) []string {
|
||||
if !g.anonymous.AllowAttempt() {
|
||||
// The breaker is open, or its half-open probe is already running:
|
||||
// refreshing now would only add to the block. Keeping nil leaves the
|
||||
// previous catalog in place.
|
||||
g.logger.Debug("anonymous model catalog refresh skipped; circuit breaker is not closed", "component", "models", "event", "anonymous_refresh_paused", "upstream", config.RedactURL(base))
|
||||
return nil
|
||||
}
|
||||
defer g.anonymous.ReleaseProbe()
|
||||
cursor := g.anonymous.CursorFor("")
|
||||
limit := g.anonymous.Len()
|
||||
limit := min(g.anonymous.Len(), g.maxAnonymousExits())
|
||||
if g.anonymous.HasPool() && g.cfg.Retry.MaxAttempts > limit {
|
||||
limit = g.cfg.Retry.MaxAttempts
|
||||
}
|
||||
@@ -277,6 +285,7 @@ func (g *Gateway) refreshAnonymousTier(ctx context.Context, base string) []strin
|
||||
cancel()
|
||||
if err == nil {
|
||||
g.anonymous.MarkSuccess(node)
|
||||
g.anonymous.NoteSuccess()
|
||||
return models
|
||||
}
|
||||
g.anonymous.MarkFailure(node, nil, err)
|
||||
|
||||
@@ -230,6 +230,7 @@ func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodie
|
||||
resp, err, used := g.doSelectedKeyUpstream(ctx, route, bodies, ids, override, attemptOffset)
|
||||
return resp, route, attemptOffset + used, err
|
||||
}
|
||||
blocked := false
|
||||
if route.Anonymous {
|
||||
resp, err, used := g.doAnonymousUpstream(ctx, route, bodies, ids, attempts)
|
||||
attempts += used
|
||||
@@ -246,11 +247,12 @@ func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodie
|
||||
return lastResponse, effectiveRoute, attempts, nil
|
||||
}
|
||||
if errors.Is(err, errFreeTierIPBlocked) {
|
||||
// The free tier flagged the egress IP. A keyed tier leaves from the
|
||||
// same network and gets the same answer, so stop here instead of
|
||||
// spending attempts that only lengthen the penalty.
|
||||
g.logger.Warn("free tier blocked the egress IP; skipping the keyed tiers", "component", "upstream", "event", "free_tier_ip_blocked", "request_id", ids.Request, "attempts", attempts)
|
||||
return lastResponse, effectiveRoute, attempts, lastErr
|
||||
// The free tier flagged the egress IP. The Zen key tier uses the
|
||||
// same free gateway and gets the same answer; the Go tier is
|
||||
// authenticated and is not subject to the free-tier IP gate, so
|
||||
// keep it available below.
|
||||
blocked = true
|
||||
g.logger.Warn("free tier blocked the egress IP; skipping the Zen key tier", "component", "upstream", "event", "free_tier_ip_blocked", "request_id", ids.Request, "attempts", attempts)
|
||||
}
|
||||
if len(route.KeyTiers) > 0 {
|
||||
g.logger.Debug("anonymous request did not succeed; entering preferred key tiers", "component", "upstream", "event", "anonymous_fallback", "request_id", ids.Request, "attempts", attempts, "key_tiers", route.KeyTiers)
|
||||
@@ -274,6 +276,10 @@ func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodie
|
||||
keyTiers = []config.Tier{route.Tier}
|
||||
}
|
||||
for _, tier := range keyTiers {
|
||||
if blocked && tier == config.TierZen {
|
||||
g.logger.Debug("skipping the Zen key tier after an IP block", "component", "upstream", "event", "free_tier_ip_blocked", "request_id", ids.Request, "tier", tier)
|
||||
continue
|
||||
}
|
||||
keyRoute := route
|
||||
keyRoute.Tier = tier
|
||||
keyRoute.Anonymous = false
|
||||
@@ -306,6 +312,15 @@ func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodie
|
||||
lastErr = err
|
||||
}
|
||||
}
|
||||
if blocked {
|
||||
// The request never left the free tier's IP block: keep the block as
|
||||
// the client-facing cause even if a Go fallback also failed, and close
|
||||
// the last free-tier response whose body the handler will not forward.
|
||||
if lastResponse != nil {
|
||||
httpx.DrainAndClose(lastResponse.Body)
|
||||
}
|
||||
return nil, effectiveRoute, attempts, errFreeTierIPBlocked
|
||||
}
|
||||
if lastResponse != nil {
|
||||
return lastResponse, effectiveRoute, attempts, nil
|
||||
}
|
||||
@@ -315,40 +330,51 @@ func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodie
|
||||
return nil, effectiveRoute, attempts, lastErr
|
||||
}
|
||||
|
||||
// maxAnonymousExits caps how many static proxies one request walks. Without it
|
||||
// a request that every exit rejects (403/429) scans the whole proxy list, up to
|
||||
// two legs per exit, and can spend minutes before failing over.
|
||||
const maxAnonymousExits = 8
|
||||
// defaultMaxAnonymousExits caps how many static proxies one request walks when
|
||||
// performance.max_anonymous_exits is zero. Without a cap, a request that every
|
||||
// exit rejects (403/429) scans the whole proxy list, up to two lanes per exit,
|
||||
// and can spend minutes before failing over.
|
||||
const defaultMaxAnonymousExits = 8
|
||||
|
||||
// maxAnonymousExits returns the configured cap, or the built-in default when
|
||||
// the operator left the setting unset.
|
||||
func (g *Gateway) maxAnonymousExits() int {
|
||||
if g != nil && g.cfg.Performance.MaxAnonymousExits > 0 {
|
||||
return g.cfg.Performance.MaxAnonymousExits
|
||||
}
|
||||
return defaultMaxAnonymousExits
|
||||
}
|
||||
|
||||
// doAnonymousUpstream walks the session's anonymous proxy cursor. Each static
|
||||
// proxy is tried at most once, up to maxAnonymousExits proxies; rotating #pool
|
||||
// proxies may be drawn again until Retry.MaxAttempts proxies were used. For
|
||||
// each proxy it tries the upstreams in anonymousUpstreams order: the configured
|
||||
// v2 /inference upstream (Upstream.Anonymous) before the v1 lane
|
||||
// (models.V1Base). Any failure, including an HTTP error response, advances to
|
||||
// the next upstream or proxy; a proxy-route failure, or a proxy marked
|
||||
// unhealthy, skips that proxy's remaining upstreams. Only a successful response
|
||||
// ends the anonymous phase; exhausting the proxy cursor returns control to the
|
||||
// preferred authenticated tiers. It returns the last response (body still
|
||||
// open), else the last error, plus the number of attempts made.
|
||||
// proxy is tried at most once, up to performance.max_anonymous_exits proxies;
|
||||
// rotating #pool proxies may be drawn again until Retry.MaxAttempts proxies
|
||||
// were used. For each proxy it tries the upstreams in anonymousUpstreams
|
||||
// order: the configured v2 /inference upstream (Upstream.Anonymous) before the
|
||||
// v1 lane (models.V1Base). Any failure, including an HTTP error response,
|
||||
// advances to the next upstream or proxy; a proxy-route failure, or a proxy
|
||||
// marked unhealthy, skips that proxy's remaining upstreams. Only a successful
|
||||
// response ends the anonymous phase; exhausting the proxy cursor returns
|
||||
// control to the preferred authenticated tiers. It returns the last response
|
||||
// (body still open), else the last error, plus the number of attempts made.
|
||||
func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (*http.Response, error, int) {
|
||||
// The breaker holds the lane shut for an hour-scale window after repeated
|
||||
// failures: poking a flagged upstream again would only extend the block.
|
||||
if g.anonymous.Paused() {
|
||||
return nil, errors.New("anonymous lane paused by its circuit breaker"), 0
|
||||
if !g.anonymous.AllowAttempt() {
|
||||
return nil, errAnonymousLanePaused, 0
|
||||
}
|
||||
defer g.anonymous.ReleaseProbe()
|
||||
var lastResponse *http.Response
|
||||
var lastErr error
|
||||
// blocked records that some exit is under the free tier's IP block. The
|
||||
// result then reports errFreeTierIPBlocked even when no exit was left to
|
||||
// try, so the caller does not fall through to the keyed tiers.
|
||||
// try, so the caller can report the block instead of a generic failure.
|
||||
blocked := false
|
||||
// halted records that the upstream rejected the request itself. The result
|
||||
// then reports errDeterministicClientRejection so the caller keeps this
|
||||
// 4xx instead of replacing it with a later tier's answer.
|
||||
halted := false
|
||||
cursor := g.anonymous.CursorFor(ids.Session)
|
||||
limit := min(g.anonymous.Len(), maxAnonymousExits)
|
||||
limit := min(g.anonymous.Len(), g.maxAnonymousExits())
|
||||
if g.anonymous.HasPool() && g.cfg.Retry.MaxAttempts > limit {
|
||||
limit = g.cfg.Retry.MaxAttempts
|
||||
}
|
||||
@@ -385,7 +411,8 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
|
||||
if node == nil {
|
||||
// Nothing usable is left. If that is because every exit is under
|
||||
// the free tier's block, report the block rather than the generic
|
||||
// no-proxy error, so the keyed tiers are not entered.
|
||||
// no-proxy error, so the caller can try the authenticated Go tier
|
||||
// or answer with the block itself.
|
||||
blocked = g.anonymous.blockedExits(time.Now())
|
||||
break
|
||||
}
|
||||
@@ -469,21 +496,45 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
|
||||
break
|
||||
}
|
||||
}
|
||||
if halted {
|
||||
// A request-level rejection is identical on every exit: another
|
||||
// proxy cannot shorten the context or repair the payload. Keep the
|
||||
// response and let the caller forward it instead of sending the
|
||||
// same request through every remaining exit.
|
||||
g.anonymous.NoteNeutral()
|
||||
break
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
break
|
||||
}
|
||||
g.observeAnonymousResult(ctx, node, nodeResp, nodeErr)
|
||||
if g.anonymous.Open() {
|
||||
// This attempt tripped the breaker (or another request did):
|
||||
// continuing the walk would keep probing a lane that is now
|
||||
// paused.
|
||||
break
|
||||
}
|
||||
}
|
||||
// Every configured exit is under the same IP block: another request
|
||||
// cannot reach a working exit, so pause the lane instead of repeating the
|
||||
// 403 walk until the exit cool-downs expire.
|
||||
if blocked && g.anonymous.blockedExits(time.Now()) {
|
||||
if pause, tripped := g.anonymous.ForceOpen(); tripped {
|
||||
g.logger.Warn("anonymous lane circuit breaker opened", "component", "upstream", "event", "anonymous_breaker_open", "reason", "all_exits_blocked", "request_id", ids.Request, "paused_for", pause.String())
|
||||
}
|
||||
}
|
||||
if lastResponse != nil {
|
||||
// The caller keeps and forwards this response; a block or a
|
||||
// deterministic rejection only changes the error so the keyed tiers
|
||||
// are skipped.
|
||||
if blocked {
|
||||
return lastResponse, errFreeTierIPBlocked, attempts
|
||||
}
|
||||
// are skipped. A request-level rejection wins over a block seen on an
|
||||
// earlier exit: it is the error the client can act on, and forwarding
|
||||
// the block instead would hide the real cause.
|
||||
if halted {
|
||||
return lastResponse, errDeterministicClientRejection, attempts
|
||||
}
|
||||
if blocked {
|
||||
return lastResponse, errFreeTierIPBlocked, attempts
|
||||
}
|
||||
return lastResponse, nil, attempts
|
||||
}
|
||||
if blocked {
|
||||
@@ -1216,16 +1267,13 @@ func (g *Gateway) observeAnonymousResult(ctx context.Context, node *anonymousNod
|
||||
g.anonymous.NoteSuccess()
|
||||
} else {
|
||||
g.anonymous.MarkFailure(node, resp, err)
|
||||
var pause time.Duration
|
||||
var tripped bool
|
||||
if status == http.StatusForbidden || status == http.StatusTooManyRequests {
|
||||
// Clearly blocked: stop probing immediately instead of letting
|
||||
// further requests extend the upstream's abuse window.
|
||||
pause, tripped = g.anonymous.ForceOpen()
|
||||
} else {
|
||||
pause, tripped = g.anonymous.NoteFailure()
|
||||
if resp != nil && peekNetworkAbuseBlock(resp) {
|
||||
// An IP block is scoped to this exit; doAnonymousUpstream marks it
|
||||
// blocked and opens the lane breaker only when no exit is left.
|
||||
// Counting it here as well would stop the other exits early.
|
||||
return
|
||||
}
|
||||
if tripped {
|
||||
if pause, tripped := g.anonymous.NoteFailure(); tripped {
|
||||
g.logger.Warn("anonymous lane circuit breaker opened",
|
||||
"component", "upstream", "event", "anonymous_breaker_open", "status", status, "paused_for", pause.String())
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user