fix: 凭据告警误报停止 + 清理注册遗留默认 token + 补还车前先看小程序状态
线上事故:部署后全站收到「微信凭据已过期」邮件,实际 token 没过期。 根因(实测复现) - 只填 token_id、没有 access_token 的用户,请求只能用假签名(fake_signature), 上游对假签名一律回 102001;而 alerts.check_user_credentials_alive 把 102001 当成「凭据过期」,于是每个 token-only 用户都收到一封「已过期」。 收件人是「alert_email 或用户自己的 email」→ 看起来就是给全站群发。 改动 1) check_user_credentials_alive 不再发信、也不再探测 - 没有 access_token 就无法区分「token 过期」和「假签名被拒」,探测纯属浪费上游配额; 改为只统计并打印一条日志。真正的到期提醒交给 check_user_credentials(能解析 exp 的) 2) 注册遗留的默认 token - 老库 users.token_id 列带 DEFAULT '1291378',注册没写该列的用户被灌了假凭据 - init_db 迁移:token_id='1291378' 且无 access_token → 置 NULL(本地库实测清掉 3 个) - 告警三处(user/global/alive)统一用 _is_legacy_default_token 跳过这类值 3) 补还车前先看小程序状态(用户手动还过车的情况) - 新增 _upstream_ride_active(user_id, order_id):查 /user/info 的 nonDealOrder - _run_recovery 先问上游:上游说这单已结束 → 只做本地收尾(expired=1 + returned_at + 取消计时器),不再发 /record/return(避免 204010 与重复还车) - sweep / 重启补还车 / 巡检三条路径都带 order_id - _close_local_reminder 改名 _close_rental_locally,reminder 单与「已在小程序还车」共用 4) 顺手修:test_history_30d 的 subprocess 在 Windows 用 GBK 读 UTF-8 输出报错 本地库实测 - 迁移清理 3 个默认 token;check_user_credentials_alive() 返回 0(14 个 token-only 用户只记日志) - 全局凭据 10.9 天后到期 → 不触发三级告警(符合预期) 测试:161 pytest(新增凭据误报回归 2 条、上游优先补还车 2 条)+ 32 node 全绿
This commit is contained in:
@@ -585,8 +585,42 @@ def _recover_throttled(rental_id: int) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _run_recovery(rental_id: int, user_id: int):
|
||||
"""巡检/重启的补还车入口:成功后清掉节流记录,别让进程里留失败痕迹。"""
|
||||
def _upstream_ride_active(user_id: int, order_id):
|
||||
"""上游这张单还在骑吗?True=在骑 / False=已结束 / None=查不到(别下结论)。
|
||||
|
||||
用户很可能直接在小程序里点了还车 —— 那种情况下本地还挂着 expired=0,
|
||||
但我们**不能**再发一次 /record/return(上游会报订单不存在,白白制造错误)。
|
||||
所以补还车前先看上游状态,上游说结束了就只做本地收尾。
|
||||
"""
|
||||
if not user_id or not order_id:
|
||||
return None
|
||||
try:
|
||||
info = request_with_user_auth(user_id, "GET", "/user/info", _silent=True)
|
||||
except Exception as exc:
|
||||
print(f"[自动还车] 查询上游订单状态失败: {exc}")
|
||||
return None
|
||||
if not isinstance(info, dict) or info.get("rtn_code") != 0:
|
||||
return None
|
||||
non_deal = (info.get("data") or {}).get("nonDealOrder") or {}
|
||||
if not non_deal or not non_deal.get("order_id"):
|
||||
return False # 上游没有未完成订单 → 已经结束了
|
||||
if str(non_deal.get("order_id")) != str(order_id):
|
||||
return False # 上游挂的是另一张单 → 这张已经结束
|
||||
return str(non_deal.get("status")) == "2" # 2=骑行中
|
||||
|
||||
|
||||
def _run_recovery(rental_id: int, user_id: int, order_id=None):
|
||||
"""巡检/重启的补还车入口:成功后清掉节流记录,别让进程里留失败痕迹。
|
||||
|
||||
先问上游状态:上游说这单已结束(用户在小程序里还了),就只做本地收尾,
|
||||
不再打 /record/return。
|
||||
"""
|
||||
active = _upstream_ride_active(user_id, order_id) if order_id else None
|
||||
if active is False:
|
||||
_close_rental_locally(rental_id, "上游订单已结束(用户已在小程序还车)")
|
||||
_recover_last_at.pop(rental_id, None)
|
||||
return {"success": True, "skipped": True,
|
||||
"message": "上游订单已结束,仅做本地收尾"}
|
||||
try:
|
||||
result = auto_return_bike(rental_id, user_id) or {}
|
||||
if result.get("success"):
|
||||
@@ -634,13 +668,14 @@ def sweep_overdue_rentals(force: bool = False) -> int:
|
||||
# reminder 是纯本地计时提醒,没有上游订单:上游还不了,但也不能
|
||||
# 一直挂着 expired=0,否则用户页面横幅永远显示「用车中」。
|
||||
if str(rental.get("source") or "") == "reminder":
|
||||
_close_local_reminder(rental["id"])
|
||||
_close_rental_locally(rental["id"], "本地提醒单到期")
|
||||
closed_local += 1
|
||||
continue
|
||||
if _recover_throttled(rental["id"]):
|
||||
continue
|
||||
threading.Thread(target=_run_recovery,
|
||||
args=(rental["id"], rental.get("user_id")), daemon=True).start()
|
||||
args=(rental["id"], rental.get("user_id"), rental.get("order_id")),
|
||||
daemon=True).start()
|
||||
started += 1
|
||||
if started:
|
||||
print(f"[计时系统] 巡检兜底:{started} 单超期未还,已排队补还车")
|
||||
@@ -649,8 +684,13 @@ def sweep_overdue_rentals(force: bool = False) -> int:
|
||||
return started
|
||||
|
||||
|
||||
def _close_local_reminder(rental_id: int):
|
||||
"""本地提醒单到期:直接标记结束,不碰上游(它本来就没有上游订单)。"""
|
||||
def _close_rental_locally(rental_id: int, reason: str = ""):
|
||||
"""只做本地收尾:标记结束 + 实际还车时间 + 取消计时器,**不碰上游**。
|
||||
|
||||
适用于两种情况:
|
||||
1. reminder 单(本来就没有上游订单);
|
||||
2. 用户已经在小程序里还车了(上游查不到这张单,再发 /record/return 只会 204010)。
|
||||
"""
|
||||
tz = dt.timezone(dt.timedelta(hours=8))
|
||||
now_str = dt.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
||||
conn = get_db()
|
||||
@@ -667,13 +707,15 @@ def _close_local_reminder(rental_id: int):
|
||||
(rental_id,))
|
||||
conn.commit()
|
||||
except Exception as exc:
|
||||
print(f"[计时系统] 关闭本地提醒单 rental_id={rental_id} 失败: {exc}")
|
||||
print(f"[计时系统] 本地收尾 rental_id={rental_id} 失败: {exc}")
|
||||
finally:
|
||||
conn.close()
|
||||
try:
|
||||
_cancel_rental_timers(rental_id)
|
||||
except Exception:
|
||||
pass
|
||||
print(f"[计时系统] 本地收尾 rental_id={rental_id}"
|
||||
+ (f":{reason}" if reason else ""))
|
||||
|
||||
|
||||
def _should_auto_return(rental) -> bool:
|
||||
@@ -995,7 +1037,7 @@ def _recover_overdue_rental(rental: dict):
|
||||
if not user_id:
|
||||
print(f"[计时系统] rental_id={rental_id} 没有 user_id,跳过补还车")
|
||||
return
|
||||
result = _run_recovery(rental_id, user_id)
|
||||
result = _run_recovery(rental_id, user_id, rental.get("order_id"))
|
||||
print(f"[计时系统] 补还车结果 rental_id={rental_id}: {result.get('message')}")
|
||||
except Exception as exc:
|
||||
print(f"[计时系统] 补还车异常 rental_id={rental_id}: {exc}")
|
||||
@@ -1119,7 +1161,7 @@ def _check_user_order(user_id: int):
|
||||
"recovering": True}
|
||||
print(f"[订单检测] rental_id={rental['id']} 已过到期时间,补一次自动还车")
|
||||
threading.Thread(
|
||||
target=lambda: _run_recovery(rental["id"], user_id),
|
||||
target=lambda: _run_recovery(rental["id"], user_id, order_id),
|
||||
daemon=True
|
||||
).start()
|
||||
return {"ok": True, "active": True, "order_id": order_id,
|
||||
|
||||
Reference in New Issue
Block a user