fix: 巡检补还车节流 + 管理端代还车复用换点重试 + 回填实际还车时间

1) 彻底失败的单被巡检无限重试
- 新增 _recover_last_at + RECOVER_INTERVAL_SECONDS=300:同一单 5 分钟内
  只补一次还车,返回 {recovering: True};
  原来每 60 秒就起一个线程、每次 3~4 个上游请求 + 睡 15 秒,永远循环

2) 管理端「代还车」还是单点老逻辑
- admin_api_return 改为复用 routes.rental._try_return_candidates:
  先发原坐标 → 失败换候选点(上游 parkeArea → 快照 → 校园停车点)
- 失败时把「已尝试 N 个位置」写进返回消息,不再是干巴巴的「还车失败」

3) 代还车只置 expired=1,不写 returned_at
- 成功后改调 _record_rental_end(order_id, user_id, lat, lng):
  同时写 returned_at + 终点坐标/标签,「已骑行」列不再一直往上爬;
  回填异常时仍兜底 UPDATE expired=1

4) _mark_notified 的 conn/cursor 参数没人用
- 5/3/2/1 分钟分支改为传已有的 conn/cursor(不再为一次 UPDATE 新开连接)

测试:152 pytest(新增巡检节流、管理端代还车链路与回填 2 条)+ 32 node 全绿
This commit is contained in:
zzy
2026-11-15 18:04:10 +08:00
parent 57eae3ac82
commit 7181973c1f
4 changed files with 146 additions and 23 deletions
+21 -2
View File
@@ -570,6 +570,21 @@ def _cancel_rental_timers(rental_id: int):
AUTO_RETURN_SOURCES = ("unlock", "sync", "shared", "subscribe")
# 巡检补还车的节流:彻底失败的单不能每分钟重打上游
_recover_last_at: dict = {}
RECOVER_INTERVAL_SECONDS = 300 # 5 分钟
def _recover_throttled(rental_id: int) -> bool:
"""5 分钟内已经补过就不再补,返回 True 表示这次要跳过。"""
now = _time.time()
last = _recover_last_at.get(rental_id, 0)
if now - last < RECOVER_INTERVAL_SECONDS:
return True
_recover_last_at[rental_id] = now
return False
def _should_auto_return(rental) -> bool:
"""这张单能不能走上游自动还车(restore / 巡检共用同一判断)。"""
if not rental:
@@ -697,8 +712,7 @@ def _schedule_reminder(rental_id: int, delay_seconds: int, reminder_type: str,
# 5/3/2/1 分钟这类纯提醒:先置位再发,发失败也不重发
if reminder_type != "0":
cursor.execute(f"UPDATE rentals SET {col} = 1 WHERE id = ?", (rental_id,))
conn.commit()
_mark_notified(rental_id, reminder_type, conn=conn, cursor=cursor)
conn.close()
if send_notification:
send_rental_notification(rental_id, reminder_type, None)
@@ -1000,6 +1014,11 @@ def _check_user_order(user_id: int):
# 只有「真的有上游订单」的来源才补(reminder 之类拿本地 id 当订单号必然失败)。
if _should_auto_return(rental) and _rental_end_time_passed(rental):
conn.close()
if _recover_throttled(rental["id"]):
# 彻底还不上(车被锁死/订单状态怪)时不能每分钟重打:
# 5 分钟一次,避免每分钟 3~4 个上游请求 + 线程睡 15 秒的死循环
return {"ok": True, "active": True, "order_id": order_id,
"recovering": True}
print(f"[订单检测] rental_id={rental['id']} 已过到期时间,补一次自动还车")
threading.Thread(
target=lambda: auto_return_bike(rental["id"], user_id),