Files
zzy aa6132f3e1 fix: 订单生命周期 / 鉴权基础设施 / 前端 UX 批量修复(R2-R12、A3-A12、F1-F14)
后端 · 订单与计时器(timer.py / routes/rental.py / routes/share.py)
- R2 关闭自动还车后,巡检 / 重启恢复 / sweep 不再强制还车(_should_auto_return 读骑行人设置)
- R3 手动还车撞续租窗口:先等 _renewal_lock,再按同车活跃行重查,不再误回「订单已结束」
- R4 续租复用巡检行时补齐 renewal_round / rounds_override / rider_user_id / source
- R5 续租策略统一读骑行人(rider_user_id or user_id);上游调用与卡支付仍用车主
- R6 续租落库失败立即 _check_user_order 兜底,仍失败则管理员告警
- R7 /record/qrOrder 失败撤销半成品订单(续租 + 共享开锁两处)
- R8 跨进程租约移入 auto_return_bike 本体(ttl 180);线程内重入只由最外层释放一次;新增 _background_enabled 总开关
- R9 自动还车失败先复查 expired,已结束则不再重试、不发紧急邮件
- R10 开锁响应 SELECT 补 order_id,轮次预估不再恒为 1 轮
- R11 共享开锁落库:IntegrityError 复用活跃行;其它异常同步订单并在响应带 warning
- R12 0 分钟自动还车的结果邮件不再依赖「0 分钟提醒」被勾选

后端 · 鉴权与基础设施
- A3  /api/admin/users 不再返回完整 access_token / token_id(只留掩码)
- A4  采集调度循环 try/except;后台线程登记,看门狗按 is_alive 重拉;租约 True/False/None 三态显式
- A5  采集改走 _request_api_uncached;map_cache 失败标 stale / stale_since,fetched_at 保持上次成功时间
- A6  bootstrap try/finally,异常时复位 _bootstrap_started
- A7  删除含明文 AK/SK 的旧分发包 1.zip
- A8  record_cooldown 不再翻转已有有效验证码的 purpose(修注册验证码 DoS)
- A9  登录新增邮箱维度限流(10 次 / 900 秒)
- A10 管理员代还车一律按订单归属用户执行,body user_id 不一致时返回 warning
- A11 /api/ring_progress 改用 /api/ring_ticket 签发的一次性 ticket,不再接受 ?token=
- A12 导出令牌绑定创建者、下载一次性、可撤销(POST /api/export/revoke)
- 时区:CURRENT_TIMESTAMP 全部统一为 datetime('now', '+8 hours')(db.py / admin.py / share.py)
- JSON:auth 入参非字符串时返回 400 而非 500

前端(src-ts / templates / static)
- F1  登录后静默定位;找车 / 导航无定位时现场申请;被拒弹卡片并提供「用地图中心找车」
- F2  真实订单的计时条不再被 status 轮询清掉;startRentalFromServer 记录 order_id
- F3  登出 / 会话失效时 resetUserState 清掉横幅、计时条、共享横幅与本地存储
- F4  toast 改为 #toast-stack(最多 3 条、role=status),不再互相覆盖
- F6  新增 fetchWithTimeout(8 秒),全站 fetch 接入;/api/config 超时显示失败卡片
- F7  getBikeState 顺序统一为 损坏→使用中→欠压→低电量→空闲,图例与卡片同源
- F8  快照刷新后卡片按车牌重绘,车辆离开实时列表则关闭并提示
- F10 共享权限复选框改为 label 包裹
- F11 分析页 echarts / mapvgl 加 defer + onerror;BMap 超时显示失败卡片
- F12 删除订阅规则增加二次确认,按钮加 tap-44
- F13 扫码查询按钮禁用态;401 / 非 JSON 响应走登录门
- F14 刷新按钮绑定真实请求,失败必提示
- ring_progress.html 改两步 ticket 流程;bike-clusters addEventListener 特性检测

测试
- 新增 tests/test_fix_order_lifecycle.py(27)、tests/test_fix_infra_fixes.py(24)、tests/test_fix_frontend.cjs(13)
- tests/test_order_sync.py、tests/test_ring_owner.py 按 R12 / A11 新语义更新
- pytest 322 passed;tsc / esbuild / verify:globals 通过;cjs 58 passed
2026-11-23 19:37:28 +08:00

2142 lines
100 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""计时器系统 + 后台订单检测模块"""
import threading
import time as _time
import datetime as dt
import sqlite3
from db import (get_db, get_user_auth, get_user_rental_settings,
mark_user_credential_blocked, is_rental_credential_blocked,
acquire_lease, release_lease)
from wechat import request_api, request_with_user_auth
from rental_mail import mark_return_tokens_used, send_rental_notification
# 后台自动动作(0 点自动还车 / 巡检补还车 / 兜底扫描)的总开关:
# 单测与「只跑 Web 请求」的进程可以关掉,避免后台线程在测试库里补还车。
_background_enabled = True
def set_background_enabled(flag: bool) -> None:
"""设置后台自动还车/巡检补还车的总开关(Web 请求路径的手动还车不受影响)。"""
global _background_enabled
_background_enabled = bool(flag)
print(f"[计时系统] 后台自动还车总开关 = {_background_enabled}")
# ========== 计时器系统 ==========
TIMER_CHECK_INTERVAL = 30
_active_timers: dict = {}
_timers_lock = threading.Lock() # 保护 _active_timers / _timer_gen(多线程增删)
# 每个 rental_id 的「代号」:start_rental_timer 每次重排都会自增,_schedule_reminder
# 注册 Timer 时代号已变的(上一代)一律丢弃 —— 同一单在并发重排下不会残留两套提醒。
_timer_gen: dict = {}
_renewal_locks: dict = {}
_renewal_locks_guard = threading.Lock()
# 进程内状态表的容量上限:这些表以 rental_id 为 key,正常条目数约等于现存订单数,
# 但出现"永远还不上"的单或脏 id 时会只增不减,因此统一做定期清理。
_RUNTIME_DICT_MAX = 2000
_PRUNE_INTERVAL_SECONDS = 300
_RECOVER_STATE_TTL = 6 * 3600 # 6 小时后视为陈旧(正常单早就还掉了)
_last_prune_at = [0.0]
def _coerce_int(value, default: int = 0) -> int:
"""安全转 int:None / 空串 / 非数字一律回落 default,不向上抛异常。
上游 `/record/detail` 的 `minutes` 实测会返回 null(BUG-06:以前 `int(None)`
直接把 `/api/rental/sync` 打成 500,并让整轮巡检作废)。
"""
if value is None or isinstance(value, bool):
return default
try:
return int(float(value))
except (TypeError, ValueError):
return default
# ========== 用户订单检测系统 ==========
_order_checker_threads: dict[int, threading.Thread] = {}
_order_checker_stop: dict[int, threading.Event] = {}
_checker_lock = threading.Lock()
# 外部(例如微信小程序)还车后,要尽快取消本地的邮件提醒。
# 10 分钟轮询会让 5/3/2/1/0 分钟提醒继续发送,改为每分钟核对一次。
ORDER_CHECK_INTERVAL = 60
# 自动还车用的停车区缓存:{user_id: (ts, parkeArea)},避免续租链反复拉地图
_PARK_AREA_CACHE: dict = {}
_PARK_AREA_TTL = 60
def _get_remaining_seconds(rental: dict) -> int:
"""计算距离过期的秒数"""
now = dt.datetime.now(dt.timezone(dt.timedelta(hours=8)))
end = dt.datetime.strptime(rental["end_time"], "%Y-%m-%d %H:%M:%S")
end = end.replace(tzinfo=dt.timezone(dt.timedelta(hours=8)))
remaining = int((end - now).total_seconds())
return max(0, remaining)
def _rental_end_time_passed(rental: dict) -> bool:
"""end_time 是否已经过去(重启补还车 / 巡检补还车共用)。"""
end_time = (rental or {}).get("end_time")
if not end_time:
return False
try:
end = dt.datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S")
except (TypeError, ValueError):
return False
tz = dt.timezone(dt.timedelta(hours=8))
return end.replace(tzinfo=tz) <= dt.datetime.now(tz)
def _extract_pay_methods(methods_result: dict):
data = methods_result.get("data", {}) if isinstance(methods_result, dict) else {}
if not isinstance(data, (list, dict)):
return []
methods = data if isinstance(data, list) else data.get(
"payMethods", data.get("methods", [])
)
if not isinstance(methods, list):
return []
return [method for method in methods if isinstance(method, dict)]
def _card_remaining_times(method: dict):
"""读取优惠卡的剩余次数;None 表示接口未提供可识别的次数。"""
values = []
infinite = False
def visit(value):
nonlocal infinite
if isinstance(value, dict):
for key, child in value.items():
normalized = str(key).lower().replace("_", "")
is_count = (
("remain" in normalized or "left" in normalized or
"surplus" in normalized or "available" in normalized)
and any(token in normalized for token in ("time", "count", "num"))
)
if is_count:
if child is None or str(child).strip().lower() in (
"", "none", "null", "infinity", "infinite", "∞"
):
infinite = True
else:
try:
values.append(int(float(child)))
except (TypeError, ValueError):
pass
visit(child)
elif isinstance(value, list):
for child in value:
visit(child)
visit(method)
if values:
return max(values)
if infinite:
return None
return None
def _has_available_card(user_id: int, code: str, package_id: str = "") -> bool:
"""确认支付后是否仍有可用优惠卡,供“优先保护月卡”使用。"""
try:
methods_result = request_with_user_auth(
user_id, "GET", "/pay/methods", params={"code": code}
)
except Exception as exc:
print(f"[自动续租] 查询优惠卡剩余次数异常: {exc}")
return False
if not isinstance(methods_result, dict) or methods_result.get("rtn_code") != 0:
return False
card_methods = [
method for method in _extract_pay_methods(methods_result)
if str(method.get("type")) in ("3", "4")
]
if not card_methods:
return False
target_methods = card_methods
if package_id:
matched = [method for method in card_methods
if str(method.get("package_id", "")) == str(package_id)]
if matched:
target_methods = matched
# /pay/methods 的部分版本不带剩余次数;/user/packages 是前端展示
# remainTimes 的同一份数据,优先用已支付的卡包进行精确保护。
try:
package_result = request_with_user_auth(user_id, "GET", "/user/packages")
except Exception as exc:
print(f"[自动续租] 查询优惠卡包异常: {exc}")
package_result = None
if isinstance(package_result, dict) and package_result.get("rtn_code") == 0:
package_data = package_result.get("data") or {}
packages = package_data.get("bike_packages", package_data.get("packages", [])) \
if isinstance(package_data, dict) else []
if isinstance(packages, list):
target_packages = packages
if package_id:
matched = [package for package in packages
if str(package.get("package_id", "")) == str(package_id)]
if matched:
target_packages = matched
package_counts = [_card_remaining_times(package) for package in target_packages
if isinstance(package, dict)]
if package_counts and any(count is not None for count in package_counts):
return any(count is None or count > 0 for count in package_counts)
# 兜底:带次数的支付方式严格判断;未带次数时,沿用上游“可用支付方式”结论。
return any(
_card_remaining_times(method) is None or _card_remaining_times(method) > 0
for method in target_methods
)
def _try_card_pay_auto(user_id: int, order_id: str, code: str) -> dict:
"""
自动尝试用月卡/周卡支付订单(从 app.py.bak 原样复制)
返回: {"success": True/False, "message": "xxx"}
"""
methods_result = request_with_user_auth(
user_id, "GET", "/pay/methods",
params={"code": code}
)
if methods_result.get("rtn_code") != 0:
return {"success": False, "message": "查询支付方式失败"}
card_methods = [
method for method in _extract_pay_methods(methods_result)
if str(method.get("type")) in ("3", "4")
and (_card_remaining_times(method) is None or _card_remaining_times(method) > 0)
]
if not card_methods:
return {"success": False, "message": "没有可用的月卡/周卡"}
preferred = card_methods[0]
for m in card_methods:
if m.get("get_type") == 2:
preferred = m
break
pay_type = str(preferred.get("type", "3"))
package_id = str(preferred.get("package_id", ""))
if not package_id:
return {"success": False, "message": "卡包ID为空"}
card_name = "月卡" if pay_type == "3" else "周卡"
print(f"[_try_card_pay_auto] 使用{card_name}支付: order_id={order_id}, code={code}, package_id={package_id}")
pay_result = request_with_user_auth(
user_id, "POST", "/pay/submit",
data={"platform": "1", "order_id": order_id, "code": code,
"type": pay_type, "package_id": package_id}
)
# 解析 /pay/submit 返回的支付状态:data 可能是 dict / 列表 / 空列表 / None,需全部兜底
_pd = pay_result.get("data")
if isinstance(_pd, list):
pay_status = str(_pd[0].get("status", "")) if _pd and isinstance(_pd[0], dict) else ""
elif isinstance(_pd, dict):
pay_status = str(_pd.get("status", ""))
else:
pay_status = ""
if pay_status == "0":
return {"success": True, "message": f"{card_name}支付成功",
"card_type": pay_type, "package_id": package_id}
elif pay_status == "1":
return {"success": False, "message": f"{card_name}余额不足,需要微信支付"}
else:
return {"success": False, "message": pay_result.get("message", "支付失败")}
def _renewal_round(rental: dict) -> int:
try:
return max(1, int(rental.get("renewal_round") or 1))
except (TypeError, ValueError):
return 1
def _planned_rounds(rental: dict, settings: dict) -> int:
"""订单计划总轮数:手动加轮的 rounds_override 优先于用户设置。"""
override = rental.get("rounds_override")
try:
return int(override) if override else int(settings.get("rental_rounds", 1))
except (TypeError, ValueError):
return int(settings.get("rental_rounds", 1))
def _mark_returned(rental_id: int, latitude=None, longitude=None):
"""结束订单并回填实际还车时间与终点(auto-return / 微信端还车共用)。"""
label = None
if latitude is not None and longitude is not None:
try:
from campus import resolve_location_label
label = resolve_location_label(latitude, longitude)
except Exception:
label = None
conn = get_db()
try:
try:
conn.execute("""
UPDATE rentals SET expired = 1, returned_at = datetime('now', '+8 hours'),
end_latitude = ?, end_longitude = ?, end_label = ?
WHERE id = ?
""", (latitude, longitude, label, rental_id))
except sqlite3.OperationalError:
# 轻量兜底:旧库/极简 schema 缺列时补齐再重试一次
for col_def in [("returned_at", "TIMESTAMP"), ("end_latitude", "REAL"),
("end_longitude", "REAL"), ("end_label", "TEXT")]:
try:
conn.execute(f"ALTER TABLE rentals ADD COLUMN {col_def[0]} {col_def[1]}")
except sqlite3.OperationalError:
pass
conn.execute("""
UPDATE rentals SET expired = 1, returned_at = datetime('now', '+8 hours'),
end_latitude = ?, end_longitude = ?, end_label = ?
WHERE id = ?
""", (latitude, longitude, label, rental_id))
conn.commit()
finally:
# 写失败也要关连接:以前这里异常会泄漏连接(fd 累积),
# 而且调用方拿不到「状态没落库」的信号
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(
user_id, "POST", "/project/bicycle", data={"code": bike_code}
)
if bike_result.get("rtn_code") != 0:
return {"success": False, "message": bike_result.get("message", "获取车辆信息失败")}
bike_data = bike_result.get("data") or {}
# 优先用实时位置开单;取不到原车位置时也不提前中止,按上游允许的方式
# 直接尝试下单开锁(不填起点坐标),确实失败再把原因明确告诉用户。
position = _live_bike_position(user_id, bike_code, first_payload=bike_data)
order_data = {"code": bike_code}
if position:
latitude, longitude = position
order_data.update({"start_longitude": longitude, "start_latitude": latitude})
else:
print(f"[续租] 未获取到 {bike_code} 的实时位置,仍直接尝试下单开锁")
order_result = request_with_user_auth(
user_id, "POST", "/record/order", data=order_data
)
order_data = order_result.get("data") or {}
if order_result.get("rtn_code") != 0 or not order_data.get("order_id"):
reason = order_result.get("message", "创建下一轮订单失败")
if not position:
reason += "(未获取到原车位置,已直接尝试下单)"
return {"success": False, "message": reason}
order_id = order_data["order_id"]
open_result = request_with_user_auth(
user_id, "POST", "/record/qrOrder", data={"order_id": order_id}
)
if open_result.get("rtn_code") != 0:
# 下一轮开锁失败:把刚下的半成品订单撤掉,否则上游留一张没人骑的
# 「未支付」单,下次开锁命中「未支付」分支时会用月卡把它付掉(白扣一次卡次)。
try:
from subscribe import _discard_pending_order
if position:
_discard_pending_order(user_id, order_id, bike_code, position[0], position[1])
else:
_discard_pending_order(user_id, order_id, bike_code, None, None)
except Exception as exc:
print(f"[自动续租] 撤销半成品下一轮订单异常: order_id={order_id}, error={exc}")
return {"success": False, "message": open_result.get("message", "下一轮开锁失败"),
"order_id": order_id}
return {"success": True, "order_id": str(order_id), "message": "下一轮开锁成功"}
def _create_renewal_rental(rental: dict, user_id: int, order_id: str,
settings: dict, next_round: int) -> int:
tz = dt.timezone(dt.timedelta(hours=8))
start_time = dt.datetime.now(tz)
duration = int(settings.get("rental_duration_minutes", 19))
end_time = start_time + dt.timedelta(minutes=duration)
source = rental.get("source") or "unlock"
if source == "reminder":
source = "unlock"
email = rental.get("email") or ""
rider_user_id = rental.get("rider_user_id")
reused = False
conn = get_db()
try:
# 正常情况下由 init_db 完成迁移;这里再做一次轻量兜底,避免旧开发库
# 缺列时把下一轮记录成“第1轮”,导致后续轮次无法正确停止。
try:
conn.execute("SELECT renewal_round FROM rentals LIMIT 0")
except sqlite3.OperationalError:
conn.execute("ALTER TABLE rentals ADD COLUMN renewal_round INTEGER NOT NULL DEFAULT 1")
try:
if rider_user_id:
cursor = conn.execute("""
INSERT INTO rentals (order_id, bike_code, email, user_id, rider_user_id,
start_time, end_time, duration, expired, source, renewal_round)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?)
""", (order_id, rental["bike_code"], email, user_id, rider_user_id,
start_time.strftime("%Y-%m-%d %H:%M:%S"),
end_time.strftime("%Y-%m-%d %H:%M:%S"), duration, source, next_round))
else:
cursor = conn.execute("""
INSERT INTO rentals (order_id, bike_code, email, user_id,
start_time, end_time, duration, expired, source, renewal_round)
VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?)
""", (order_id, rental["bike_code"], email, user_id,
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 侧刚开锁/订阅/共享落了库)。复用那一行,不能让巡检线程
# 因为唯一冲突抛异常退出 —— 上游在计费,本地一旦没有计时器就再没人还车。
rental_id = _active_rental_id_for_order(conn, order_id)
if rental_id is None:
raise
print(f"[自动续租] order_id={order_id} 已有未结束记录 rental_id={rental_id},复用不新建")
# 复用行要带上本次续租的意图:轮次(否则第 3 轮起停不下来)、加轮承诺、
# 实际骑行者(策略按骑行者算)、来源。每一列单独 UPDATE,缺列(老库)只跳过该列。
_apply_renewal_fields(conn, rental_id, rental, next_round, source)
reused = True
conn.commit()
finally:
conn.close()
# 复用行时 web 侧通常已经挂了计时器:没有活的才补启动,避免把别人那套提醒重排掉。
if reused and _has_active_timer(rental_id):
return rental_id
try:
start_rental_timer(rental_id, email, rental["bike_code"], duration, user_id)
except Exception as exc:
# 上游订单和本地记录已经建立,计时器恢复流程仍可在下次启动时接管。
print(f"[自动续租] 新订单计时器启动失败: rental_id={rental_id}, error={exc}")
return rental_id
def _apply_renewal_fields(conn, rental_id: int, rental: dict, next_round: int, source: str):
"""复用已存在的活跃行时,把本次续租的意图写回去(每列独立容错)。"""
updates = (
("renewal_round = ?", (next_round,)),
("rounds_override = ?", (rental.get("rounds_override"),)),
("rider_user_id = ?", (rental.get("rider_user_id"),)),
("source = ?", (source,)),
)
for assignment, params in updates:
try:
conn.execute(f"UPDATE rentals SET {assignment} WHERE id = ?", (*params, rental_id))
except sqlite3.OperationalError as exc:
print(f"[自动续租] 复用行 rental_id={rental_id} 更新 {assignment.split(' =')[0]} "
f"失败(缺列,跳过): {exc}")
def _has_active_timer(rental_id: int) -> bool:
"""该单当前是否还挂着活着的 Timer(复用行时用来判断要不要重新启动计时器)。"""
with _timers_lock:
timers = list(_active_timers.get(rental_id) or [])
for t in timers:
fn = getattr(t, "is_alive", None)
try:
if not callable(fn) or fn():
return True
except Exception:
return True
return False
def _maybe_renew_after_return(rental: dict, user_id: int,
pay_result: dict, allow_renewal: bool = True) -> dict:
"""根据还车后实时读取的设置决定是否进入下一轮。"""
if not allow_renewal or not pay_result.get("success"):
return {"renewed": False}
# 策略(是否续租 / 几轮 / 保卡)按实际骑行者算;上游调用与卡支付仍用车主 user_id(卡属于车主)。
policy_id = rental.get("rider_user_id") or user_id
settings = get_user_rental_settings(policy_id)
current_round = _renewal_round(rental)
total_rounds = _planned_rounds(rental, settings)
if not settings.get("auto_return_enabled", True) or current_round >= total_rounds:
return {"renewed": False, "round": current_round, "total_rounds": total_rounds}
if settings.get("protect_card", True) and not _has_available_card(
user_id, rental["bike_code"], pay_result.get("package_id", "")):
return {"renewed": False, "blocked": True, "round": current_round,
"total_rounds": total_rounds,
"message": "优先保护优惠卡:支付后已无可用优惠卡,未开启下一轮"}
try:
reopen_result = _reopen_same_bike(user_id, rental["bike_code"])
except Exception as exc:
print(f"[自动续租] 重开车辆异常: {exc}")
return {"renewed": False, "round": current_round, "total_rounds": total_rounds,
"message": f"下一轮开锁异常: {exc}"}
if not reopen_result.get("success"):
return {"renewed": False, "round": current_round, "total_rounds": total_rounds,
"message": reopen_result.get("message", "下一轮开锁失败")}
next_round = current_round + 1
try:
new_rental_id = _create_renewal_rental(
rental, user_id, reopen_result["order_id"], settings, next_round
)
except Exception as exc:
# 下一轮已经开锁(上游在计费),本地却没落上记录:先立刻跑一次订单同步补上这一行,
# 同步也补不上就升级为严重告警 —— 这种单子没有任何计时器,没人会去还车。
print(f"[自动续租] 本地记录下一轮订单异常: {exc}")
return _recover_renewal_record_failure(
rental, user_id, reopen_result.get("order_id"), current_round, total_rounds, exc)
return {"renewed": True, "round": next_round, "total_rounds": total_rounds,
"rental_id": new_rental_id, "order_id": reopen_result["order_id"],
"message": f"已自动开启第{next_round}轮"}
def _recover_renewal_record_failure(rental: dict, user_id: int, order_id,
current_round: int, total_rounds: int, exc) -> dict:
"""`_create_renewal_rental` 失败后的兜底:先订单同步补记录,仍失败则严重告警。"""
synced = False
try:
result = _check_user_order(user_id) or {}
synced = bool(result.get("ok"))
print(f"[自动续租] 本地记录失败后已跑订单同步: order_id={order_id}, result={result}")
except Exception as check_exc:
print(f"[自动续租] 本地记录失败后订单同步异常: order_id={order_id}, error={check_exc}")
# 再确认一次这一单在本地是否有活跃行(同步 ok 不代表就落上了这一单)
if synced:
try:
conn = get_db()
try:
synced = _active_rental_id_for_order(conn, order_id) is not None
finally:
conn.close()
except Exception as probe_exc:
print(f"[自动续租] 复查本地记录异常: order_id={order_id}, error={probe_exc}")
synced = False
if not synced:
print(f"[自动续租][严重] 下一轮已开锁但本地无记录且同步失败,无人会自动还车: "
f"order_id={order_id}, bike_code={rental.get('bike_code')}, "
f"user_id={user_id}, error={exc}")
try:
_alert_auto_return_exhausted(
rental.get("id"), rental.get("bike_code"),
f"下一轮订单 {order_id} 已开锁但本地记录失败且订单同步未补上,"
f"该单没有计时器、不会自动还车,请人工处理。错误:{exc}")
except Exception as alert_exc:
print(f"[自动续租] 严重告警发送失败: {alert_exc}")
return {"renewed": False, "round": current_round, "total_rounds": total_rounds,
"message": f"下一轮已开锁,但本地记录失败: {exc}"}
return {"renewed": True, "round": current_round + 1, "total_rounds": total_rounds,
"order_id": order_id,
"message": f"已自动开启第{current_round + 1}轮(本地记录已由订单同步补上)"}
def _renewal_lock(rental_id: int):
"""按 rental_id 复用的还车串行锁;表有容量上限,避免脏 id 无限堆积。
淘汰只针对「当前没人持有」的锁(lock.locked() 为假),避免把别人正在用的锁换掉。
"""
with _renewal_locks_guard:
lock = _renewal_locks.get(rental_id)
if lock is not None:
return lock
if len(_renewal_locks) >= _RUNTIME_DICT_MAX:
free = [k for k, v in _renewal_locks.items() if not v.locked()]
for key in free[:max(1, len(free) // 2)]:
_renewal_locks.pop(key, None)
lock = threading.Lock()
_renewal_locks[rental_id] = lock
return lock
def _park_areas_for_user(user_id: int) -> list:
"""用用户凭据取上游停车区多边形(GCJ02)。结果短缓存,避免续租链反复拉地图。"""
import park_area
cached = _PARK_AREA_CACHE.get(user_id)
now = _time.time()
if cached and now - cached[0] < _PARK_AREA_TTL:
return cached[1]
try:
result = request_with_user_auth(
user_id, "GET", "/project/map", params={"type": "1"}, _silent=True
)
except Exception as exc:
print(f"[自动还车] 读取停车区失败: {exc}")
return []
if not isinstance(result, dict) or result.get("rtn_code") not in (None, 0):
return []
areas = park_area.parse_park_areas(result.get("data") or {})
if areas:
_PARK_AREA_CACHE[user_id] = (now, areas)
return areas
def _align_to_park_area(user_id: int, latitude, longitude):
"""把自动还车的坐标对齐到停车区(入参/返回都是 GCJ02)。
返回 (lat, lng, moved, distance)。拿不到 parkeArea 时原样返回。
自动还车前**先**对齐一次,绝大多数情况一次就还成功,不必靠重试撞。
"""
import park_area
areas = _park_areas_for_user(user_id)
if not areas:
return latitude, longitude, False, 0.0
try:
resolved = park_area.resolve_return_coord(latitude, longitude, areas)
except Exception as exc:
print(f"[自动还车] 停车区判定异常: {exc}")
return latitude, longitude, False, 0.0
if resolved and resolved.get("moved"):
return (resolved["latitude"], resolved["longitude"], True,
float(resolved.get("distance") or 0.0))
return latitude, longitude, False, 0.0
def _is_credential_failure(result) -> bool:
"""上游已明确拒绝用户凭据:继续重试只会在每次部署后制造新的无效请求。"""
if not isinstance(result, dict):
return False
if result.get("token_invalid") or result.get("rtn_code") == 102001:
return True
message = str(result.get("message") or "")
return result.get("rtn_code") == 401 and "Token ID" in message
def _pause_for_invalid_credential(rental_id: int, user_id: int, result) -> dict:
"""落库暂停该用户的自动还车,等待保存新凭据后恢复。"""
newly_blocked = mark_user_credential_blocked(user_id)
message = (result or {}).get("message") or "微信凭据需要更新"
print(f"[自动还车] rental_id={rental_id} 用户凭据失效,"
f"新增暂停 {newly_blocked} 单;保存新凭据后自动恢复")
return {
"success": False, "skipped": True, "credential_blocked": True,
"attempted": True, "rtn_code": (result or {}).get("rtn_code", 102001),
"message": message,
}
def _auto_return_bike(rental_id: int, user_id: int, allow_renewal: bool = False):
"""自动还车(含重试:最多3次),返回明确的成败结果。
坐标链路(与手动还车同一套停车区规则):
1. 取车辆坐标(`/project/bicycle`,上游 = GCJ02,不要再转);
2. **发还车前**先用本地 parkeArea 多边形判定一次,不在停车区就先吸附到
最近的合法点 —— 原来直接发原始坐标,parkNoShow 时三次重试注定全失败;
3. 万一对齐后仍失败,第 2 次重试前再吸附一次(应对上游边界与本地不一致)。
"""
conn = get_db()
try:
cursor = conn.cursor()
cursor.execute("SELECT * FROM rentals WHERE id = ?", (rental_id,))
rental = cursor.fetchone()
finally:
# 这个连接只用来读这一行,读完立刻关:以前一直挂到函数末尾,
# 中间任何异常(上游超时、写库失败)都会把连接漏掉。
conn.close()
if not rental:
print(f"[自动还车] 记录不存在: rental_id={rental_id}")
return {"success": False, "rtn_code": 404, "message": "本地租车记录不存在"}
if rental["expired"]:
return {"success": True, "rtn_code": 0, "message": "订单已结束"}
if is_rental_credential_blocked(rental_id):
return {"success": False, "skipped": True, "credential_blocked": True,
"message": "微信凭据已失效,自动还车暂停;保存新凭据后自动恢复"}
bike_code = rental["bike_code"]
# 统一使用用户 token 查询车辆(与开锁/下单保持同一身份)
bike_result = request_with_user_auth(user_id, "POST", "/project/bicycle", data={"code": bike_code})
if _is_credential_failure(bike_result):
return _pause_for_invalid_credential(rental_id, user_id, bike_result)
latitude = bike_result.get("data", {}).get("latitude", 36.67) if bike_result.get("data") else 36.67
longitude = bike_result.get("data", {}).get("longitude", 116.98) if bike_result.get("data") else 116.98
# 上游要求真实订单号;老记录可能只有本地自增 id,则兜底用它
upstream_order_id = rental["order_id"] if rental["order_id"] else str(rental_id)
# 发还车前先对齐停车区:车辆坐标不在 parkeArea 内时直接换成最近的合法点,
# 否则 parkNoShow 会让三次重试全都打在同一个错坐标上。
latitude, longitude, aligned, aligned_m = _align_to_park_area(
user_id, latitude, longitude
)
if aligned:
print(f"[自动还车] 车辆坐标不在停车区,已对齐到最近停车区 "
f"({latitude:.6f}, {longitude:.6f}) [{aligned_m:.0f}m]")
return_result = None
last_error = None
snap_attempted = aligned # 已经对齐过的话,重试前不必再对齐一次
for attempt in range(1, 4):
try:
return_result = request_with_user_auth(
user_id, "POST", "/record/return",
data={"order_id": upstream_order_id, "longitude": longitude,
"latitude": latitude, "code": bike_code}
)
if _is_credential_failure(return_result):
return _pause_for_invalid_credential(rental_id, user_id, return_result)
if return_result.get("rtn_code") == 0:
print(f"[自动还车] 第{attempt}次调用成功")
break
else:
last_error = f"API返回非0: {return_result.get('message')}"
print(f"[自动还车] 第{attempt}次失败: {last_error}")
except Exception as e:
last_error = str(e)
print(f"[自动还车] 第{attempt}次异常: {last_error}")
# 首次失败:再对齐一次停车区(应对上游边界与本地多边形不一致)
if not snap_attempted and attempt < 3:
snap_attempted = True
new_lat, new_lng, moved, moved_m = _align_to_park_area(
user_id, latitude, longitude
)
if moved:
latitude, longitude = new_lat, new_lng
print(f"[自动还车] 已吸附到最近停车区 "
f"({latitude:.6f}, {longitude:.6f}) [{moved_m:.0f}m],准备重试")
if attempt < 3:
_time.sleep(5)
success = bool(return_result and return_result.get("rtn_code") == 0)
pay_result = {"success": False, "message": "未执行自动支付"}
if success:
try:
pay_result = _try_card_pay_auto(user_id, upstream_order_id, bike_code)
print(f"[自动还车] 月卡支付结果: {pay_result}")
except Exception as e:
pay_result = {"success": False, "message": f"自动支付异常: {e}"}
print(f"[自动还车] 月卡支付异常: {e}")
elif last_error:
print(f"[自动还车] 所有重试失败: {last_error}")
# 只有上游明确返回成功才结束本地订单。失败时保留 active,
# 让邮件按钮可重试,后台对账也能继续跟踪真实状态。
if success:
_mark_returned(rental_id, latitude, longitude)
# 续租会换新的 order_id;不清掉 60 秒的 /user/info 缓存的话,
# 前端在缓存窗口内点还车会拿到旧 order_id、被判「已结束」返回 rtn 0,
# 而车其实已经在第 2 轮计费。
try:
from routes.rental import _user_info_cache
_user_info_cache.pop(user_id, None)
except Exception:
pass
renewal_result = {"renewed": False}
if success:
_cancel_rental_timers(rental_id)
mark_return_tokens_used(rental_id)
if not allow_renewal:
# 邮件链接等手动还车:清掉后续自动重试状态,绝不能因为剩余轮次再开锁。
_clear_auto_return_state(rental_id)
try:
renewal_result = _maybe_renew_after_return(
dict(rental), user_id, pay_result, allow_renewal
)
except Exception as exc:
print(f"[自动续租] 处理下一轮异常: {exc}")
renewal_result = {"renewed": False, "message": f"自动续租处理异常: {exc}"}
status = "成功" if success else "失败"
print(f"[自动还车] rental_id={rental_id}, bike={bike_code}, {status}")
message = (return_result or {}).get("message") or last_error or (
"还车成功" if success else "自动还车失败"
)
if success and pay_result.get("message"):
message += f",{pay_result['message']}"
if renewal_result.get("renewed"):
message += f",{renewal_result['message']}"
elif renewal_result.get("blocked"):
message += f",{renewal_result['message']}"
return {
"attempted": True,
"success": success,
"rtn_code": return_result.get("rtn_code", 500) if return_result else 500,
"message": message,
"card_pay": pay_result,
"renewal": renewal_result,
}
def auto_return_bike(rental_id: int, user_id: int, allow_renewal: bool = False):
"""串行执行还车。默认按用户手动还车处理,不续租;
只有 0 点定时器与过期巡检显式传 allow_renewal=True 才允许进入下一轮。
跨进程租约放在这里(而不是只放在 _run_recovery):0 点 Timer、邮件按钮、
管理后台代还车都要经过本函数,多 worker 下同一单只能有一个进程去打
/record/return + 提交月卡。_renewal_lock 只是进程内的 threading.Lock。
"""
lease_name = f"rental-return:{rental_id}"
# None = 租约表不可用(老库/临时库),按单进程处理;False = 别的进程正在处理。
lease_result = None
try:
lease_result = acquire_lease(lease_name, 180)
except Exception as exc:
print(f"[自动还车] 租约获取失败(按单进程处理): {exc}")
if lease_result is False:
print(f"[自动还车] rental_id={rental_id} 另一进程正在处理该订单还车,本次跳过")
return {"success": False, "skipped": True,
"message": "另一进程正在处理该订单还车"}
# 同一线程重入(_run_recovery 外层已持有同名租约):内层只续期,不释放,
# 由最外层统一释放,避免内层跑完就把外层还在用的租约删掉。
_lease_enter(lease_name)
try:
with _renewal_lock(rental_id):
return _auto_return_bike(rental_id, user_id, allow_renewal)
finally:
if _lease_exit(lease_name) == 0:
try:
release_lease(lease_name)
except Exception as exc:
print(f"[自动还车] 释放租约失败(等 TTL 过期即可): {exc}")
# 线程内租约重入计数:同名租约在本线程嵌套持有时,只有最外层负责 release。
_lease_depth = threading.local()
def _lease_enter(name: str) -> int:
names = getattr(_lease_depth, "names", None)
if names is None:
names = {}
_lease_depth.names = names
names[name] = names.get(name, 0) + 1
return names[name]
def _lease_exit(name: str) -> int:
"""退出一层持有,返回剩余层数(0 = 本线程已不再持有,调用方应 release)。"""
names = getattr(_lease_depth, "names", {})
left = names.get(name, 0) - 1
if left > 0:
names[name] = left
else:
names.pop(name, None)
left = 0
return left
def _cancel_rental_timers(rental_id: int) -> int:
"""取消某次租车的所有计时器,并返回该单的新一代代号。
用 pop 一次取出再取消:原来是 `in` 判断 + 取列表 + `del`,
中间被别的线程删掉会抛 KeyError;`del` 之后另一线程刚 append 的 timer
也会随之消失(脱管的计时器永远取消不掉,导致重复提醒/重复还车)。
代号自增与 pop 在同一个临界区完成:上一代还没注册完的 `_schedule_reminder`
会发现代号已变而放弃注册(BUG-12:并发重排不再留下两套提醒)。
"""
with _timers_lock:
timers = _active_timers.pop(rental_id, [])
gen = _timer_gen.get(rental_id, 0) + 1
_timer_gen[rental_id] = gen
for t in timers:
try:
t.cancel()
except Exception:
pass
return gen
def _timer_generation(rental_id: int) -> int:
"""当前代号(注册 Timer 时用来判断自己是否已经过期)。"""
with _timers_lock:
return _timer_gen.get(rental_id, 0)
# 只有这些来源才代表「真的有上游骑行订单」,才能走自动还车。
# reminder 是前端自己开的计时提醒,没有上游订单;把本地自增 id 当订单号发出去
# 必然 204010,白打三次上游还要 sleep 15 秒。
AUTO_RETURN_SOURCES = ("unlock", "sync", "shared", "subscribe")
# 巡检补还车的节流:彻底失败的单不能每分钟重打上游
_recover_last_at: dict = {}
RECOVER_INTERVAL_SECONDS = 300 # 5 分钟
def _prune_runtime_state(force: bool = False) -> None:
"""清理进程内状态表(_recover_last_at / 退避表 / 代号表)。
这些表以 rental_id 为 key,正常情况下条目数≈现存订单数;但"永远还不上"的单、
客户端传上来的脏 id(BUG-11)会让它们只增不减。这里按 TTL + 容量上限收缩,
每 5 分钟最多扫一次(force=True 可强制,测试用)。
"""
now = _time.time()
if not force and now - _last_prune_at[0] < _PRUNE_INTERVAL_SECONDS:
return
_last_prune_at[0] = now
stale_before = now - _RECOVER_STATE_TTL
for table in (_recover_last_at, _auto_return_backoff_until, _auto_return_first_fail_at):
for key in [k for k, ts in list(table.items())
if not isinstance(ts, (int, float)) or ts < stale_before]:
table.pop(key, None)
# 计数/档位表没有时间戳:只按"这个单还有没有活动状态"来收缩
live = set(_active_timers) | set(_recover_last_at) | set(_auto_return_backoff_until)
for table in (_auto_return_retries, _auto_return_alert_levels):
if len(table) <= _RUNTIME_DICT_MAX:
continue
for key in [k for k in list(table) if k not in live]:
table.pop(key, None)
if len(_timer_gen) > _RUNTIME_DICT_MAX:
with _timers_lock:
for key in [k for k in list(_timer_gen) if k not in _active_timers]:
_timer_gen.pop(key, None)
def _recover_throttled(rental_id: int) -> bool:
"""这次补还车是否要跳过(True=跳过)。
两种节流来源:
1. 基础间隔 5 分钟(临时故障时不要每分钟打上游);
2. 退避表 `_auto_return_backoff_until` —— 进入退避阶段后,间隔由失败次数与
已耗时决定(30 分钟内恒 60s,之后 60/120/300s 封顶),此时以退避表为准,
不再叠加基础间隔,否则 60 秒的退避会被 5 分钟基础间隔吃掉。
"""
if is_rental_credential_blocked(rental_id):
return True
now = _time.time()
due = _auto_return_backoff_until.get(rental_id)
if due is not None:
if now < due:
return True
_auto_return_backoff_until.pop(rental_id, None)
_recover_last_at[rental_id] = now
_prune_runtime_state()
return False
last = _recover_last_at.get(rental_id, 0)
if now - last < RECOVER_INTERVAL_SECONDS:
return True
_recover_last_at[rental_id] = now
_prune_runtime_state()
return False
def _upstream_ride_active(user_id: int, order_id):
"""上游这张单还在骑吗?True=在骑 / False=已结束 / None=查不到(别下结论)。
用户很可能直接在小程序里点了还车 —— 那种情况下本地还挂着 expired=0,
但我们**不能**再发一次 /record/return(上游会报订单不存在,白白制造错误)。
所以补还车前先看上游状态,上游说结束了就只做本地收尾。
"""
if not user_id or not order_id:
return None
try:
info = request_with_user_auth(user_id, "GET", "/user/info", _silent=True)
except Exception as exc:
print(f"[自动还车] 查询上游订单状态失败: {exc}")
return None
if not isinstance(info, dict) or info.get("rtn_code") != 0:
return None
non_deal = (info.get("data") or {}).get("nonDealOrder") or {}
if not non_deal or not non_deal.get("order_id"):
return False # 上游没有未完成订单 → 已经结束了
if str(non_deal.get("order_id")) != str(order_id):
return False # 上游挂的是另一张单 → 这张已经结束
return str(non_deal.get("status")) == "2" # 2=骑行中
def _run_recovery(rental_id: int, user_id: int, order_id=None):
"""巡检/重启的补还车入口:成功后清掉节流记录,别让进程里留失败痕迹。
先问上游状态:上游说这单已结束(用户在小程序里还了),就只做本地收尾,
不再打 /record/return。
"""
# 跨进程独占:多 worker 下同一单只让一个进程去还,避免两次 /record/return +
# 两次月卡提交(_renewal_lock 只是进程内的 threading.Lock)。
#
# 租约本身由 auto_return_bike 持有并在 finally 释放(租约按 owner 判定,
# 同一进程再次 acquire 只是续期,不会互相拦)。这里保留一层:巡检要先问上游
# 状态、再决定「本地收尾」还是「补还车」,这段时间也不该有第二个进程插进来。
# 两层同名租约在本线程内是重入关系(见 _lease_enter/_lease_exit):
# 内层只续期不释放,真正的 release 只发生在这一层返回时,且只发生一次。
#
# 租约必须**用完就释放**:原来只 acquire 不 release,一次还车就把它占满 TTL,
# 之后 300 秒内其它进程(重启后的新进程、另一个 worker、邮件按钮重试)
# 全被判「另一个进程正在处理这一单」—— 其实根本没有进程在跑,是残留租约。
lease_name = f"rental-return:{rental_id}"
lease_acquired = False
try:
# 一次还车实测最长几十秒(含 3 次重试 + 续租下单);180 秒足够覆盖,
# 异常退出也不会长期占位。
lease_acquired = acquire_lease(lease_name, 180) is not False
except Exception as exc:
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": "另一个进程正在处理这一单"}
_lease_enter(lease_name)
try:
return _run_recovery_locked(rental_id, user_id, order_id)
finally:
# 只有最外层(本层)真正释放;内层 auto_return_bike 是重入,只续期不释放。
if _lease_exit(lease_name) == 0:
try:
release_lease(lease_name)
except Exception as exc:
print(f"[自动还车] 释放租约失败(等 TTL 过期即可): {exc}")
def _run_recovery_locked(rental_id: int, user_id: int, order_id=None):
"""`_run_recovery` 拿到跨进程租约之后的本体(调用方负责释放租约)。"""
active = _upstream_ride_active(user_id, order_id) if order_id else None
if active is False:
_close_rental_locally(rental_id, "上游订单已结束(用户已在小程序还车)")
_clear_auto_return_state(rental_id)
return {"success": True, "skipped": True,
"message": "上游订单已结束,仅做本地收尾"}
try:
result = auto_return_bike(rental_id, user_id, allow_renewal=True) or {}
if result.get("success"):
_clear_auto_return_state(rental_id)
elif not result.get("skipped"):
# 失败:只有进入退避阶段(快保次数已经用完)才由这里推进下一次到点时间,
# 快保阶段由 Timer 链自己负责,避免两套重试互相抢节奏。
# 返回 0 表示「已到绝对上限、彻底停手」,此时不再留 backoff 到点时间。
_advance_auto_return_backoff(
rental_id, str(result.get("message") or ""))
return result
except Exception as exc:
print(f"[自动还车] 补还车异常 rental_id={rental_id}: {exc}")
_advance_auto_return_backoff(rental_id, 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
if not _background_enabled:
print("[计时系统] 后台自动还车总开关已关闭,本轮兜底扫描不补还车")
return 0
for rental in rows:
if not _should_auto_return(rental):
# reminder 是纯本地计时提醒,没有上游订单:上游还不了,但也不能
# 一直挂着 expired=0,否则用户页面横幅永远显示「用车中」。
if str(rental.get("source") or "") == "reminder":
_close_rental_locally(rental["id"], "本地提醒单到期")
closed_local += 1
continue
if _recover_throttled(rental["id"]):
continue
threading.Thread(target=_run_recovery,
args=(rental["id"], rental.get("user_id"), rental.get("order_id")),
daemon=True).start()
started += 1
if started:
print(f"[计时系统] 巡检兜底:{started} 单超期未还,已排队补还车")
if closed_local:
print(f"[计时系统] 巡检兜底:{closed_local} 条本地提醒单超期,已就地关闭")
return started
def _close_rental_locally(rental_id: int, reason: str = ""):
"""只做本地收尾:标记结束 + 实际还车时间 + 取消计时器,**不碰上游**。
适用于两种情况:
1. reminder 单(本来就没有上游订单);
2. 用户已经在小程序里还车了(上游查不到这张单,再发 /record/return 只会 204010)。
"""
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
print(f"[计时系统] 本地收尾 rental_id={rental_id}"
+ (f":{reason}" if reason else ""))
def _should_auto_return(rental) -> bool:
"""这张单能不能走上游自动还车(restore / 巡检共用同一判断)。"""
if not rental:
return False
if str(rental.get("source") or "") not in AUTO_RETURN_SOURCES:
return False
if not rental.get("order_id"):
return False
# 用户关了「自动还车」:所有恢复路径(巡检 / 兜底扫描 / 重启恢复)一律不动真实订单,
# 只保留提醒;否则用户关掉的开关会被后台线程悄悄绕过。
try:
policy_user_id = rental.get("rider_user_id") or rental.get("user_id")
policy = get_user_rental_settings(policy_user_id) if policy_user_id else {}
except Exception as exc:
print(f"[自动还车] 读取自动还车设置失败 rental_id={rental.get('id')}: {exc}")
policy = {}
if policy and not policy.get("auto_return_enabled", True):
return False
return True
def _mark_notified(rental_id: int, reminder_type: str, conn=None, cursor=None):
"""把 notified_X 置位(缺列就跳过)。
调用方已经拿着连接/游标时直接复用,不再为一次 UPDATE 新开连接。
"""
col = f"notified_{reminder_type}"
if cursor is not None and conn is not None:
try:
cols = [d[0] for d in cursor.description]
if col in cols:
conn.execute(f"UPDATE rentals SET {col} = 1 WHERE id = ?", (rental_id,))
conn.commit()
except Exception as exc:
print(f"[提醒] 置位 {col} 失败: {exc}")
return
own_conn = get_db()
try:
cur = own_conn.execute("SELECT * FROM rentals WHERE id = ?", (rental_id,))
if col in [d[0] for d in cur.description]:
own_conn.execute(f"UPDATE rentals SET {col} = 1 WHERE id = ?", (rental_id,))
own_conn.commit()
except Exception as exc:
print(f"[提醒] 置位 {col} 失败: {exc}")
finally:
own_conn.close()
# ===== 0 分钟自动还车失败后的重试策略(BUG-07)=====
# 用户口径:只要求"尽可能让用户少损失、尽可能在预定时间内还车"——所以**不放弃**:
# 1) 快保阶段:前 AUTO_RETURN_MAX_RETRIES 次每 30 秒一次(进程内 Timer,尽量准点还掉);
# 2) 退避阶段:之后继续重试,但间隔 1m → 2m → 5m → 10m 封顶,由巡检按
# `_auto_return_backoff_until` 到点放行(不再长期挂 Timer,也不每分钟打上游);
# 3) 只有上游确认已还(auto_return_bike 成功 / 上游说订单已结束)才落 expired 与 returned_at;
# 4) 告警只在"进入退避"以及每升一档时各发一封,不重复轰炸。
_auto_return_retries: dict = {} # rental_id -> 已失败次数
_auto_return_alert_levels: dict = {} # rental_id -> 已发过告警的档位
_auto_return_backoff_until: dict = {} # rental_id -> 下一次允许重试的 epoch 秒
_auto_return_first_fail_at: dict = {} # rental_id -> 首次自动还车失败时刻
# 绝对上限:再"不放弃"也不能对着一个永久失败的单无限重试 —— 每 10 分钟打一次上游、
# 刷一条日志,线上排查时全是噪音。到点发一封告警后停手,等人工或页面重试兜底。
AUTO_RETURN_GIVE_UP_SECONDS = 6 * 3600
# 到点还车失败的密集重试曲线(秒)。用户口径:不能超过 1 分钟的时间窗口才还上,
# 所以前 5 分钟按 10~60 秒递进,之后**长期保持 60 秒**,只有拖了半小时以上才允许
# 拉长到 2/5 分钟(避免对同一张单无限高频打上游)。
AUTO_RETURN_RETRY_DELAYS = (10, 10, 15, 15, 20, 20, 30, 30, 30, 45, 60)
AUTO_RETURN_DENSE_SECONDS = 30 * 60 # 这个时间窗内重试间隔一律 ≤ 60 秒
AUTO_RETURN_BACKOFF_DELAYS = (60, 120, 300) # 超过窗口后才逐步拉长,末位封顶 5 分钟
# 兼容旧名字(外部/测试可能引用)
AUTO_RETURN_RETRY_DELAY = AUTO_RETURN_RETRY_DELAYS[0]
AUTO_RETURN_MAX_RETRIES = len(AUTO_RETURN_RETRY_DELAYS)
def _auto_return_retry_delay(failures: int, elapsed_seconds=None) -> int:
"""第 failures+1 次重试前要等多少秒。
- 前 len(AUTO_RETURN_RETRY_DELAYS) 次:按 10/10/15/15/20/20/30/30/30/45/60 递进;
- 之后:只要从首次失败算起还没超过 AUTO_RETURN_DENSE_SECONDS,就一直 60 秒;
- 超过窗口(默认 30 分钟)才允许 2/5 分钟,避免长期高频打上游。
elapsed_seconds 传 None 时按"窗口内"处理(保守:宁可多试一次)。
"""
n = _coerce_int(failures, 0)
if n < len(AUTO_RETURN_RETRY_DELAYS):
return AUTO_RETURN_RETRY_DELAYS[n]
elapsed = None
if elapsed_seconds is not None:
try:
elapsed = float(elapsed_seconds)
except (TypeError, ValueError):
elapsed = None
if elapsed is None or elapsed <= AUTO_RETURN_DENSE_SECONDS:
return AUTO_RETURN_BACKOFF_DELAYS[0] # 60 秒
over = n - len(AUTO_RETURN_RETRY_DELAYS)
idx = min(over, len(AUTO_RETURN_BACKOFF_DELAYS) - 1)
return AUTO_RETURN_BACKOFF_DELAYS[idx]
def _auto_return_alert_level(failures: int) -> int:
"""告警档位:快保阶段为 0(不打扰),进入退避后每换一个间隔档位 +1。"""
n = _coerce_int(failures, 0)
if n < AUTO_RETURN_MAX_RETRIES:
return 0
return 1 + min(n - AUTO_RETURN_MAX_RETRIES, len(AUTO_RETURN_BACKOFF_DELAYS) - 1)
def _rental_already_ended(rental_id: int) -> bool:
"""重新读一次这一行:已经 expired=1(或行已不存在)就视为已结束。"""
try:
conn = get_db()
try:
row = conn.execute("SELECT expired FROM rentals WHERE id = ?", (rental_id,)).fetchone()
finally:
conn.close()
except Exception as exc:
print(f"[自动还车] 复查 rental_id={rental_id} 状态失败: {exc}")
return False
if row is None:
return True
try:
return bool(row["expired"])
except (TypeError, IndexError):
return bool(row[0])
def _rental_contact(rental_id: int):
"""取告警/日志要用的车牌与收件邮箱(读不到就给空串,不影响重试)。"""
try:
conn = get_db()
try:
row = conn.execute(
"SELECT bike_code, email FROM rentals WHERE id = ?", (rental_id,)).fetchone()
finally:
conn.close()
if not row:
return "", ""
return (row["bike_code"] or ""), (row["email"] or "")
except Exception:
return "", ""
def _clear_auto_return_state(rental_id: int, *, keep_backoff: bool = False) -> None:
"""订单已经收尾(还车成功 / 上游确认结束):把这条单的重试状态全部清干净。"""
_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)
def _advance_auto_return_backoff(rental_id: int, message: str = "") -> int:
"""退避阶段记一次失败:推进到点时间、按档位升级告警。返回下一次等待秒数。
只有在快保次数已经用完(n >= AUTO_RETURN_MAX_RETRIES)时才生效 ——
否则快保阶段由 Timer 链自己推进,两套机制同时改计数会互相抢节奏。
"""
if is_rental_credential_blocked(rental_id):
_clear_auto_return_state(rental_id)
return 0
n = _auto_return_retries.get(rental_id, 0)
if n < len(AUTO_RETURN_RETRY_DELAYS):
return 0
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] = 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
bike_code, _email = _rental_contact(rental_id)
_alert_auto_return_exhausted(rental_id, bike_code, message, delay)
print(f"[自动还车] rental_id={rental_id} 第 {n + 1} 次失败,"
f"{delay}s 后由巡检再试(退避档位 {level})")
_prune_runtime_state()
return delay
def _notify_auto_return_recovered(rental_id: int):
"""重试若干次后终于还车成功:再发一封「已还上」,别让用户去点邮件里的旧按钮。"""
try:
from email_utils import send_email
conn = get_db()
row = conn.execute(
"SELECT bike_code, email FROM rentals WHERE id = ?", (rental_id,)).fetchone()
conn.close()
if not row:
return
to_email = (row["email"] or "").strip()
if not to_email:
return
titled = f"自动还车已成功(#{row['bike_code']})"
body = (f"上次自动还车失败后系统已重试并成功,车辆 #{row['bike_code']} 已还车,"
f"这单不会再计费。\n\n如果你刚才点了邮件里的「还车」按钮,"
f"看到「订单已结束」是正常的 —— 不用再操作。")
send_email(to_email, f"【小白超人】{titled}", body,
f"<p>{body.replace(chr(10), '<br/>')}</p>")
print(f"[自动还车] rental_id={rental_id} 重试成功,已发最终成功通知")
except Exception as exc:
print(f"[自动还车] 重试成功通知发送失败: {exc}")
def _alert_auto_return_exhausted(rental_id: int, bike_code: str, message: str = "",
retry_delay: int = None):
"""自动还车进入退避/升级重试:给管理员发告警(同一档位只发一封,由调用方去重)。
注意口径:不是"放弃",系统仍在按退避间隔自动重试(1m→2m→5m→10m 封顶)。
"""
try:
from alerts import get_alert_emails
from email_utils import send_email
recipients = get_alert_emails()
if not recipients:
print(f"[自动还车] rental_id={rental_id} 需要人工关注,但没有配置告警邮箱")
return
delay = max(30, _coerce_int(retry_delay, AUTO_RETURN_BACKOFF_DELAYS[0]))
title = f"自动还车仍失败,系统仍在重试(#{bike_code})"
body = (f"rental_id={rental_id} 车辆 #{bike_code} 自动还车已失败多次,"
f"系统不会放弃,正按退避间隔继续自动重试(当前约每 "
f"{max(1, delay // 60)} 分钟一次)。\n"
f"最后一次错误:{message or '(无)'}\n\n"
f"这单在上游可能仍在计费。建议:① 等系统自动还上;"
f"② 到管理后台「代还车」手动处理。")
for to in recipients:
send_email(to, f"【小白超人·告警】{title}", body,
f"<p>{body.replace(chr(10), '<br/>')}</p>")
print(f"[自动还车] rental_id={rental_id} 已发告警给 {len(recipients)} 个邮箱")
except Exception as exc:
print(f"[自动还车] 重试告警发送失败: {exc}")
def _schedule_auto_return_retry(rental_id: int, email: str, bike_code: str, user_id,
message: str = ""):
"""自动还车失败后推进重试:快保阶段挂 30s Timer,之后转入退避由巡检驱动。
`notified_0` 保持 0,让各处调度(巡检 / 兜底扫描 / 页面横幅重试)还能再次触发。
"""
if is_rental_credential_blocked(rental_id):
_clear_auto_return_state(rental_id)
return
now_ts = _time.time()
first_fail = _auto_return_first_fail_at.setdefault(rental_id, now_ts)
if now_ts - first_fail > AUTO_RETURN_GIVE_UP_SECONDS:
# 超过 6 小时还还不上:停止自动重试(只告警一次),避免无限刷上游和日志
if _auto_return_alert_levels.get(rental_id, 0) < 99:
_auto_return_alert_levels[rental_id] = 99
_alert_auto_return_exhausted(
rental_id, bike_code or _rental_contact(rental_id)[0],
(message or "") + f"(已重试超过 {AUTO_RETURN_GIVE_UP_SECONDS // 3600} 小时,自动重试已停止)",
0)
print(f"[自动还车] rental_id={rental_id} 超过 "
f"{AUTO_RETURN_GIVE_UP_SECONDS // 3600} 小时仍未成功,停止自动重试")
_auto_return_backoff_until.pop(rental_id, None)
_prune_runtime_state()
return
n = _auto_return_retries.get(rental_id, 0)
delay = _auto_return_retry_delay(n, now_ts - first_fail)
_auto_return_retries[rental_id] = n + 1
level = _auto_return_alert_level(n + 1)
if level > _auto_return_alert_levels.get(rental_id, 0):
_auto_return_alert_levels[rental_id] = level
_alert_auto_return_exhausted(rental_id, bike_code or _rental_contact(rental_id)[0],
message, delay)
if n < len(AUTO_RETURN_RETRY_DELAYS):
# 快保阶段:进程内 Timer 精确重试,尽量在原定时刻附近把车还掉
print(f"[自动还车] rental_id={rental_id} 第 {n + 1} 次重试将在 {delay}s 后执行")
_schedule_reminder(rental_id, delay, "0", email, bike_code,
user_id, send_notification=False,
auto_return_enabled=True, auto_return_configured=True,
gen=_timer_generation(rental_id))
else:
# 退避阶段:不再长期挂 Timer(重启/多进程都不丢),交给巡检按到点时间重试
_auto_return_backoff_until[rental_id] = _time.time() + delay
print(f"[自动还车] rental_id={rental_id} 进入退避重试,下一次约 {delay}s 后由巡检触发")
_prune_runtime_state()
def _schedule_reminder(rental_id: int, delay_seconds: int, reminder_type: str,
email: str, bike_code: str, user_id: int = None,
send_notification: bool = True,
auto_return_enabled: bool = True,
auto_return_configured: bool = True,
gen: int = None):
"""调度单个提醒。
`gen` 是该单在 `start_rental_timer` 里取到的代号:注册时若代号已变(说明这一代
已被取消/重排),直接丢弃,避免同一单留下两套提醒。传 None 表示不做代号校验
(测试与一次性调度用)。
"""
def fire():
conn = get_db()
cursor = conn.cursor()
cursor.execute("SELECT * FROM rentals WHERE id = ?", (rental_id,))
rental = cursor.fetchone()
if not rental or rental["expired"] == 1:
conn.close()
return
col = f"notified_{reminder_type}"
has_col = col in [d[0] for d in cursor.description]
if not (has_col and rental[col] == 0):
conn.close()
return
# 5/3/2/1 分钟这类纯提醒:先置位再发,发失败也不重发
if reminder_type != "0":
_mark_notified(rental_id, reminder_type, conn=conn, cursor=cursor)
conn.close()
if send_notification:
send_rental_notification(rental_id, reminder_type, None)
return
# 0 分钟:先把车还了,成功了才置位。
# 原来先置位再还车,上游三次重试一失败就再也不会重试,订单在上游继续计费。
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:
if not _background_enabled:
print(f"[自动还车] rental_id={rental_id} 后台自动还车总开关已关闭,跳过 0 分钟自动还车")
return
try:
return_result = auto_return_bike(rental_id, user_id, allow_renewal=True)
except Exception as e:
print(f"[自动还车] 失败: {e}")
return_result = {"attempted": True, "success": False, "message": str(e)}
elif not auto_return_configured:
return_result = {"attempted": False, "success": False,
"message": "用户未开启自动还车"}
else:
return_result = {"attempted": False, "success": False,
"message": "该提醒未绑定微信订单,无法自动还车"}
success = bool(return_result and return_result.get("success"))
had_retries = _auto_return_retries.get(rental_id, 0)
if success:
_clear_auto_return_state(rental_id)
_mark_notified(rental_id, "0")
if had_retries:
# 之前发过「自动还车失败」,这次终于还上了,必须再发一封收尾,
# 否则用户会去点旧邮件里的还车按钮(那时订单已结束)
_notify_auto_return_recovered(rental_id)
elif auto_return_enabled and user_id and _rental_already_ended(rental_id):
# 失败期间这张单已经被别处结束(用户在小程序/网页还了、巡检补上了、
# 或续租刚换了新单):不再重试、不发失败邮件,只做本地收尾。
print(f"[自动还车] rental_id={rental_id} 本次还车失败,但该单已结束,不再重试")
_clear_auto_return_state(rental_id)
_mark_notified(rental_id, "0")
return
elif auto_return_enabled and user_id:
# 失败:不置位。快保阶段短周期重试,之后转退避(不放弃,也不高频打上游)
_schedule_auto_return_retry(
rental_id, email, bike_code, user_id,
str((return_result or {}).get("message") or ""))
else:
_mark_notified(rental_id, "0") # 未绑定/未开启:一次性事件,直接置位
if send_notification:
send_rental_notification(rental_id, reminder_type, return_result)
timer = threading.Timer(delay_seconds, fire)
timer.daemon = True
with _timers_lock:
if isinstance(gen, int) and _timer_gen.get(rental_id, 0) != gen:
# 这一代已经被取消/取代(并发重排或还车),注册即作废,避免残留重复提醒
return None
# 顺手丢掉已经跑完的死 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
def start_rental_timer(rental_id: int, email: str, bike_code: str,
duration_minutes: int, user_id: int = None):
"""按订单双方的偏好启动提醒,并按实际骑行者偏好决定是否自动还车。
幂等:同一个 rental_id 重复调用只会留下一套 Timer。取消上一代与登记新代号在
同一个临界区里完成(BUG-12),上一代还没注册完的提醒会被代号校验丢弃。
"""
_cancel_rental_timers(rental_id) # pop 上一代 Timer + 自增代号
with _timers_lock:
gen = _timer_gen.get(rental_id, 0)
_active_timers[rental_id] = []
conn = get_db()
row = conn.execute("SELECT * FROM rentals WHERE id = ?", (rental_id,)).fetchone()
conn.close()
rental = dict(row) if row else {}
owner_user_id = rental.get("user_id") or user_id
rider_user_id = rental.get("rider_user_id") or owner_user_id
recipient_ids = {uid for uid in (owner_user_id, rider_user_id) if uid}
settings_by_user = {uid: get_user_rental_settings(uid) for uid in recipient_ids}
policy_settings = settings_by_user.get(rider_user_id) or get_user_rental_settings(rider_user_id)
reminders = set()
for settings in settings_by_user.values():
if settings["reminder_enabled"]:
reminders.update(settings["reminder_minutes"])
can_auto_return = bool(policy_settings["auto_return_enabled"] and rental.get("order_id"))
schedule_points = set(reminders)
if can_auto_return:
schedule_points.add(0)
remaining = duration_minutes * 60
for mins in sorted(schedule_points, reverse=True):
delay = remaining - (mins * 60)
if delay >= 0:
_schedule_reminder(
rental_id, delay, str(mins), email, bike_code, owner_user_id,
# 0 分钟且会自动还车:无论是否勾了「0」提醒都要发结果邮件
# (还车成功/失败都关系到是否扣钱);其余点按用户提醒偏好。
send_notification=(mins in reminders) or (mins == 0 and can_auto_return),
auto_return_enabled=can_auto_return if mins == 0 else False,
auto_return_configured=policy_settings["auto_return_enabled"],
gen=gen,
)
def reschedule_user_rental_timers(user_id: int, apply_duration: bool = False):
"""立即应用用户设置并重排相关进行中订单。
提醒偏好会影响用户作为车主或骑行人的所有相关订单;到期时长属于
实际骑行人策略,只更新该用户本人正在骑行的订单。新到期时间始终按
``start_time + rental_duration_minutes`` 计算,避免在每次保存时重复续时。
"""
conn = get_db()
rows = conn.execute("""
SELECT * FROM rentals
WHERE expired = 0 AND (user_id = ? OR rider_user_id = ?)
""", (user_id, user_id)).fetchall()
if apply_duration:
duration = get_user_rental_settings(user_id)["rental_duration_minutes"]
for row in rows:
rental = dict(row)
policy_user_id = rental.get("rider_user_id") or rental.get("user_id")
if policy_user_id != user_id or not rental.get("start_time"):
continue
try:
start_time = dt.datetime.strptime(
rental["start_time"], "%Y-%m-%d %H:%M:%S"
)
except (TypeError, ValueError):
print(f"[计时系统] 无法解析开始时间,跳过实时改期: rental_id={rental['id']}")
continue
new_end = start_time + dt.timedelta(minutes=duration)
conn.execute(
"UPDATE rentals SET end_time = ?, duration = ? WHERE id = ?",
(new_end.strftime("%Y-%m-%d %H:%M:%S"), duration, rental["id"]),
)
conn.commit()
rows = conn.execute("""
SELECT * FROM rentals
WHERE expired = 0 AND (user_id = ? OR rider_user_id = ?)
""", (user_id, user_id)).fetchall()
conn.close()
count = 0
for row in rows:
rental = dict(row)
remaining = _get_remaining_seconds(rental)
if remaining <= 0 and _rental_already_ended(rental["id"]):
# 拿着的是循环前的快照:这一行在改期期间已被还掉(网页/巡检/续租换单),
# 再按 0 分钟立即触发会对一张已结束的单补还车/发失败邮件。
print(f"[计时系统] rental_id={rental['id']} 已结束,跳过到期立即触发")
continue
# remaining=0 时仍需重排:缩短到已经到期应立即触发 0 分钟策略。
start_rental_timer(
rental["id"], rental.get("email", ""), rental.get("bike_code", ""),
remaining / 60, rental.get("user_id"),
)
count += 1
return count
def restore_active_timers():
"""启动时恢复计时器;**重启前就已越过到期时间**的单子立刻补一次自动还车。
以前这里只捞 `end_time > now`,服务重启时刚好跨过 19 分钟的那一单
既不会恢复计时器、也不会补还车,于是永久失去「自动还车」,
月卡还会按超时继续扣钱。现在把「已过期但没有 expired」的行单独捡出来补还。
"""
conn = get_db()
cursor = conn.cursor()
cursor.execute("SELECT * FROM rentals WHERE expired = 0")
active_rows = [dict(r) for r in cursor.fetchall()]
conn.close()
restored = 0
overdue = []
skipped = 0
for rental in active_rows:
remaining = _get_remaining_seconds(rental)
if remaining > 0:
start_rental_timer(rental["id"], rental["email"], rental["bike_code"],
remaining / 60, rental["user_id"])
restored += 1
elif _should_auto_return(rental):
overdue.append(rental)
else:
# reminder 之类没有真实上游订单的单子:不要拿本地 id 去猜订单号
skipped += 1
print(f"[计时系统] 已恢复 {restored} 个活跃计时器")
if skipped:
print(f"[计时系统] {skipped} 个过期单没有上游订单(reminder 等),跳过补还车")
# 补还车放到后台线程,别把启动流程卡住
for rental in overdue:
print(f"[计时系统] rental_id={rental['id']} 在重启前已过期,补一次自动还车")
threading.Thread(target=_recover_overdue_rental, args=(rental,),
daemon=True).start()
def _recover_overdue_rental(rental: dict):
"""重启补还车:失败就交给巡检线程与告警,不在这里死磕。"""
rental_id = rental.get("id")
user_id = rental.get("user_id")
if not _should_auto_return(rental):
# 没有真实上游订单(reminder / 老记录),补还车必然 204010,别白打三次上游
print(f"[计时系统] rental_id={rental_id} 没有上游订单号,跳过补还车")
return
try:
_time.sleep(3) # 等调度线程和上游会话就绪
if not user_id:
print(f"[计时系统] rental_id={rental_id} 没有 user_id,跳过补还车")
return
result = _run_recovery(rental_id, user_id, rental.get("order_id"))
print(f"[计时系统] 补还车结果 rental_id={rental_id}: {result.get('message')}")
except Exception as exc:
print(f"[计时系统] 补还车异常 rental_id={rental_id}: {exc}")
# ========== 用户订单检测系统 ==========
def start_user_order_checker(user_id: int):
"""为指定用户启动订单检测守护线程"""
with _checker_lock:
if user_id in _order_checker_threads and _order_checker_threads[user_id].is_alive():
return
stop_event = threading.Event()
_order_checker_stop[user_id] = stop_event
t = threading.Thread(
target=_user_order_checker_loop,
args=(user_id, stop_event), daemon=True,
name=f"order-checker-{user_id}"
)
t.start()
_order_checker_threads[user_id] = t
print(f"[订单检测] 为用户 {user_id} 启动检测线程")
def stop_user_order_checker(user_id: int):
"""停止指定用户的订单检测线程"""
with _checker_lock:
if user_id in _order_checker_stop:
_order_checker_stop[user_id].set()
del _order_checker_stop[user_id]
if user_id in _order_checker_threads:
del _order_checker_threads[user_id]
print(f"[订单检测] 已停止用户 {user_id} 的检测线程")
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:
print(f"[订单检测] 用户 {user_id} 检测异常: {e}")
stop_event.wait(ORDER_CHECK_INTERVAL)
def _check_user_order(user_id: int):
"""检查单个用户的微信订单状态并同步到本地"""
import datetime as dt
token_id, access_token = get_user_auth(user_id)
if not token_id:
print(f"[订单检测] 用户 {user_id} 无凭据,停止检测")
stop_user_order_checker(user_id)
return {"ok": False, "active": None, "message": "用户未配置微信凭据"}
conn = get_db()
cursor = conn.cursor()
cursor.execute("SELECT email FROM users WHERE id = ?", (user_id,))
row = cursor.fetchone()
if not row:
conn.close()
stop_user_order_checker(user_id)
return {"ok": False, "active": None, "message": "用户不存在"}
email = row["email"]
conn.close()
info = request_with_user_auth(user_id, "GET", "/user/info", _silent=True)
if info.get("rtn_code") != 0:
if info.get("rtn_code") == 102001 or info.get("token_invalid"):
# token_id 已被上游判定失效(凭据过期/被上游拒绝):
# 停止轮询避免无效请求;用户在个人中心/管理端更新凭据时会自动重启线程
print(f"[订单检测] 用户 {user_id} 凭据已失效,停止检测线程,等待更新凭据")
stop_user_order_checker(user_id)
return {"ok": False, "active": None,
"rtn_code": info.get("rtn_code", 500),
"message": info.get("message", "获取微信订单状态失败")}
non_deal = info.get("data", {}).get("nonDealOrder")
if not non_deal or not non_deal.get("order_id"):
_finish_active_wechat_rentals(user_id, "微信端已无未完成订单")
return {"ok": True, "active": False}
order_id = str(non_deal.get("order_id"))
order_status = non_deal.get("status") # 1=未支付, 2=进行中
if str(order_status) == "2":
# 用户可能先在官方小程序还了 A,又在同步间隙从官方小程序开了 B。
# 上游只保留当前进行中的 B:其它本地活跃单必须按「A 已在小程序还车」
# 收尾,绝不能留两条骑行计时,也不能因为 A 的剩余轮次再自动开锁。
_finish_active_wechat_rentals(
user_id, f"上游已切换到订单 {order_id},其它订单已在小程序结束",
keep_order_id=order_id,
)
if str(order_status) != "2":
# 微信端还车后,nonDealOrder 可能仍保留但状态变为 1(待支付)。
# 订单横幅仍由 /api/order/status 展示,但本地骑行计时和邮件必须立即停止。
_finish_active_wechat_rentals(
user_id, f"微信订单 {order_id} 已非骑行中(status={order_status})"
)
return {"ok": True, "active": False, "order_id": order_id,
"order_status": order_status}
conn = get_db()
cursor = conn.cursor()
cursor.execute(
# 同一 order_id 可能既有历史行(expired=1)又有活跃行:优先活跃行,
# 否则会把已结束的历史单「复活」,撞唯一索引后再靠兜底救回来(多一次写 + 误导日志)
"SELECT id, order_id, source, expired, end_time, rider_user_id FROM rentals "
"WHERE order_id = ? AND user_id = ? "
"ORDER BY expired ASC, id DESC",
(order_id, user_id)
)
existing = cursor.fetchone()
# 到期时长属于实际骑行者策略:已有行带 rider_user_id 就按骑行者的设置算,
# 否则按车主;上游调用始终用车主 user_id(卡属于车主)。
policy_user_id = user_id
if existing and "rider_user_id" in existing.keys():
policy_user_id = existing["rider_user_id"] or user_id
if existing and existing["expired"] == 0:
rental = dict(existing)
# 到期时间已经过了却还挂着(重启丢了计时器、或 0 点那次失败):
# 巡检必须补一次自动还车,不能再无脑 return,否则这一单永远还不掉。
# 只有「真的有上游订单」的来源才补(reminder 之类拿本地 id 当订单号必然失败)。
if _should_auto_return(rental) and _rental_end_time_passed(rental):
conn.close()
if not _background_enabled:
print(f"[订单检测] rental_id={rental['id']} 后台自动还车总开关已关闭,不补还车")
return {"ok": True, "active": True, "order_id": order_id}
if _recover_throttled(rental["id"]):
# 还不上时不能每分钟重打上游:基础 5 分钟一次;进入退避阶段后
# 由 _auto_return_backoff_until 决定(1m→2m→5m→10m 封顶,不放弃)
return {"ok": True, "active": True, "order_id": order_id,
"recovering": True}
print(f"[订单检测] rental_id={rental['id']} 已过到期时间,补一次自动还车")
threading.Thread(
target=lambda: _run_recovery(rental["id"], user_id, order_id),
daemon=True
).start()
return {"ok": True, "active": True, "order_id": order_id,
"recovered": True}
conn.close()
return {"ok": True, "active": True, "order_id": order_id}
detail = request_with_user_auth(user_id, "GET", "/record/detail",
params={"order_id": order_id}, _silent=True)
if detail.get("rtn_code") != 0 or not detail.get("data"):
conn.close()
return {"ok": False, "active": None,
"rtn_code": detail.get("rtn_code") or 502,
"message": detail.get("message", "获取微信订单详情失败")}
# 上游字段不稳:minutes 实测会返回 null,data 甚至可能不是 dict。
# 以前裸 int() 会把 /api/rental/sync 打成 500 并让整轮巡检作废(BUG-06)。
detail_data = detail.get("data")
if not isinstance(detail_data, dict):
detail_data = {}
minutes = max(0, _coerce_int(detail_data.get("minutes"), 0))
code = detail_data.get("code") or non_deal.get("code", "")
duration = get_user_rental_settings(policy_user_id)["rental_duration_minutes"]
remaining = max(duration - minutes, 1)
tz = dt.timezone(dt.timedelta(hours=8))
now = dt.datetime.now(tz)
end_time = now + dt.timedelta(minutes=remaining)
end_str = end_time.strftime("%Y-%m-%d %H:%M:%S")
# 上游 minutes 是本次订单已经骑行的分钟数,据此反推真实开始时间。
# 后续实时修改总时长时才能正确按整段骑行计算,而不是从同步时刻重新计时。
start_str = (now - dt.timedelta(minutes=minutes)).strftime("%Y-%m-%d %H:%M:%S")
if existing:
rental_id = existing["id"]
# 复活这张单时把 notified_* 一起复位:本地可能刚被 _close_rental_locally /
# _finish_active_wechat_rentals 置过 expired=1,那些提醒位还留着 1,
# 复活的单就再也收不到 5/3/2/1 提醒和 0 分钟自动还车了。
def _apply_revive(target_id):
try:
cursor.execute("""
UPDATE rentals SET expired = 0, source = 'sync',
start_time = ?, end_time = ?, duration = ?, email = ?,
notified_10 = 0, notified_5 = 0, notified_3 = 0,
notified_2 = 0, notified_1 = 0, notified_0 = 0
WHERE id = ?
""", (start_str, end_str, duration, email, target_id))
except sqlite3.OperationalError:
# 极简 schema 没有这些列:退回原来的更新
cursor.execute("""
UPDATE rentals SET expired = 0, source = 'sync',
start_time = ?, end_time = ?, duration = ?, email = ? WHERE id = ?
""", (start_str, end_str, duration, email, target_id))
try:
_apply_revive(rental_id)
except sqlite3.IntegrityError:
# 唯一索引:这个 order_id 已经有另一行未结束(并发落库)。改去复活
# 那一行,把计时器挂到真正生效的记录上,别让巡检线程崩掉。
other_id = _active_rental_id_for_order(conn, order_id)
if other_id is None or other_id == rental_id:
raise
print(f"[订单检测] order_id={order_id} 已有未结束记录 rental_id={other_id},"
f"改复活该行(原 id={rental_id})")
rental_id = other_id
_apply_revive(rental_id)
old_source = existing["source"]
print(f"[订单检测] 升级租车记录: rental_id={rental_id}, order_id={order_id}, "
f"source={old_source}→sync, 剩余={remaining}分钟")
else:
cursor.execute("""
INSERT INTO rentals (order_id, bike_code, email, user_id,
start_time, end_time, duration, expired, source)
VALUES (?, ?, ?, ?, ?, ?, ?, 0, 'sync')
""", (order_id, code, email, user_id, start_str, end_str, duration))
rental_id = cursor.lastrowid
print(f"[订单检测] 创建新租车记录: rental_id={rental_id}, order_id={order_id}, "
f"code={code}, 剩余={remaining}分钟")
cursor.execute("""
UPDATE rentals SET expired = 1 WHERE user_id = ? AND bike_code = ? AND source = 'reminder' AND expired = 0
""", (user_id, code))
cleaned = cursor.rowcount
if cleaned:
print(f"[订单检测] 已清理 {cleaned} 条旧的 reminder 记录")
conn.commit()
conn.close()
# sync 单来自上游已有订单,没有坐标:用开始时间附近的采集点回填起点,
# 否则后台订单表一直显示「起点未知」
try:
_fill_missing_start(rental_id, code, start_str)
except Exception as exc:
print(f"[订单检测] 回填 sync 起点失败: {exc}")
_cancel_rental_timers(rental_id)
start_rental_timer(rental_id, email, code, remaining, user_id)
return {"ok": True, "active": True, "order_id": order_id}
SYNC_START_TOLERANCE_MINUTES = 15 # sync 单起点回填:用开始时间附近的历史点
def _bike_pos_from_history(bike_code: str, when_str: str = None,
tolerance_minutes: int = SYNC_START_TOLERANCE_MINUTES):
"""从 bike_history 取这辆车的位置(GCJ02)。
- 给了 when_str:取该时刻附近(±tolerance)最近的一条 —— 用于 sync 单回填起点;
- 没给:取最新一条 —— 用于还车时补终点。
采集频率是 5~10 分钟,所以只能近似;拿不到就返回 None,不编造坐标。
"""
if not bike_code:
return None
conn = get_db()
try:
if when_str:
try:
when = dt.datetime.strptime(str(when_str), "%Y-%m-%d %H:%M:%S")
except (TypeError, ValueError):
return None
tz = dt.timezone(dt.timedelta(hours=8))
lo = (when - dt.timedelta(minutes=tolerance_minutes)).strftime("%Y-%m-%d %H:%M:%S")
hi = (when + dt.timedelta(minutes=tolerance_minutes)).strftime("%Y-%m-%d %H:%M:%S")
row = conn.execute("""
SELECT latitude, longitude FROM bike_history
WHERE bike_code = ? AND recorded_at BETWEEN ? AND ?
ORDER BY ABS(julianday(recorded_at) - julianday(?)) LIMIT 1
""", (str(bike_code), lo, hi, str(when_str))).fetchone()
else:
row = conn.execute("""
SELECT latitude, longitude FROM bike_history
WHERE bike_code = ? AND latitude IS NOT NULL AND longitude IS NOT NULL
ORDER BY recorded_at DESC LIMIT 1
""", (str(bike_code),)).fetchone()
except Exception as exc:
print(f"[位置回填] 查询 bike_history 失败: {exc}")
return None
finally:
conn.close()
if not row:
return None
try:
return float(row["latitude"]), float(row["longitude"])
except (TypeError, ValueError):
return None
def _fill_missing_start(rental_id: int, bike_code: str, start_str: str):
"""给 sync 单补起点坐标与位置标签(只在为空时补,不覆盖已有值)。
sync 单是我们从上游"发现"的订单:`/record/detail` 只给分钟数和车牌,
没有坐标,所以之前后台一直显示「起点未知」。用开始时间附近的采集点近似。
"""
pos = _bike_pos_from_history(bike_code, start_str)
if not pos:
return False
lat, lng = pos
label = None
try:
from campus import resolve_location_label
label = resolve_location_label(lat, lng)
except Exception:
label = None
conn = get_db()
try:
conn.execute("""
UPDATE rentals SET start_latitude = ?, start_longitude = ?, start_label = ?
WHERE id = ? AND (start_latitude IS NULL OR start_longitude IS NULL)
""", (lat, lng, label, rental_id))
conn.commit()
except Exception as exc:
print(f"[位置回填] 写起点失败 rental_id={rental_id}: {exc}")
return False
finally:
conn.close()
return True
def _finish_active_wechat_rentals(user_id: int, reason: str, keep_order_id=None):
"""结束本地镜像记录并取消邮件计时器。
只处理由微信订单产生的 unlock/sync/shared/subscribe 记录,不影响用户
单独创建的 reminder 计时。该函数只能在上游请求成功后调用,
避免把网络或凭据故障误判为已还车。
keep_order_id 用于「A 已在小程序还车、马上又开了 B」:保留当前上游 B,
只收尾其它本地活跃单;没有订单号的记录无法确认身份,不会误关。
"""
conn = get_db()
cursor = conn.cursor()
cursor.execute("""
SELECT id, order_id, source, bike_code FROM rentals
WHERE user_id = ? AND expired = 0
AND source IN ('unlock', 'sync', 'shared', 'subscribe')
""", (user_id,))
active_rows = cursor.fetchall()
conn.close()
for row in active_rows:
if keep_order_id is not None:
# 无订单号的记录无法判断是否就是 B,保守跳过,避免误关真实骑行。
if not row["order_id"] or str(row["order_id"]) == str(keep_order_id):
continue
# 微信端自行还车:上游只告诉我们"订单没了",没有坐标;
# 用这辆车最新的采集点当作终点,避免后台显示「终点未知」
pos = _bike_pos_from_history(row["bike_code"])
if pos:
_mark_returned(row["id"], pos[0], pos[1])
else:
_mark_returned(row["id"])
_cancel_rental_timers(row["id"])
# 官方小程序手动还车:这里只做本地收尾,清掉后续自动还车/续租状态,
# 即使本轮之后还有剩余轮次,也不能再把车开起来。
_clear_auto_return_state(row["id"])
print(f"[订单检测] 结束本地骑行记录: rental_id={row['id']}, "
f"order_id={row['order_id']}, source={row['source']}, reason={reason}")
def start_all_order_checkers():
"""启动所有有凭据用户的订单检测线程。
错峰启动:每个线程间隔 5 秒,避免启动瞬间并发请求上游被限流。"""
conn = get_db()
cursor = conn.cursor()
cursor.execute("SELECT id FROM users WHERE token_id IS NOT NULL AND token_id != ''")
users = cursor.fetchall()
conn.close()
def staggered():
for i, row in enumerate(users):
if i > 0:
_time.sleep(5)
start_user_order_checker(row["id"])
print(f"[订单检测] 已启动 {len(users)} 个用户的订单检测线程")
threading.Thread(target=staggered, daemon=True, name="order-checker-starter").start()
def _active_rental_id_for_order(conn, order_id):
"""同一 order_id 当前未结束的那一行 id(唯一索引冲突时用来复用)。
唯一索引 idx_rentals_active_order 只约束 expired=0 的行,所以这里也用
COALESCE(expired,0)=0 判定,跟索引谓词保持一致。
"""
if order_id is None or str(order_id) == "":
return None
try:
row = conn.execute(
"SELECT id FROM rentals WHERE order_id = ? AND COALESCE(expired, 0) = 0 "
"ORDER BY id DESC LIMIT 1", (str(order_id),)).fetchone()
except sqlite3.OperationalError:
return None
if not row:
return None
try:
return row["id"]
except (TypeError, IndexError):
return row[0]