From b8b1454a0ef505d023f2e53e5193671ee7f30c13 Mon Sep 17 00:00:00 2001 From: Jason Xu Date: Sun, 25 Oct 2026 06:49:00 +0800 Subject: [PATCH] fix(warp): rotate exits on a live pool and size it to concurrency The WARP pool could never rotate: its lifetime context was derived from the startup deadline, so every standby registration and replacement died with "context canceled" and requests stayed on the first egress forever. Give the first registration the caller's deadline and the pool a context that only Close cancels. - warp.pool_size is an upper bound. The active ring follows concurrency (one exit per lease, one per queued request, plus a spare) and trims idle surplus after 60 seconds, so a burst expands it and quiet periods shrink it. - An IPv6 exit is deduplicated and cooled by its /64 for 30 minutes (IPv4 by its /32), since the free quota is scoped to that block. - 429/403 retires an exit immediately and re-registers right away; a free model request keeps switching exits and only returns the last 429 after retry.max_attempts, on both the anonymous and the Zen-key lane. 429s no longer trip the anonymous breaker or cool the key. - Pin HTTP/1.1 ALPN and TLSNextProto on the WARP transport: a clone of DefaultTransport made after its first dial negotiated h2 and fed SETTINGS frames to the HTTP/1.x reader, breaking catalog refresh. - Default to the IPv6 stack and, with warp.source_ipv6, let each exit bind its own outer source from a routed prefix via IPV6_FREEBIND. Endpoints try IPv6 first and fall back to IPv4, so IPv4-only hosts keep working. - WebUI, config example and all READMEs describe the new pool and rotation behaviour. --- README.it.md | 9 +- README.md | 9 +- README.vi.md | 9 +- README.zh-CN.md | 9 +- config.example.json | 3 +- docs/management.zh-CN.md | 3 +- internal/config/config.go | 24 ++- internal/gateway/runtime.go | 20 +- internal/gateway/warp.go | 30 ++- internal/warp/bind.go | 44 ++++ internal/warp/exit.go | 80 ++++++-- internal/warp/freebind_linux.go | 23 +++ internal/warp/freebind_other.go | 9 + internal/warp/pool.go | 345 +++++++++++++++++++++++--------- webui/index.html | 18 +- webui/js/i18n.js | 27 ++- webui/js/pages/config.js | 4 +- 17 files changed, 520 insertions(+), 146 deletions(-) create mode 100644 internal/warp/freebind_linux.go create mode 100644 internal/warp/freebind_other.go diff --git a/README.it.md b/README.it.md index 2190988..c0b65b5 100644 --- a/README.it.md +++ b/README.it.md @@ -232,7 +232,9 @@ I modelli gratuiti non richiedono una chiave Zen: con `anonymous: true` usano il Il tunnel vive nel processo del gateway: registra un dispositivo WARP, parla WireGuard su UDP con Cloudflare e termina in uno stack di rete in userspace. Non richiede dispositivi TUN, root, `NET_ADMIN` né modifiche alla tabella di routing, ma l'host o il container deve poter inviare UDP verso l'endpoint di Cloudflare (porta `2408`). Registrazione e probe del trace `warp=on` avvengono all'avvio; se WARP non riesce a inizializzarsi, l'avvio fallisce invece di ripiegare silenziosamente sui proxy. Anche l'abilitazione dalla WebUI è fail-closed: un valore errato restituisce un errore e il runtime precedente continua a servire. -`warp.pool_size` (1–8, predefinito `2`) mantiene attive altrettante uscite e sostituisce automaticamente un'uscita bloccata o guasta; `warp.stack` seleziona `ipv4` (predefinito), `ipv6` o `dual`. `/healthz` restituisce un blocco `warp` e risponde 503 quando WARP è attivo ma nessuna uscita è operativa; `no_healthy_proxies` blocca la readiness solo con WARP disattivato o quando servono proxy per le chiavi Go. Le richieste diagnostiche acquisiscono un'uscita ma non la ruotano né la penalizzano. Disattivando WARP, i canali gratuiti tornano a usare i proxy. +`warp.pool_size` (1–32, predefinito `2`) è un **limite massimo**, non un numero fisso. Il ring attivo segue la concorrenza: un'uscita per ogni richiesta in corso più una di riserva, almeno una e mai oltre il massimo configurato; le uscite in eccesso rimaste inattive per 60 secondi vengono ritirate, quindi un picco amplia il ring e la quiete lo riduce. La prima risposta 429 o 403 dell'upstream ritira subito l'uscita e ne avvia la registrazione in background (le registrazioni restano cadenzate dal limite API di 12 secondi di Cloudflare, quindi un massimo più alto si scalda più lentamente: dimensiona il valore sulla concorrenza di picco); una richiesta per modelli gratuiti continua a cambiare uscita e restituisce l'ultimo 429 al client solo dopo aver esaurito `retry.max_attempts`. `warp.stack` seleziona `ipv6` (predefinito), `ipv4` o `dual`. + +La quota gratuita dell'upstream è legata al **blocco di uscita**, quindi la rotazione serve solo se la nuova uscita proviene da un blocco diverso: un'uscita IPv6 è identificata e raffreddata per 30 minuti dal suo `/64`, una IPv4 dal suo `/32`. L'uscita IPv4 di Cloudflare WARP è di solito un unico indirizzo NAT condiviso, spesso già esaurito da altri utenti; lo stack IPv6 ricava l'uscita dall'indirizzo sorgente WireGuard esterno. Imposta `warp.source_ipv6` su un prefisso IPv6 instradato verso l'host (di solito un `/64`, lo stack predefinito è già `ipv6`) perché ogni uscita associ il proprio indirizzo sorgente da quel prefisso. Su Linux l'indirizzo viene associato con `IPV6_FREEBIND` (impostato dal gateway) oppure deve essere già assegnato a un'interfaccia. La famiglia degli endpoint non viene verificata in anticipo: l'handshake prova prima gli endpoint IPv6 e ripiega su quelli IPv4 quando nessuno risponde (in quel caso l'uscita è l'indirizzo condiviso). Lasciando vuoto il campo si usa l'indirizzo sorgente predefinito dell'host. Su reti con il pool di uscite WARP già saturo anche una nuova uscita può rispondere 429: il gateway continua a ruotare e restituisce un 429 solo esaurito il budget di tentativi. `/healthz` restituisce un blocco `warp` e risponde 503 quando WARP è attivo ma nessuna uscita è operativa; `no_healthy_proxies` blocca la readiness solo con WARP disattivato o quando servono proxy per le chiavi Go. Le richieste diagnostiche acquisiscono un'uscita ma non la ruotano né la penalizzano. Disattivando WARP, i canali gratuiti tornano a usare i proxy. ### System prompt ufficiale @@ -283,8 +285,9 @@ Consulta [config.example.json](config.example.json) per una configurazione inizi | `zen_keys`, `go_keys` | È richiesta una chiave upstream, salvo accesso anonimo abilitato. | | `anonymous` | `false`. | | `warp.enabled` | `false`; il traffico dei canali gratuiti esce via Cloudflare WARP, senza proxy. | -| `warp.pool_size` | `2`; uscite WARP attive, 1–8. | -| `warp.stack` | `ipv4`; `ipv4`, `ipv6` o `dual`. | +| `warp.pool_size` | `2`; limite massimo di uscite WARP (il ring attivo segue la concorrenza), 1–32. | +| `warp.stack` | `ipv6`; `ipv6`, `ipv4` o `dual`. | +| `warp.source_ipv6` | vuoto; prefisso IPv6 (`/64`) da cui ogni uscita associa la sorgente esterna; richiede `stack = "ipv6"`. | | `prefer` | `go`; accetta `go` o `zen`. | | `upstream.zen` | `https://opencode.ai/inference/openai`. | | `upstream.go` | `https://opencode.ai/zen/go`. | diff --git a/README.md b/README.md index 5f7bf2a..475d608 100644 --- a/README.md +++ b/README.md @@ -234,7 +234,9 @@ Free models never need a Zen key: with `anonymous: true` they are served by the The tunnel lives inside the gateway process: it registers a WARP device, speaks WireGuard over UDP to Cloudflare, and terminates in a userspace network stack. It needs no TUN device, root, `NET_ADMIN`, or routing-table change, but the host or container must be able to send UDP to Cloudflare's endpoint (port `2408`). Registration and the `warp=on` trace probe run at startup; if WARP cannot initialize, startup fails instead of silently falling back to proxies. Enabling it through the WebUI is also fail-closed: a bad value returns an error and the previous runtime keeps serving. -`warp.pool_size` (1–8, default `2`) keeps that many exits active and replaces a blocked or broken exit automatically. `warp.stack` selects `ipv4` (default), `ipv6`, or `dual`. `/healthz` reports a `warp` block and answers 503 while WARP is enabled but no exit is active; `no_healthy_proxies` only blocks readiness when WARP is off or Go keys need proxies. Diagnostics acquire an exit but never rotate or penalize it. Turning WARP off restores proxy routing for the free lanes. +`warp.pool_size` (1–32, default `2`) is an upper bound, not a fixed count. The active ring follows concurrency: one exit per in-flight lease plus a spare, at least one, and never more than the configured maximum. Surplus exits that stay idle for 60 seconds are retired, so a burst scales the ring up and a quiet period scales it back down. An exit answered with 429 or 403 is retired immediately — a free-model request keeps switching to another exit and only returns the last 429 to the client once `retry.max_attempts` is spent — and the retired exit is re-registered in the background right away (registrations remain paced by Cloudflare's 12-second API limit, so a larger maximum also warms up more slowly; size it to your peak free-model concurrency). `warp.stack` selects `ipv6` (default), `ipv4`, or `dual`. + +The upstream free quota is scoped to the egress block, so rotation only helps when a replacement leaves from a different one: an IPv6 exit is keyed and cooled by its `/64` for 30 minutes, an IPv4 exit by its `/32`. Cloudflare's WARP IPv4 egress is usually one shared NAT address, which other users routinely exhaust; the IPv6 stack gets an egress derived from the outer WireGuard source. Set `warp.source_ipv6` to an IPv6 prefix routed to the host (usually a `/64`), with the default `ipv6` stack to make every exit bind its own source address from that prefix. The prefix needs `IPV6_FREEBIND` on Linux (the gateway sets it) or addresses already assigned to an interface. Endpoint family is not probed in advance: the handshake tries IPv6 endpoints first and falls back to IPv4 ones when none answer (the exit then egresses from the shared address). Leave `source_ipv6` empty to keep the host's default source address. On networks whose WARP egress pool is saturated every fresh exit can still answer 429; the gateway then churns exits without ever surfacing a 429 before the attempt budget is spent. `/healthz` reports a `warp` block and answers 503 while WARP is enabled but no exit is active; `no_healthy_proxies` only blocks readiness when WARP is off or Go keys need proxies. Diagnostics acquire an exit but never rotate or penalize it. Turning WARP off restores proxy routing for the free lanes. ### Official system prompt @@ -285,8 +287,9 @@ See [config.example.json](config.example.json) for a complete starting configura | `zen_keys`, `go_keys` | At least one upstream key is required unless anonymous access is enabled. | | `anonymous` | `false`. | | `warp.enabled` | `false`; free-lane traffic leaves through Cloudflare WARP and no proxy. | -| `warp.pool_size` | `2`; active WARP exits, 1–8. | -| `warp.stack` | `ipv4`; `ipv4`, `ipv6`, or `dual`. | +| `warp.pool_size` | `2`; upper bound on WARP exits (the active ring follows concurrency), 1–32. | +| `warp.stack` | `ipv6`; `ipv6`, `ipv4`, or `dual`. | +| `warp.source_ipv6` | empty; IPv6 prefix (`/64`) each exit binds its outer source from; requires `stack = "ipv6"`. | | `prefer` | `go`; accepts `go` or `zen`. | | `upstream.zen` | `https://opencode.ai/zen`. | | `upstream.go` | `https://opencode.ai/zen/go`. | diff --git a/README.vi.md b/README.vi.md index 70ce3af..7344f28 100644 --- a/README.vi.md +++ b/README.vi.md @@ -238,7 +238,9 @@ Mô hình miễn phí không bao giờ cần key Zen: với `anonymous: true` ch Đường hầm chạy bên trong tiến trình gateway: đăng ký thiết bị WARP, nói WireGuard qua UDP với Cloudflare và kết thúc trong một ngăn xếp mạng userspace. Nó không cần thiết bị TUN, root, `NET_ADMIN` hay thay đổi bảng định tuyến, nhưng máy chủ hoặc container phải gửi được UDP tới endpoint của Cloudflare (cổng `2408`). Đăng ký và probe trace `warp=on` chạy lúc khởi động; nếu WARP không khởi tạo được, quá trình khởi động thất bại thay vì âm thầm quay về proxy. Bật qua WebUI cũng đóng khi lỗi: giá trị sai trả về lỗi và runtime cũ tiếp tục phục vụ. -`warp.pool_size` (1–8, mặc định `2`) giữ số đầu ra đó ở trạng thái hoạt động và tự thay thế đầu ra bị chặn hoặc hỏng; `warp.stack` chọn `ipv4` (mặc định), `ipv6` hoặc `dual`. `/healthz` trả về khối `warp` và 503 khi WARP bật nhưng không có đầu ra nào hoạt động; `no_healthy_proxies` chỉ chặn readiness khi WARP tắt hoặc có key Go cần proxy. Request chẩn đoán có lấy đầu ra nhưng không bao giờ luân chuyển hay phạt nó. Tắt WARP sẽ khôi phục định tuyến qua proxy cho các làn miễn phí. +`warp.pool_size` (1–32, mặc định `2`) là **giới hạn trên**, không phải số cố định. Vòng đầu ra hoạt động thay đổi theo mức đồng thời: một đầu ra cho mỗi request đang chạy cộng một đầu ra dự phòng, ít nhất một và không vượt quá giới hạn; các đầu ra thừa rảnh rỗi 60 giây sẽ bị thu hồi, nên lưu lượng đột biến làm vòng phình ra và lúc rảnh thì thu lại. Đầu ra nhận 429 hoặc 403 lần đầu sẽ bị loại ngay và được đăng ký lại ở nền (việc đăng ký vẫn theo nhịp API 12 giây của Cloudflare, nên giới hạn càng lớn càng lâu khởi động: hãy đặt theo mức đồng thời cao nhất của model miễn phí); request model miễn phí tiếp tục đổi đầu ra và chỉ trả 429 cuối cùng cho client sau khi dùng hết `retry.max_attempts`. `warp.stack` chọn `ipv6` (mặc định), `ipv4` hoặc `dual`. + +Hạn mức miễn phí của upstream tính theo **dải đầu ra**, nên luân chuyển chỉ có tác dụng khi đầu ra thay thế đến từ dải khác: đầu ra IPv6 được nhận diện và làm nguội theo `/64` trong 30 phút, đầu ra IPv4 theo `/32`. Đầu ra IPv4 của Cloudflare WARP thường là một địa chỉ NAT dùng chung và đã bị người dùng khác dùng hết; ngăn xếp IPv6 lấy đầu ra từ địa chỉ nguồn WireGuard bên ngoài. Đặt `warp.source_ipv6` thành tiền tố IPv6 được định tuyến tới máy chủ (thường là `/64`, stack mặc định đã là `ipv6`) để mỗi đầu ra tự bind một địa chỉ nguồn trong tiền tố đó. Trên Linux địa chỉ này được bind qua `IPV6_FREEBIND` (gateway tự đặt), hoặc phải được gán sẵn cho giao diện. Không dò trước họ địa chỉ: handshake thử các endpoint IPv6 trước và tự quay về endpoint IPv4 khi tất cả đều lỗi (khi đó đầu ra là địa chỉ dùng chung). Để trống thì dùng địa chỉ nguồn mặc định của máy chủ. Trên mạng có pool đầu ra WARP đã cạn, đầu ra mới cũng có thể trả 429: gateway vẫn tiếp tục luân chuyển và chỉ trả 429 khi hết ngân sách thử. `/healthz` trả về khối `warp` và 503 khi WARP bật nhưng không có đầu ra nào hoạt động; `no_healthy_proxies` chỉ chặn readiness khi WARP tắt hoặc có key Go cần proxy. Request chẩn đoán có lấy đầu ra nhưng không bao giờ luân chuyển hay phạt nó. Tắt WARP sẽ khôi phục định tuyến qua proxy cho các làn miễn phí. ### System prompt chính thức @@ -289,8 +291,9 @@ Xem [config.example.json](config.example.json) để có một cấu hình khở | `zen_keys`, `go_keys` | Cần ít nhất một key upstream trừ khi bật truy cập ẩn danh. | | `anonymous` | `false`. | | `warp.enabled` | `false`; lưu lượng làn miễn phí đi qua Cloudflare WARP, không dùng proxy. | -| `warp.pool_size` | `2`; số đầu ra WARP hoạt động, 1–8. | -| `warp.stack` | `ipv4`; `ipv4`, `ipv6` hoặc `dual`. | +| `warp.pool_size` | `2`; giới hạn trên số đầu ra WARP (vòng hoạt động theo mức đồng thời), 1–32. | +| `warp.stack` | `ipv6`; `ipv6`, `ipv4` hoặc `dual`. | +| `warp.source_ipv6` | rỗng; tiền tố IPv6 (`/64`) mỗi đầu ra bind nguồn bên ngoài; cần `stack = "ipv6"`. | | `prefer` | `go`; nhận `go` hoặc `zen`. | | `upstream.zen` | `https://opencode.ai/zen`. | | `upstream.go` | `https://opencode.ai/zen/go`. | diff --git a/README.zh-CN.md b/README.zh-CN.md index 3a06f3c..cc3deba 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -234,7 +234,9 @@ System One 将自由文本状态与类型化问题配对,并返回类型化答 隧道运行在网关进程内:注册 WARP 设备,通过 UDP 与 Cloudflare 建立 WireGuard 连接,并在用户态网络栈中终结。它不需要 TUN 设备、root、`NET_ADMIN` 或修改路由表,但宿主机(或容器)必须能向 Cloudflare 端点发送 UDP(端口 `2408`)。注册与 `warp=on` 的 trace 探测在启动时完成;WARP 无法初始化时启动直接失败,不会静默回退到代理。通过 WebUI 启用同样采用失败即拒绝:参数错误会返回错误,旧运行时继续服务。 -`warp.pool_size`(1–8,默认 `2`)保持相应数量的出口可用,并在出口被封锁或损坏时自动替换;`warp.stack` 可选 `ipv4`(默认)、`ipv6` 或 `dual`。`/healthz` 会返回 `warp` 状态块;启用 WARP 但没有任何活跃出口时返回 503。只有 WARP 关闭或存在 Go Key 需要代理时,`no_healthy_proxies` 才会阻塞就绪。诊断请求会占用出口,但不会轮换或淘汰它。关闭 WARP 后,免费通道恢复使用代理。 +`warp.pool_size`(1–32,默认 `2`)是**上限**而不是固定数量。活跃出口按并发动态调整:每个在途请求一个出口,另加一个备用,最少 1 个、最多不超过配置上限;空闲 60 秒的多余出口会被回收,因此突发流量会把出口环撑大,空闲后再缩回。出口第一次收到上游 429 或 403 即被淘汰并立刻在后台重新注册(注册仍受 Cloudflare 12 秒的 API 节奏限制,上限越大预热越慢,应按免费模型的并发峰值设置);免费模型请求会持续切换到其他出口,直到用完 `retry.max_attempts` 次才把最后一个 429 返回客户端。`warp.stack` 默认 `ipv6`,可选 `ipv4` 或 `dual`。 + +上游的免费额度按**出口网段**计算,所以只有替换出口能拿到不同网段时轮换才有意义:IPv6 出口按 `/64` 去重并冷却 30 分钟,IPv4 出口按 `/32`。Cloudflare WARP 的 IPv4 出口通常是同一个共享 NAT 地址,常被其他用户用尽;IPv6 网络栈的出口则由外层 WireGuard 源地址决定。把 `warp.source_ipv6` 设为路由到本机的 IPv6 前缀(通常是 `/64`,`warp.stack` 默认已是 `ipv6`),每个出口就会从该前缀绑定自己的源地址。Linux 下该地址通过 `IPV6_FREEBIND` 绑定(网关已自动设置),或要求地址已分配到网卡。不会预先探测地址族:握手先尝试 IPv6 端点,全部失败时自动回退到 IPv4 端点(此时出口为共享地址)。留空则共用本机默认源地址。某些网络的 WARP 出口池本身已被用尽,此时每个新出口也会返回 429,网关会持续轮换出口,但仍会在尝试次数用尽后返回 429。`/healthz` 会返回 `warp` 状态块;启用 WARP 但没有任何活跃出口时返回 503。只有 WARP 关闭或存在 Go Key 需要代理时,`no_healthy_proxies` 才会阻塞就绪。诊断请求会占用出口,但不会轮换或淘汰它。关闭 WARP 后,免费通道恢复使用代理。 ### 官方系统提示词 @@ -285,8 +287,9 @@ Key 初始化时均衡分配到代理。真实流量可以触发代理检查、K | `zen_keys`、`go_keys` | 未启用匿名模式时,至少需要一个上游 Key。 | | `anonymous` | `false`。 | | `warp.enabled` | `false`;免费通道流量通过 Cloudflare WARP 出口,不使用代理。 | -| `warp.pool_size` | `2`;活跃 WARP 出口数量,1–8。 | -| `warp.stack` | `ipv4`;可选 `ipv4`、`ipv6`、`dual`。 | +| `warp.pool_size` | `2`;WARP 出口上限(活跃出口按并发动态调整),1–32。 | +| `warp.stack` | `ipv6`;可选 `ipv6`、`ipv4`、`dual`。 | +| `warp.source_ipv6` | 空;每个出口绑定的外层 IPv6 源前缀(`/64`),要求 `stack = "ipv6"`。 | | `prefer` | `go`;可选 `go`、`zen`。 | | `upstream.zen` | `https://opencode.ai/zen`。 | | `upstream.go` | `https://opencode.ai/zen/go`。 | diff --git a/config.example.json b/config.example.json index 3528a1d..f768d1c 100644 --- a/config.example.json +++ b/config.example.json @@ -7,7 +7,8 @@ "warp": { "enabled": false, "pool_size": 2, - "stack": "ipv4" + "stack": "ipv6", + "source_ipv6": "" }, "proxies": ["direct"], "proxyfile": "", diff --git a/docs/management.zh-CN.md b/docs/management.zh-CN.md index 7a1a663..bcdaa2e 100644 --- a/docs/management.zh-CN.md +++ b/docs/management.zh-CN.md @@ -29,9 +29,10 @@ ## WARP 免费模型出口 -WebUI「Proxy 节点」页底部新增 WARP 开关,对应配置 `warp.enabled`(默认关闭)、`warp.pool_size`(1–8,默认 2)和 `warp.stack`(`ipv4`、`ipv6` 或 `dual`)。开启后,匿名通道、免费模型的 Zen Key 回退、免费模型可用性探测和匿名模型目录刷新都通过用户态 Cloudflare WARP 出网,不再使用任何代理;Go 套餐 Key 与付费模型保持原有代理绑定。 +WebUI「Proxy 节点」页底部新增 WARP 开关,对应配置 `warp.enabled`(默认关闭)、`warp.pool_size`(1–32,默认 2;出口数量上限,活跃出口按并发动态调整)、`warp.stack`(默认 `ipv6`,可选 `ipv4` 或 `dual`)和 `warp.source_ipv6`(外层 IPv6 源前缀,需配合 `stack = "ipv6"`)。开启后,匿名通道、免费模型的 Zen Key 回退、免费模型可用性探测和匿名模型目录刷新都通过用户态 Cloudflare WARP 出网,不再使用任何代理;Go 套餐 Key 与付费模型保持原有代理绑定。 - 主机或容器必须能向 Cloudflare 端点发送 UDP(端口 `2408`);不需要 TUN 设备、root、`NET_ADMIN` 或修改路由表。 +- 出口第一次收到上游 429/403 即被淘汰并立刻在后台重新注册;免费模型请求会持续切换到其他出口,用完 `retry.max_attempts` 次后才把最后一个 429 返回客户端。活跃出口数按并发动态调整(每个在途请求一个,另留一个备用,上限为 `warp.pool_size`),空闲 60 秒的多余出口自动回收。免费额度按出口网段计算:IPv6 出口按 `/64`、IPv4 出口按 `/32` 去重并冷却 30 分钟。Cloudflare WARP 的共享 IPv4 出口通常已被用尽,`warp.stack` 默认 `ipv6`,配合 `warp.source_ipv6`(路由到本机的 `/64`,Linux 下通过 `IPV6_FREEBIND` 绑定)让每个出口使用独立源地址时,替换出口才会获得新的公网地址。 - WARP 无法初始化时启动直接失败;通过 WebUI 启用时参数错误会返回错误,旧运行时继续服务,不会静默回退到代理。 - `/healthz` 的 `warp` 块与 `/api/monitor` 的 `resources.warp` 显示堆栈、出口数量、活跃/备用/冷却数量和出口地址;启用 WARP 但无活跃出口时健康检查返回 503,此时若没有 Go Key,`no_healthy_proxies` 不再阻塞就绪。 diff --git a/internal/config/config.go b/internal/config/config.go index c9f581f..0e0c216 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "fmt" + "net/netip" "net/url" "os" "strings" @@ -75,6 +76,11 @@ type WarpConfig struct { Enabled bool `json:"enabled"` PoolSize int `json:"pool_size,omitempty"` Stack string `json:"stack,omitempty"` + // SourceIPv6 is an outer IPv6 prefix (usually a routed /64) each WARP exit + // binds its WireGuard socket to. Rotating the source is what gives a + // replacement exit a new public egress; without it, exits share one + // address and an egress-scoped free quota stays exhausted. + SourceIPv6 string `json:"source_ipv6,omitempty"` } // Normalize fills the defaults and canonicalizes the stack name. @@ -90,8 +96,22 @@ func (w *WarpConfig) Normalize() error { return fmt.Errorf("warp.stack: %w", err) } w.Stack = string(stack) - if w.PoolSize < 1 || w.PoolSize > 8 { - return errors.New("warp.pool_size must be between 1 and 8") + if w.PoolSize < 1 || w.PoolSize > 32 { + return errors.New("warp.pool_size must be between 1 and 32") + } + w.SourceIPv6 = strings.TrimSpace(w.SourceIPv6) + if w.SourceIPv6 != "" { + prefix, err := netip.ParsePrefix(w.SourceIPv6) + if err != nil || !prefix.Addr().Is6() || prefix.Addr().Is4In6() { + return fmt.Errorf("warp.source_ipv6: %q is not an IPv6 prefix", w.SourceIPv6) + } + if prefix.Bits() > 64 { + return fmt.Errorf("warp.source_ipv6: %s must be /64 or shorter", prefix) + } + if stack != warp.StackIPv6 { + return errors.New("warp.source_ipv6 requires warp.stack to be \"ipv6\"; an IPv4 stack cannot present an IPv6 egress") + } + w.SourceIPv6 = prefix.Masked().String() } return nil } diff --git a/internal/gateway/runtime.go b/internal/gateway/runtime.go index 0b9ee17..34f9722 100644 --- a/internal/gateway/runtime.go +++ b/internal/gateway/runtime.go @@ -5,6 +5,7 @@ import ( "fmt" "log/slog" "net/http" + "net/netip" "os" "sync" "sync/atomic" @@ -216,24 +217,33 @@ func (m *RuntimeController) build(cfg config.Config) (*gatewayRuntime, error) { } // selectWARP returns the WARP pool a runtime built for cfg must use. A pool -// with the same size and stack is shared across runtimes; creating a new one -// registers its first exit synchronously, so enabling WARP fails closed when -// Cloudflare cannot be reached. A disabled configuration returns no pool. +// with the same size, stack and outer source prefix is shared across runtimes; +// creating a new one registers its first exit synchronously, so enabling WARP +// fails closed when Cloudflare cannot be reached. A disabled configuration +// returns no pool. func (m *RuntimeController) selectWARP(cfg config.Config) (*warp.Pool, string, bool, error) { if !cfg.Warp.Enabled { return nil, "", false, nil } - key := fmt.Sprintf("%d|%s", cfg.Warp.PoolSize, cfg.Warp.Stack) + key := fmt.Sprintf("%d|%s|%s", cfg.Warp.PoolSize, cfg.Warp.Stack, cfg.Warp.SourceIPv6) if m.warpPool != nil && m.warpKey == key { return m.warpPool, key, false, nil } + var source netip.Prefix + if cfg.Warp.SourceIPv6 != "" { + prefix, err := netip.ParsePrefix(cfg.Warp.SourceIPv6) + if err != nil { + return nil, "", false, fmt.Errorf("initialize WARP egress: warp.source_ipv6: %w", err) + } + source = prefix.Masked() + } timeout := time.Duration(cfg.Retry.TimeoutSeconds) * time.Second if timeout <= 0 || timeout > 2*time.Minute { timeout = 2 * time.Minute } ctx, cancel := context.WithTimeout(m.root, timeout) defer cancel() - pool, err := warp.NewWithStack(ctx, m.logger, cfg.Warp.PoolSize, warp.Stack(cfg.Warp.Stack)) + pool, err := warp.NewWithOptions(ctx, m.logger, warp.Options{Size: cfg.Warp.PoolSize, Stack: warp.Stack(cfg.Warp.Stack), SourceIPv6: source}) if err != nil { return nil, "", false, fmt.Errorf("initialize WARP egress: %w", err) } diff --git a/internal/gateway/warp.go b/internal/gateway/warp.go index f31d475..f9b96f3 100644 --- a/internal/gateway/warp.go +++ b/internal/gateway/warp.go @@ -2,6 +2,7 @@ package gateway import ( "context" + "crypto/tls" "errors" "fmt" "io" @@ -67,6 +68,19 @@ func (g *Gateway) newWarpLease(lease *warp.Lease, useBun bool) (*warpLease, erro transport.Proxy = nil transport.DialContext = dial transport.ForceAttemptHTTP2 = false + // A clone of DefaultTransport made after its first dial inherits the + // configured HTTP/2 ALPN and TLSNextProto map, so the transport negotiates + // h2 and then hands SETTINGS frames to the HTTP/1.x reader ("malformed HTTP + // response"). Every WARP attempt must speak HTTP/1.1 over a fresh tunnel, + // so pin the ALPN and disable the h2 wiring explicitly. + transport.TLSNextProto = make(map[string]func(authority string, c *tls.Conn) http.RoundTripper) + if transport.TLSClientConfig == nil { + transport.TLSClientConfig = &tls.Config{NextProtos: []string{"http/1.1"}} + } else { + tlsCfg := transport.TLSClientConfig.Clone() + tlsCfg.NextProtos = []string{"http/1.1"} + transport.TLSClientConfig = tlsCfg + } transport.MaxIdleConns = perf.MaxIdleConns transport.MaxIdleConnsPerHost = perf.MaxIdleConnsPerHost transport.MaxConnsPerHost = perf.MaxConnsPerHost @@ -224,7 +238,13 @@ func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Rout for index, baseURL := range upstreams { prepared[index], renames[index] = prepareAnonymousBody(rawBody, protocol, models.IsV1Upstream(baseURL)) } - limit := max(g.cfg.Retry.MaxAttempts, g.warp.Size()+1) + // A 429 is scoped to the exit that carried it, so the request keeps + // rotating exits until the configured attempt budget is spent; only then + // does the last 429 reach the client. + limit := g.cfg.Retry.MaxAttempts + if limit < 1 { + limit = 1 + } firstEventTimeout := time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds) * time.Second var lastResponse *http.Response var lastErr error @@ -301,7 +321,7 @@ func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Rout if halted || ctx.Err() != nil { break } - if !leaseBlocked { + if !leaseBlocked && upstreamStatus(lastResponse) != http.StatusTooManyRequests { if pause, tripped := g.anonymous.NoteFailure(); tripped { g.logger.Warn("anonymous lane circuit breaker opened", "component", "upstream", "event", "anonymous_breaker_open", "status", upstreamStatus(lastResponse), "paused_for", pause.String()) break @@ -344,5 +364,11 @@ func (g *Gateway) observeKeyResultWARP(ctx context.Context, nodes *upstreamNodes // never judged this key. The pool already retired the exit. return } + // A 429 or a network-abuse 403 is scoped to the WARP exit, which the pool + // has just retired; holding it against the key would stop a single-key + // rotation after the first attempt instead of retrying on a fresh exit. + if resp != nil && (resp.StatusCode == http.StatusTooManyRequests || peekNetworkAbuseBlock(resp)) { + return + } nodes.MarkFailure(node, resp, err) } diff --git a/internal/warp/bind.go b/internal/warp/bind.go index 36e54ce..135f659 100644 --- a/internal/warp/bind.go +++ b/internal/warp/bind.go @@ -1,9 +1,12 @@ package warp import ( + "context" "errors" + "fmt" "net" "net/netip" + "strconv" "sync" "golang.zx2c4.com/wireguard/conn" @@ -13,6 +16,7 @@ type simpleBind struct { mu sync.Mutex ipv4 *net.UDPConn ipv6 *net.UDPConn + source netip.Addr closed bool } @@ -27,6 +31,23 @@ func (b *simpleBind) Open(port uint16) ([]conn.ReceiveFunc, uint16, error) { return nil, 0, conn.ErrBindAlreadyOpen } b.closed = false + if b.source.IsValid() { + v6, err := b.listenIPv6(port) + if err != nil { + return nil, 0, err + } + port = uint16(v6.LocalAddr().(*net.UDPAddr).Port) + // Keep an IPv4 socket as well: if no IPv6 endpoint answers, the + // handshake falls back to IPv4 and the tunnel still comes up. + v4, _ := net.ListenUDP("udp4", &net.UDPAddr{Port: int(port)}) + var receives []conn.ReceiveFunc + if v4 != nil { + receives = append(receives, receiveUDP(v4)) + } + receives = append(receives, receiveUDP(v6)) + b.ipv4, b.ipv6 = v4, v6 + return receives, port, nil + } var v4, v6 *net.UDPConn var err error if port == 0 { @@ -70,6 +91,25 @@ func receiveUDP(udp *net.UDPConn) conn.ReceiveFunc { } } +// listenIPv6 opens the WireGuard socket bound to the exit's outer source +// address. Every packet — handshake and data — leaves from that address, so a +// replacement exit presents Cloudflare with a new source and receives a new +// public egress. +func (b *simpleBind) listenIPv6(port uint16) (*net.UDPConn, error) { + address := net.JoinHostPort(b.source.String(), strconv.Itoa(int(port))) + config := net.ListenConfig{Control: freebindControl} + packet, err := config.ListenPacket(context.Background(), "udp6", address) + if err != nil { + return nil, fmt.Errorf("bind WARP outer source %s: %w", b.source, err) + } + conn, ok := packet.(*net.UDPConn) + if !ok { + packet.Close() + return nil, fmt.Errorf("bind WARP outer source %s: unexpected connection %T", b.source, packet) + } + return conn, nil +} + func (b *simpleBind) Close() error { b.mu.Lock() defer b.mu.Unlock() @@ -104,8 +144,12 @@ func (b *simpleBind) Send(bufs [][]byte, endpoint conn.Endpoint) error { udp = b.ipv6 } closed := b.closed + source := b.source b.mu.Unlock() if closed || udp == nil { + if !closed && source.IsValid() && ep.addr.Addr().Is4() { + return fmt.Errorf("WARP exit bound to outer source %s cannot reach IPv4 endpoint %s", source, ep.addr) + } return net.ErrClosed } for _, buf := range bufs { diff --git a/internal/warp/exit.go b/internal/warp/exit.go index de95c94..9f65ea0 100644 --- a/internal/warp/exit.go +++ b/internal/warp/exit.go @@ -19,8 +19,6 @@ import ( "golang.zx2c4.com/wireguard/tun/netstack" ) -const rateLimitWindow = 10 - const ( probeTimeout = 5 * time.Second probeCandidates = 10 @@ -33,7 +31,12 @@ const ( StackIPv6 Stack = "ipv6" StackDual Stack = "dual" - DefaultStack = StackIPv4 + // DefaultStack is IPv6: a WARP IPv4 egress is a public address shared by + // every user behind Cloudflare's NAT, so the upstream's per-address free + // quota is usually already spent, while the IPv6 egress belongs to the + // tunnel. The handshake still falls back to IPv4 endpoints when IPv6 does + // not answer, so an IPv4-only host keeps working without extra settings. + DefaultStack = StackIPv6 ) var ( @@ -67,15 +70,18 @@ type exit struct { retired bool closed bool penalized bool - recent []int closeOnce sync.Once } func newExit(ctx context.Context, reg registration) (*exit, error) { - return newExitWithStack(ctx, reg, DefaultStack) + return newExitWithStack(ctx, reg, DefaultStack, netip.Addr{}) } -func newExitWithStack(ctx context.Context, reg registration, stack Stack) (*exit, error) { +// newExitWithStack builds one userspace tunnel for reg. A valid source pins +// the outer WireGuard socket to that address and restricts the peer endpoints +// to IPv6, so the public egress is derived from the rotating source rather than +// from whatever address the host happens to share. +func newExitWithStack(ctx context.Context, reg registration, stack Stack, source netip.Addr) (*exit, error) { normalized, err := ParseStack(string(stack)) if err != nil { return nil, err @@ -129,7 +135,14 @@ func newExitWithStack(ctx context.Context, reg registration, stack Stack) (*exit tunDevice.Close() return nil, err } - wg := device.NewDevice(tunDevice, &simpleBind{}, device.NewLogger(device.LogLevelError, "warp: ")) + if source.IsValid() { + // Try IPv6 endpoints first so the rotating source is used, but keep + // the IPv4 ones behind them: a host (or network) that cannot reach + // Cloudflare over IPv6 still gets a working tunnel, just with the + // shared address the prefix was supposed to avoid. + endpoints = preferIPv6Endpoints(endpoints) + } + wg := device.NewDevice(tunDevice, &simpleBind{source: source}, device.NewLogger(device.LogLevelError, "warp: ")) uapi := fmt.Sprintf( "private_key=%s\npublic_key=%s\nallowed_ip=0.0.0.0/0\nallowed_ip=::/0\nendpoint=%s\npersistent_keepalive_interval=25\n", privateKey, peerKey, endpoints[0], @@ -154,6 +167,30 @@ func newExitWithStack(ctx context.Context, reg registration, stack Stack) (*exit return e, nil } +// preferIPv6Endpoints returns endpoints with the IPv6 ones first and the IPv4 +// ones after them, both in their original order. Nothing is dropped: an IPv4 +// fallback keeps WARP usable on a host that cannot reach Cloudflare over IPv6. +func preferIPv6Endpoints(endpoints []string) []string { + ordered := make([]string, 0, len(endpoints)) + ipv4 := make([]string, 0, len(endpoints)) + for _, endpoint := range endpoints { + host, _, err := net.SplitHostPort(endpoint) + if err != nil { + continue + } + addr, err := netip.ParseAddr(host) + if err != nil || addr.Is4In6() { + continue + } + if addr.Is6() { + ordered = append(ordered, endpoint) + } else { + ipv4 = append(ipv4, endpoint) + } + } + return append(ordered, ipv4...) +} + func resolveEndpoints(ctx context.Context, candidates []string, fallback string) ([]string, error) { if len(candidates) == 0 && fallback != "" { candidates = []string{fallback} @@ -389,24 +426,18 @@ func (e *exit) observe(status int, body []byte) (bool, string) { return false, "" } if status == http.StatusForbidden { - e.recent = e.recent[:0] reason := "HTTP 403" if networkAnomaly(body) { reason += " network anomaly" } return true, reason } - if status != http.StatusTooManyRequests { - e.recent = e.recent[:0] - return false, "" - } - e.recent = append(e.recent, status) - if len(e.recent) > rateLimitWindow { - e.recent = e.recent[len(e.recent)-rateLimitWindow:] - } - if len(e.recent) == rateLimitWindow { - e.recent = e.recent[:0] - return true, fmt.Sprintf("%d consecutive HTTP 429 responses", rateLimitWindow) + // A free-tier 429 is scoped to the egress address, not to the request, the + // key or the session: retrying the same exit repeats it. Replace the exit + // on the first one, as the instant-rotate deployment does, so the retry + // draws a fresh outer source and a new public egress. + if status == http.StatusTooManyRequests { + return true, "HTTP 429" } return false, "" } @@ -481,5 +512,16 @@ func (e *exit) egressKey() string { if !e.egress.Is6() { return "" } + // The free tier treats a Cloudflare /64 as one quota scope: rotating inside + // the same /64 yields a new /128 but the same exhausted quota. Keying on + // the /64 keeps every active and cooling exit on a distinct scope, so a + // replacement is a real rotation rather than a cosmetic address change. return netip.PrefixFrom(e.egress, 64).Masked().String() } + +// idle reports whether no lease currently holds this exit. +func (e *exit) idle() bool { + e.mu.Lock() + defer e.mu.Unlock() + return e.refs == 0 && !e.retired && !e.closed +} diff --git a/internal/warp/freebind_linux.go b/internal/warp/freebind_linux.go new file mode 100644 index 0000000..dd9db37 --- /dev/null +++ b/internal/warp/freebind_linux.go @@ -0,0 +1,23 @@ +//go:build linux + +package warp + +import "syscall" + +// ipv6FREEBIND is IPV6_FREEBIND (Linux 2.6.22+), which lets a socket bind an +// IPv6 source address that is routed to this host but not assigned to an +// interface. golang.org/x/sys/unix does not export the constant yet. +const ipv6FREEBIND = 78 + +// freebindControl permits binding an outer source address from the configured +// prefix. Without it the kernel refuses every address the host did not assign +// to an interface, which is the normal case for a routed /64. +func freebindControl(_, _ string, raw syscall.RawConn) error { + var sockErr error + if err := raw.Control(func(fd uintptr) { + sockErr = syscall.SetsockoptInt(int(fd), syscall.IPPROTO_IPV6, ipv6FREEBIND, 1) + }); err != nil { + return err + } + return sockErr +} diff --git a/internal/warp/freebind_other.go b/internal/warp/freebind_other.go new file mode 100644 index 0000000..174a6d7 --- /dev/null +++ b/internal/warp/freebind_other.go @@ -0,0 +1,9 @@ +//go:build !linux + +package warp + +import "syscall" + +// freebindControl is a no-op outside Linux: the configured source address must +// already be assigned to an interface. +func freebindControl(_, _ string, _ syscall.RawConn) error { return nil } diff --git a/internal/warp/pool.go b/internal/warp/pool.go index 9233cc8..d35881f 100644 --- a/internal/warp/pool.go +++ b/internal/warp/pool.go @@ -2,17 +2,31 @@ package warp import ( "context" + "crypto/rand" "errors" "fmt" "log/slog" "net" + "net/netip" "sync" "time" ) const DefaultPoolSize = 2 -const egressCooldown = 10 * time.Minute +// egressCooldown keeps a public /64 (or IPv4 /32) that the upstream has +// rejected out of the pool for this long. The free tier scopes its quota to +// that block, so a new tunnel inside it would only repeat the same answer. +const egressCooldown = 30 * time.Minute + +// refillRetryDelay spaces out a failed registration attempt. A successful +// attempt is only limited by the registrar's own 12-second pacing. +const refillRetryDelay = 5 * time.Second + +// scaleDownDelay keeps exits created for a burst hot for a while after the +// burst, so a following burst reuses them instead of paying for new +// registrations. +const scaleDownDelay = 60 * time.Second // ErrClosed is returned when a pool is used after Close. Callers use it to // tell a retiring pool apart from a temporary capacity wait. @@ -62,42 +76,67 @@ type Pool struct { stack Stack newExit func(context.Context) (*exit, error) - mu sync.Mutex - active []*exit - standby []*exit - activeTarget int - standbyTarget int - next int - reserved map[string]bool - cooling map[string]time.Time - changed chan struct{} - closed bool - refilling bool - wait sync.WaitGroup - createMu sync.Mutex + mu sync.Mutex + active []*exit + inflight int + waiting int + next int + reserved map[string]bool + cooling map[string]time.Time + changed chan struct{} + closed bool + refilling bool + scaling bool + wait sync.WaitGroup + createMu sync.Mutex } type Lease struct { + pool *Pool exit *exit once sync.Once } // Snapshot is a point-in-time view of a pool for health and admin reporting. type Snapshot struct { - Stack string - Size int + Stack string + Size int + // Active is the number of exits currently in the ring. Standby counts the + // idle part of it: exits not held by a lease and ready to replace a + // penalized one immediately. Active int Standby int Cooling int Egress []string } -// NewWithStack creates a WARP pool whose exits use the selected IP stack. -func NewWithStack(ctx context.Context, log *slog.Logger, size int, stack Stack) (*Pool, error) { - normalized, err := ParseStack(string(stack)) +// Options configure a WARP pool. +type Options struct { + // Size is the upper bound on exits. The pool keeps as many exits hot as + // the current concurrency needs (leases in flight plus queued requests, + // plus a spare) and never exceeds Size. + Size int + // Stack selects the address family inside the tunnel. An IPv6 stack makes + // the public egress an IPv6 address. + Stack Stack + // SourceIPv6, when valid, is the outer IPv6 prefix each exit binds its + // WireGuard socket to. Every exit draws its own address from it, so a + // replacement reaches Cloudflare from a new source and receives a new + // public egress — the only way past an egress-scoped free usage limit. + SourceIPv6 netip.Prefix +} + +// NewWithOptions creates a WARP pool whose exits use the selected IP stack and, +// optionally, rotate their outer IPv6 source within a prefix. +func NewWithOptions(ctx context.Context, log *slog.Logger, opts Options) (*Pool, error) { + normalized, err := ParseStack(string(opts.Stack)) if err != nil { return nil, err } + if opts.SourceIPv6.IsValid() && (!opts.SourceIPv6.Addr().Is6() || opts.SourceIPv6.Bits() > 64) { + return nil, fmt.Errorf("WARP outer source must be an IPv6 prefix of /64 or shorter, got %s", opts.SourceIPv6) + } + size := opts.Size if size <= 0 { size = DefaultPoolSize } @@ -107,7 +146,14 @@ func NewWithStack(ctx context.Context, log *slog.Logger, size int, stack Stack) if err != nil { return nil, err } - return newExitWithStack(ctx, reg, normalized) + var source netip.Addr + if opts.SourceIPv6.IsValid() { + source, err = randomSource(opts.SourceIPv6) + if err != nil { + return nil, err + } + } + return newExitWithStack(ctx, reg, normalized, source) }) if err != nil { return nil, err @@ -116,37 +162,77 @@ func NewWithStack(ctx context.Context, log *slog.Logger, size int, stack Stack) return pool, nil } +// randomSource draws one host address from prefix. The bits above the prefix +// length are kept, every bit below is random, so two exits practically never +// share an outer source. +func randomSource(prefix netip.Prefix) (netip.Addr, error) { + address := prefix.Masked().Addr().As16() + var noise [16]byte + if _, err := rand.Read(noise[:]); err != nil { + return netip.Addr{}, fmt.Errorf("draw WARP outer source: %w", err) + } + keep := prefix.Bits() + for index := range address { + switch bits := keep - index*8; { + case bits >= 8: + case bits <= 0: + address[index] = noise[index] + default: + mask := byte(0xFF) << (8 - bits) + address[index] = address[index]&mask | noise[index]&^mask + } + } + return netip.AddrFrom16(address), nil +} + func newPool(ctx context.Context, log logger, size int, create func(context.Context) (*exit, error)) (*Pool, error) { if size <= 0 { size = DefaultPoolSize } - poolCtx, cancel := context.WithCancel(ctx) - activeTarget, standbyTarget := poolTargets(size) + // The caller's context bounds the synchronous first registration, not the + // pool: it is typically an initialization deadline that expires moments + // after NewWithOptions returns. Deriving the pool lifetime from it would + // cancel every later refill and replacement with "context canceled", + // leaving the pool stuck on its first egress forever. + poolCtx, cancel := context.WithCancel(context.WithoutCancel(ctx)) p := &Pool{ - ctx: poolCtx, - cancel: cancel, - logger: log, - size: size, - activeTarget: activeTarget, - standbyTarget: standbyTarget, - newExit: create, - reserved: make(map[string]bool), - cooling: make(map[string]time.Time), - changed: make(chan struct{}), + ctx: poolCtx, + cancel: cancel, + logger: log, + size: size, + newExit: create, + reserved: make(map[string]bool), + cooling: make(map[string]time.Time), + changed: make(chan struct{}), } - first, err := p.createExit(poolCtx) + first, err := p.createExit(ctx) if err != nil { cancel() return nil, err } p.active = []*exit{first} if log != nil { - log.Infof("OpenCode WARP/%s egress %s ready at %s (active target %d, standby target %d)", first.stack, first.id, first.egress, activeTarget, standbyTarget) + log.Infof("OpenCode WARP/%s pool ready (max %d exits, one spare)", first.stack, size) } p.startRefill() return p, nil } +// desiredLocked is the number of exits the pool should keep hot: one per +// in-flight lease, one for every request waiting for an exit, plus a spare, so +// a 429 can switch to a ready exit instead of waiting for a registration. Size +// is the upper bound; at idle a pool of two or more keeps one spare. +func (p *Pool) desiredLocked() int { + want := p.inflight + p.waiting + 1 + if want < 2 { + want = 2 + } + if want > p.size { + want = p.size + } + return want +} + func (p *Pool) Acquire(ctx context.Context) (*Lease, error) { for { p.mu.Lock() @@ -159,19 +245,35 @@ func (p *Pool) Acquire(ctx context.Context) (*Lease, error) { p.next = (p.next + 1) % len(p.active) active := p.active[index] if active.addRef() { + p.inflight++ p.mu.Unlock() - return &Lease{exit: active}, nil + // Demand just rose: grow the ring toward it in the background. + p.startRefill() + return &Lease{pool: p, exit: active}, nil } } + p.waiting++ changed := p.changed + needRefill := len(p.active) < p.desiredLocked() p.mu.Unlock() + if needRefill { + // Queued demand is demand too: start growing before we block. + p.startRefill() + } + var err error select { case <-ctx.Done(): - return nil, ctx.Err() + err = ctx.Err() case <-p.ctx.Done(): - return nil, ErrClosed + err = ErrClosed case <-changed: } + p.mu.Lock() + p.waiting-- + p.mu.Unlock() + if err != nil { + return nil, err + } } } @@ -203,10 +305,13 @@ func (p *Pool) Size() int { return p.size } func (p *Pool) Snapshot() Snapshot { p.mu.Lock() defer p.mu.Unlock() - snapshot := Snapshot{Stack: string(p.stack), Size: p.size, Active: len(p.active), Standby: len(p.standby), Cooling: len(p.cooling)} + snapshot := Snapshot{Stack: string(p.stack), Size: p.size, Active: len(p.active), Cooling: len(p.cooling)} for _, active := range p.active { - if key := active.egressKey(); key != "" { - snapshot.Egress = append(snapshot.Egress, key) + if active.idle() { + snapshot.Standby++ + } + if active.egress.IsValid() { + snapshot.Egress = append(snapshot.Egress, active.egress.String()) } } return snapshot @@ -235,31 +340,15 @@ func (p *Pool) penalize(bad *exit, reason string) { if p.next >= len(p.active) { p.next = 0 } - var replacement *exit - if len(p.standby) > 0 && len(p.active) < p.activeTarget { - replacement = p.standby[0] - p.standby = p.standby[1:] - p.active = append(p.active, replacement) - } - if replacement != nil { - p.wait.Add(1) - } - p.wait.Add(1) p.notifyLocked() + p.wait.Add(1) p.mu.Unlock() if p.logger != nil { p.logger.Warnf("Rotating OpenCode WARP egress %s (%s)", bad.id, reason) } - if replacement != nil { - go func() { - defer p.wait.Done() - bad.retire() - }() - if p.logger != nil { - p.logger.Infof("OpenCode WARP exit switched to standby %s at %s", replacement.id, replacement.egress) - } - } + // Re-register immediately: the retired exit is replaced in the background + // and the retry draws whichever active exit is ready first. go func() { defer p.wait.Done() p.replace(bad, reason) @@ -307,12 +396,9 @@ func (p *Pool) replace(old *exit, reason string) { return } placed := false - if len(p.active) < p.activeTarget { + if len(p.active) < p.size { p.active = append(p.active, replacement) placed = true - } else if len(p.standby) < p.standbyTarget { - p.standby = append(p.standby, replacement) - placed = true } p.notifyLocked() p.mu.Unlock() @@ -323,7 +409,7 @@ func (p *Pool) replace(old *exit, reason string) { return } if p.logger != nil { - p.logger.Infof("OpenCode WARP egress %s replaced by %s at %s (%s), active=%d standby=%d", old.id, replacement.id, replacement.egress, reason, len(p.active), len(p.standby)) + p.logger.Infof("OpenCode WARP egress %s replaced by %s at %s (%s), active=%d", old.id, replacement.id, replacement.egress, reason, len(p.active)) } old.retire() p.startRefill() @@ -331,7 +417,7 @@ func (p *Pool) replace(old *exit, reason string) { func (p *Pool) refill() { p.mu.Lock() - if p.closed || p.refilling || len(p.active) == 0 || !p.needsRefillLocked() { + if p.closed || p.refilling || !p.needsRefillLocked() { p.mu.Unlock() return } @@ -341,18 +427,13 @@ func (p *Pool) refill() { replacement, err := p.createExit(p.ctx) p.mu.Lock() p.refilling = false - if err == nil && !p.closed { - if len(p.active) < p.activeTarget { - p.active = append(p.active, replacement) - replacement = nil - p.notifyLocked() - } else if len(p.standby) < p.standbyTarget { - p.standby = append(p.standby, replacement) - replacement = nil - p.notifyLocked() - } + placed := false + if err == nil && !p.closed && len(p.active) < p.size { + p.active = append(p.active, replacement) + replacement = nil + placed = true } - if p.closed { + if placed || p.closed { p.notifyLocked() } p.mu.Unlock() @@ -361,15 +442,21 @@ func (p *Pool) refill() { p.releaseReservation(replacement) replacement.close() } - if err != nil && p.ctx.Err() == nil && p.logger != nil { - p.logger.Warnf("Cannot pre-register OpenCode WARP egress: %v", err) + if err != nil && p.ctx.Err() == nil { + if p.logger != nil { + p.logger.Warnf("Cannot pre-register OpenCode WARP egress: %v", err) + } + // Every registration is already paced by the registrar; retry soon + // instead of leaving the pool under its target for a long window. + p.after(refillRetryDelay, p.startRefill) + return } p.startRefill() } func (p *Pool) startRefill() { p.mu.Lock() - if p.closed || p.refilling || len(p.active) == 0 || !p.needsRefillLocked() { + if p.closed || p.refilling || !p.needsRefillLocked() { p.mu.Unlock() return } @@ -381,6 +468,85 @@ func (p *Pool) startRefill() { }() } +// released records that a lease was returned and trims the ring back toward +// the demand of the moment. Freed exits stay hot for scaleDownDelay, so a +// burst that pauses does not immediately pay for re-registering them. +func (p *Pool) released() { + p.mu.Lock() + if p.inflight > 0 { + p.inflight-- + } + closed := p.closed + wantRefill := !closed && len(p.active) < p.desiredLocked() + started := p.scaling + if !closed && !started && len(p.active) > p.desiredLocked() { + p.scaling = true + started = true + } + p.mu.Unlock() + if closed { + return + } + if wantRefill { + p.startRefill() + } + if started { + p.after(scaleDownDelay, p.scaleDown) + } +} + +// scaleDown retires every idle exit above the current demand. Busy surplus +// exits are left to their release, which arms another pass if the ring is +// still over target then. +func (p *Pool) scaleDown() { + p.mu.Lock() + p.scaling = false + if p.closed { + p.mu.Unlock() + return + } + want := p.desiredLocked() + var dropped []*exit + if surplus := len(p.active) - want; surplus > 0 { + kept := p.active[:0] + for _, candidate := range p.active { + if surplus > 0 && candidate.idle() { + dropped = append(dropped, candidate) + surplus-- + continue + } + kept = append(kept, candidate) + } + p.active = kept + } + if p.next >= len(p.active) { + p.next = 0 + } + p.mu.Unlock() + for _, drop := range dropped { + p.releaseReservation(drop) + drop.retire() + if p.logger != nil { + p.logger.Infof("OpenCode WARP egress %s scaled down at %s", drop.id, drop.egress) + } + } +} + +// after runs fn once delay has elapsed, unless the pool closes first. +func (p *Pool) after(delay time.Duration, fn func()) { + p.wait.Add(1) + go func() { + defer p.wait.Done() + timer := time.NewTimer(delay) + defer timer.Stop() + select { + case <-p.ctx.Done(): + case <-timer.C: + fn() + } + }() +} + func (p *Pool) createExit(ctx context.Context) (*exit, error) { p.createMu.Lock() defer p.createMu.Unlock() @@ -410,6 +576,9 @@ func (p *Pool) createExit(ctx context.Context) (*exit, error) { } p.mu.Unlock() if usable { + if p.logger != nil { + p.logger.Infof("OpenCode WARP/%s egress %s ready at %s", candidate.stack, candidate.id, candidate.egress) + } return candidate, nil } lastErr = fmt.Errorf("WARP egress %s is already active or cooling down", key) @@ -449,14 +618,7 @@ func (p *Pool) activeIndexLocked(target *exit) int { } func (p *Pool) needsRefillLocked() bool { - return len(p.active) < p.activeTarget || len(p.standby) < p.standbyTarget -} - -func poolTargets(size int) (active, standby int) { - if size <= 1 { - return 1, 0 - } - return size - 1, 1 + return len(p.active) < p.desiredLocked() } func (p *Pool) Close() { @@ -468,8 +630,6 @@ func (p *Pool) Close() { p.closed = true active := p.active p.active = nil - standby := p.standby - p.standby = nil p.notifyLocked() p.mu.Unlock() @@ -478,10 +638,6 @@ func (p *Pool) Close() { p.releaseReservation(item) item.retire() } - for _, item := range standby { - p.releaseReservation(item) - item.retire() - } p.wait.Wait() } @@ -500,6 +656,9 @@ func (l *Lease) Release() { if l.exit != nil { l.exit.release() } + if l.pool != nil { + l.pool.released() + } }) } diff --git a/webui/index.html b/webui/index.html index 1c6f06a..a9aaa40 100644 --- a/webui/index.html +++ b/webui/index.html @@ -866,7 +866,7 @@

WARP 出口

- 开启后,免费模型流量(匿名通道、免费模型 Zen Key、免费模型探测)改走用户态 WARP,不再使用任何 Proxy;Go 套餐与付费模型保持不变。 + 开启后,免费模型流量(匿名通道、免费模型 Zen Key、免费模型探测)改走用户态 WARP,不再使用任何 Proxy;Go 套餐与付费模型保持不变。出口收到 429/403 立即淘汰并在后台重新注册,免费模型请求持续轮换出口,用完 retry.max_attempts 次后才把最后一个 429 返回客户端。

@@ -878,17 +878,27 @@
- - + + +

+ 上限而非固定值:活跃出口随并发调整(每个在途请求一个,另留一个备用),空闲 60 秒后自动回收。 +

+
+ + +

+ 仅在使用 IPv6 网络栈时生效。每个 WARP 出口从该前缀取一个源地址出网,换出口即换公网地址;留空则共用本机默认源地址。 +

+
diff --git a/webui/js/i18n.js b/webui/js/i18n.js index 25be64c..22d40d0 100644 --- a/webui/js/i18n.js +++ b/webui/js/i18n.js @@ -262,11 +262,16 @@ const DICTIONARY = { "config.proxy.add": "Add proxies (one per line)", "config.warp.title": "WARP egress", "config.warp.caption": - "While enabled, free-model traffic (anonymous channel, free-model Zen keys, free-model probes) leaves through a userspace Cloudflare WARP tunnel and never through a proxy; Go-plan and paid models keep their proxy bindings.", + "While enabled, free-model traffic (anonymous channel, free-model Zen keys, free-model probes) leaves through a userspace Cloudflare WARP tunnel and never through a proxy; Go-plan and paid models keep their proxy bindings. An exit answered with 429/403 is retired and re-registered in the background, and a free-model request keeps rotating exits until retry.max_attempts is spent before the last 429 reaches the client.", "config.warp.enabled": "Send free-model traffic through WARP", - "config.warp.pool": "WARP exit count", + "config.warp.pool": "Maximum WARP exits", + "config.warp.pool.hint": + "An upper bound, not a fixed count: the active ring follows concurrency (one exit per in-flight request plus a spare) and shrinks after 60 idle seconds.", "config.warp.stack": "Network stack", "config.warp.stack.dual": "Dual stack", + "config.warp.source": "Outer IPv6 source prefix (/64)", + "config.warp.source.hint": + "Used only with the IPv6 network stack. Every WARP exit binds one source address from this prefix, so replacing an exit also replaces its public egress; leave empty to share this host's default source address.", "config.upstream.title": "Upstream and protocol routing", "config.upstream.caption": "anonymous will use every available proxy; an explicit protocol mapping wins over inferring the protocol from the model name.", @@ -816,11 +821,16 @@ const DICTIONARY = { "config.proxy.add": "Thêm Proxy (mỗi dòng một cái)", "config.warp.title": "Đầu ra WARP", "config.warp.caption": - "Khi bật, lưu lượng model miễn phí (kênh ẩn danh, Zen Key cho model miễn phí, kiểm tra model miễn phí) đi qua đường hầm Cloudflare WARP chạy trong tiến trình và không dùng proxy nào; gói Go và model trả phí vẫn giữ proxy.", + "Khi bật, lưu lượng model miễn phí (kênh ẩn danh, Zen Key cho model miễn phí, kiểm tra model miễn phí) đi qua đường hầm Cloudflare WARP chạy trong tiến trình và không dùng proxy nào; gói Go và model trả phí vẫn giữ proxy. Đầu ra trả 429/403 bị loại và đăng ký lại ở nền; yêu cầu model miễn phí tiếp tục đổi đầu ra cho đến khi hết retry.max_attempts rồi mới trả 429 cuối cùng cho client.", "config.warp.enabled": "Đưa lưu lượng model miễn phí qua WARP", - "config.warp.pool": "Số đầu ra WARP", + "config.warp.pool": "Số đầu ra WARP tối đa", + "config.warp.pool.hint": + "Là giới hạn trên, không phải số cố định: vòng đầu ra đang hoạt động thay đổi theo mức đồng thời (mỗi yêu cầu đang chạy một đầu ra, cộng một đầu ra dự phòng) và thu gọn sau 60 giây nhàn rỗi.", "config.warp.stack": "Ngăn xếp mạng", "config.warp.stack.dual": "Hai ngăn xếp", + "config.warp.source": "Tiền tố nguồn IPv6 bên ngoài (/64)", + "config.warp.source.hint": + "Chỉ dùng với ngăn xếp mạng IPv6. Mỗi đầu ra WARP gắn một địa chỉ nguồn trong tiền tố này, nên khi thay đầu ra là thay luôn địa chỉ công cộng; để trống sẽ dùng địa chỉ nguồn mặc định của máy chủ.", "config.upstream.title": "Upstream và định tuyến giao thức", "config.upstream.caption": "anonymous sẽ dùng hết các Proxy khả dụng; ánh xạ protocol tường minh được ưu tiên hơn việc suy luận từ tên mô hình.", @@ -1381,11 +1391,16 @@ const DICTIONARY = { "config.proxy.add": "Aggiungi proxy (uno per riga)", "config.warp.title": "Uscita WARP", "config.warp.caption": - "Quando è attivo, il traffico dei modelli gratuiti (canale anonimo, Zen Key per modelli gratuiti, probe dei modelli gratuiti) esce attraverso un tunnel Cloudflare WARP in userspace e non usa alcun proxy; piano Go e modelli a pagamento mantengono i loro proxy.", + "Quando è attivo, il traffico dei modelli gratuiti (canale anonimo, Zen Key per modelli gratuiti, probe dei modelli gratuiti) esce attraverso un tunnel Cloudflare WARP in userspace e non usa alcun proxy; piano Go e modelli a pagamento mantengono i loro proxy. Un'uscita che risponde 429/403 viene ritirata e registrata di nuovo in background; una richiesta per modelli gratuiti continua a cambiare uscita finché non esaurisce retry.max_attempts, e solo allora l'ultimo 429 raggiunge il client.", "config.warp.enabled": "Instrada il traffico dei modelli gratuiti tramite WARP", - "config.warp.pool": "Numero di uscite WARP", + "config.warp.pool": "Numero massimo di uscite WARP", + "config.warp.pool.hint": + "È un limite massimo, non un numero fisso: il ring attivo segue la concorrenza (un'uscita per richiesta in corso più una di riserva) e si riduce dopo 60 secondi di inattività.", "config.warp.stack": "Stack di rete", "config.warp.stack.dual": "Doppio stack", + "config.warp.source": "Prefisso sorgente IPv6 esterno (/64)", + "config.warp.source.hint": + "Usato solo con lo stack IPv6. Ogni uscita WARP associa un indirizzo sorgente da questo prefisso, quindi sostituire un'uscita sostituisce anche l'indirizzo pubblico; lascia vuoto per usare l'indirizzo sorgente predefinito dell'host.", "config.upstream.title": "Upstream e instradamento protocolli", "config.upstream.caption": "anonymous userà ogni proxy disponibile; una mappatura esplicita di protocollo prevale sull'inferenza del protocollo dal nome del modello.", diff --git a/webui/js/pages/config.js b/webui/js/pages/config.js index cc397aa..4d73da8 100644 --- a/webui/js/pages/config.js +++ b/webui/js/pages/config.js @@ -56,7 +56,8 @@ function fillConfig(value) { const warp = value.warp || {}; $("#c-warp-enabled").checked = !!warp.enabled; $("#c-warp-pool").value = warp.pool_size || 2; - $("#c-warp-stack").value = warp.stack || "ipv4"; + $("#c-warp-stack").value = warp.stack || "ipv6"; + $("#c-warp-source").value = warp.source_ipv6 || ""; $("#c-proxyfile").value = value.proxyfile; $("#c-up-zen").value = value.upstream.zen; $("#c-up-go").value = value.upstream.go; @@ -98,6 +99,7 @@ async function save(event) { enabled: $("#c-warp-enabled").checked, pool_size: numberValue("#c-warp-pool"), stack: $("#c-warp-stack").value, + source_ipv6: $("#c-warp-source").value.trim(), }, proxies: secretInputs("proxies"), proxyfile: $("#c-proxyfile").value,