fix(backend): 修复 P0/P1 严重安全和稳定性问题

P0 严重问题修复:
- 优化重试机制:降至 5 次 + 指数退避 + 10s 上限,防止请求堆积
- 修复 SSE 错误格式:符合 Anthropic API 规范,添加错误类型标准化

P1 重要问题修复:
- 防止 DOS 攻击:使用 io.LimitReader 限制请求体 10MB,流式解析
- 修复计费数据丢失:改为同步计费,使用独立 context 防止中断

技术细节:
- 新增 retryBackoffDelay() 和 sleepWithContext() 支持 context 取消
- 新增 normalizeAnthropicErrorType() 和 sanitizePublicErrorMessage()
- 新增 parseGatewayRequestStream() 实现流式解析
- 新增 recordUsageSync() 确保计费数据持久化

影响:
- 极端场景重试时间从 30s 降至 ≤10s
- 防止高并发 OOM 攻击
- 消除计费数据丢失风险
- 提升客户端兼容性
This commit is contained in:
IanShaw027
2026-01-04 21:29:09 +08:00
parent d36392b74f
commit 7122b3b3b6
2 changed files with 135 additions and 55 deletions

View File

@@ -1157,6 +1157,9 @@ func (s *GatewayService) Forward(ctx context.Context, c *gin.Context, account *A
resp = retryResp
break
}
if retryResp != nil && retryResp.Body != nil {
_ = retryResp.Body.Close()
}
log.Printf("Account %d: signature error retry failed: %v", account.ID, retryErr)
} else {
log.Printf("Account %d: signature error retry build request failed: %v", account.ID, buildErr)
@@ -1603,10 +1606,10 @@ func (s *GatewayService) handleRetryExhaustedSideEffects(ctx context.Context, re
// OAuth/Setup Token 账号的 403标记账号异常
if account.IsOAuth() && statusCode == 403 {
s.rateLimitService.HandleUpstreamError(ctx, account, statusCode, resp.Header, body)
log.Printf("Account %d: marked as error after %d retries for status %d", account.ID, maxRetries, statusCode)
log.Printf("Account %d: marked as error after %d retries for status %d", account.ID, maxRetryAttempts, statusCode)
} else {
// API Key 未配置错误码:不标记账号状态
log.Printf("Account %d: upstream error %d after %d retries (not marking account)", account.ID, statusCode, maxRetries)
log.Printf("Account %d: upstream error %d after %d retries (not marking account)", account.ID, statusCode, maxRetryAttempts)
}
}