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:
@@ -654,29 +654,76 @@ def api_history_heatmap():
|
|||||||
|
|
||||||
|
|
||||||
# ========== 启动 ==========
|
# ========== 启动 ==========
|
||||||
|
# 后台线程原来只挂在 `if __name__ == "__main__":` 里,换成 gunicorn/`flask run`
|
||||||
|
# 或任何 WSGI 启动方式时全都不会启动(且静默)——定时采集、订单巡检、
|
||||||
|
# 自动还车、订阅提醒、凭据告警会一起残废。这里收进幂等的 bootstrap(),
|
||||||
|
# WSGI 与 __main__ 都会调用,再由 before_request 兜住「首次请求」。
|
||||||
|
_bootstrap_lock = threading.Lock()
|
||||||
|
_bootstrap_done = False
|
||||||
|
|
||||||
|
|
||||||
|
def bootstrap():
|
||||||
|
"""初始化数据库并启动所有后台线程。幂等:重复调用只会执行一次。"""
|
||||||
|
global _bootstrap_done
|
||||||
|
with _bootstrap_lock:
|
||||||
|
if _bootstrap_done:
|
||||||
|
return False
|
||||||
|
_bootstrap_done = True
|
||||||
|
|
||||||
|
print("[启动] bootstrap: 初始化数据库 + 启动后台线程")
|
||||||
|
try:
|
||||||
|
init_db()
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[启动] init_db 失败: {exc}")
|
||||||
|
|
||||||
|
steps = [
|
||||||
|
("恢复计时器", restore_active_timers),
|
||||||
|
("补还超期订单", _sweep_on_boot),
|
||||||
|
("订单巡检", start_all_order_checkers),
|
||||||
|
("数据采集", start_snapshot_scheduler),
|
||||||
|
]
|
||||||
|
for name, fn in steps:
|
||||||
|
try:
|
||||||
|
fn()
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[启动] {name} 失败: {exc}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
from subscribe import start_subscribe_scheduler
|
||||||
|
start_subscribe_scheduler()
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[启动] 订阅调度失败: {exc}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
from alerts import start_alert_scheduler
|
||||||
|
start_alert_scheduler()
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[启动] 告警调度失败: {exc}")
|
||||||
|
|
||||||
|
print("[启动] bootstrap 完成")
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def _sweep_on_boot():
|
||||||
|
"""启动时把「expired=0 且已过期」的僵尸单捞一遍(带 5 分钟节流)。"""
|
||||||
|
try:
|
||||||
|
from timer import sweep_overdue_rentals
|
||||||
|
n = sweep_overdue_rentals(force=True)
|
||||||
|
if n:
|
||||||
|
print(f"[启动] 补还超期订单 {n} 单")
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[启动] 补还超期订单失败: {exc}")
|
||||||
|
|
||||||
|
|
||||||
|
@app.before_request
|
||||||
|
def _ensure_bootstrap():
|
||||||
|
"""WSGI 部署(gunicorn 等)不会走 __main__,靠首个请求把后台线程拉起来。"""
|
||||||
|
if not _bootstrap_done:
|
||||||
|
bootstrap()
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
from pathlib import Path
|
bootstrap()
|
||||||
|
|
||||||
# 初始化数据库
|
|
||||||
init_db()
|
|
||||||
|
|
||||||
# 恢复未过期的计时器
|
|
||||||
restore_active_timers()
|
|
||||||
|
|
||||||
# 启动用户订单检测
|
|
||||||
start_all_order_checkers()
|
|
||||||
|
|
||||||
# 启动数据采集
|
|
||||||
start_snapshot_scheduler()
|
|
||||||
|
|
||||||
# 启动订阅提醒调度(定时查看教学楼附近车辆 → 邮件)
|
|
||||||
from subscribe import start_subscribe_scheduler
|
|
||||||
start_subscribe_scheduler()
|
|
||||||
|
|
||||||
# 启动凭据到期告警调度(1天/1小时/已过期 三级)
|
|
||||||
from alerts import start_alert_scheduler
|
|
||||||
start_alert_scheduler()
|
|
||||||
|
|
||||||
PORT = 98
|
PORT = 98
|
||||||
# 只监听本机回环:对外统一走 nginx 的 HTTPS(同机回环转发到本端口)。
|
# 只监听本机回环:对外统一走 nginx 的 HTTPS(同机回环转发到本端口)。
|
||||||
# 绑定 0.0.0.0 会让明文 HTTP 绕过 nginx 直接暴露,token/凭据可被局域网窃听。
|
# 绑定 0.0.0.0 会让明文 HTTP 绕过 nginx 直接暴露,token/凭据可被局域网窃听。
|
||||||
|
|||||||
@@ -624,6 +624,7 @@ class OrderSyncTests(unittest.TestCase):
|
|||||||
patch.object(timer, "get_user_auth", return_value=("token", "access")), \
|
patch.object(timer, "get_user_auth", return_value=("token", "access")), \
|
||||||
patch.object(timer, "threading", wraps=timer.threading), \
|
patch.object(timer, "threading", wraps=timer.threading), \
|
||||||
patch.object(timer.threading, "Thread", ImmediateThread), \
|
patch.object(timer.threading, "Thread", ImmediateThread), \
|
||||||
|
patch.object(timer, "sweep_overdue_rentals", return_value=0), \
|
||||||
patch.object(timer, "request_with_user_auth", return_value=active), \
|
patch.object(timer, "request_with_user_auth", return_value=active), \
|
||||||
patch.object(timer, "auto_return_bike", return_value={
|
patch.object(timer, "auto_return_bike", return_value={
|
||||||
"success": True, "message": "ok"
|
"success": True, "message": "ok"
|
||||||
@@ -772,6 +773,7 @@ class OrderSyncTests(unittest.TestCase):
|
|||||||
with patch.object(timer, "get_db", self._get_db), \
|
with patch.object(timer, "get_db", self._get_db), \
|
||||||
patch.object(timer, "get_user_auth", return_value=("token", "access")), \
|
patch.object(timer, "get_user_auth", return_value=("token", "access")), \
|
||||||
patch.object(timer.threading, "Thread", ImmediateThread), \
|
patch.object(timer.threading, "Thread", ImmediateThread), \
|
||||||
|
patch.object(timer, "sweep_overdue_rentals", return_value=0), \
|
||||||
patch.object(timer, "request_with_user_auth", return_value=active), \
|
patch.object(timer, "request_with_user_auth", return_value=active), \
|
||||||
patch.object(timer, "auto_return_bike", return_value={
|
patch.object(timer, "auto_return_bike", return_value={
|
||||||
"success": False, "message": "boom"
|
"success": False, "message": "boom"
|
||||||
@@ -785,6 +787,58 @@ 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_sweep_queues_overdue_rentals_and_is_throttled(self):
|
||||||
|
"""兜底扫描:超期未还的单要排队补还车,且 10 分钟内不重复扫。"""
|
||||||
|
class ImmediateThread:
|
||||||
|
def __init__(self, target=None, args=(), **kwargs):
|
||||||
|
self.target, self.args = target, args
|
||||||
|
def start(self):
|
||||||
|
if self.target:
|
||||||
|
self.target(*self.args)
|
||||||
|
|
||||||
|
conn = self._get_db()
|
||||||
|
conn.execute("""
|
||||||
|
INSERT INTO rentals
|
||||||
|
(id, order_id, user_id, source, expired, start_time, end_time, bike_code, email)
|
||||||
|
VALUES (111, '9011', 7, 'unlock', 0, '2026-01-01 09:00:00',
|
||||||
|
'2026-01-01 09:19:00', '50011', 'rider@example.test')
|
||||||
|
""")
|
||||||
|
conn.execute("""
|
||||||
|
INSERT INTO rentals
|
||||||
|
(id, order_id, user_id, source, expired, start_time, end_time, bike_code, email)
|
||||||
|
VALUES (112, NULL, 7, 'reminder', 0, '2026-01-01 09:00:00',
|
||||||
|
'2026-01-01 09:19:00', '50012', 'rider@example.test')
|
||||||
|
""")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
timer._recover_last_at.clear()
|
||||||
|
timer._sweep_last_at[0] = 0
|
||||||
|
try:
|
||||||
|
with patch.object(timer, "get_db", self._get_db), \
|
||||||
|
patch.object(timer.threading, "Thread", ImmediateThread), \
|
||||||
|
patch.object(timer, "auto_return_bike", return_value={
|
||||||
|
"success": True, "message": "ok"
|
||||||
|
}) as auto_return:
|
||||||
|
first = timer.sweep_overdue_rentals(force=True)
|
||||||
|
second = timer.sweep_overdue_rentals() # 10 分钟内不再扫
|
||||||
|
finally:
|
||||||
|
timer._recover_last_at.clear()
|
||||||
|
timer._sweep_last_at[0] = 0
|
||||||
|
|
||||||
|
self.assertEqual(1, first) # 只有 unlock 那单
|
||||||
|
self.assertEqual(0, second) # 被节流
|
||||||
|
recovered_ids = [c.args[0] for c in auto_return.call_args_list]
|
||||||
|
self.assertIn(111, recovered_ids)
|
||||||
|
self.assertNotIn(112, recovered_ids) # reminder 不补
|
||||||
|
|
||||||
|
conn = self._get_db()
|
||||||
|
try:
|
||||||
|
row = conn.execute("SELECT expired FROM rentals WHERE id = 112").fetchone()
|
||||||
|
self.assertEqual(1, row["expired"]) # 本地提醒单就地关闭
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
|
||||||
def test_recovery_success_clears_throttle_record(self):
|
def test_recovery_success_clears_throttle_record(self):
|
||||||
"""补还车成功后要清掉节流记录,别在进程里留失败痕迹。"""
|
"""补还车成功后要清掉节流记录,别在进程里留失败痕迹。"""
|
||||||
timer._recover_last_at[109] = timer._time.time()
|
timer._recover_last_at[109] = timer._time.time()
|
||||||
|
|||||||
@@ -597,6 +597,85 @@ def _run_recovery(rental_id: int, user_id: int):
|
|||||||
return {"success": False, "message": str(exc)}
|
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:
|
def _should_auto_return(rental) -> bool:
|
||||||
"""这张单能不能走上游自动还车(restore / 巡检共用同一判断)。"""
|
"""这张单能不能走上游自动还车(restore / 巡检共用同一判断)。"""
|
||||||
if not rental:
|
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):
|
def _user_order_checker_loop(user_id: int, stop_event: threading.Event):
|
||||||
"""用户订单检测线程主循环"""
|
"""用户订单检测线程主循环"""
|
||||||
while not stop_event.is_set():
|
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:
|
try:
|
||||||
_check_user_order(user_id)
|
_check_user_order(user_id)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|||||||
Reference in New Issue
Block a user