fix: 全局凭据写入兼容 Docker 挂载,地图支持账户凭据兜底

凭据保存
- token_config.txt 是 Docker 单文件 bind mount,容器内 os.replace 会返回 EBUSY,
  导致更新全局凭据必定 500。
- 保留原子替换;rename 失败时回退 O_TRUNC 原地写入 + fsync,并清理临时文件。

地图兜底
- request_map_uncached 统一供 /api/map、采集任务、管理端原始地图使用。
- 全局凭据返回 102001/token_invalid,或强验证缺 AccessToken 时,
  改用账户里带真实 AccessToken 的用户凭据重拉地图。
- 优先复用上次成功账户,失败账户短期标记,全局恢复后自动切回。
- 无可用账户时返回明确原因,不再只报“全局凭据失效”。

测试
- 新增 test_token_config_save.py:EBUSY 回退、正常原子写两条路径。
- 新增 test_map_credential_fallback.py:全局正常、失效兜底、坏账户跳过、
  无可用账户、强验证 403 五种场景。
- 全量 329 pytest 通过。
This commit is contained in:
zzy
2026-11-26 18:34:01 +08:00
parent aa6132f3e1
commit bc37f86eac
4 changed files with 270 additions and 4 deletions
+110 -3
View File
@@ -274,13 +274,100 @@ def _normalize_token_invalid(result: dict, scope: str):
return result
# 全局凭据失效时,本进程最近一次兜底成功的用户;以及短期内确认不可用的用户,
# 避免每次刷新地图都把同一批失效凭据重新试一遍。
_MAP_FALLBACK_USER_ID = None
_MAP_BAD_USERS: dict = {}
_MAP_BAD_TTL_SECONDS = 600
def _is_map_auth_failure(result) -> bool:
"""全局/用户凭据被上游明确拒绝(区别于网络故障、限流等临时错误)。"""
if not isinstance(result, dict):
return False
if result.get("token_invalid") or result.get("rtn_code") == 102001:
return True
message = str(result.get("message") or "")
return result.get("rtn_code") == 403 and "AccessToken" in message
def _map_fallback_candidates(limit: int = 8):
"""可按「全局凭据」替代拉地图的用户:必须同时有 token_id 和真实 access_token。
只有 token_id 的用户只能用伪装签名,上游一律 102001,拿来兜底没有意义。
"""
from db import get_db
conn = get_db()
try:
rows = conn.execute("""
SELECT id FROM users
WHERE token_id IS NOT NULL AND token_id != ''
AND token_id != '1291378'
AND access_token IS NOT NULL AND access_token != ''
AND access_token != 'xiaobai'
ORDER BY id DESC LIMIT ?
""", (int(limit),)).fetchall()
return [int(r["id"]) for r in rows]
except Exception as exc:
print(f"[地图兜底] 查询可用账户失败: {exc}")
return []
finally:
conn.close()
def request_map_uncached(bike_type: str = "1") -> dict:
"""拉实时地图;全局凭据失效时改用账户里可用的用户凭据兜底。
这条链被 /api/map、采集任务、管理端原始地图共同使用,所以放在这里,
避免每个调用点各自实现一遍。
"""
global _MAP_FALLBACK_USER_ID
params = {"type": str(bike_type).strip() or "1"}
result = _request_api_uncached("GET", "/project/map", params=params)
if not _is_map_auth_failure(result):
if _MAP_FALLBACK_USER_ID is not None:
print("[地图兜底] 全局凭据已恢复,改回全局凭据拉取地图")
_MAP_FALLBACK_USER_ID = None
return result
now = time.time()
for uid in [k for k, until in _MAP_BAD_USERS.items() if until <= now]:
_MAP_BAD_USERS.pop(uid, None)
candidates = []
if _MAP_FALLBACK_USER_ID is not None:
candidates.append(_MAP_FALLBACK_USER_ID)
for uid in _map_fallback_candidates():
if uid not in candidates:
candidates.append(uid)
for uid in candidates:
bad_until = _MAP_BAD_USERS.get(uid, 0)
if bad_until and now < bad_until:
continue
candidate = request_with_user_auth(
uid, "GET", "/project/map", params=params, _silent=True)
if candidate.get("rtn_code") == 0:
if _MAP_FALLBACK_USER_ID != uid:
print(f"[地图兜底] 全局凭据不可用,改用用户 #{uid} 的凭据拉取地图")
_MAP_FALLBACK_USER_ID = uid
return candidate
if _is_map_auth_failure(candidate):
_MAP_BAD_USERS[uid] = now + _MAP_BAD_TTL_SECONDS
# 没有可用账户:保留全局错误,但把原因说清楚,方便管理员判断该更新哪一边。
fallback = dict(result)
fallback["message"] = ("地图数据暂不可用:服务器全局凭据失效,"
"且没有配置了有效 AccessToken 的账户可兜底")
print("[地图兜底] 全局凭据失效,且没有可用账户凭据")
return fallback
def request_api(method: str, path: str, params: dict = None, data: dict = None) -> dict:
"""Share global map reads across users, collection jobs and worker processes."""
if method.upper() == "GET" and path == "/project/map":
from map_cache import shared_map_cache
bike_type = str((params or {}).get("type", "1")).strip()
return shared_map_cache.get(bike_type, lambda: _request_api_uncached(
method, path, params={**(params or {}), "type": bike_type}, data=data))
return shared_map_cache.get(bike_type, lambda: request_map_uncached(bike_type))
return _request_api_uncached(method, path, params=params, data=data)
@@ -403,7 +490,27 @@ def save_token_config(token_id: str, access_token: str):
os.chmod(tmp_path, 0o600)
except OSError:
pass
os.replace(str(tmp_path), str(_TOKEN_CONFIG_PATH))
try:
os.replace(str(tmp_path), str(_TOKEN_CONFIG_PATH))
except OSError as exc:
# Docker 里 token_config.txt 常以**单文件 bind mount** 挂进来:
# 容器内对挂载点 rename 会返回 EBUSY(Device or resource busy),
# 于是原来的原子写必定保存失败。此时退回「原地截断写入」:
# 无法跨文件原子替换,但对挂载文件是唯一可行的写法。
print(f"[token配置] rename 不可用({exc}),改走原地写入"
f"(单文件挂载的预期情况)")
in_place = os.open(
str(_TOKEN_CONFIG_PATH),
os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
try:
os.write(in_place, text.encode("utf-8"))
os.fsync(in_place)
finally:
os.close(in_place)
try:
tmp_path.unlink()
except OSError:
pass
try:
os.chmod(_TOKEN_CONFIG_PATH, 0o600)
except OSError: