fix(批次C): 多进程选主 + 计时器锁 + bootstrap 完成后再置位

- db.py 新增 leases 表与 acquire_lease/release_lease/lease_held_by_me:
  BEGIN IMMEDIATE 保证「读-判断-写」原子,多进程同时抢只有一个成功;
  租约表不可用时返回 None(老库/临时库),调用方按单进程处理,不会误拦
- app.bootstrap:抢 LEADER_LEASE(120s TTL,30s 续期)才启动采集/巡检/定时器/
  订阅/告警;非 leader 直接当 web worker。解决多 worker 下重复发信、
  重复自动还车、月卡重复扣费
- bootstrap 标志:新增 _bootstrap_started 防重入,_bootstrap_done 改为
  工作真正完成后再置位(原来先置 True,并发请求会以为已完成)
- timer._run_recovery:按 rental 抢 300 秒租约,跨进程只有一个进程去还这一单
- timer._active_timers:加 _timers_lock,取消时用 pop 一次取出(原来 in→del
  之间被删会 KeyError;del 会连带抹掉别的线程刚 append 的 timer,导致脱管)

测试:164 pytest(新增租约 3 条)+ 32 node 全绿
This commit is contained in:
zzy
2026-11-15 23:33:08 +08:00
parent 6847482447
commit d34b5bc375
4 changed files with 200 additions and 10 deletions
+25 -7
View File
@@ -13,6 +13,7 @@ from rental_mail import mark_return_tokens_used, send_rental_notification
# ========== 计时器系统 ==========
TIMER_CHECK_INTERVAL = 30
_active_timers: dict = {}
_timers_lock = threading.Lock() # 保护 _active_timers(多线程增删)
_renewal_locks: dict = {}
_renewal_locks_guard = threading.Lock()
@@ -571,11 +572,19 @@ def auto_return_bike(rental_id: int, user_id: int, allow_renewal: bool = True):
def _cancel_rental_timers(rental_id: int):
"""取消某次租车的所有计时器"""
if rental_id in _active_timers:
for t in _active_timers[rental_id]:
"""取消某次租车的所有计时器。
用 pop 一次取出再取消:原来是 `in` 判断 + 取列表 + `del`,
中间被别的线程删掉会抛 KeyError;`del` 之后另一线程刚 append 的 timer
也会随之消失(脱管的计时器永远取消不掉,导致重复提醒/重复还车)。
"""
with _timers_lock:
timers = _active_timers.pop(rental_id, [])
for t in timers:
try:
t.cancel()
del _active_timers[rental_id]
except Exception:
pass
# 只有这些来源才代表「真的有上游骑行订单」,才能走自动还车。
@@ -629,6 +638,16 @@ def _run_recovery(rental_id: int, user_id: int, order_id=None):
先问上游状态:上游说这单已结束(用户在小程序里还了),就只做本地收尾,
不再打 /record/return。
"""
# 跨进程独占:多 worker 下同一单只让一个进程去还,避免两次 /record/return +
# 两次月卡提交(_renewal_lock 只是进程内的 threading.Lock)
try:
from db import acquire_lease
if acquire_lease(f"rental-return:{rental_id}", 300) is False:
return {"success": False, "skipped": True,
"message": "另一个进程正在处理这一单"}
except Exception as exc:
print(f"[自动还车] 租约获取失败(按单进程处理): {exc}")
active = _upstream_ride_active(user_id, order_id) if order_id else None
if active is False:
_close_rental_locally(rental_id, "上游订单已结束(用户已在小程序还车)")
@@ -904,9 +923,8 @@ def _schedule_reminder(rental_id: int, delay_seconds: int, reminder_type: str,
timer = threading.Timer(delay_seconds, fire)
timer.daemon = True
if rental_id not in _active_timers:
_active_timers[rental_id] = []
_active_timers[rental_id].append(timer)
with _timers_lock:
_active_timers.setdefault(rental_id, []).append(timer)
# 先登记再启动,避免 0 秒任务先完成/取消后又被追加回活动列表。
timer.start()
return timer