fix(P0): 后台线程改为幂等 bootstrap(),僵尸订单由巡检定期兜底

1) 后台线程绑定在 __main__ 里 → WSGI/`flask run` 启动时全部静默不启动
- 新增 app.bootstrap():init_db + 恢复计时器 + 补还超期单 + 订单巡检 +
  数据采集 + 订阅调度 + 告警调度,threading.Lock 保证只执行一次
- @app.before_request 首次请求兜底调用(WSGI 部署也能起来),
  __main__ 同样调 bootstrap()

2) expired=0 且 end_time 已过的僵尸单只在启动时清一次
- 新增 timer.sweep_overdue_rentals():全局扫描超期未还的单,按
  _should_auto_return 过滤后排队 _run_recovery,进程内 10 分钟节流
- 巡检线程循环每轮调用一次(放在 _user_order_checker_loop,不污染单测)
- reminder 来源的单没有上游订单,就地关闭(expired=1 + returned_at),
  否则用户页面横幅永远显示「用车中」

3) 顺手修的 bug
- sweep 里先把 sqlite3.Row 转 dict 再关连接,避免关库后读行
- _close_local_reminder 兼容没有 returned_at 列的极简 schema
- 该测试自带的连接泄漏(断言抛错时没关库)导致 teardown PermissionError

实测(真实库):启动时 3 单真订单排队补还车,44 条本地提醒单就地关闭
测试:157 pytest(新增 sweep 排队/节流/本地单关闭)+ 32 node 全绿
This commit is contained in:
zzy
2026-11-15 21:18:35 +08:00
parent 9bdef68650
commit 246f81137a
3 changed files with 209 additions and 22 deletions
+86
View File
@@ -597,6 +597,85 @@ def _run_recovery(rental_id: int, user_id: int):
return {"success": False, "message": str(exc)}
# 全局兜底扫描的节流(进程内一次/10 分钟,避免每个用户的巡检都全表扫)
_sweep_last_at = [0.0]
SWEEP_INTERVAL_SECONDS = 600
def sweep_overdue_rentals(force: bool = False) -> int:
"""兜底:捞「expired=0 且 end_time 已过」的单补还车,返回排队数量。
以前这件事只在 `restore_active_timers()` 里做一次;启动方式一变
(WSGI / `flask run` / 直接 import),这些僵尸单就永远挂着,
用户页面横幅一直显示「用车中」。现在巡检也会定期顺手扫一遍。
"""
now = _time.time()
if not force and now - _sweep_last_at[0] < SWEEP_INTERVAL_SECONDS:
return 0
_sweep_last_at[0] = now
tz = dt.timezone(dt.timedelta(hours=8))
now_str = dt.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
conn = get_db()
try:
rows = [dict(r) for r in conn.execute(
"SELECT * FROM rentals WHERE expired = 0 AND end_time < ?", (now_str,)
).fetchall()]
except Exception as exc:
print(f"[计时系统] 扫描超期订单失败: {exc}")
return 0
finally:
conn.close()
started = 0
closed_local = 0
for rental in rows:
if not _should_auto_return(rental):
# reminder 是纯本地计时提醒,没有上游订单:上游还不了,但也不能
# 一直挂着 expired=0,否则用户页面横幅永远显示「用车中」。
if str(rental.get("source") or "") == "reminder":
_close_local_reminder(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()
started += 1
if started:
print(f"[计时系统] 巡检兜底:{started} 单超期未还,已排队补还车")
if closed_local:
print(f"[计时系统] 巡检兜底:{closed_local} 条本地提醒单超期,已就地关闭")
return started
def _close_local_reminder(rental_id: int):
"""本地提醒单到期:直接标记结束,不碰上游(它本来就没有上游订单)。"""
tz = dt.timezone(dt.timedelta(hours=8))
now_str = dt.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
conn = get_db()
try:
try:
conn.execute(
"UPDATE rentals SET expired = 1, returned_at = COALESCE(returned_at, ?) "
"WHERE id = ? AND expired = 0", (now_str, rental_id))
except Exception as exc:
if "no such column" not in str(exc).lower():
raise
# 极简/旧 schema 没有 returned_at:只置 expired 也要把它关掉
conn.execute("UPDATE rentals SET expired = 1 WHERE id = ? AND expired = 0",
(rental_id,))
conn.commit()
except Exception as exc:
print(f"[计时系统] 关闭本地提醒单 rental_id={rental_id} 失败: {exc}")
finally:
conn.close()
try:
_cancel_rental_timers(rental_id)
except Exception:
pass
def _should_auto_return(rental) -> bool:
"""这张单能不能走上游自动还车(restore / 巡检共用同一判断)。"""
if not rental:
@@ -955,6 +1034,13 @@ def stop_user_order_checker(user_id: int):
def _user_order_checker_loop(user_id: int, stop_event: threading.Event):
"""用户订单检测线程主循环"""
while not stop_event.is_set():
# 兜底扫一遍超期未还的单(内部 10 分钟节流,不会每轮都全表扫)。
# 放在循环里而不是 _check_user_order 里:启动路径一变 restore 不跑时,
# 这些僵尸单就靠这里清;同时保持单测里的 _check_user_order 纯净。
try:
sweep_overdue_rentals()
except Exception as exc:
print(f"[订单检测] 超期订单兜底扫描失败: {exc}")
try:
_check_user_order(user_id)
except Exception as e: