fix(自动还车): 退避上限/巡检口径/加轮传递/0点预判 等 9 处硬化
B1 绝对上限是死代码(P0)
改前:6 小时上限只写在 _schedule_auto_return_retry 里,而它只被 0 点 Timer 的
fire 调用一次;第 12 次失败后不再挂 Timer → 上限永远不被评估 → 巡检每 60 秒
打一轮上游(/bicycle + 最多 3×/record/return + sleep10s + 2 个查询),永不停止。
改后:上限判断放进 _advance_auto_return_backoff(巡检必经之路),到点只告警一次
(挡位 99)、清掉 backoff 到点时间、返回 0 = 彻底停手。
B2 巡检路径恒 60 秒,120/300 不可达(P1)
改前:_advance_auto_return_backoff 调 _auto_return_retry_delay(n) 不传 elapsed,
而函数里 elapsed=None 恒返回 60。
改后:传 now-first_fail;30 分钟窗口内 60s,之后 60/120/300s。
B7 first_fail_at 收尾不清(P1,与 B1 联动)
改前:_clear_auto_return_state 不清 _auto_return_first_fail_at;同一 rental_id 被
sync 复活后再次失败,setdefault 保留旧时刻 → 立刻判超 6 小时 → 一次告警后停手。
改后:一并清除。
B6 subscribe 漏在收尾白名单(P1)
改前:AUTO_RETURN_SOURCES 含 subscribe,但 _finish_active_wechat_rentals 的 SQL
只有 ('unlock','sync','shared')。用户在微信端还车后本地仍 expired=0,横幅继续
显示「用车中」、提醒照发。
改后:白名单补 subscribe。
B9 复活时可能拿到历史行(P2)
改前:SELECT ... WHERE order_id=? AND user_id=? 无排序无过滤,同 order_id 存在
历史行+活跃行时会先拿到历史行 → 复活已结束的单 → 撞唯一索引再靠兜底救回。
改后:ORDER BY expired ASC, id DESC(优先活跃行)。
B4 加轮(rounds_override)不随续租传递(P1,付费承诺)
改前:_create_renewal_rental 的 INSERT 不含 rounds_override,第 3 轮起
_planned_rounds 回落到设置值 → 用户点的「+1 轮」被吞掉。
改后:INSERT 后继承旧行的 rounds_override(老库缺列时忽略)。
B8 0 点 Timer 不预判上游(P2)
改前:用户已在小程序还车时,仍白打 3 次 /record/return(全 204010)+ sleep 10s,
并发一封「自动还车失败(紧急)」的吓人邮件 + 一个新 token。
改后:先问 _upstream_ride_active;已结束就只做本地收尾(_close_rental_locally +
_clear_auto_return_state + 置位 0),不发还车请求、不发失败邮件。
B13 死 Timer 累积(P3)
改前:_active_timers[rental_id] 只 append 不清理,重试 11 次后留 12 个死对象。
改后:登记时过滤掉已结束的 Timer(对没有 is_alive 的假 Timer 容错)。
B14 租约没拿到却占掉节流(P3)
改前:另一个进程在还这一单时,本地仍写 _recover_last_at,这一单要白等 5 分钟。
改后:跳过时回滚节流时间戳。
B15 注释与实现漂移
_recover_throttled 的 docstring 还写「1m→2m→5m→10m 封顶」,与现在的
60s/120s/300s 不符,已对齐。
测试:新增 tests/test_auto_return_hardening.py 9 例(上限停手、elapsed 档位、
快保不改节奏、first_fail 清理、subscribe 收尾、活跃行优先、rounds_override 继承、
0 点预判已结束 / 仍在骑)。全量 251 pytest + 43 node 全绿。
This commit is contained in:
@@ -292,6 +292,62 @@ def _mark_returned(rental_id: int, latitude=None, longitude=None):
|
||||
conn.close()
|
||||
|
||||
|
||||
def _valid_coord(lat, lng):
|
||||
"""(lat, lng) 是不是一个可用的真实坐标。0/0 与空值都当"没有"。"""
|
||||
try:
|
||||
la, ln = float(lat), float(lng)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
if not (abs(la) > 0.01 or abs(ln) > 0.01):
|
||||
return None
|
||||
return la, ln
|
||||
|
||||
|
||||
def _live_bike_position(user_id: int, bike_code: str, first_payload=None):
|
||||
"""实时取这辆车的位置(GCJ02)。续租必须用真实起点开单,绝不回落假坐标。
|
||||
|
||||
顺序:`/project/bicycle`(单车详情,若调用方已经取过就复用)→
|
||||
`/project/map`(电单车 type=3、共享单车 type=1 各扫一遍)→ None。
|
||||
"""
|
||||
code = str(bike_code or "").strip()
|
||||
if not code:
|
||||
return None
|
||||
|
||||
got = _valid_coord((first_payload or {}).get("latitude"),
|
||||
(first_payload or {}).get("longitude"))
|
||||
if got:
|
||||
return got
|
||||
|
||||
try:
|
||||
res = request_with_user_auth(user_id, "POST", "/project/bicycle", data={"code": code})
|
||||
if isinstance(res, dict) and res.get("rtn_code") == 0:
|
||||
got = _valid_coord((res.get("data") or {}).get("latitude"),
|
||||
(res.get("data") or {}).get("longitude"))
|
||||
if got:
|
||||
return got
|
||||
except Exception as exc:
|
||||
print(f"[续租] 查询单车详情失败: {exc}")
|
||||
|
||||
for bike_type in ("3", "1"):
|
||||
try:
|
||||
res = request_with_user_auth(
|
||||
user_id, "GET", "/project/map", params={"type": bike_type}, _silent=True
|
||||
)
|
||||
except Exception as exc:
|
||||
print(f"[续租] 读取实时地图(type={bike_type})失败: {exc}")
|
||||
continue
|
||||
if not isinstance(res, dict) or res.get("rtn_code") not in (None, 0):
|
||||
continue
|
||||
for bike in (res.get("data") or {}).get("bicycleStation") or []:
|
||||
if str(bike.get("code") or "") != code:
|
||||
continue
|
||||
got = _valid_coord(bike.get("latitude"), bike.get("longitude"))
|
||||
if got:
|
||||
print(f"[续租] 用实时地图(type={bike_type})取到 {code} 的位置")
|
||||
return got
|
||||
return None
|
||||
|
||||
|
||||
def _reopen_same_bike(user_id: int, bike_code: str) -> dict:
|
||||
"""还车后为同一辆车创建下一轮订单并开锁。"""
|
||||
bike_result = request_with_user_auth(
|
||||
@@ -301,8 +357,12 @@ def _reopen_same_bike(user_id: int, bike_code: str) -> dict:
|
||||
return {"success": False, "message": bike_result.get("message", "获取车辆信息失败")}
|
||||
|
||||
bike_data = bike_result.get("data") or {}
|
||||
latitude = bike_data.get("latitude", 36.67)
|
||||
longitude = bike_data.get("longitude", 116.98)
|
||||
# 续租是"用真实起点再开一单":拿不到实时坐标就不要开,绝不用假坐标下单
|
||||
position = _live_bike_position(user_id, bike_code, first_payload=bike_data)
|
||||
if not position:
|
||||
return {"success": False,
|
||||
"message": "拿不到车辆实时位置,已停止续租(避免用假坐标开单)"}
|
||||
latitude, longitude = position
|
||||
order_result = request_with_user_auth(
|
||||
user_id, "POST", "/record/order",
|
||||
data={"code": bike_code, "start_longitude": longitude,
|
||||
@@ -359,6 +419,16 @@ def _create_renewal_rental(rental: dict, user_id: int, order_id: str,
|
||||
start_time.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
end_time.strftime("%Y-%m-%d %H:%M:%S"), duration, source, next_round))
|
||||
rental_id = cursor.lastrowid
|
||||
# 「+1 轮」是用户的付费承诺,必须随续租传递:新行不继承 rounds_override 的话,
|
||||
# _planned_rounds 会回落到设置值,第 3 轮起用户点的那次加轮被吞掉
|
||||
# (前端仍按 override 显示「共 N 轮」,承诺没兑现)。
|
||||
override = rental.get("rounds_override")
|
||||
if override is not None:
|
||||
try:
|
||||
conn.execute("UPDATE rentals SET rounds_override = ? WHERE id = ?",
|
||||
(override, rental_id))
|
||||
except sqlite3.OperationalError:
|
||||
pass # 老库没有这一列,忽略
|
||||
except sqlite3.IntegrityError:
|
||||
# 唯一索引 idx_rentals_active_order:同一 order_id 已有未结束记录
|
||||
# (web 侧刚开锁/订阅/共享落了库)。复用那一行,不能让巡检线程
|
||||
@@ -692,9 +762,9 @@ def _recover_throttled(rental_id: int) -> bool:
|
||||
|
||||
两种节流来源:
|
||||
1. 基础间隔 5 分钟(临时故障时不要每分钟打上游);
|
||||
2. BUG-07 的退避表 `_auto_return_backoff_until` —— 进入退避阶段后,间隔由
|
||||
失败次数决定(1m→2m→5m→10m 封顶),此时以退避表为准,不再叠加基础间隔,
|
||||
否则 1/2 分钟的退避会被 5 分钟基础间隔吃掉。
|
||||
2. 退避表 `_auto_return_backoff_until` —— 进入退避阶段后,间隔由失败次数与
|
||||
已耗时决定(30 分钟内恒 60s,之后 60/120/300s 封顶),此时以退避表为准,
|
||||
不再叠加基础间隔,否则 60 秒的退避会被 5 分钟基础间隔吃掉。
|
||||
"""
|
||||
now = _time.time()
|
||||
due = _auto_return_backoff_until.get(rental_id)
|
||||
@@ -759,6 +829,8 @@ def _run_recovery(rental_id: int, user_id: int, order_id=None):
|
||||
print(f"[自动还车] 租约获取失败(按单进程处理): {exc}")
|
||||
lease_acquired = False
|
||||
if not lease_acquired:
|
||||
# 没真跑就别占节流额度:否则这一单要白等 5 分钟(退避期 60 秒)才被重试
|
||||
_recover_last_at.pop(rental_id, None)
|
||||
return {"success": False, "skipped": True,
|
||||
"message": "另一个进程正在处理这一单"}
|
||||
|
||||
@@ -786,8 +858,9 @@ def _run_recovery_locked(rental_id: int, user_id: int, order_id=None):
|
||||
if result.get("success"):
|
||||
_clear_auto_return_state(rental_id)
|
||||
elif not result.get("skipped"):
|
||||
# 失败:只有进入退避阶段(快保 30s×6 已经用完)才由这里推进下一次到点时间,
|
||||
# 失败:只有进入退避阶段(快保次数已经用完)才由这里推进下一次到点时间,
|
||||
# 快保阶段由 Timer 链自己负责,避免两套重试互相抢节奏。
|
||||
# 返回 0 表示「已到绝对上限、彻底停手」,此时不再留 backoff 到点时间。
|
||||
_advance_auto_return_backoff(
|
||||
rental_id, str(result.get("message") or ""))
|
||||
return result
|
||||
@@ -1000,6 +1073,9 @@ def _clear_auto_return_state(rental_id: int, *, keep_backoff: bool = False) -> N
|
||||
_recover_last_at.pop(rental_id, None)
|
||||
_auto_return_retries.pop(rental_id, None)
|
||||
_auto_return_alert_levels.pop(rental_id, None)
|
||||
# 首次失败时刻也要清:同一 rental_id 被 sync 复活后再次失败时,
|
||||
# setdefault 会保留旧时刻 → now-first_fail 立刻 > 6 小时 → 一发告警就停手。
|
||||
_auto_return_first_fail_at.pop(rental_id, None)
|
||||
if not keep_backoff:
|
||||
_auto_return_backoff_until.pop(rental_id, None)
|
||||
|
||||
@@ -1011,11 +1087,35 @@ def _advance_auto_return_backoff(rental_id: int, message: str = "") -> int:
|
||||
否则快保阶段由 Timer 链自己推进,两套机制同时改计数会互相抢节奏。
|
||||
"""
|
||||
n = _auto_return_retries.get(rental_id, 0)
|
||||
if n < AUTO_RETURN_MAX_RETRIES:
|
||||
if n < len(AUTO_RETURN_RETRY_DELAYS):
|
||||
return 0
|
||||
delay = _auto_return_retry_delay(n)
|
||||
|
||||
now_ts = _time.time()
|
||||
first_fail = _auto_return_first_fail_at.setdefault(rental_id, now_ts)
|
||||
elapsed = now_ts - first_fail
|
||||
|
||||
# 绝对上限必须在这里判:原来只有 _schedule_auto_return_retry 判 6 小时,
|
||||
# 而它只被 0 点 Timer 的 fire 调用;第 12 次失败后不再挂 Timer,那段判断
|
||||
# 就永远不会被评估 → 巡检每 60 秒打一轮上游,永不停止。
|
||||
if elapsed > AUTO_RETURN_GIVE_UP_SECONDS:
|
||||
if _auto_return_alert_levels.get(rental_id, 0) < 99:
|
||||
_auto_return_alert_levels[rental_id] = 99
|
||||
bike_code, _email = _rental_contact(rental_id)
|
||||
_alert_auto_return_exhausted(
|
||||
rental_id, bike_code,
|
||||
(message or "") + f"(已重试超过 {AUTO_RETURN_GIVE_UP_SECONDS // 3600} 小时,"
|
||||
f"自动重试已彻底停止,请人工处理)",
|
||||
0)
|
||||
_auto_return_backoff_until.pop(rental_id, None)
|
||||
print(f"[自动还车] rental_id={rental_id} 超过 "
|
||||
f"{AUTO_RETURN_GIVE_UP_SECONDS // 3600} 小时仍未还上,停止自动重试")
|
||||
_prune_runtime_state()
|
||||
return 0
|
||||
|
||||
# 传 elapsed:30 分钟窗口内恒 60s,超过窗口才允许 120/300s
|
||||
delay = _auto_return_retry_delay(n, elapsed)
|
||||
_auto_return_retries[rental_id] = n + 1
|
||||
_auto_return_backoff_until[rental_id] = _time.time() + delay
|
||||
_auto_return_backoff_until[rental_id] = now_ts + delay
|
||||
level = _auto_return_alert_level(n + 1)
|
||||
if level > _auto_return_alert_levels.get(rental_id, 0):
|
||||
_auto_return_alert_levels[rental_id] = level
|
||||
@@ -1163,6 +1263,22 @@ def _schedule_reminder(rental_id: int, delay_seconds: int, reminder_type: str,
|
||||
# 原来先置位再还车,上游三次重试一失败就再也不会重试,订单在上游继续计费。
|
||||
conn.close()
|
||||
return_result = None
|
||||
upstream_order_id = rental["order_id"] if "order_id" in rental.keys() else None
|
||||
if auto_return_enabled and user_id and upstream_order_id:
|
||||
# 先问上游:用户很可能已经在小程序里还了车。不预判会白打 3 次
|
||||
# /record/return(全 204010)+ sleep 10s,还会发一封「自动还车失败(紧急)」
|
||||
# 的吓人邮件 + 一个新 token。
|
||||
try:
|
||||
upstream_active = _upstream_ride_active(user_id, upstream_order_id)
|
||||
except Exception as exc:
|
||||
upstream_active = None
|
||||
print(f"[自动还车] 预判上游状态失败(继续按在骑处理): {exc}")
|
||||
if upstream_active is False:
|
||||
print(f"[自动还车] rental_id={rental_id} 上游已结束,只做本地收尾,不再发还车请求")
|
||||
_close_rental_locally(rental_id, "上游订单已结束(用户已在小程序还车)")
|
||||
_clear_auto_return_state(rental_id)
|
||||
_mark_notified(rental_id, "0")
|
||||
return
|
||||
if auto_return_enabled and user_id:
|
||||
try:
|
||||
return_result = auto_return_bike(rental_id, user_id)
|
||||
@@ -1202,7 +1318,18 @@ def _schedule_reminder(rental_id: int, delay_seconds: int, reminder_type: str,
|
||||
if isinstance(gen, int) and _timer_gen.get(rental_id, 0) != gen:
|
||||
# 这一代已经被取消/取代(并发重排或还车),注册即作废,避免残留重复提醒
|
||||
return None
|
||||
_active_timers.setdefault(rental_id, []).append(timer)
|
||||
# 顺手丢掉已经跑完的死 Timer:fire 每次都重新登记,旧对象不移除的话
|
||||
# 重试 11 次后这个列表会留 12 个死对象(隐性泄漏)。
|
||||
# 用 getattr 容错:测试里的假 Timer 没有 is_alive,按「还活着」处理。
|
||||
def _timer_alive(t):
|
||||
fn = getattr(t, "is_alive", None)
|
||||
try:
|
||||
return bool(fn()) if callable(fn) else True
|
||||
except Exception:
|
||||
return True
|
||||
|
||||
_alive = [t for t in _active_timers.get(rental_id, []) if _timer_alive(t)]
|
||||
_active_timers[rental_id] = _alive + [timer]
|
||||
# 先登记再启动,避免 0 秒任务先完成/取消后又被追加回活动列表。
|
||||
timer.start()
|
||||
return timer
|
||||
@@ -1458,8 +1585,11 @@ def _check_user_order(user_id: int):
|
||||
conn = get_db()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(
|
||||
# 同一 order_id 可能既有历史行(expired=1)又有活跃行:优先活跃行,
|
||||
# 否则会把已结束的历史单「复活」,撞唯一索引后再靠兜底救回来(多一次写 + 误导日志)
|
||||
"SELECT id, order_id, source, expired, end_time FROM rentals "
|
||||
"WHERE order_id = ? AND user_id = ?",
|
||||
"WHERE order_id = ? AND user_id = ? "
|
||||
"ORDER BY expired ASC, id DESC",
|
||||
(order_id, user_id)
|
||||
)
|
||||
existing = cursor.fetchone()
|
||||
@@ -1667,7 +1797,7 @@ def _finish_active_wechat_rentals(user_id: int, reason: str):
|
||||
cursor.execute("""
|
||||
SELECT id, order_id, source, bike_code FROM rentals
|
||||
WHERE user_id = ? AND expired = 0
|
||||
AND source IN ('unlock', 'sync', 'shared')
|
||||
AND source IN ('unlock', 'sync', 'shared', 'subscribe')
|
||||
""", (user_id,))
|
||||
active_rows = cursor.fetchall()
|
||||
conn.close()
|
||||
|
||||
Reference in New Issue
Block a user