Merge pull request #7891 from aishangwuji/fix/opencode-go-usage-retry-after-and-403

fix(opencode): cap Retry-After backoff at 24h and report neutral 403
This commit is contained in:
Wesley Liddick authored and GitHub committed 2026-10-08 11:31:40 +08:00
commit bbf1d37783
6 files changed
+59 -15

No files matched your search

+11 -2
View File
@@ -779,7 +779,7 @@ func (s *OpenCodeGoUsageService) refreshLoadedAccount(ctx context.Context, accou
return s.persistFailure(ctx, account, intervalMinutes, now, resp.StatusCode, "unauthorized", retryAfter(resp.Header, now), true)
}
if resp.StatusCode == http.StatusForbidden {
return s.persistFailure(ctx, account, intervalMinutes, now, resp.StatusCode, "OpenCode Go subscription required (403)", retryAfter(resp.Header, now), false)
return s.persistFailure(ctx, account, intervalMinutes, now, resp.StatusCode, "forbidden", retryAfter(resp.Header, now), false)
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return s.persistFailure(ctx, account, intervalMinutes, now, resp.StatusCode, "http_error", retryAfter(resp.Header, now), false)
@@ -1000,8 +1000,17 @@ func decodeOpenCodeGoUsageSnapshot(extra map[string]any) *OpenCodeGoUsageSnapsho
// nextOpenCodeGoUsageDelay computes the not-before delay for the next refresh:
// interval * 2^min(failureCount-1, 6) capped at 24h, ±10% jitter capped at 5min,
// never below a Retry-After hint or one minute.
// never below a Retry-After hint or one minute. The hint is honored over the
// local backoff but clamped to the same 24h ceiling: it arrives over a network
// path we do not control (upstream CDN, account proxy), and an unbounded value
// would freeze a group's auto refresh indefinitely.
func nextOpenCodeGoUsageDelay(intervalMinutes, failureCount int, retryAfterDuration time.Duration) time.Duration {
if retryAfterDuration < 0 {
retryAfterDuration = 0
}
if retryAfterDuration > opencodeGoUsageMaxDelay {
retryAfterDuration = opencodeGoUsageMaxDelay
}
minimumDelay := retryAfterDuration
base := time.Duration(intervalMinutes) * time.Minute
if base < opencodeGoUsageMinIntervalMinutes*time.Minute {
@@ -320,7 +320,7 @@ func TestOpenCodeGoUsageRefresh401Unauthorized(t *testing.T) {
require.True(t, openCodeGoUsageAutoRefreshEnabled(account))
}
func TestOpenCodeGoUsageRefresh403SubscriptionRequired(t *testing.T) {
func TestOpenCodeGoUsageRefresh403Forbidden(t *testing.T) {
account := openCodeGoUsageAccount(7)
repo := &openCodeGoUsageTestRepo{accounts: map[int64]*Account{7: account}}
stub := &openCodeGoUsageHTTPStub{status: http.StatusForbidden}
@@ -330,7 +330,7 @@ func TestOpenCodeGoUsageRefresh403SubscriptionRequired(t *testing.T) {
require.NoError(t, err)
require.Equal(t, OpenCodeGoUsageStatusFailed, state.Snapshot.Status)
require.Equal(t, http.StatusForbidden, state.Snapshot.HTTPStatus)
require.Equal(t, "OpenCode Go subscription required (403)", state.Snapshot.LastError)
require.Equal(t, "forbidden", state.Snapshot.LastError)
require.Equal(t, 1, state.Snapshot.FailureCount)
}
@@ -403,11 +403,39 @@ func TestNextOpenCodeGoUsageDelayBackoff(t *testing.T) {
delay = nextOpenCodeGoUsageDelay(15, 0, 2*time.Hour)
require.GreaterOrEqual(t, delay, 2*time.Hour)
// a hint beyond the 24h ceiling is clamped, never adopted verbatim
delay = nextOpenCodeGoUsageDelay(15, 0, 48*time.Hour)
require.GreaterOrEqual(t, delay, 23*time.Hour+55*time.Minute)
require.LessOrEqual(t, delay, 24*time.Hour+5*time.Minute)
// floor of one minute
delay = nextOpenCodeGoUsageDelay(5, 0, 0)
require.GreaterOrEqual(t, delay, time.Minute)
}
func TestOpenCodeGoUsageRefreshClampsHugeRetryAfter(t *testing.T) {
now := time.Now().UTC()
account := openCodeGoUsageAccount(7)
repo := &openCodeGoUsageTestRepo{accounts: map[int64]*Account{7: account}}
stub := &openCodeGoUsageHTTPStub{
status: http.StatusTooManyRequests,
header: http.Header{"Retry-After": []string{"99999999"}},
}
svc := newOpenCodeGoUsageTestService(t, repo, stub, &upstreamBillingProbeSettingRepo{})
svc.now = func() time.Time { return now }
state, err := svc.Refresh(context.Background(), 7)
require.NoError(t, err)
require.Equal(t, OpenCodeGoUsageStatusFailed, state.Snapshot.Status)
require.Equal(t, http.StatusTooManyRequests, state.Snapshot.HTTPStatus)
require.Equal(t, "http_error", state.Snapshot.LastError)
maxExpected := now.Add(24*time.Hour + 5*time.Minute)
minExpected := now.Add(23*time.Hour + 55*time.Minute)
require.True(t, state.Snapshot.NextRefreshAt.Before(maxExpected.Add(time.Second)))
require.True(t, state.Snapshot.NextRefreshAt.After(minExpected.Add(-time.Second)))
}
func TestOpenCodeGoUsageManualRefreshThrottle(t *testing.T) {
now := time.Now().UTC()
account := openCodeGoUsageAccount(7)
@@ -1105,6 +1105,12 @@ func (s *UpstreamBillingProbeService) currentTime() time.Time {
}
func nextProbeDelay(intervalMinutes int, retryAfterDuration time.Duration) time.Duration {
if retryAfterDuration < 0 {
retryAfterDuration = 0
}
if retryAfterDuration > upstreamBillingProbeMaxDelay {
retryAfterDuration = upstreamBillingProbeMaxDelay
}
interval := time.Duration(intervalMinutes) * time.Minute
if interval < upstreamBillingProbeMinIntervalMinutes*time.Minute {
interval = upstreamBillingProbeMinIntervalMinutes * time.Minute
@@ -1120,8 +1126,8 @@ func nextProbeDelay(intervalMinutes int, retryAfterDuration time.Duration) time.
interval += time.Duration(rand.Int64N(int64(jitterRange)*2+1)) - jitterRange
}
if retryAfterDuration > interval {
// Retry-After is an explicit upstream instruction; do not shorten it
// with the local maximum delay.
// Retry-After is an explicit upstream instruction; honor it over the
// local backoff interval, clamped to the same 24h ceiling.
return retryAfterDuration
}
if interval > upstreamBillingProbeMaxDelay {
@@ -1133,8 +1139,7 @@ func nextProbeDelay(intervalMinutes int, retryAfterDuration time.Duration) time.
// unsupportedProbeDelay 拉长 unsupported 账号的重探间隔,让无效候选自然退出
// 热队列,不再和真正接入 sub2api 的中转账号抢每周期的探测名额。
// 仍按 upstreamBillingProbeMaxDelay 封顶,保证上游后来接入 sub2api 时最迟一天
// 内会被重新发现;base 本身已达上限(例如 Retry-After 明确要求更久)时原样返回,
// 不缩短上游指令。
// 内会被重新发现;base 本身亦受 24h 封顶保护。
func unsupportedProbeDelay(intervalMinutes int, retryAfterDuration time.Duration) time.Duration {
base := nextProbeDelay(intervalMinutes, retryAfterDuration)
if base >= upstreamBillingProbeMaxDelay {
@@ -767,13 +767,13 @@ func TestUpstreamBillingProbeFailurePreservesLastSuccessAndRetryAfter(t *testing
require.Equal(t, initialRate, *account.RateMultiplier)
}
func TestUpstreamBillingProbeRetryAfterIsNotShortened(t *testing.T) {
func TestUpstreamBillingProbeRetryAfterIsCappedAtMaxDelay(t *testing.T) {
delay := nextProbeDelay(30, 48*time.Hour)
require.Equal(t, 48*time.Hour, delay)
require.Equal(t, upstreamBillingProbeMaxDelay, delay)
}
// unsupported 的重探间隔明显长于普通失败,但始终有上界:上游后来接入 sub2api
// 时最迟一天内会被重新发现,且不会缩短上游 Retry-After 指令。
// 时最迟一天内会被重新发现,且上游超长 Retry-After 亦受 24h 封顶保护。
func TestUpstreamBillingProbeUnsupportedDelayIsStretchedAndBounded(t *testing.T) {
// 默认 30 分钟 interval:普通失败 24~36 分钟,unsupported 为其 8 倍。
stretched := unsupportedProbeDelay(30, 0)
@@ -785,8 +785,8 @@ func TestUpstreamBillingProbeUnsupportedDelayIsStretchedAndBounded(t *testing.T)
require.LessOrEqual(t, unsupportedProbeDelay(upstreamBillingProbeMaxIntervalMinutes, 0), upstreamBillingProbeMaxDelay)
require.Positive(t, unsupportedProbeDelay(upstreamBillingProbeMinIntervalMinutes, 0))
// Retry-After 更长时原样保留,不被封顶缩短;更短时至少不早于该指令。
require.Equal(t, 48*time.Hour, unsupportedProbeDelay(30, 48*time.Hour))
// Retry-After 更长时受封顶保护,不超过 upstreamBillingProbeMaxDelay;更短时至少不早于该指令。
require.Equal(t, upstreamBillingProbeMaxDelay, unsupportedProbeDelay(30, 48*time.Hour))
require.GreaterOrEqual(t, unsupportedProbeDelay(30, time.Hour), time.Hour)
}
@@ -203,7 +203,8 @@ export default {
refreshSuccess: 'OpenCode Go usage refreshed',
refreshFailed: 'Failed to refresh OpenCode Go usage',
errors: {
OPENCODE_GO_USAGE_REFRESH_RATE_LIMITED: 'Refresh is limited. Try again in {retry_after_seconds} seconds.'
OPENCODE_GO_USAGE_REFRESH_RATE_LIMITED: 'Refresh is limited. Try again in {retry_after_seconds} seconds.',
forbidden: 'Upstream returned 403: could be a missing/expired OpenCode Go subscription or a WAF/access-policy block; check the network path and HTTP status.'
}
},
types: {
@@ -406,7 +406,8 @@ export default {
refreshSuccess: 'OpenCode Go 用量已刷新',
refreshFailed: '刷新 OpenCode Go 用量失败',
errors: {
OPENCODE_GO_USAGE_REFRESH_RATE_LIMITED: '刷新过于频繁,请在 {retry_after_seconds} 秒后重试。'
OPENCODE_GO_USAGE_REFRESH_RATE_LIMITED: '刷新过于频繁,请在 {retry_after_seconds} 秒后重试。',
forbidden: '上游返回 403:可能是订阅缺失/失效,也可能是 WAF 或访问策略拦截,请结合网络路径与 HTTP 状态排查。'
}
},
types: {