mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-06 08:03:47 +00:00
feat(gateway): pause the anonymous lane after repeated failures
A flagged free-tier exit keeps answering 403 (IP-level abuse detection) and retrying only extends the penalty. Add an optional lane-level circuit breaker, configured with models.anonymous_backoff: - threshold consecutive failed anonymous attempts, or one 403/429, pause the whole lane for base_hours, doubling on every further trip up to max_hours; - while paused, no proxy is drawn and no upstream request is made, so routing falls straight through to the authenticated tiers; - a successful attempt closes the breaker and restores the free lane; - absent config leaves behavior unchanged; - availability probes honour the breaker instead of refreshing the block.
This commit is contained in:
1 parent
f0f064f31d
commit
8cc5e96489
6 files changed
+155
-4
No files matched your search
@@ -100,6 +100,46 @@ type ModelsConfig struct {
|
||||
// FreeOnly limits discovery and routing to free models, even when Zen or
|
||||
// Go keys could serve paid ones. Free models may still fall back to keys.
|
||||
FreeOnly bool `json:"free_only"`
|
||||
// AnonymousBackoff configures a circuit breaker for the keyless lane: after
|
||||
// Threshold consecutive failed attempts, or immediately on a 403 or 429,
|
||||
// the lane pauses for BaseHours, doubling on every further trip up to
|
||||
// MaxHours. An absent block leaves the lane unpaused, which is the previous
|
||||
// behavior.
|
||||
AnonymousBackoff *AnonymousBackoffConfig `json:"anonymous_backoff,omitempty"`
|
||||
}
|
||||
|
||||
// AnonymousBackoffConfig tunes the keyless lane's circuit breaker. Zero fields
|
||||
// take the defaults shown in Normalize.
|
||||
type AnonymousBackoffConfig struct {
|
||||
Threshold int `json:"threshold,omitempty"`
|
||||
BaseHours int `json:"base_hours,omitempty"`
|
||||
MaxHours int `json:"max_hours,omitempty"`
|
||||
}
|
||||
|
||||
// Normalize fills the defaults and rejects nonsensical windows.
|
||||
func (b *AnonymousBackoffConfig) Normalize() error {
|
||||
if b == nil {
|
||||
return nil
|
||||
}
|
||||
if b.Threshold == 0 {
|
||||
b.Threshold = 6
|
||||
}
|
||||
if b.BaseHours == 0 {
|
||||
b.BaseHours = 1
|
||||
}
|
||||
if b.MaxHours == 0 {
|
||||
b.MaxHours = 24
|
||||
}
|
||||
if b.Threshold < 1 {
|
||||
return errors.New("models.anonymous_backoff.threshold must be at least 1")
|
||||
}
|
||||
if b.BaseHours < 1 {
|
||||
return errors.New("models.anonymous_backoff.base_hours must be at least 1")
|
||||
}
|
||||
if b.MaxHours < b.BaseHours {
|
||||
return errors.New("models.anonymous_backoff.max_hours must not be smaller than base_hours")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LoggingConfig sets the minimum log level (debug, info, warn or error) and
|
||||
@@ -306,6 +346,9 @@ func Normalize(path string, cfg Config) (Config, error) {
|
||||
return Config{}, fmt.Errorf("unsupported proxy scheme %q", u.Scheme)
|
||||
}
|
||||
}
|
||||
if err := cfg.Models.AnonymousBackoff.Normalize(); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
for model, protocol := range cfg.Models.Protocols {
|
||||
if model == "" || !wire.Valid(wire.Protocol(protocol)) {
|
||||
return Config{}, fmt.Errorf("models.protocols contains invalid mapping %q: %q", model, protocol)
|
||||
|
||||
@@ -119,13 +119,26 @@ func New(cfg config.Config, logger *slog.Logger, monitor *telemetry.Metrics) (*G
|
||||
transports: transports,
|
||||
zenNodes: zenNodes,
|
||||
goNodes: goNodes,
|
||||
anonymous: anonymousPool(cfg.Anonymous, transports, cooldown),
|
||||
anonymous: anonymousPool(cfg.Anonymous, transports, cooldown, anonymousBackoffFromConfig(cfg.Models.AnonymousBackoff)),
|
||||
catalog: catalog,
|
||||
monitor: monitor,
|
||||
attemptTimeout: attemptDeadline(cfg),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// anonymousBackoffFromConfig converts the configured hours into the breaker's
|
||||
// thresholds and durations. A nil block disables the breaker (threshold 0).
|
||||
func anonymousBackoffFromConfig(cfg *config.AnonymousBackoffConfig) anonymousBackoff {
|
||||
if cfg == nil {
|
||||
return anonymousBackoff{}
|
||||
}
|
||||
return anonymousBackoff{
|
||||
threshold: int32(cfg.Threshold),
|
||||
base: time.Duration(cfg.BaseHours) * time.Hour,
|
||||
max: time.Duration(cfg.MaxHours) * time.Hour,
|
||||
}
|
||||
}
|
||||
|
||||
// Handler returns the gateway's HTTP API: the server-key authenticated /v1
|
||||
// model, inference and System One routes plus the open /healthz, wrapped in
|
||||
// panic recovery.
|
||||
|
||||
@@ -53,6 +53,20 @@ type anonymousNodes struct {
|
||||
next atomic.Uint64
|
||||
cooldown time.Duration
|
||||
hasPool bool
|
||||
// breaker stops the whole lane after repeated failures instead of poking
|
||||
// a flagged upstream forever: after backoff.threshold consecutive failed
|
||||
// attempts the lane pauses for backoff.base, doubling every further trip
|
||||
// (one strike per trip) up to backoff.max. A success closes the breaker.
|
||||
backoff anonymousBackoff
|
||||
breakerUntil atomic.Int64
|
||||
breakerStrikes atomic.Int32
|
||||
consecutive atomic.Int32
|
||||
}
|
||||
|
||||
type anonymousBackoff struct {
|
||||
threshold int32
|
||||
base time.Duration
|
||||
max time.Duration
|
||||
}
|
||||
|
||||
type anonymousNode struct {
|
||||
@@ -73,8 +87,8 @@ type anonymousCursor struct {
|
||||
|
||||
// anonymousPool builds one anonymous node per proxy transport, or an empty
|
||||
// pool when the anonymous tier is disabled.
|
||||
func anonymousPool(enabled bool, transports *proxyTransports, cooldown time.Duration) *anonymousNodes {
|
||||
pool := &anonymousNodes{cooldown: cooldown}
|
||||
func anonymousPool(enabled bool, transports *proxyTransports, cooldown time.Duration, backoff anonymousBackoff) *anonymousNodes {
|
||||
pool := &anonymousNodes{cooldown: cooldown, backoff: backoff}
|
||||
if !enabled || transports == nil {
|
||||
return pool
|
||||
}
|
||||
@@ -119,6 +133,60 @@ func (p *anonymousNodes) CursorFor(affinity string) anonymousCursor {
|
||||
return anonymousCursor{pool: p, start: start}
|
||||
}
|
||||
|
||||
// Paused reports whether the breaker currently holds the lane shut.
|
||||
func (p *anonymousNodes) Paused() bool {
|
||||
if p == nil {
|
||||
return false
|
||||
}
|
||||
until := p.breakerUntil.Load()
|
||||
return until != 0 && time.Now().UnixNano() < until
|
||||
}
|
||||
|
||||
// NoteSuccess closes the breaker and forgets the strikes.
|
||||
func (p *anonymousNodes) NoteSuccess() {
|
||||
if p == nil {
|
||||
return
|
||||
}
|
||||
p.consecutive.Store(0)
|
||||
p.breakerStrikes.Store(0)
|
||||
p.breakerUntil.Store(0)
|
||||
}
|
||||
|
||||
// NoteFailure records one failed attempt. It reports the pause window when the
|
||||
// consecutive-failure threshold trips the breaker.
|
||||
func (p *anonymousNodes) NoteFailure() (time.Duration, bool) {
|
||||
if p == nil || p.backoff.threshold < 1 {
|
||||
return 0, false
|
||||
}
|
||||
if p.consecutive.Add(1) < p.backoff.threshold {
|
||||
return 0, false
|
||||
}
|
||||
return p.trip()
|
||||
}
|
||||
|
||||
// ForceOpen trips the breaker immediately. A 403 or 429 from the anonymous
|
||||
// upstream is a clear "blocked" signal (abuse detection, fingerprint gate or
|
||||
// region lock), and continuing to probe only extends the block, so it does
|
||||
// not wait for the consecutive-failure threshold.
|
||||
func (p *anonymousNodes) ForceOpen() (time.Duration, bool) {
|
||||
if p == nil || p.backoff.threshold < 1 {
|
||||
return 0, false
|
||||
}
|
||||
return p.trip()
|
||||
}
|
||||
|
||||
// trip opens the breaker for the next backoff window and returns it.
|
||||
func (p *anonymousNodes) trip() (time.Duration, bool) {
|
||||
p.consecutive.Store(0)
|
||||
strike := p.breakerStrikes.Add(1)
|
||||
pause := p.backoff.base << min(strike-1, 30)
|
||||
if pause > p.backoff.max || pause <= 0 {
|
||||
pause = p.backoff.max
|
||||
}
|
||||
p.breakerUntil.Store(time.Now().Add(pause).UnixNano())
|
||||
return pause, true
|
||||
}
|
||||
|
||||
// Next returns the next node to try. Its first pass visits every node once
|
||||
// from the cursor's start and returns each healthy, non-cooling static proxy
|
||||
// and each rotating proxy-pool transport (#pool) it reaches, so healthy nodes
|
||||
|
||||
@@ -88,6 +88,11 @@ func probePayload(model string, protocol wire.Protocol, effort string, v1 bool)
|
||||
// when every lane reported it; any other failure keeps the result
|
||||
// inconclusive.
|
||||
func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult {
|
||||
if g.anonymous.Paused() {
|
||||
// The breaker is open; probing now would just refresh the upstream's
|
||||
// abuse window.
|
||||
return probeResult{reason: "anonymous_paused", attempted: false}
|
||||
}
|
||||
if !g.catalog.IsFreeModel(model) {
|
||||
return probeResult{reason: "not_free"}
|
||||
}
|
||||
|
||||
@@ -303,6 +303,11 @@ func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodie
|
||||
// tiers. It returns the last response (body still open), else the last error,
|
||||
// plus the number of attempts made.
|
||||
func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (*http.Response, error, int) {
|
||||
// The breaker holds the lane shut for an hour-scale window after repeated
|
||||
// failures: poking a flagged upstream again would only extend the block.
|
||||
if g.anonymous.Paused() {
|
||||
return nil, errors.New("anonymous lane paused by its circuit breaker"), 0
|
||||
}
|
||||
var lastResponse *http.Response
|
||||
var lastErr error
|
||||
cursor := g.anonymous.CursorFor(ids.Session)
|
||||
@@ -1136,8 +1141,22 @@ func (g *Gateway) observeAnonymousResult(ctx context.Context, node *anonymousNod
|
||||
g.syncProxyResult(ctx, node.proxy, status, err)
|
||||
if err == nil && status/100 == 2 {
|
||||
g.anonymous.MarkSuccess(node)
|
||||
g.anonymous.NoteSuccess()
|
||||
} else {
|
||||
g.anonymous.MarkFailure(node, resp, err)
|
||||
var pause time.Duration
|
||||
var tripped bool
|
||||
if status == http.StatusForbidden || status == http.StatusTooManyRequests {
|
||||
// Clearly blocked: stop probing immediately instead of letting
|
||||
// further requests extend the upstream's abuse window.
|
||||
pause, tripped = g.anonymous.ForceOpen()
|
||||
} else {
|
||||
pause, tripped = g.anonymous.NoteFailure()
|
||||
}
|
||||
if tripped {
|
||||
g.logger.Warn("anonymous lane circuit breaker opened",
|
||||
"component", "upstream", "event", "anonymous_breaker_open", "status", status, "paused_for", pause.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user