feat:优化执行步骤

This commit is contained in:
2026-10-08 00:28:29 -07:00
parent 62a5b2a8f4
commit 05c050d2ba
20 changed files with 625 additions and 69 deletions
+33 -11
View File
@@ -1,5 +1,6 @@
"""用户中心客户端:用请求携带的 token 换取当前用户,结果短时缓存"""
import asyncio
import hashlib
import time
from functools import cache
@@ -14,6 +15,9 @@ from app.schemas.user import CurrentUser
# 用户中心 401 时提示调用方用 Bearer token 重新认证
BEARER_CHALLENGE = {"WWW-Authenticate": "Bearer"}
# 瞬时故障的重试间隔(秒),长度即重试次数
RETRY_DELAYS = (0.2, 0.5)
class UserCenterClient:
def __init__(
@@ -55,23 +59,41 @@ class UserCenterClient:
del self._cache[stale]
self._cache[key] = (now + ttl, user)
async def _request_with_retry(self, token: str) -> httpx.Response:
"""校验是幂等的 GET:连接失败、超时和 5xx 属于瞬时故障,短间隔重试"""
attempts = 1 + len(RETRY_DELAYS)
for attempt in range(attempts):
try:
response = await self._get_client().get(
"/api/users/me", headers={"Authorization": f"Bearer {token}"}
)
except httpx.HTTPError as error:
logger.opt(exception=error).warning(
"用户中心请求失败 attempt={}/{}", attempt + 1, attempts
)
if attempt == attempts - 1:
raise BizException(503, "用户中心不可用") from error
else:
if response.status_code < 500:
return response
logger.warning(
"用户中心返回 HTTP {} attempt={}/{}",
response.status_code,
attempt + 1,
attempts,
)
if attempt == attempts - 1:
raise BizException(503, "用户中心不可用")
await asyncio.sleep(RETRY_DELAYS[attempt])
raise AssertionError("unreachable")
async def fetch_current_user(self, token: str) -> CurrentUser:
key = hashlib.sha256(token.encode()).hexdigest()
user = self._cached(key)
if user is not None:
return user
try:
response = await self._get_client().get(
"/api/users/me", headers={"Authorization": f"Bearer {token}"}
)
except httpx.HTTPError as error:
logger.opt(exception=error).warning("用户中心请求失败")
raise BizException(503, "用户中心不可用") from error
if response.status_code >= 500:
logger.warning("用户中心返回 HTTP {}", response.status_code)
raise BizException(503, "用户中心不可用")
response = await self._request_with_retry(token)
try:
body = response.json()
except ValueError: