mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-06 00:01:05 +00:00
fix: accurately identify token expiration vs network issues and skip retries/fallback for expired tokens (#308)
This commit is contained in:
1 parent
19bfce3167
commit
e1b538c84b
3 files changed
+59
-11
No files matched your search
@@ -63,13 +63,42 @@ class RateLimitsReverse:
|
||||
)
|
||||
|
||||
if response.status_code != 200:
|
||||
try:
|
||||
resp_text = response.text
|
||||
except Exception:
|
||||
resp_text = "N/A"
|
||||
|
||||
# --- 识别逻辑开始 ---
|
||||
# 区分是真正的 Token 过期还是 Cloudflare 拦截
|
||||
is_token_expired = False
|
||||
server_header = response.headers.get("Server", "").lower()
|
||||
content_type = response.headers.get("Content-Type", "").lower()
|
||||
|
||||
# 1. 如果是 Cloudflare 拦截,通常 Server 头包含 cloudflare,且返回 HTML (包含 challenge 关键字)
|
||||
is_cloudflare = "cloudflare" in server_header or "challenge-platform" in resp_text
|
||||
|
||||
# 2. 如果是 401 且返回 JSON 内容包含认证失败关键字,则确认为 Token 过期
|
||||
if response.status_code == 401 and "application/json" in content_type:
|
||||
# Grok 典型的认证失败返回通常包含 unauthorized 相关信息
|
||||
if "unauthorized" in resp_text.lower() or "not logged in" in resp_text.lower():
|
||||
is_token_expired = True
|
||||
# --- 识别逻辑结束 ---
|
||||
|
||||
logger.error(
|
||||
f"RateLimitsReverse: Request failed, {response.status_code}",
|
||||
f"RateLimitsReverse: Request failed, status={response.status_code}, "
|
||||
f"is_token_expired={is_token_expired}, is_cloudflare={is_cloudflare}, "
|
||||
f"Body: {resp_text[:300]}",
|
||||
extra={"error_type": "UpstreamException"},
|
||||
)
|
||||
|
||||
raise UpstreamException(
|
||||
message=f"RateLimitsReverse: Request failed, {response.status_code}",
|
||||
details={"status": response.status_code},
|
||||
details={
|
||||
"status": response.status_code,
|
||||
"body": resp_text,
|
||||
"is_token_expired": is_token_expired,
|
||||
"is_cloudflare": is_cloudflare
|
||||
},
|
||||
)
|
||||
|
||||
return response
|
||||
|
||||
@@ -32,7 +32,7 @@ class RetryContext:
|
||||
# Decorrelated jitter state
|
||||
self._last_delay = self.backoff_base
|
||||
|
||||
def should_retry(self, status_code: int) -> bool:
|
||||
def should_retry(self, status_code: int, error: Exception = None) -> bool:
|
||||
"""Check if should retry."""
|
||||
if self.attempt >= self.max_retry:
|
||||
return False
|
||||
@@ -40,6 +40,15 @@ class RetryContext:
|
||||
return False
|
||||
if self.total_delay >= self.retry_budget:
|
||||
return False
|
||||
|
||||
# --- 准确判定逻辑开始 ---
|
||||
# 如果已经明确判定为 Token 过期,则不进行重试
|
||||
if isinstance(error, UpstreamException) and error.details:
|
||||
if error.details.get("is_token_expired", False):
|
||||
logger.warning("Confirmed Token Expired, skipping retries.")
|
||||
return False
|
||||
# --- 准确判定逻辑结束 ---
|
||||
|
||||
return True
|
||||
|
||||
def record_error(self, status_code: int, error: Exception):
|
||||
@@ -182,7 +191,7 @@ async def retry_on_status(
|
||||
ctx.record_error(status_code, e)
|
||||
|
||||
# Check if should retry
|
||||
if ctx.should_retry(status_code):
|
||||
if ctx.should_retry(status_code, e):
|
||||
# Extract Retry-After
|
||||
retry_after = extract_retry_after(e)
|
||||
|
||||
|
||||
@@ -576,13 +576,23 @@ class TokenManager:
|
||||
|
||||
except Exception as e:
|
||||
if isinstance(e, UpstreamException):
|
||||
status = None
|
||||
if e.details and "status" in e.details:
|
||||
status = e.details["status"]
|
||||
else:
|
||||
status = getattr(e, "status_code", None)
|
||||
if status == 401:
|
||||
status = e.details.get("status") if e.details else getattr(e, "status_code", None)
|
||||
is_token_expired = e.details.get("is_token_expired", False) if e.details else False
|
||||
|
||||
# 如果 401 且已确认是 Token 过期(非 Cloudflare 拦截等环境问题)
|
||||
if status == 401 and is_token_expired:
|
||||
await self.record_fail(token_str, status, "rate_limits_auth_failed")
|
||||
# Token 已过期,不进行本地降级,直接返回失败以寻找下一个可用 Token
|
||||
logger.warning(
|
||||
f"Token {raw_token[:10]}...: API sync failed (Confirmed Token Expired), skipping fallback"
|
||||
)
|
||||
return False
|
||||
|
||||
# 如果是 401 但无法确认过期(可能是环境干扰、Cloudflare、或不明确的 401)
|
||||
# 我们按照您的要求“保留之前的逻辑不变”,即记录失败后尝试降级(fallback to local)
|
||||
if status == 401:
|
||||
await self.record_fail(token_str, status, "rate_limits_auth_unknown")
|
||||
|
||||
logger.warning(
|
||||
f"Token {raw_token[:10]}...: API sync failed, fallback to local ({e})"
|
||||
)
|
||||
@@ -605,7 +615,7 @@ class TokenManager:
|
||||
|
||||
Args:
|
||||
token_str: Token 字符串
|
||||
status_code: HTTP 状态码
|
||||
status_code: HTTP Status Code
|
||||
reason: 失败原因
|
||||
|
||||
Returns:
|
||||
|
||||
Reference in new issue
Block a user