feat(warp): preload half the pool and register without a fixed gap

Registrations were paced by a fixed 12-second gap, which made a cold pool
and a 429 replacement wait minutes for capacity. Remove the gap: the
registrar now issues registrations back to back in the background,
serialized by the pool's create mutex, and only a rejected attempt backs
off (doJSON still honours Retry-After).

Keep half of warp.pool_size (at least one) hot as a preload: the first
exit still gates readiness, the rest register in the background, and
desiredLocked/scaleDown treat the preload as a floor so idle surplus is
still retired after 60 seconds but the warm bench survives. A 429 or 403
removes the exit from the ring and the next request uses a preloaded exit
immediately.

/healthz reports warp.preload, and the WebUI and all four READMEs
describe the behaviour.
This commit is contained in:
Jason Xu committed 2026-10-25 07:42:10 +08:00
1 parent b8b1454a0e
commit 7d34bdde33
9 files changed
+51 -45

No files matched your search

+2 -2
View File
@@ -232,7 +232,7 @@ 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–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`.
`warp.pool_size` (1–32, predefinito `2`) è un **limite massimo**, non un numero fisso. La prima uscita viene registrata in modo sincrono e determina la readiness; poi il pool registra in background metà del massimo (almeno una), così un picco trova uscite già calde senza attendere. Il ring attivo segue la concorrenza: un'uscita per ogni richiesta in corso più una di riserva, mai oltre il massimo; le uscite in eccesso rimaste inattive per 60 secondi vengono ritirate. La prima risposta 429 o 403 ritira subito l'uscita e una uscita pre-registrata ne prende il posto; una richiesta per modelli gratuiti continua a cambiare uscita e restituisce l'ultimo 429 al client solo dopo aver esaurito `retry.max_attempts`, mentre l'uscita ritirata viene registrata di nuovo subito in background. Le registrazioni restano serializzate ma senza un intervallo fisso. `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.
@@ -285,7 +285,7 @@ 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`; limite massimo di uscite WARP (il ring attivo segue la concorrenza), 1–32. |
| `warp.pool_size` | `2`; limite massimo di uscite WARP (metà pre-registrata in background; 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`. |
+2 -2
View File
@@ -234,7 +234,7 @@ 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–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`.
`warp.pool_size` (1–32, default `2`) is an upper bound, not a fixed count. The first exit registers synchronously and gates readiness; the pool then registers half of the ceiling (at least one) in the background, so a burst finds warm exits instead of waiting for registrations. The active ring follows concurrency: one exit per in-flight lease plus a spare, never more than the maximum. Surplus exits that stay idle for 60 seconds are retired, so a quiet period scales back down. An exit answered with 429 or 403 is retired immediately and a pre-registered exit takes its place — 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 are serialized but no longer spaced by a fixed delay. `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.
@@ -287,7 +287,7 @@ 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`; upper bound on WARP exits (the active ring follows concurrency), 1–32. |
| `warp.pool_size` | `2`; upper bound on WARP exits (half pre-registered in the background; 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`. |
+2 -2
View File
@@ -238,7 +238,7 @@ 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–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`.
`warp.pool_size` (1–32, mặc định `2`) là **giới hạn trên**, không phải số cố định. Đầu ra đầu tiên được đăng ký đồng bộ và quyết định trạng thái sẵn sàng; sau đó pool đăng ký nền một nửa giới hạn (ít nhất một) để lưu lượng đột biến có sẵn đầu ra đã ấm. 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, 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. Đầu ra nhận 429 hoặc 403 lần đầu sẽ bị loại ngay và một đầu ra đã đăng ký trước thay vào; 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`, còn đầu ra bị loại được đăng ký lại ngay ở nền. Việc đăng ký vẫn tuần tự nhưng không còn khoảng nghỉ cố định. `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í.
@@ -291,7 +291,7 @@ 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`; giới hạn trên số đầu ra WARP (vòng hoạt động theo mức đồng thời), 1–32. |
| `warp.pool_size` | `2`; giới hạn trên số đầu ra WARP (một nửa đăng ký trước ở nền; 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`. |
+2 -2
View File
@@ -234,7 +234,7 @@ System One 将自由文本状态与类型化问题配对,并返回类型化答
隧道运行在网关进程内:注册 WARP 设备,通过 UDP 与 Cloudflare 建立 WireGuard 连接,并在用户态网络栈中终结。它不需要 TUN 设备、root、`NET_ADMIN` 或修改路由表,但宿主机(或容器)必须能向 Cloudflare 端点发送 UDP(端口 `2408`)。注册与 `warp=on` 的 trace 探测在启动时完成;WARP 无法初始化时启动直接失败,不会静默回退到代理。通过 WebUI 启用同样采用失败即拒绝:参数错误会返回错误,旧运行时继续服务。
`warp.pool_size`(1–32,默认 `2`)是**上限**而不是固定数量。活跃出口按并发动态调整:每个在途请求一个出口,另加一个备用,最少 1 个、最多不超过配置上限;空闲 60 秒的多余出口会被回收,因此突发流量会把出口环撑大,空闲后再缩回。出口第一次收到上游 429 或 403 即被淘汰并立刻在后台重新注册(注册仍受 Cloudflare 12 秒的 API 节奏限制,上限越大预热越慢,应按免费模型的并发峰值设置);免费模型请求会持续切换到其他出口,直到用完 `retry.max_attempts` 次才把最后一个 429 返回客户端。`warp.stack` 默认 `ipv6`,可选 `ipv4` 或 `dual`。
`warp.pool_size`(1–32,默认 `2`)是**上限**而不是固定数量。第一个出口同步注册、决定服务是否 ready;之后池子在后台预注册上限的一半(至少 1 个),突发流量可以直接拿到预热出口而不用等注册。活跃出口再按并发调整:每个在途请求一个出口,另加一个备用,最多不超过上限;空闲 60 秒的多余出口会被回收。出口第一次收到上游 429 或 403 即被淘汰,由预注册的出口立刻顶上——免费模型请求会持续切换到其他出口,直到用完 `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 后,免费通道恢复使用代理。
@@ -287,7 +287,7 @@ Key 初始化时均衡分配到代理。真实流量可以触发代理检查、K
| `zen_keys`、`go_keys` | 未启用匿名模式时,至少需要一个上游 Key。 |
| `anonymous` | `false`。 |
| `warp.enabled` | `false`;免费通道流量通过 Cloudflare WARP 出口,不使用代理。 |
| `warp.pool_size` | `2`;WARP 出口上限(活跃出口按并发动态调整),1–32。 |
| `warp.pool_size` | `2`;WARP 出口上限(后台预注册一半,活跃出口按并发调整),1–32。 |
| `warp.stack` | `ipv6`;可选 `ipv6`、`ipv4`、`dual`。 |
| `warp.source_ipv6` | 空;每个出口绑定的外层 IPv6 源前缀(`/64`),要求 `stack = "ipv6"`。 |
| `prefer` | `go`;可选 `go`、`zen`。 |
+2
View File
@@ -54,6 +54,7 @@ type healthWarp struct {
Status string `json:"status"`
Stack string `json:"stack"`
Size int `json:"size"`
Preload int `json:"preload"`
Active int `json:"active"`
Standby int `json:"standby"`
Cooling int `json:"cooling"`
@@ -79,6 +80,7 @@ func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) {
Status: "unavailable",
Stack: snapshot.Stack,
Size: snapshot.Size,
Preload: snapshot.Preload,
Active: snapshot.Active,
Standby: snapshot.Standby,
Cooling: snapshot.Cooling,
+30 -11
View File
@@ -19,8 +19,8 @@ const DefaultPoolSize = 2
// 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.
// refillRetryDelay spaces out a failed registration attempt. Successful
// registrations run back to back in the background.
const refillRetryDelay = 5 * time.Second
// scaleDownDelay keeps exits created for a burst hot for a while after the
@@ -73,6 +73,7 @@ type Pool struct {
cancel context.CancelFunc
logger logger
size int
preload int
stack Stack
newExit func(context.Context) (*exit, error)
@@ -101,6 +102,10 @@ type Lease struct {
type Snapshot struct {
Stack string
Size int
// Preload is the number of exits kept hot even when the pool is idle:
// half of Size (at least one), registered in the background after the
// first exit so a burst does not wait for a registration.
Preload 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.
@@ -112,9 +117,9 @@ type Snapshot struct {
// 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 is the upper bound on exits. Half of it (at least one) is kept hot
// as a preload even while the pool is idle; beyond that the pool keeps as
// many exits hot as the current concurrency needs and never exceeds Size.
Size int
// Stack selects the address family inside the tunnel. An IPv6 stack makes
// the public egress an IPv6 address.
@@ -189,6 +194,14 @@ func newPool(ctx context.Context, log logger, size int, create func(context.Cont
if size <= 0 {
size = DefaultPoolSize
}
// Keep half of the ceiling warm (at least one) so a burst finds ready
// exits instead of paying for registrations while requests queue. The
// first exit is synchronous and gates readiness; the rest register in the
// background.
preload := size / 2
if preload < 1 {
preload = 1
}
// 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
@@ -200,6 +213,7 @@ func newPool(ctx context.Context, log logger, size int, create func(context.Cont
cancel: cancel,
logger: log,
size: size,
preload: preload,
newExit: create,
reserved: make(map[string]bool),
cooling: make(map[string]time.Time),
@@ -212,7 +226,7 @@ func newPool(ctx context.Context, log logger, size int, create func(context.Cont
}
p.active = []*exit{first}
if log != nil {
log.Infof("OpenCode WARP/%s pool ready (max %d exits, one spare)", first.stack, size)
log.Infof("OpenCode WARP/%s pool ready (max %d exits, preloading %d)", first.stack, size, preload)
}
p.startRefill()
return p, nil
@@ -220,10 +234,14 @@ func newPool(ctx context.Context, log logger, size int, create func(context.Cont
// 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.
// a 429 can switch to a ready exit instead of waiting for a registration. The
// preload floor keeps half the ceiling registered while the pool is idle.
// 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 < p.preload {
want = p.preload
}
if want < 2 {
want = 2
}
@@ -305,7 +323,7 @@ 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), Cooling: len(p.cooling)}
snapshot := Snapshot{Stack: string(p.stack), Size: p.size, Preload: p.preload, Active: len(p.active), Cooling: len(p.cooling)}
for _, active := range p.active {
if active.idle() {
snapshot.Standby++
@@ -446,8 +464,9 @@ func (p *Pool) refill() {
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.
// A rejected registration (for example an API rate limit) backs off a
// little instead of leaving the pool under its target for a long
// window.
p.after(refillRetryDelay, p.startRefill)
return
}
+7 -22
View File
@@ -15,14 +15,12 @@ import (
"net/netip"
"strconv"
"strings"
"sync"
"time"
)
const (
defaultAPIBase = "https://api.cloudflareclient.com/v0i1909051800"
defaultPeer = "bmXOC+F1FxEMF9dyiK2H5/1SUtzH0JuVo51h2wPfgyo="
registerGap = 12 * time.Second
)
var fallbackEndpoints = []string{
@@ -45,11 +43,8 @@ type registration struct {
}
type registrar struct {
base string
client *http.Client
minGap time.Duration
mu sync.Mutex
lastReg time.Time
base string
client *http.Client
}
func newRegistrar() *registrar {
@@ -65,25 +60,15 @@ func newRegistrar() *registrar {
TLSHandshakeTimeout: 10 * time.Second,
},
},
minGap: registerGap,
}
}
// register creates and enables one WARP device. Registrations are no longer
// paced by a fixed gap: the pool registers in the background while traffic is
// served, so a fixed delay only slowed down prefills and 429 replacements.
// Callers already serialize registrations through the pool's create mutex; a
// rejected attempt backs off in the refill loop.
func (r *registrar) register(ctx context.Context) (registration, error) {
r.mu.Lock()
defer r.mu.Unlock()
if wait := r.minGap - time.Since(r.lastReg); wait > 0 {
timer := time.NewTimer(wait)
defer timer.Stop()
select {
case <-ctx.Done():
return registration{}, ctx.Err()
case <-timer.C:
}
}
r.lastReg = time.Now()
privateKey, publicKey, err := wireGuardKeypair()
if err != nil {
return registration{}, err
+1 -1
View File
@@ -881,7 +881,7 @@
<label for="c-warp-pool" data-i18n="config.warp.pool">WARP 出口上限</label>
<input id="c-warp-pool" type="number" min="1" max="32" step="1" />
<p class="section-caption" data-i18n="config.warp.pool.hint">
上限而非固定值:活跃出口随并发调整(每个在途请求一个,另留一个备用),空闲 60 秒后自动回收。
上限而非固定值:第一个出口就绪后,后台预注册一半(至少 1 个)作为暖池;活跃出口随并发调整(每个在途请求一个,另留一个备用),空闲 60 秒后回收多余出口。
</p>
</div>
<div class="field">
+3 -3
View File
@@ -266,7 +266,7 @@ const DICTIONARY = {
"config.warp.enabled": "Send free-model traffic through WARP",
"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.",
"An upper bound, not a fixed count: after the first exit is ready, half of it (at least one) is pre-registered in the background as warm capacity; the active ring then 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)",
@@ -825,7 +825,7 @@ const DICTIONARY = {
"config.warp.enabled": "Đưa lưu lượng model miễn phí qua 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.",
"Là giới hạn trên, không phải số cố định: sau khi đầu ra đầu tiên sẵn sàng, một nửa (ít nhất một) được đăng ký trước ở nền; vòng hoạt động sau đó 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)",
@@ -1395,7 +1395,7 @@ const DICTIONARY = {
"config.warp.enabled": "Instrada il traffico dei modelli gratuiti tramite 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à.",
"È un limite massimo, non un numero fisso: dopo la prima uscita, metà del valore (almeno una) viene pre-registrata in background; il ring attivo segue poi 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)",