fix(warp): pace registration from Cloudflare and stop probe churn

A Cloudflare 429 on /reg no longer sleeps inside the registration path:
the registrar records the Retry-After window and fails fast, and the pool
schedules its next attempt after that window. Registration can no longer
hold createMu for minutes while requests wait for an exit.

Refill backs off when the colo hands out fewer distinct egress blocks
than the preload: three consecutive duplicate registrations pause it for
1-5 minutes instead of registering into a saturated colo forever.

Automatic free-model probes skip a pool with fewer than two exits and
stop the sweep after one probe retires an exit, so they cannot drain the
warm bench. Diagnostics are unaffected.
This commit is contained in:
Jason Xu committed 2026-10-25 07:54:03 +08:00
1 parent 7d34bdde33
commit 5143e12e48
7 files changed
+192 -31

No files matched your search

+1 -1
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. 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`.
`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; il 429/Retry-After di Cloudflare detta il ritmo al posto di un intervallo fisso. Se il colo assegna meno blocchi di uscita distinti del preload, il pool arretra invece di registrare all'infinito; le probe automatiche dei modelli gratuiti saltano un pool senza uscita di riserva e fermano il ciclo dopo che una probe ha ritirato un'uscita. `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.
+1 -1
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 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`.
`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; Cloudflare's 429/Retry-After answer sets the pacing instead of a fixed delay. If the colo hands out fewer distinct egress blocks than the preload, the pool backs off instead of registering forever, and automatic free-model probes skip a pool without a spare exit and stop the sweep after one probe retires an exit. `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.
+1 -1
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. Đầ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`.
`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ự; phản hồi 429/Retry-After của Cloudflare quyết định nhịp thay cho khoảng nghỉ cố định. Nếu colo cấp ít khối đầu ra khác nhau hơn mức preload, pool sẽ lùi lại thay vì đăng ký vô hạn; kiểm tra tự động model miễn phí bỏ qua pool không có đầu ra dự phòng và dừng lượt sau khi một lần kiểm tra loại bỏ một đầu ra. `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í.
+1 -1
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`)是**上限**而不是固定数量。第一个出口同步注册、决定服务是否 ready;之后池子在后台预注册上限的一半(至少 1 个),突发流量可以直接拿到预热出口而不用等注册。活跃出口再按并发调整:每个在途请求一个出口,另加一个备用,最多不超过上限;空闲 60 秒的多余出口会被回收。出口第一次收到上游 429 或 403 即被淘汰,由预注册的出口立刻顶上——免费模型请求会持续切换到其他出口,直到用完 `retry.max_attempts` 次才把最后一个 429 返回客户端;被淘汰的出口马上在后台重新注册。注册仍然串行,但不再有固定的间隔限制。`warp.stack` 默认 `ipv6`,可选 `ipv4` 或 `dual`。
`warp.pool_size`(1–32,默认 `2`)是**上限**而不是固定数量。第一个出口同步注册、决定服务是否 ready;之后池子在后台预注册上限的一半(至少 1 个),突发流量可以直接拿到预热出口而不用等注册。活跃出口再按并发调整:每个在途请求一个出口,另加一个备用,最多不超过上限;空闲 60 秒的多余出口会被回收。出口第一次收到上游 429 或 403 即被淘汰,由预注册的出口立刻顶上——免费模型请求会持续切换到其他出口,直到用完 `retry.max_attempts` 次才把最后一个 429 返回客户端;被淘汰的出口马上在后台重新注册。注册仍然串行,节流改由 Cloudflare 的 429 / Retry-After 决定,而不是固定间隔。若机房能给出的不同出口网段少于预注册目标,池子会退避而不是无限注册;自动免费模型探测在没有备用出口时跳过,并在一轮探测淘汰出口后停止本轮。`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 后,免费通道恢复使用代理。
+17
View File
@@ -94,6 +94,18 @@ func (m *RuntimeController) checkFreeModels(ctx context.Context) {
if r == nil {
return
}
// A WARP probe is a real OpenCode request: an automatic sweep must not
// take the last exit and rotate it away on a 429. Wait until the pool
// has a spare, and stop the sweep entirely once one probe has retired
// an exit, so a burst of probes cannot drain the warm bench.
var warpCooling int
if r.gateway.warp != nil {
snapshot := r.gateway.warp.Snapshot()
if snapshot.Active <= 1 {
return
}
warpCooling = snapshot.Cooling
}
item = r.availability.Get(item.Model)
if item.Manual {
continue
@@ -114,5 +126,10 @@ func (m *RuntimeController) checkFreeModels(ctx context.Context) {
m.logger.Info("free model availability checked", "component", "models", "event", "availability_checked", "model", item.Model, "available", result.success, "reason", result.reason, "channel", result.channel)
}
m.updateMu.Unlock()
if r.gateway.warp != nil && r.gateway.warp.Snapshot().Cooling > warpCooling {
// The probe's 429 retired an exit. Leave the rest of the sweep for
// the next tick instead of spending the remaining warm exits.
return
}
}
}
+85 -11
View File
@@ -23,6 +23,20 @@ const egressCooldown = 30 * time.Minute
// registrations run back to back in the background.
const refillRetryDelay = 5 * time.Second
// A pool can only hold as many exits as Cloudflare hands out distinct egress
// blocks. When preload is larger than that supply, every extra registration is
// a duplicate; after a few in a row the pool stops trying for a while instead
// of hammering the registration API forever.
const (
refillFailureThreshold = 3
refillBackoffBase = time.Minute
refillBackoffMax = 5 * time.Minute
)
// errDuplicateEgress reports a registration whose public egress block is
// already active or cooling down.
var errDuplicateEgress = errors.New("WARP egress is already active or cooling down")
// 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.
@@ -88,8 +102,12 @@ type Pool struct {
closed bool
refilling bool
scaling bool
wait sync.WaitGroup
createMu sync.Mutex
// refillFailures counts consecutive failed preload registrations;
// refillPaused keeps every refill trigger quiet until it expires.
refillFailures int
refillPaused time.Time
wait sync.WaitGroup
createMu sync.Mutex
}
type Lease struct {
@@ -401,7 +419,11 @@ func (p *Pool) replace(old *exit, reason string) {
old.retire()
}
if p.logger != nil {
p.logger.Errorf("Cannot replace OpenCode WARP egress %s: %v", old.id, err)
if pause := registrationPause(err); pause > 0 {
p.logger.Infof("OpenCode WARP replacement paused for %s", pause.Round(time.Second))
} else {
p.logger.Errorf("Cannot replace OpenCode WARP egress %s: %v", old.id, err)
}
}
p.startRefill()
return
@@ -435,7 +457,7 @@ func (p *Pool) replace(old *exit, reason string) {
func (p *Pool) refill() {
p.mu.Lock()
if p.closed || p.refilling || !p.needsRefillLocked() {
if p.closed || p.refilling || time.Now().Before(p.refillPaused) || !p.needsRefillLocked() {
p.mu.Unlock()
return
}
@@ -451,6 +473,10 @@ func (p *Pool) refill() {
replacement = nil
placed = true
}
if err == nil {
p.refillFailures = 0
p.refillPaused = time.Time{}
}
if placed || p.closed {
p.notifyLocked()
}
@@ -461,21 +487,69 @@ func (p *Pool) refill() {
replacement.close()
}
if err != nil && p.ctx.Err() == nil {
if p.logger != nil {
delay := refillRetryDelay
if pause := registrationPause(err); pause > 0 {
// Cloudflare's rate limit is the pacing: wait out the window it
// asked for instead of retrying into the same answer.
delay = pause
if delay < refillRetryDelay {
delay = refillRetryDelay
}
if delay > maxRateLimitPause {
delay = maxRateLimitPause
}
if p.logger != nil {
p.logger.Infof("OpenCode WARP registration paused for %s", delay.Round(time.Second))
}
} else if errors.Is(err, errDuplicateEgress) {
p.mu.Lock()
p.refillFailures++
failures := p.refillFailures
p.mu.Unlock()
if failures >= refillFailureThreshold {
// The egress supply is smaller than the target. Back off
// exponentially so a saturated colo is not registered into
// forever.
shift := failures - refillFailureThreshold
if shift > 3 {
shift = 3
}
delay = refillBackoffBase << shift
if delay > refillBackoffMax {
delay = refillBackoffMax
}
if p.logger != nil {
p.logger.Infof("OpenCode WARP preload paused for %s after %d duplicate egresses", delay.Round(time.Second), failures)
}
}
} else if p.logger != nil {
p.logger.Warnf("Cannot pre-register OpenCode WARP egress: %v", err)
}
// 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)
p.mu.Lock()
if paused := time.Now().Add(delay); paused.After(p.refillPaused) {
p.refillPaused = paused
}
p.mu.Unlock()
p.after(delay, p.retryRefill)
return
}
p.startRefill()
}
// retryRefill is the timer half of a failed refill: it clears the pause that
// kept ordinary triggers quiet and asks for another attempt. Going through
// startRefill (rather than calling refill directly) keeps the single-flight
// guard.
func (p *Pool) retryRefill() {
p.mu.Lock()
p.refillPaused = time.Time{}
p.mu.Unlock()
p.startRefill()
}
func (p *Pool) startRefill() {
p.mu.Lock()
if p.closed || p.refilling || !p.needsRefillLocked() {
if p.closed || p.refilling || time.Now().Before(p.refillPaused) || !p.needsRefillLocked() {
p.mu.Unlock()
return
}
@@ -600,7 +674,7 @@ func (p *Pool) createExit(ctx context.Context) (*exit, error) {
}
return candidate, nil
}
lastErr = fmt.Errorf("WARP egress %s is already active or cooling down", key)
lastErr = fmt.Errorf("%w: %s", errDuplicateEgress, key)
if p.logger != nil {
p.logger.Warnf("Discarding duplicate WARP exit %s: %v", candidate.id, lastErr)
}
+86 -16
View File
@@ -15,9 +15,43 @@ import (
"net/netip"
"strconv"
"strings"
"sync"
"time"
)
const (
// defaultRateLimitPause is used when Cloudflare answers a registration
// with 429 but omits Retry-After. It matches the historical registration
// cadence.
defaultRateLimitPause = 12 * time.Second
// maxRateLimitPause bounds how long a rate-limit answer can keep new
// registrations out. A larger server value is clamped so a bad header
// cannot freeze the pool for hours.
maxRateLimitPause = 5 * time.Minute
)
// registrationPausedError reports that Cloudflare asked for a pause before
// the next device registration. The pool schedules its retry from it instead
// of sleeping inside the registration path.
type registrationPausedError struct {
retryAfter time.Duration
reason string
}
func (e *registrationPausedError) Error() string {
return fmt.Sprintf("Cloudflare registration paused for %s: %s", e.retryAfter.Round(time.Second), e.reason)
}
// registrationPause returns the delay a failed registration asked for, or 0
// when the failure was not a rate limit.
func registrationPause(err error) time.Duration {
var paused *registrationPausedError
if errors.As(err, &paused) {
return paused.retryAfter
}
return 0
}
const (
defaultAPIBase = "https://api.cloudflareclient.com/v0i1909051800"
defaultPeer = "bmXOC+F1FxEMF9dyiK2H5/1SUtzH0JuVo51h2wPfgyo="
@@ -45,6 +79,9 @@ type registration struct {
type registrar struct {
base string
client *http.Client
mu sync.Mutex
blockedTill time.Time
}
func newRegistrar() *registrar {
@@ -63,12 +100,39 @@ func newRegistrar() *registrar {
}
}
// 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.
// blocked reports how much longer Cloudflare's last rate-limit answer keeps
// new registrations out.
func (r *registrar) blocked() time.Duration {
r.mu.Lock()
defer r.mu.Unlock()
if wait := time.Until(r.blockedTill); wait > 0 {
return wait
}
return 0
}
// pause records Cloudflare's rate-limit window. Existing windows only grow,
// so overlapping answers cannot shorten one another.
func (r *registrar) pause(wait time.Duration) {
if wait <= 0 {
return
}
r.mu.Lock()
defer r.mu.Unlock()
if until := time.Now().Add(wait); until.After(r.blockedTill) {
r.blockedTill = until
}
}
// register creates and enables one WARP device. Registrations are not paced by
// a fixed gap: the pool registers in the background while traffic is served.
// Cloudflare's own 429/Retry-After answer becomes the pacing instead — it is
// recorded here and the caller retries when the window ends, so a rate limit
// never blocks registration behind a long sleep.
func (r *registrar) register(ctx context.Context) (registration, error) {
if wait := r.blocked(); wait > 0 {
return registration{}, &registrationPausedError{retryAfter: wait, reason: "Cloudflare rate limit"}
}
privateKey, publicKey, err := wireGuardKeypair()
if err != nil {
return registration{}, err
@@ -224,18 +288,24 @@ func (r *registrar) doJSON(ctx context.Context, method, path string, body []byte
continue
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
lastErr = fmt.Errorf("Cloudflare API HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(data)))
if resp.StatusCode != http.StatusTooManyRequests && resp.StatusCode < 500 {
return lastErr
}
if retryAfter := parseRetryAfter(resp.Header.Get("Retry-After")); retryAfter > 0 {
timer := time.NewTimer(retryAfter)
select {
case <-ctx.Done():
timer.Stop()
return ctx.Err()
case <-timer.C:
bodyText := strings.TrimSpace(string(data))
if resp.StatusCode == http.StatusTooManyRequests {
// Cloudflare's own limit becomes the pacing. Record it and fail
// fast: sleeping here would hold the pool's create mutex and
// stall replacements for the whole window.
pause := parseRetryAfter(resp.Header.Get("Retry-After"))
if pause <= 0 {
pause = defaultRateLimitPause
}
if pause > maxRateLimitPause {
pause = maxRateLimitPause
}
r.pause(pause)
return &registrationPausedError{retryAfter: pause, reason: bodyText}
}
lastErr = fmt.Errorf("Cloudflare API HTTP %d: %s", resp.StatusCode, bodyText)
if resp.StatusCode < 500 {
return lastErr
}
continue
}