mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-06 08:03:47 +00:00
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:
1 parent
7d34bdde33
commit
5143e12e48
7 files changed
+192
-31
No files matched your search
@@ -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
@@ -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
@@ -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{}, ®istrationPausedError{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 ®istrationPausedError{retryAfter: pause, reason: bodyText}
|
||||
}
|
||||
lastErr = fmt.Errorf("Cloudflare API HTTP %d: %s", resp.StatusCode, bodyText)
|
||||
if resp.StatusCode < 500 {
|
||||
return lastErr
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user