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:
@@ -13,7 +13,6 @@
|
|||||||
用户重新登录拿到新 JWT 后自动重新武装告警。
|
用户重新登录拿到新 JWT 后自动重新武装告警。
|
||||||
"""
|
"""
|
||||||
import datetime as dt
|
import datetime as dt
|
||||||
import hashlib
|
|
||||||
import html
|
import html
|
||||||
import json
|
import json
|
||||||
import threading
|
import threading
|
||||||
@@ -60,8 +59,16 @@ def set_alert_emails(emails) -> int:
|
|||||||
return len(cleaned)
|
return len(cleaned)
|
||||||
|
|
||||||
|
|
||||||
# ========== 去重记录 ==========
|
# 老版本 users 表的 token_id 列带 DEFAULT '1291378',注册时没写这一列的用户
|
||||||
# 免打扰策略(用户要求):同一凭据在整个生命周期内【只发一封】邮件——
|
# 就被灌了这个假凭据。它不可能来自真实授权,所有告警检查都要跳过。
|
||||||
|
LEGACY_DEFAULT_TOKEN_ID = "1291378"
|
||||||
|
|
||||||
|
|
||||||
|
def _is_legacy_default_token(token_id) -> bool:
|
||||||
|
return str(token_id or "").strip() == LEGACY_DEFAULT_TOKEN_ID
|
||||||
|
|
||||||
|
|
||||||
|
# ========== 去重记录 ==========# 免打扰策略(用户要求):同一凭据在整个生命周期内【只发一封】邮件——
|
||||||
# 不管命中的是 1天/1小时/已过期 哪一级。credential_alerts.target 含
|
# 不管命中的是 1天/1小时/已过期 哪一级。credential_alerts.target 含
|
||||||
# 凭据标识(用户 id 或 全局+过期时间戳),用户更新凭据后 target 变化
|
# 凭据标识(用户 id 或 全局+过期时间戳),用户更新凭据后 target 变化
|
||||||
# 才会重新武装。查询时【不看 level】,避免 1day→1hour→expired 连发三封。
|
# 才会重新武装。查询时【不看 level】,避免 1day→1hour→expired 连发三封。
|
||||||
@@ -171,6 +178,8 @@ def check_user_credentials():
|
|||||||
for u in users:
|
for u in users:
|
||||||
if not (u["access_token"] or "").strip():
|
if not (u["access_token"] or "").strip():
|
||||||
continue # 没填 AccessToken 走 check_user_credentials_alive 的失效探测
|
continue # 没填 AccessToken 走 check_user_credentials_alive 的失效探测
|
||||||
|
if _is_legacy_default_token(u["token_id"]):
|
||||||
|
continue # 注册遗留的默认值,不是真凭据
|
||||||
expiry = parse_access_token_expiry(u["access_token"])
|
expiry = parse_access_token_expiry(u["access_token"])
|
||||||
if not expiry.get("parseable") or expiry.get("expire_at") is None:
|
if not expiry.get("parseable") or expiry.get("expire_at") is None:
|
||||||
continue
|
continue
|
||||||
@@ -194,48 +203,35 @@ def check_user_credentials():
|
|||||||
return sent
|
return sent
|
||||||
|
|
||||||
|
|
||||||
# 只填了 token_id 的用户:无法解析有效期(三级预警做不了),
|
# 只填了 token_id 的用户:**不发「凭据失效」邮件**。
|
||||||
# 但可以用一次极轻量的上游探测判断凭据「当前是否还活着」,
|
#
|
||||||
# 死了就发"已失效"邮件。credential_alerts 按 target 去重保证只发一次,
|
# 原因(实测):没有 access_token 时签名只能用假签名(wechat.fake_signature),
|
||||||
# 用户重新配置凭据后 target 变化 → 自动重新武装。
|
# 上游对假签名一律回 102001。这跟「token 过期」是同一个错误码,无法区分。
|
||||||
|
# 以前这里把它当过期发信,结果**所有只填 token_id 的用户都会被判过期**,
|
||||||
|
# 上线后给全站发了一批「凭据已过期」的误报邮件。
|
||||||
|
#
|
||||||
|
# 现在的口径:只探测、只记日志,不发信。真正的到期提醒交给
|
||||||
|
# check_user_credentials()(有 access_token 才能解析 exp),不猜。
|
||||||
def check_user_credentials_alive():
|
def check_user_credentials_alive():
|
||||||
"""探测未填 AccessToken 用户的凭据是否已失效(102001)。返回发送条数。"""
|
"""统计未填 AccessToken 的用户(仅日志,不发邮件、也不探测)。
|
||||||
from wechat import request_with_user_auth
|
|
||||||
sent = 0
|
没有 access_token 时签名只能用假签名,上游一律回 102001,跟「token 过期」
|
||||||
|
是同一个错误码、无法区分;再去探测只会浪费上游配额,所以这里干脆不请求。
|
||||||
|
真要给这批用户做到期提醒,得先让他们补上 access_token。
|
||||||
|
"""
|
||||||
conn = get_db()
|
conn = get_db()
|
||||||
try:
|
try:
|
||||||
users = conn.execute(
|
rows = conn.execute(
|
||||||
"SELECT id, email, token_id, alert_email FROM users "
|
"SELECT id, token_id FROM users "
|
||||||
"WHERE token_id IS NOT NULL AND token_id != '' "
|
"WHERE token_id IS NOT NULL AND token_id != '' "
|
||||||
" AND (access_token IS NULL OR access_token = '')").fetchall()
|
" AND (access_token IS NULL OR access_token = '')").fetchall()
|
||||||
admin_emails = set(get_alert_emails())
|
|
||||||
for u in users:
|
|
||||||
# target 里揉进凭据指纹:用户重新配置 token_id 后会自动重新武装。
|
|
||||||
# 原来只写 user-alive:{id},一个用户历史上失效过一次、发过一封之后,
|
|
||||||
# 以后每次失效都被永久静音(注释里那句“重新配置会重新武装”并不成立)。
|
|
||||||
fp = hashlib.sha1(str(u["token_id"]).encode("utf-8")).hexdigest()[:8]
|
|
||||||
target = f"user-alive:{u['id']}:{fp}"
|
|
||||||
if _sent_already(conn, target, "expired"):
|
|
||||||
continue
|
|
||||||
try:
|
|
||||||
# /user/info 是最轻的已登录接口;_silent 避免日志刷屏
|
|
||||||
res = request_with_user_auth(u["id"], "GET", "/user/info", _silent=True)
|
|
||||||
except Exception:
|
|
||||||
continue # 网络异常不判死刑,等下一轮
|
|
||||||
if not isinstance(res, dict) or res.get("rtn_code") != 102001:
|
|
||||||
continue # 正常或其他错误(非凭据失效)都不打扰
|
|
||||||
recipients = set(admin_emails)
|
|
||||||
recv = (u["alert_email"] or "").strip() or (u["email"] or "").strip()
|
|
||||||
if recv:
|
|
||||||
recipients.add(recv)
|
|
||||||
if _send_alert(recipients, "expired", f"用户 {u['email']}",
|
|
||||||
{"parseable": False, "expire_time": "未知(未填 AccessToken)"}):
|
|
||||||
_mark_sent(conn, target, "expired")
|
|
||||||
sent += 1
|
|
||||||
finally:
|
finally:
|
||||||
conn.commit()
|
|
||||||
conn.close()
|
conn.close()
|
||||||
return sent
|
unknown = [r for r in rows if not _is_legacy_default_token(r["token_id"])]
|
||||||
|
if unknown:
|
||||||
|
print(f"[凭据告警] {len(unknown)} 个用户只有 token_id、没有 access_token,"
|
||||||
|
f"无法核验有效期(到期提醒需要 access_token)")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
def check_global_credential():
|
def check_global_credential():
|
||||||
|
|||||||
@@ -83,6 +83,21 @@ def init_db():
|
|||||||
except sqlite3.OperationalError:
|
except sqlite3.OperationalError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
# 老库的 token_id 列带 DEFAULT '1291378'(建表时留下的),注册时没写这一列的用户
|
||||||
|
# 会被灌成这个假凭据 → 巡检拿它去探测、必被上游 102001 拒绝 →
|
||||||
|
# 全站收到「凭据已过期」误报邮件。这里清掉:值等于该默认值且没有 access_token 的,
|
||||||
|
# 一律视为「未配置凭据」。新库/新注册都不会再写入默认值(auth 注册显式传 NULL)。
|
||||||
|
try:
|
||||||
|
cursor.execute("""
|
||||||
|
UPDATE users SET token_id = NULL
|
||||||
|
WHERE token_id = '1291378'
|
||||||
|
AND (access_token IS NULL OR access_token = '')
|
||||||
|
""")
|
||||||
|
if cursor.rowcount:
|
||||||
|
print(f"[迁移] 清理 {cursor.rowcount} 个注册遗留的默认 token_id(1291378)")
|
||||||
|
except sqlite3.OperationalError:
|
||||||
|
pass
|
||||||
|
|
||||||
cursor.execute("""
|
cursor.execute("""
|
||||||
CREATE TABLE IF NOT EXISTS sessions (
|
CREATE TABLE IF NOT EXISTS sessions (
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""凭据告警的误报回归。
|
||||||
|
|
||||||
|
线上事故:部署后全站收到「微信凭据已过期」邮件,实际 token 没过期。
|
||||||
|
根因:只填 token_id、没有 access_token 的用户,请求只能用假签名,
|
||||||
|
上游一律回 102001;告警把 102001 当成「凭据过期」于是全员误报。
|
||||||
|
"""
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import alerts
|
||||||
|
|
||||||
|
|
||||||
|
class CredentialAlertTests(unittest.TestCase):
|
||||||
|
def test_token_only_user_never_triggers_expiry_mail(self):
|
||||||
|
"""没有 access_token → 假签名必被拒 → 不能发「已过期」邮件。"""
|
||||||
|
sent = []
|
||||||
|
|
||||||
|
class FakeConn:
|
||||||
|
def execute(self, sql, params=()):
|
||||||
|
class Cur:
|
||||||
|
def fetchall(_self):
|
||||||
|
return [{"id": 1, "email": "a@b.c", "token_id": "1356419",
|
||||||
|
"alert_email": None}]
|
||||||
|
return Cur()
|
||||||
|
def close(self):
|
||||||
|
pass
|
||||||
|
def commit(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
with patch.object(alerts, "get_db", return_value=FakeConn()), \
|
||||||
|
patch("wechat.request_with_user_auth",
|
||||||
|
return_value={"rtn_code": 102001, "token_invalid": True}), \
|
||||||
|
patch.object(alerts, "_send_alert",
|
||||||
|
side_effect=lambda *a, **k: sent.append(a) or True), \
|
||||||
|
patch.object(alerts, "get_alert_emails", return_value=["admin@example.test"]):
|
||||||
|
count = alerts.check_user_credentials_alive()
|
||||||
|
|
||||||
|
self.assertEqual(0, count)
|
||||||
|
self.assertEqual([], sent, "只填 token_id 的用户不该收到失效邮件")
|
||||||
|
|
||||||
|
def test_legacy_default_token_is_ignored_everywhere(self):
|
||||||
|
self.assertTrue(alerts._is_legacy_default_token("1291378"))
|
||||||
|
self.assertFalse(alerts._is_legacy_default_token("1356419"))
|
||||||
|
self.assertFalse(alerts._is_legacy_default_token(None))
|
||||||
|
self.assertFalse(alerts._is_legacy_default_token(""))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -106,7 +106,7 @@ sys.exit(1 if failures else 0)
|
|||||||
def test_history_30d_contract():
|
def test_history_30d_contract():
|
||||||
r = subprocess.run([sys.executable, "-c", CHILD],
|
r = subprocess.run([sys.executable, "-c", CHILD],
|
||||||
capture_output=True, text=True, timeout=180,
|
capture_output=True, text=True, timeout=180,
|
||||||
cwd=str(ROOT))
|
cwd=str(ROOT), encoding="utf-8", errors="replace")
|
||||||
out = (r.stdout or "") + (r.stderr or "")
|
out = (r.stdout or "") + (r.stderr or "")
|
||||||
print(out[-4000:] if len(out) > 4000 else out)
|
print(out[-4000:] if len(out) > 4000 else out)
|
||||||
assert r.returncode == 0, "子进程契约验证失败(见上方输出)"
|
assert r.returncode == 0, "子进程契约验证失败(见上方输出)"
|
||||||
@@ -787,6 +787,52 @@ class OrderSyncTests(unittest.TestCase):
|
|||||||
self.assertTrue(second.get("recovering")) # 第二次被节流
|
self.assertTrue(second.get("recovering")) # 第二次被节流
|
||||||
self.assertEqual(1, auto_return.call_count) # 只补了一次
|
self.assertEqual(1, auto_return.call_count) # 只补了一次
|
||||||
|
|
||||||
|
def test_recovery_skips_return_when_user_already_returned_in_miniprogram(self):
|
||||||
|
"""用户在小程序里还了车:上游查不到这单 → 只做本地收尾,不再打 /record/return。"""
|
||||||
|
conn = self._get_db()
|
||||||
|
conn.execute("""
|
||||||
|
INSERT INTO rentals
|
||||||
|
(id, order_id, user_id, source, expired, start_time, end_time, bike_code, email)
|
||||||
|
VALUES (120, '9020', 7, 'unlock', 0, '2026-01-01 09:00:00',
|
||||||
|
'2026-01-01 09:19:00', '50020', 'rider@example.test')
|
||||||
|
""")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
with patch.object(timer, "get_db", self._get_db), \
|
||||||
|
patch.object(timer, "_upstream_ride_active", return_value=False), \
|
||||||
|
patch.object(timer, "auto_return_bike") as auto_return:
|
||||||
|
result = timer._run_recovery(120, 7, "9020")
|
||||||
|
|
||||||
|
auto_return.assert_not_called() # 关键:不再制造 204010
|
||||||
|
self.assertTrue(result.get("skipped"))
|
||||||
|
conn = self._get_db()
|
||||||
|
try:
|
||||||
|
row = conn.execute("SELECT expired FROM rentals WHERE id = 120").fetchone()
|
||||||
|
self.assertEqual(1, row["expired"])
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
def test_recovery_still_returns_when_upstream_order_is_active(self):
|
||||||
|
conn = self._get_db()
|
||||||
|
conn.execute("""
|
||||||
|
INSERT INTO rentals
|
||||||
|
(id, order_id, user_id, source, expired, start_time, end_time, bike_code, email)
|
||||||
|
VALUES (121, '9021', 7, 'unlock', 0, '2026-01-01 09:00:00',
|
||||||
|
'2026-01-01 09:19:00', '50021', 'rider@example.test')
|
||||||
|
""")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
with patch.object(timer, "_upstream_ride_active", return_value=True), \
|
||||||
|
patch.object(timer, "auto_return_bike", return_value={
|
||||||
|
"success": True, "message": "ok"
|
||||||
|
}) as auto_return:
|
||||||
|
result = timer._run_recovery(121, 7, "9021")
|
||||||
|
|
||||||
|
auto_return.assert_called_once_with(121, 7)
|
||||||
|
self.assertTrue(result.get("success"))
|
||||||
|
|
||||||
def test_sweep_queues_overdue_rentals_and_is_throttled(self):
|
def test_sweep_queues_overdue_rentals_and_is_throttled(self):
|
||||||
"""兜底扫描:超期未还的单要排队补还车,且 10 分钟内不重复扫。"""
|
"""兜底扫描:超期未还的单要排队补还车,且 10 分钟内不重复扫。"""
|
||||||
class ImmediateThread:
|
class ImmediateThread:
|
||||||
|
|||||||
@@ -585,8 +585,42 @@ def _recover_throttled(rental_id: int) -> bool:
|
|||||||
return False
|
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:
|
try:
|
||||||
result = auto_return_bike(rental_id, user_id) or {}
|
result = auto_return_bike(rental_id, user_id) or {}
|
||||||
if result.get("success"):
|
if result.get("success"):
|
||||||
@@ -634,13 +668,14 @@ def sweep_overdue_rentals(force: bool = False) -> int:
|
|||||||
# reminder 是纯本地计时提醒,没有上游订单:上游还不了,但也不能
|
# reminder 是纯本地计时提醒,没有上游订单:上游还不了,但也不能
|
||||||
# 一直挂着 expired=0,否则用户页面横幅永远显示「用车中」。
|
# 一直挂着 expired=0,否则用户页面横幅永远显示「用车中」。
|
||||||
if str(rental.get("source") or "") == "reminder":
|
if str(rental.get("source") or "") == "reminder":
|
||||||
_close_local_reminder(rental["id"])
|
_close_rental_locally(rental["id"], "本地提醒单到期")
|
||||||
closed_local += 1
|
closed_local += 1
|
||||||
continue
|
continue
|
||||||
if _recover_throttled(rental["id"]):
|
if _recover_throttled(rental["id"]):
|
||||||
continue
|
continue
|
||||||
threading.Thread(target=_run_recovery,
|
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
|
started += 1
|
||||||
if started:
|
if started:
|
||||||
print(f"[计时系统] 巡检兜底:{started} 单超期未还,已排队补还车")
|
print(f"[计时系统] 巡检兜底:{started} 单超期未还,已排队补还车")
|
||||||
@@ -649,8 +684,13 @@ def sweep_overdue_rentals(force: bool = False) -> int:
|
|||||||
return started
|
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))
|
tz = dt.timezone(dt.timedelta(hours=8))
|
||||||
now_str = dt.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
now_str = dt.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
||||||
conn = get_db()
|
conn = get_db()
|
||||||
@@ -667,13 +707,15 @@ def _close_local_reminder(rental_id: int):
|
|||||||
(rental_id,))
|
(rental_id,))
|
||||||
conn.commit()
|
conn.commit()
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
print(f"[计时系统] 关闭本地提醒单 rental_id={rental_id} 失败: {exc}")
|
print(f"[计时系统] 本地收尾 rental_id={rental_id} 失败: {exc}")
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
try:
|
try:
|
||||||
_cancel_rental_timers(rental_id)
|
_cancel_rental_timers(rental_id)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
print(f"[计时系统] 本地收尾 rental_id={rental_id}"
|
||||||
|
+ (f":{reason}" if reason else ""))
|
||||||
|
|
||||||
|
|
||||||
def _should_auto_return(rental) -> bool:
|
def _should_auto_return(rental) -> bool:
|
||||||
@@ -995,7 +1037,7 @@ def _recover_overdue_rental(rental: dict):
|
|||||||
if not user_id:
|
if not user_id:
|
||||||
print(f"[计时系统] rental_id={rental_id} 没有 user_id,跳过补还车")
|
print(f"[计时系统] rental_id={rental_id} 没有 user_id,跳过补还车")
|
||||||
return
|
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')}")
|
print(f"[计时系统] 补还车结果 rental_id={rental_id}: {result.get('message')}")
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
print(f"[计时系统] 补还车异常 rental_id={rental_id}: {exc}")
|
print(f"[计时系统] 补还车异常 rental_id={rental_id}: {exc}")
|
||||||
@@ -1119,7 +1161,7 @@ def _check_user_order(user_id: int):
|
|||||||
"recovering": True}
|
"recovering": True}
|
||||||
print(f"[订单检测] rental_id={rental['id']} 已过到期时间,补一次自动还车")
|
print(f"[订单检测] rental_id={rental['id']} 已过到期时间,补一次自动还车")
|
||||||
threading.Thread(
|
threading.Thread(
|
||||||
target=lambda: _run_recovery(rental["id"], user_id),
|
target=lambda: _run_recovery(rental["id"], user_id, order_id),
|
||||||
daemon=True
|
daemon=True
|
||||||
).start()
|
).start()
|
||||||
return {"ok": True, "active": True, "order_id": order_id,
|
return {"ok": True, "active": True, "order_id": order_id,
|
||||||
|
|||||||
Reference in New Issue
Block a user