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:
@@ -0,0 +1,271 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""B1/B2/B4/B6/B7/B8/B9 的针对性回归测试。
|
||||||
|
|
||||||
|
这些路径原来没有任何测试覆盖 —— 现场故障(到点不还、邮件不发、加轮被吞)
|
||||||
|
恰好都落在这些空档里。
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import db
|
||||||
|
import timer
|
||||||
|
|
||||||
|
_RUNTIME_TABLES = None
|
||||||
|
|
||||||
|
|
||||||
|
def _runtime_tables():
|
||||||
|
global _RUNTIME_TABLES
|
||||||
|
if _RUNTIME_TABLES is None:
|
||||||
|
_RUNTIME_TABLES = (
|
||||||
|
timer._auto_return_retries, timer._auto_return_alert_levels,
|
||||||
|
timer._auto_return_backoff_until, timer._auto_return_first_fail_at,
|
||||||
|
timer._recover_last_at, timer._active_timers,
|
||||||
|
)
|
||||||
|
return _RUNTIME_TABLES
|
||||||
|
|
||||||
|
|
||||||
|
class _ImmediateTimer:
|
||||||
|
"""start() 立刻执行 fire():避免 delay=0 的 Timer 带来的竞态。"""
|
||||||
|
|
||||||
|
def __init__(self, delay, fn, *a, **kw):
|
||||||
|
self.delay = delay
|
||||||
|
self.fn = fn
|
||||||
|
|
||||||
|
def start(self):
|
||||||
|
self.fn()
|
||||||
|
|
||||||
|
def cancel(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def is_alive(self):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
class _Base(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
os.environ["XBCR_DISABLE_BACKGROUND"] = "1"
|
||||||
|
os.environ["XBCR_DISABLE_LEASES"] = "1"
|
||||||
|
self.tmp = tempfile.TemporaryDirectory()
|
||||||
|
self._old_path = db.DB_PATH
|
||||||
|
db.DB_PATH = Path(self.tmp.name) / "fix.db"
|
||||||
|
db.init_db()
|
||||||
|
for table in _runtime_tables():
|
||||||
|
table.clear()
|
||||||
|
conn = db.get_db()
|
||||||
|
conn.row_factory = sqlite3.Row
|
||||||
|
conn.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, email TEXT)")
|
||||||
|
conn.execute("INSERT OR IGNORE INTO users (id, email) VALUES (7, 'rider@example.test')")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
db.DB_PATH = self._old_path
|
||||||
|
for table in _runtime_tables():
|
||||||
|
table.clear()
|
||||||
|
self.tmp.cleanup()
|
||||||
|
|
||||||
|
def add_rental(self, rid, order_id, source="unlock", expired=0,
|
||||||
|
start="2026-01-01 09:00:00", end="2026-01-01 09:19:00", bike="51287"):
|
||||||
|
conn = db.get_db()
|
||||||
|
conn.execute("""
|
||||||
|
INSERT INTO rentals (id, order_id, bike_code, email, user_id, start_time, end_time,
|
||||||
|
duration, expired, source)
|
||||||
|
VALUES (?, ?, ?, 'rider@example.test', 7, ?, ?, 19, ?, ?)
|
||||||
|
""", (rid, order_id, bike, start, end, expired, source))
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
|
class BackoffCeilingTests(_Base):
|
||||||
|
"""B1+B2:退避阶段的绝对上限与档位(原来 6 小时是死代码)。"""
|
||||||
|
|
||||||
|
def test_gives_up_after_absolute_ceiling_and_stops_scheduling(self):
|
||||||
|
rid = 9101
|
||||||
|
timer._auto_return_retries[rid] = 20
|
||||||
|
timer._auto_return_first_fail_at[rid] = time.time() - 7 * 3600 # 已失败 7 小时
|
||||||
|
|
||||||
|
with patch.object(timer, "_alert_auto_return_exhausted") as alert, \
|
||||||
|
patch.object(timer, "_rental_contact", return_value=("51287", "r@example.test")):
|
||||||
|
delay = timer._advance_auto_return_backoff(rid, "关锁失败")
|
||||||
|
|
||||||
|
self.assertEqual(0, delay, "到绝对上限必须返回 0(停手)")
|
||||||
|
self.assertNotIn(rid, timer._auto_return_backoff_until,
|
||||||
|
"停手后不能再留下一次到点时间")
|
||||||
|
alert.assert_called_once()
|
||||||
|
self.assertEqual(99, timer._auto_return_alert_levels[rid], "只告警一次(挡位 99)")
|
||||||
|
|
||||||
|
with patch.object(timer, "_alert_auto_return_exhausted") as alert2, \
|
||||||
|
patch.object(timer, "_rental_contact", return_value=("51287", "r@example.test")):
|
||||||
|
timer._advance_auto_return_backoff(rid, "关锁失败")
|
||||||
|
alert2.assert_not_called()
|
||||||
|
|
||||||
|
def test_elapsed_controls_delay_after_dense_phase(self):
|
||||||
|
rid = 9102
|
||||||
|
timer._auto_return_retries[rid] = 15
|
||||||
|
timer._auto_return_first_fail_at[rid] = time.time() - 20 * 60 # 窗口内
|
||||||
|
with patch.object(timer, "_alert_auto_return_exhausted"), \
|
||||||
|
patch.object(timer, "_rental_contact", return_value=("51287", "r@example.test")):
|
||||||
|
self.assertEqual(60, timer._advance_auto_return_backoff(rid, "x"))
|
||||||
|
|
||||||
|
timer._auto_return_retries[rid] = 20
|
||||||
|
timer._auto_return_first_fail_at[rid] = time.time() - 40 * 60 # 超过 30 分钟窗口
|
||||||
|
with patch.object(timer, "_alert_auto_return_exhausted"), \
|
||||||
|
patch.object(timer, "_rental_contact", return_value=("51287", "r@example.test")):
|
||||||
|
delay = timer._advance_auto_return_backoff(rid, "x")
|
||||||
|
self.assertIn(delay, (120, 300), f"超过窗口后应拉长,实际 {delay}")
|
||||||
|
|
||||||
|
def test_dense_phase_still_no_op(self):
|
||||||
|
rid = 9103
|
||||||
|
timer._auto_return_retries[rid] = 3
|
||||||
|
self.assertEqual(0, timer._advance_auto_return_backoff(rid, "x"))
|
||||||
|
|
||||||
|
|
||||||
|
class ClearStateTests(_Base):
|
||||||
|
"""B7:收尾要清掉首次失败时刻,否则复活后立刻被判超 6 小时。"""
|
||||||
|
|
||||||
|
def test_clear_removes_first_fail_marker(self):
|
||||||
|
rid = 9201
|
||||||
|
timer._auto_return_first_fail_at[rid] = time.time() - 8 * 3600
|
||||||
|
timer._auto_return_retries[rid] = 5
|
||||||
|
timer._clear_auto_return_state(rid)
|
||||||
|
self.assertNotIn(rid, timer._auto_return_first_fail_at)
|
||||||
|
|
||||||
|
|
||||||
|
class SubscribeWhitelistTests(_Base):
|
||||||
|
"""B6:subscribe 单也要能被「微信端已还车」收尾。"""
|
||||||
|
|
||||||
|
def test_subscribe_row_is_finished(self):
|
||||||
|
self.add_rental(9301, "ORD-9301", source="subscribe")
|
||||||
|
with patch.object(timer, "_bike_pos_from_history", return_value=None):
|
||||||
|
timer._finish_active_wechat_rentals(7, "上游已无订单")
|
||||||
|
conn = db.get_db()
|
||||||
|
row = conn.execute("SELECT expired FROM rentals WHERE id = 9301").fetchone()
|
||||||
|
conn.close()
|
||||||
|
self.assertEqual(1, row["expired"], "subscribe 单漏在白名单外会一直显示「用车中」")
|
||||||
|
|
||||||
|
|
||||||
|
class ActiveRowSelectionTests(_Base):
|
||||||
|
"""B9:同 order_id 有历史行 + 活跃行时,必须拿活跃行。"""
|
||||||
|
|
||||||
|
def test_prefers_active_row(self):
|
||||||
|
self.add_rental(9400, "ORD-9400", expired=1)
|
||||||
|
self.add_rental(9401, "ORD-9400", expired=0)
|
||||||
|
|
||||||
|
active_payload = {"rtn_code": 0, "data": {"nonDealOrder": {
|
||||||
|
"order_id": "ORD-9400", "status": 2, "code": "51287"}}}
|
||||||
|
detail_payload = {"rtn_code": 0, "data": {"minutes": 5, "code": "51287"}}
|
||||||
|
|
||||||
|
def fake_auth(user_id, method, path, **kw):
|
||||||
|
return active_payload if path == "/user/info" else detail_payload
|
||||||
|
|
||||||
|
with patch.object(timer, "get_user_auth", return_value=("t", "a")), \
|
||||||
|
patch.object(timer, "request_with_user_auth", side_effect=fake_auth), \
|
||||||
|
patch.object(timer, "get_user_rental_settings",
|
||||||
|
return_value={"reminder_enabled": False, "reminder_minutes": [],
|
||||||
|
"rental_duration_minutes": 19,
|
||||||
|
"auto_return_enabled": False}), \
|
||||||
|
patch.object(timer, "start_rental_timer"), \
|
||||||
|
patch.object(timer, "_bike_pos_from_history", return_value=None):
|
||||||
|
timer._check_user_order(7)
|
||||||
|
|
||||||
|
conn = db.get_db()
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT id, expired FROM rentals WHERE order_id='ORD-9400' ORDER BY id").fetchall()
|
||||||
|
conn.close()
|
||||||
|
state = {r["id"]: r["expired"] for r in rows}
|
||||||
|
self.assertEqual(1, state[9400], "历史行应保持已结束")
|
||||||
|
self.assertEqual(0, state[9401], "活跃行应被复活并继续计时")
|
||||||
|
|
||||||
|
|
||||||
|
class RoundOverrideTests(_Base):
|
||||||
|
"""B4:+1 轮是付费承诺,必须随续租传递。"""
|
||||||
|
|
||||||
|
def test_renewal_inherits_rounds_override(self):
|
||||||
|
self.add_rental(9501, "ORD-9501")
|
||||||
|
conn = db.get_db()
|
||||||
|
try:
|
||||||
|
conn.execute("UPDATE rentals SET rounds_override = 5 WHERE id = 9501")
|
||||||
|
conn.commit()
|
||||||
|
except sqlite3.OperationalError:
|
||||||
|
conn.close()
|
||||||
|
self.skipTest("当前 schema 没有 rounds_override")
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
rental = {"id": 9501, "order_id": "ORD-9501", "bike_code": "51287",
|
||||||
|
"email": "rider@example.test", "source": "unlock",
|
||||||
|
"renewal_round": 1, "rounds_override": 5,
|
||||||
|
"end_time": "2026-01-01 09:19:00"}
|
||||||
|
|
||||||
|
def fake_auth(user_id, method, path, **kw):
|
||||||
|
if path == "/record/order":
|
||||||
|
return {"rtn_code": 0, "data": {"order_id": "ORD-9502"}}
|
||||||
|
return {"rtn_code": 0, "data": {}}
|
||||||
|
|
||||||
|
with patch.object(timer, "_live_bike_position", return_value=(36.5318, 116.7802)), \
|
||||||
|
patch.object(timer, "request_with_user_auth", side_effect=fake_auth), \
|
||||||
|
patch.object(timer, "start_rental_timer"):
|
||||||
|
new_id = timer._create_renewal_rental(
|
||||||
|
rental, 7, "ORD-9502",
|
||||||
|
{"rental_duration_minutes": 19, "auto_return_enabled": True,
|
||||||
|
"reminder_enabled": False, "reminder_minutes": []},
|
||||||
|
2)
|
||||||
|
|
||||||
|
conn = db.get_db()
|
||||||
|
row = conn.execute("SELECT rounds_override FROM rentals WHERE id = ?",
|
||||||
|
(new_id,)).fetchone()
|
||||||
|
conn.close()
|
||||||
|
self.assertEqual(5, row["rounds_override"],
|
||||||
|
"续租没继承 rounds_override → 第 3 轮起用户加的轮被吞掉")
|
||||||
|
|
||||||
|
|
||||||
|
class ZeroMinutePrecheckTests(_Base):
|
||||||
|
"""B8:0 点 Timer 先问上游,别对已还车订单发「自动还车失败(紧急)」。"""
|
||||||
|
|
||||||
|
def test_upstream_finished_only_closes_locally(self):
|
||||||
|
self.add_rental(9601, "ORD-9601")
|
||||||
|
with patch.object(timer.threading, "Timer", _ImmediateTimer), \
|
||||||
|
patch.object(timer, "_upstream_ride_active", return_value=False) as precheck, \
|
||||||
|
patch.object(timer, "auto_return_bike") as auto_return, \
|
||||||
|
patch.object(timer, "send_rental_notification") as notify, \
|
||||||
|
patch.object(timer, "_close_rental_locally") as close_local, \
|
||||||
|
patch.object(timer, "_clear_auto_return_state"), \
|
||||||
|
patch.object(timer, "_mark_notified"):
|
||||||
|
timer._schedule_reminder(
|
||||||
|
rental_id=9601, delay_seconds=0, reminder_type="0",
|
||||||
|
email="rider@example.test", bike_code="51287", user_id=7,
|
||||||
|
send_notification=True, gen=None,
|
||||||
|
)
|
||||||
|
|
||||||
|
precheck.assert_called_once()
|
||||||
|
auto_return.assert_not_called()
|
||||||
|
close_local.assert_called_once()
|
||||||
|
notify.assert_not_called()
|
||||||
|
|
||||||
|
def test_upstream_still_active_goes_ahead(self):
|
||||||
|
"""上游确实还在骑时,不能因为预判把自动还车拦掉。"""
|
||||||
|
self.add_rental(9602, "ORD-9602")
|
||||||
|
with patch.object(timer.threading, "Timer", _ImmediateTimer), \
|
||||||
|
patch.object(timer, "_upstream_ride_active", return_value=True), \
|
||||||
|
patch.object(timer, "auto_return_bike",
|
||||||
|
return_value={"success": True, "message": "ok"}) as auto_return, \
|
||||||
|
patch.object(timer, "send_rental_notification"), \
|
||||||
|
patch.object(timer, "_close_rental_locally") as close_local, \
|
||||||
|
patch.object(timer, "_clear_auto_return_state"), \
|
||||||
|
patch.object(timer, "_mark_notified"):
|
||||||
|
timer._schedule_reminder(
|
||||||
|
rental_id=9602, delay_seconds=0, reminder_type="0",
|
||||||
|
email="rider@example.test", bike_code="51287", user_id=7,
|
||||||
|
send_notification=True, gen=None,
|
||||||
|
)
|
||||||
|
|
||||||
|
auto_return.assert_called_once()
|
||||||
|
close_local.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -292,6 +292,62 @@ def _mark_returned(rental_id: int, latitude=None, longitude=None):
|
|||||||
conn.close()
|
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:
|
def _reopen_same_bike(user_id: int, bike_code: str) -> dict:
|
||||||
"""还车后为同一辆车创建下一轮订单并开锁。"""
|
"""还车后为同一辆车创建下一轮订单并开锁。"""
|
||||||
bike_result = request_with_user_auth(
|
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", "获取车辆信息失败")}
|
return {"success": False, "message": bike_result.get("message", "获取车辆信息失败")}
|
||||||
|
|
||||||
bike_data = bike_result.get("data") or {}
|
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(
|
order_result = request_with_user_auth(
|
||||||
user_id, "POST", "/record/order",
|
user_id, "POST", "/record/order",
|
||||||
data={"code": bike_code, "start_longitude": longitude,
|
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"),
|
start_time.strftime("%Y-%m-%d %H:%M:%S"),
|
||||||
end_time.strftime("%Y-%m-%d %H:%M:%S"), duration, source, next_round))
|
end_time.strftime("%Y-%m-%d %H:%M:%S"), duration, source, next_round))
|
||||||
rental_id = cursor.lastrowid
|
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:
|
except sqlite3.IntegrityError:
|
||||||
# 唯一索引 idx_rentals_active_order:同一 order_id 已有未结束记录
|
# 唯一索引 idx_rentals_active_order:同一 order_id 已有未结束记录
|
||||||
# (web 侧刚开锁/订阅/共享落了库)。复用那一行,不能让巡检线程
|
# (web 侧刚开锁/订阅/共享落了库)。复用那一行,不能让巡检线程
|
||||||
@@ -692,9 +762,9 @@ def _recover_throttled(rental_id: int) -> bool:
|
|||||||
|
|
||||||
两种节流来源:
|
两种节流来源:
|
||||||
1. 基础间隔 5 分钟(临时故障时不要每分钟打上游);
|
1. 基础间隔 5 分钟(临时故障时不要每分钟打上游);
|
||||||
2. BUG-07 的退避表 `_auto_return_backoff_until` —— 进入退避阶段后,间隔由
|
2. 退避表 `_auto_return_backoff_until` —— 进入退避阶段后,间隔由失败次数与
|
||||||
失败次数决定(1m→2m→5m→10m 封顶),此时以退避表为准,不再叠加基础间隔,
|
已耗时决定(30 分钟内恒 60s,之后 60/120/300s 封顶),此时以退避表为准,
|
||||||
否则 1/2 分钟的退避会被 5 分钟基础间隔吃掉。
|
不再叠加基础间隔,否则 60 秒的退避会被 5 分钟基础间隔吃掉。
|
||||||
"""
|
"""
|
||||||
now = _time.time()
|
now = _time.time()
|
||||||
due = _auto_return_backoff_until.get(rental_id)
|
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}")
|
print(f"[自动还车] 租约获取失败(按单进程处理): {exc}")
|
||||||
lease_acquired = False
|
lease_acquired = False
|
||||||
if not lease_acquired:
|
if not lease_acquired:
|
||||||
|
# 没真跑就别占节流额度:否则这一单要白等 5 分钟(退避期 60 秒)才被重试
|
||||||
|
_recover_last_at.pop(rental_id, None)
|
||||||
return {"success": False, "skipped": True,
|
return {"success": False, "skipped": True,
|
||||||
"message": "另一个进程正在处理这一单"}
|
"message": "另一个进程正在处理这一单"}
|
||||||
|
|
||||||
@@ -786,8 +858,9 @@ def _run_recovery_locked(rental_id: int, user_id: int, order_id=None):
|
|||||||
if result.get("success"):
|
if result.get("success"):
|
||||||
_clear_auto_return_state(rental_id)
|
_clear_auto_return_state(rental_id)
|
||||||
elif not result.get("skipped"):
|
elif not result.get("skipped"):
|
||||||
# 失败:只有进入退避阶段(快保 30s×6 已经用完)才由这里推进下一次到点时间,
|
# 失败:只有进入退避阶段(快保次数已经用完)才由这里推进下一次到点时间,
|
||||||
# 快保阶段由 Timer 链自己负责,避免两套重试互相抢节奏。
|
# 快保阶段由 Timer 链自己负责,避免两套重试互相抢节奏。
|
||||||
|
# 返回 0 表示「已到绝对上限、彻底停手」,此时不再留 backoff 到点时间。
|
||||||
_advance_auto_return_backoff(
|
_advance_auto_return_backoff(
|
||||||
rental_id, str(result.get("message") or ""))
|
rental_id, str(result.get("message") or ""))
|
||||||
return result
|
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)
|
_recover_last_at.pop(rental_id, None)
|
||||||
_auto_return_retries.pop(rental_id, None)
|
_auto_return_retries.pop(rental_id, None)
|
||||||
_auto_return_alert_levels.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:
|
if not keep_backoff:
|
||||||
_auto_return_backoff_until.pop(rental_id, None)
|
_auto_return_backoff_until.pop(rental_id, None)
|
||||||
|
|
||||||
@@ -1011,11 +1087,35 @@ def _advance_auto_return_backoff(rental_id: int, message: str = "") -> int:
|
|||||||
否则快保阶段由 Timer 链自己推进,两套机制同时改计数会互相抢节奏。
|
否则快保阶段由 Timer 链自己推进,两套机制同时改计数会互相抢节奏。
|
||||||
"""
|
"""
|
||||||
n = _auto_return_retries.get(rental_id, 0)
|
n = _auto_return_retries.get(rental_id, 0)
|
||||||
if n < AUTO_RETURN_MAX_RETRIES:
|
if n < len(AUTO_RETURN_RETRY_DELAYS):
|
||||||
return 0
|
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_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)
|
level = _auto_return_alert_level(n + 1)
|
||||||
if level > _auto_return_alert_levels.get(rental_id, 0):
|
if level > _auto_return_alert_levels.get(rental_id, 0):
|
||||||
_auto_return_alert_levels[rental_id] = level
|
_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()
|
conn.close()
|
||||||
return_result = None
|
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:
|
if auto_return_enabled and user_id:
|
||||||
try:
|
try:
|
||||||
return_result = auto_return_bike(rental_id, user_id)
|
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:
|
if isinstance(gen, int) and _timer_gen.get(rental_id, 0) != gen:
|
||||||
# 这一代已经被取消/取代(并发重排或还车),注册即作废,避免残留重复提醒
|
# 这一代已经被取消/取代(并发重排或还车),注册即作废,避免残留重复提醒
|
||||||
return None
|
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 秒任务先完成/取消后又被追加回活动列表。
|
# 先登记再启动,避免 0 秒任务先完成/取消后又被追加回活动列表。
|
||||||
timer.start()
|
timer.start()
|
||||||
return timer
|
return timer
|
||||||
@@ -1458,8 +1585,11 @@ def _check_user_order(user_id: int):
|
|||||||
conn = get_db()
|
conn = get_db()
|
||||||
cursor = conn.cursor()
|
cursor = conn.cursor()
|
||||||
cursor.execute(
|
cursor.execute(
|
||||||
|
# 同一 order_id 可能既有历史行(expired=1)又有活跃行:优先活跃行,
|
||||||
|
# 否则会把已结束的历史单「复活」,撞唯一索引后再靠兜底救回来(多一次写 + 误导日志)
|
||||||
"SELECT id, order_id, source, expired, end_time FROM rentals "
|
"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)
|
(order_id, user_id)
|
||||||
)
|
)
|
||||||
existing = cursor.fetchone()
|
existing = cursor.fetchone()
|
||||||
@@ -1667,7 +1797,7 @@ def _finish_active_wechat_rentals(user_id: int, reason: str):
|
|||||||
cursor.execute("""
|
cursor.execute("""
|
||||||
SELECT id, order_id, source, bike_code FROM rentals
|
SELECT id, order_id, source, bike_code FROM rentals
|
||||||
WHERE user_id = ? AND expired = 0
|
WHERE user_id = ? AND expired = 0
|
||||||
AND source IN ('unlock', 'sync', 'shared')
|
AND source IN ('unlock', 'sync', 'shared', 'subscribe')
|
||||||
""", (user_id,))
|
""", (user_id,))
|
||||||
active_rows = cursor.fetchall()
|
active_rows = cursor.fetchall()
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|||||||
Reference in New Issue
Block a user