fix: 缺陷审计批次(231 例)+ 复核补钉(①–⑦)

一、审计修复(另一侧完成,我复核通过)
- 认证/限流:_client_ip 归一、限流统一走 rate_limit._SlidingTable(超限只淘汰最旧 key,
  不再整表 clear 自毁)、每用户会话上限 10 + 过期清理
- 邮件验证码:锁内原子占位 → 锁外发信 → 成功落码,失败回滚冷却(并发不再双发)
- 租赁:rentals 部分唯一索引(同 order_id 只允许一行 expired=0,迁移前先查重)、
  开锁幂等落库、Timer 代号机制(取消/重排同临界区)、minutes=null 兜底、
  自动还车 30s×6 → 1m/2m/5m/10m 退避
- 安全:ring 四接口登录 + 任务归属校验(Bearer 或 ?token=,校验 sessions 表)、
  共享还车坐标不再伪造、代开锁 IntegrityError 兜底、token 配置原子写(fsync + 0600)
- 入口鉴权:8 个历史/分析接口未登录 401(HTTP 与 rtn_code 同时给)、
  analysis.html 带 Bearer + 未登录门 + 截断提示、历史查询 LIMIT 60000 并回传 truncated
- UX 四个 P0:计时条出现、真实单走 /api/order/return 而 reminder 走 /api/rental/return、
  定位失败不伪造坐标(三选一弹窗)、地图/配置/脚本失败统一落到可自救失败卡片
- 测试:新增 6 个文件 62 例;既有 test_history_30d 只补登录前置

二、我复核时发现并修掉的 7 处
① email_verify.record_cooldown 的 expires 写成 now,会被 send_code 开头的
   _cleanup_locked 整条删掉 —— 任何人发一次验证码就废掉「未注册邮箱」的冷却,
   找回密码又能枚举邮箱是否注册。改为活过冷却窗口,并补 3 例测试
② timer.py 两处落库(自动续租 INSERT、sync 复活 UPDATE)没防新唯一索引:
   撞索引抛 IntegrityError 会让巡检线程退出,该单从此没有计时器/自动还车(上游还在计费)。
   新增 _active_rental_id_for_order(),捕获后复用存活行
③ (0,0) 当合法坐标会先发给上游:/record/return 不校验范围,宽松后端会把车"还"在海里。
   新增 _coords_usable(),不可用就跳过原始点;候选列表永远丢掉第 0 项
④ boot_smoke.py 按旧契约要求 200,加鉴权后永远失败 → HTTPError 401 视为「未登录,预期」
⑤ 自动还车「不放弃」缺绝对上限:加 AUTO_RETURN_GIVE_UP_SECONDS=6h,到点只告警一次并停手
⑥ 索引谓词 aligned 到查重口径:COALESCE(expired,0)=0,旧定义自动重建
⑦ 访问日志脱敏:?token= / ?ticket= / ?access_token= 的值替换为 ***(werkzeug + root logger)
   否则容器日志里就是明文会话令牌
配套改写 tests/test_rental_dedup.py::test_return_accepts_zero_coordinates →
test_return_treats_zero_coordinates_as_missing(原断言把 (0,0) 当合法值发上游)

三、验证
- python -m pytest -q → 234 passed(基线 231,净增 3)
- node 5 套 → 44 pass / 0 fail
- 14 个 .py ast.parse、node --check dist/app.js → 全部通过
- boot_smoke.py → exit=0;未登录 /api/history/stats、/api/analysis/overview、
  /api/ring_progress/* 实测 401,/api/config 200
- 行为级:传 (0,0) 时上游只收到候选点;合法坐标仍先发上报值;唯一索引拦住重复插入
This commit is contained in:
zzy
2026-11-17 09:58:16 +08:00
parent 7a5840e0c3
commit f34ed304bc
59 changed files with 6487 additions and 802 deletions
+89 -14
View File
@@ -4,6 +4,7 @@
import datetime as dt
import json
import random
import sqlite3
from functools import wraps
from pathlib import Path
from flask import Blueprint, jsonify, request, render_template, session, redirect
@@ -72,12 +73,16 @@ def hash_admin_password(password: str) -> str:
def _nearby_coord(lat, lng, jitter=0.0001):
"""在车辆坐标附近加随机抖动,模拟真实定位(避免每次上报同一精确点被判远程操作)"""
"""在车辆坐标附近加随机抖动,模拟真实定位(避免每次上报同一精确点被判远程操作)。
坐标非法时直接抛 ValueError:宁可报错也不要编造一个假坐标去下单/还车
(旧版这里兜底 (36.67, 116.98),离校区约 20km,见 BUG-17)。
"""
try:
lat = float(lat)
lng = float(lng)
except (TypeError, ValueError):
lat, lng = 36.67, 116.98
raise ValueError("缺少有效坐标")
return {
"lat": lat + random.uniform(-jitter, jitter),
"lng": lng + random.uniform(-jitter, jitter),
@@ -282,7 +287,23 @@ def admin_api_return():
bike_result = request_with_user_auth(
int(user_id), "POST", "/project/bicycle", data={"code": rental["bike_code"]}, _silent=True)
bike_data = bike_result.get("data", {}) or {}
pos = _nearby_coord(bike_data.get("latitude", 36.67), bike_data.get("longitude", 116.98))
# 终点坐标:车辆详情真实坐标 → 该车最近一次 bike_history → 校园中心;
# 都没有就不拿假坐标去还车(旧版兜底 (36.67, 116.98) 会把终点写坏,BUG-17)。
if bike_data.get("latitude") is not None and bike_data.get("longitude") is not None:
coord = (bike_data.get("latitude"), bike_data.get("longitude"))
else:
from routes.share import _fallback_coord
coord = _fallback_coord(rental["bike_code"])
if not coord:
conn.close()
return jsonify({"rtn_code": 400,
"message": "缺少车辆定位,无法代还车,请让用户在地图页自行还车"})
try:
pos = _nearby_coord(coord[0], coord[1])
except ValueError:
conn.close()
return jsonify({"rtn_code": 400,
"message": "车辆坐标异常,无法代还车,请让用户在地图页自行还车"})
latitude = pos["lat"]
longitude = pos["lng"]
@@ -378,7 +399,23 @@ def admin_api_unlock():
return jsonify({"rtn_code": 400, "message": f"查车辆信息失败: {bike_result.get('message', '未知错误')}"})
bike_data = bike_result.get("data", {})
pos = _nearby_coord(bike_data.get("latitude", 36.67), bike_data.get("longitude", 116.98))
# 起点坐标:车辆详情真实坐标 → 该车最近一次 bike_history → 校园中心。
# 都没有就明确失败,不要再用一个离校区 20km 的常量坐标去下单(BUG-17 同源)。
if bike_data.get("latitude") is not None and bike_data.get("longitude") is not None:
coord = (bike_data.get("latitude"), bike_data.get("longitude"))
else:
from routes.share import _fallback_coord
coord = _fallback_coord(code)
if not coord:
conn.close()
return jsonify({"rtn_code": 400,
"message": "缺少车辆定位,无法创建订单,请到地图页确认车辆位置后重试"})
try:
pos = _nearby_coord(coord[0], coord[1])
except ValueError:
conn.close()
return jsonify({"rtn_code": 400,
"message": "车辆坐标异常,无法创建订单,请到地图页确认车辆位置后重试"})
latitude = pos["lat"]
longitude = pos["lng"]
@@ -416,25 +453,63 @@ def admin_api_unlock():
duration = get_user_rental_settings(user_id)["rental_duration_minutes"]
end = now + dt.timedelta(minutes=duration)
cursor.execute("""
INSERT INTO rentals (id, order_id, bike_code, email, user_id, start_time, end_time,
duration, expired, source)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 'unlock')
""", (int(order_id), order_id, code, user["email"], user_id,
now.strftime("%Y-%m-%d %H:%M:%S"), end.strftime("%Y-%m-%d %H:%M:%S"),
duration))
rental_id = int(order_id)
start_str = now.strftime("%Y-%m-%d %H:%M:%S")
end_str = end.strftime("%Y-%m-%d %H:%M:%S")
try:
cursor.execute("""
INSERT INTO rentals (id, order_id, bike_code, email, user_id, start_time, end_time,
duration, expired, source)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 'unlock')
""", (rental_id, order_id, code, user["email"], user_id,
start_str, end_str, duration))
except sqlite3.IntegrityError:
# 上游 order_id 撞上历史 rentals.id(reminder 单/重复行都会占号):
# 改用自增 id 落库,order_id 仍记录真实订单号,计时器挂真实 rental_id。
try:
cursor.execute("""
INSERT INTO rentals (order_id, bike_code, email, user_id, start_time, end_time,
duration, expired, source)
VALUES (?, ?, ?, ?, ?, ?, ?, 0, 'unlock')
""", (order_id, code, user["email"], user_id,
start_str, end_str, duration))
rental_id = int(cursor.lastrowid)
except sqlite3.Error as exc:
conn.rollback()
print(f"[admin] 代开锁本地记录写入失败 order_id={order_id}: {exc}")
conn.close()
return jsonify({
"rtn_code": 500,
"message": (f"车辆 {code} 已在上游开锁(订单 {order_id}),"
f"但本地计时记录写入失败,请稍后核对并手动补录:{exc}"),
"order_id": order_id,
"local_synced": False,
})
except sqlite3.Error as exc:
conn.rollback()
print(f"[admin] 代开锁本地记录写入失败 order_id={order_id}: {exc}")
conn.close()
return jsonify({
"rtn_code": 500,
"message": (f"车辆 {code} 已在上游开锁(订单 {order_id}),"
f"但本地计时记录写入失败,请稍后核对并手动补录:{exc}"),
"order_id": order_id,
"local_synced": False,
})
conn.commit()
from timer import start_rental_timer
start_rental_timer(rental_id=int(order_id), email=user["email"],
start_rental_timer(rental_id=rental_id, email=user["email"],
bike_code=code, duration_minutes=duration, user_id=user_id)
try:
from routes.rental import _record_rental_start
_record_rental_start(int(order_id), latitude, longitude)
_record_rental_start(rental_id, latitude, longitude)
except Exception as e:
print(f"[admin] 回填开锁起点失败: {e}")
conn.close()
return jsonify({"rtn_code": 0, "message": f"已为用户 {user['email']} 开锁车辆 {code}"})
return jsonify({"rtn_code": 0, "message": f"已为用户 {user['email']} 开锁车辆 {code}",
"order_id": order_id, "rental_id": rental_id,
"local_synced": True})
else:
conn.close()
return jsonify({"rtn_code": open_result.get("rtn_code", 500),
+158 -70
View File
@@ -1,10 +1,10 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""用户认证路由"""
import ipaddress
import re
import hashlib
import secrets
import threading
import time
from flask import Blueprint, jsonify, request
@@ -17,45 +17,92 @@ import rate_limit
bp = Blueprint("auth", __name__)
# ========== 简易限流(内存版,单进程足够) ==========
# 登录:同一 (IP, 邮箱) 连续失败 5 次锁定 15 分钟
# ========== 简易限流(内存版,单进程足够;口径统一走 rate_limit 的滑动窗口) ==========
# 登录:同一 (IP, 邮箱) 窗口内失败 5 次 → 锁 15 分钟(滑动窗口,不是阶梯计数)
# 注册:同一 IP 每小时最多 5 次注册
_rl_lock = threading.Lock()
_login_fail: dict = {} # (ip, email) -> [fail_count, first_fail_ts]
_register_ips: dict = {} # ip -> [count, window_start_ts]
LOGIN_MAX_FAILS = 5
LOGIN_LOCK_SECONDS = 15 * 60
REGISTER_MAX_PER_HOUR = 5
# 每个账号最多保留的登录会话数(多设备登录的硬上限,BUG-15)
MAX_SESSIONS_PER_USER = 10
def _normalize_ip(value):
"""把代理头里的值规整成合法 IP 字符串;不是合法 IP 时返回 None。
容错口径(nginx / 云 LB / 部分 CDN 都会带这些花样):
- 前后空白、成对引号:" 1.2.3.4 " / '"1.2.3.4"';
- IPv4 带端口:"1.2.3.4:5678";
- IPv6 带方括号与端口:"[2001:db8::1]" / "[2001:db8::1]:443";
- IPv4-mapped IPv6:"::ffff:1.2.3.4" → "1.2.3.4"(否则容器里会多出一层
等价但不相等的 key,限流被稀释)。
"""
raw = str(value or "").strip().strip("'\"").strip()
if not raw:
return None
if raw.startswith("[") and "]" in raw:
raw = raw[1:raw.index("]")]
elif raw.count(":") == 1:
# 只对「恰好一个冒号」的形态剥端口:IPv6 本身就有多个冒号,不能按冒号切
host, _, port = raw.partition(":")
if host and port.isdigit():
raw = host
raw = raw.strip().strip("[]").strip()
if not raw:
return None
try:
addr = ipaddress.ip_address(raw)
except ValueError:
return None
if addr.version == 6 and addr.ipv4_mapped is not None:
addr = addr.ipv4_mapped
return str(addr)
def _trusted_proxy_prefixes():
"""可信反代前缀列表(可用环境变量 TRUSTED_PROXIES 覆盖,逗号分隔)。"""
import os as _os
return tuple(
part.strip() for part in
_os.environ.get("TRUSTED_PROXIES", "127.,::1,172.,10.,192.168.").split(",")
if part.strip()
)
def _client_ip() -> str:
"""获取真实客户端 IP。
本服务部署在 nginx 反代之后(HTTP 直连本机),取 IP 的规则:
- 仅当请求来自本机回环(nginx 与本服务同机部署)时,才信任代理注入的头:
优先 X-Real-IP,其次 X-Forwarded-For 的最右一项;
- 其余来源(含内网直连)一律使用 remote_addr,
防止局域网/直连客户端伪造 X-Real-IP 绕过限流与登录锁定。"""
remote = request.remote_addr or ""
# 可信代理:默认回环 + 常见容器网段(Docker/兄弟 nginx 下 remote_addr 是 172.x)。
# 可用环境变量 TRUSTED_PROXIES 覆盖(逗号分隔的前缀,如 "127.,172.,10.")。
# 不这样做的话,容器部署里所有客户端会塌成同一个限流 key:
# 45 次/分钟变成全站共享额度,一两个人就能把所有人打成 429。
import os as _os
trusted = tuple(
part.strip() for part in
_os.environ.get("TRUSTED_PROXIES", "127.,::1,172.,10.,192.168.").split(",")
if part.strip()
)
信任模型(**故意**保留 RFC1918 网段,别收紧成只信回环):
本服务跑在 docker 容器里、前面是同宿主机/同 compose 项目的 nginx 反代,
此时 `request.remote_addr` 永远是容器网关(172.x)。nginx 用
`proxy_set_header X-Real-IP $remote_addr;` 注入真实来源。
如果只信 127.0.0.1,所有客户端会塌成同一个限流 key:
「45 次/分钟」变成全站共享额度,一个人连点 5 次就能把全站打成 429。
所以默认 TRUSTED_PROXIES = "127.,::1,172.,10.,192.168." 保持不变 ——
它信任的是「反代/容器网络」这一层,不是公网客户端。
对应的健壮性要求(BUG-01):
- 头里的值必须是**合法 IP**(`ipaddress.ip_address()` 能解析,允许
「空白/引号/方括号/IPv4:端口」这些代理写法),否则丢掉、回落到 remote_addr;
- `X-Forwarded-For` 取**最右一项**(最左是客户端可自填的,取最左等于把伪造
权交回客户端),并同样校验合法性;
- 来源不在可信网段时一律用 remote_addr,完全不看这两个头。
"""
remote_raw = (request.remote_addr or "").strip()
remote = _normalize_ip(remote_raw) or remote_raw
trusted = _trusted_proxy_prefixes()
is_trusted = remote in ("127.0.0.1", "::1") or any(
remote.startswith(pref) for pref in trusted if pref not in ("127.", "::1"))
if remote in ("127.0.0.1", "::1") or is_trusted:
real = request.headers.get("X-Real-IP", "").strip()
if is_trusted:
real = _normalize_ip(request.headers.get("X-Real-IP", ""))
if real:
return real
xff = request.headers.get("X-Forwarded-For", "").strip()
xff = (request.headers.get("X-Forwarded-For", "") or "").strip()
if xff:
return xff.split(",")[-1].strip()
rightmost = _normalize_ip(xff.split(",")[-1])
if rightmost:
return rightmost
return remote or "unknown"
@@ -65,49 +112,36 @@ def _strict_signature_required() -> bool:
return is_strict_mode()
def _login_key(ip: str, email: str):
"""登录失败锁定的 key:IP + 邮箱两个维度(换 IP 也要重新计数,换邮箱同理)。"""
return ("login_fail", ip, (email or "").strip().lower())
def _login_rate_ok(ip: str, email: str):
"""检查登录是否被锁定。返回 (ok, 剩余秒数)"""
key = (ip, email)
now = time.time()
with _rl_lock:
entry = _login_fail.get(key)
if not entry:
return True, 0
count, first_ts = entry
if now - first_ts > LOGIN_LOCK_SECONDS:
# 窗口已过,重置
del _login_fail[key]
return True, 0
if count >= LOGIN_MAX_FAILS:
return False, int(LOGIN_LOCK_SECONDS - (now - first_ts))
return True, 0
"""检查登录是否被锁定。返回 (ok, 剩余秒数)。
注意极性:`rate_limit.fail_locked` 返回的是 (locked, 剩余秒数),
这里对外沿用历史的 (ok, 剩余秒数) 口径(ok=True 表示还能登录)。
"""
locked, wait_seconds = rate_limit.fail_locked(
_login_key(ip, email), LOGIN_MAX_FAILS, LOGIN_LOCK_SECONDS)
return (not locked), wait_seconds
def _login_record_fail(ip: str, email: str):
key = (ip, email)
now = time.time()
with _rl_lock:
entry = _login_fail.get(key)
if not entry or now - entry[1] > LOGIN_LOCK_SECONDS:
_login_fail[key] = [1, now]
else:
entry[0] += 1
"""记录一次登录失败。返回是否已触发锁定。"""
return rate_limit.record_fail(_login_key(ip, email),
LOGIN_MAX_FAILS, LOGIN_LOCK_SECONDS)
def _login_record_success(ip: str, email: str):
with _rl_lock:
_login_fail.pop((ip, email), None)
"""登录成功即清空该 (IP, 邮箱) 的失败窗口。"""
rate_limit.record_success(_login_key(ip, email))
def _register_rate_ok(ip: str):
now = time.time()
with _rl_lock:
entry = _register_ips.get(ip)
if not entry or now - entry[1] > 3600:
_register_ips[ip] = [1, now]
return True
entry[0] += 1
return entry[0] <= REGISTER_MAX_PER_HOUR
"""同一 IP 每小时最多 REGISTER_MAX_PER_HOUR 次注册(滑动窗口)。"""
return rate_limit.hit(("register_ip", ip), REGISTER_MAX_PER_HOUR, 3600)
def hash_password(password: str) -> str:
@@ -215,20 +249,26 @@ def get_current_user():
if not token:
return None
conn = get_db()
cursor = conn.cursor()
cursor.execute("""
SELECT users.id, users.email FROM sessions
JOIN users ON sessions.user_id = users.id
WHERE sessions.token = ? AND sessions.expires_at > datetime('now', '+8 hours')
""", (token,))
user = cursor.fetchone()
if user:
try:
cursor = conn.cursor()
cursor.execute("""
SELECT users.id, users.email FROM sessions
JOIN users ON sessions.user_id = users.id
WHERE sessions.token = ? AND sessions.expires_at > datetime('now', '+8 hours')
""", (token,))
user = cursor.fetchone()
if not user:
return None
# BUG-21:这是**每个带 token 的请求**都要走的路径,两条 UPDATE 无脑 commit
# 等于每请求一次 WAL 写。改成按 rowcount 判断:只有真的改到行才提交。
changed = 0
# 最近活跃时间:节流刷新(至多每 5 分钟写一次),供“登录设备管理”展示;时间统一为 GMT+8
cursor.execute("""
UPDATE sessions SET last_active = datetime('now', '+8 hours')
WHERE token = ? AND (last_active IS NULL
OR last_active < datetime('now', '+8 hours', '-300 seconds'))
""", (token,))
changed += cursor.rowcount or 0
# 登录设备类型:只要有请求(含打开页面时的 /api/auth/status)就按最新 UA 刷新,
# 同一会话换浏览器/进原生壳后立即生效;仅在类型确实变化时才产生写入
ua = (request.headers.get("User-Agent", "") or "").strip()
@@ -239,9 +279,12 @@ def get_current_user():
SET device_name = ?, user_agent = ?
WHERE token = ? AND (device_name != ? OR user_agent != ?)
""", (label, ua[:500], token, label, ua[:500]))
conn.commit()
conn.close()
return dict(user) if user else None
changed += cursor.rowcount or 0
if changed:
conn.commit()
return dict(user)
finally:
conn.close()
def login_required():
@@ -252,6 +295,47 @@ def login_required():
return user
def _prune_user_sessions(cursor, user_id: int, keep_token: str = "") -> int:
"""会话上限 + 过期清理(BUG-15)。返回删除的行数。
以前每次登录只新增一条会话、永不上限,只在 leader 每天 23 小时节流跑一次
`cleanup_old_data`。实测一个用户攒到 65 条 30 天有效的 token —— 每条被偷都是
完整账号,而且 `get_current_user` 要在这张表上按 token 命中 + 写 last_active。
这里在**写新会话的同一事务里**做两件事:
1. 删掉该用户已经过期的会话;
2. 按 id 倒序只保留最近 MAX_SESSIONS_PER_USER 条(id 自增 = 创建先后),
多出来的最旧会话删掉。keep_token 命中的会话永远保留。
"""
if not user_id:
return 0
deleted = 0
cursor.execute(
"DELETE FROM sessions WHERE user_id = ? AND expires_at <= datetime('now', '+8 hours')",
(user_id,))
deleted += cursor.rowcount or 0
cursor.execute(
"SELECT id, token FROM sessions WHERE user_id = ? ORDER BY id DESC", (user_id,))
rows = cursor.fetchall()
# keep_token(本次刚登录的那条)先占一个名额,再按 id 倒序补齐剩下的名额;
# 名额用完后的都是最旧的会话,直接删。这样上限是硬上限,不会被 keep 顶穿。
keep_ids = {row["id"] for row in rows if keep_token and row["token"] == keep_token}
room = max(MAX_SESSIONS_PER_USER - len(keep_ids), 0)
for row in rows:
if row["id"] in keep_ids:
continue
if room <= 0:
cursor.execute("DELETE FROM sessions WHERE id = ? AND user_id = ?",
(row["id"], user_id))
deleted += cursor.rowcount or 0
continue
keep_ids.add(row["id"])
room -= 1
if deleted:
print(f"[会话] 用户 {user_id} 清理 {deleted} 条会话(上限 {MAX_SESSIONS_PER_USER})")
return deleted
@bp.route("/api/auth/send_code", methods=["POST"])
def auth_send_code():
"""发送邮箱验证码。purpose=register 注册 / reset 重置密码。
@@ -351,6 +435,8 @@ def register():
INSERT INTO sessions (user_id, token, expires_at, device_name, device_id, user_agent, last_active)
VALUES (?, ?, datetime('now', '+8 hours', '+30 days'), ?, ?, ?, datetime('now', '+8 hours'))
""", (user_id, session_token, device_name, device_id, user_agent))
# 会话上限(BUG-15):注册也会新增会话,同样受 MAX_SESSIONS_PER_USER 约束
_prune_user_sessions(cursor, user_id, keep_token=session_token)
conn.commit()
conn.close()
@@ -456,6 +542,8 @@ def login():
INSERT INTO sessions (user_id, token, expires_at, device_name, device_id, user_agent, last_active)
VALUES (?, ?, datetime('now', '+8 hours', '+30 days'), ?, ?, ?, datetime('now', '+8 hours'))
""", (user["id"], session_token, device_name, device_id, user_agent))
# 会话上限(BUG-15):保留最近 MAX_SESSIONS_PER_USER 条,顺带清掉该用户已过期的会话
_prune_user_sessions(cursor, user["id"], keep_token=session_token)
conn.commit()
conn.close()
+188 -18
View File
@@ -24,6 +24,106 @@ BATCH_RING_ALLOWED_EMAILS = {"3146527494@qq.com"}
ring_tasks: dict = {}
_ring_lock = threading.Lock()
# 首页静态资源版本号的进程内缓存(BUG-21):只有签名变化才重算 sha256
_map_asset_version_lock = threading.Lock()
_map_asset_version_cache = {"signature": None, "version": None}
# 寻车任务生命周期:已完成/失败的任务保留 30 分钟后删除,字典另有硬上限。
# 之前只有显式 /api/ring_status_clear 才 pop,前端不调就永久驻留(每条含
# 车辆列表与统计),随使用次数线性增长(BUG-20)。
RING_TASK_TTL_SECONDS = 30 * 60 # 已结束任务的保留时间
RING_TASK_CLEANUP_INTERVAL = 60 # 清理最小间隔:不是每个请求都扫全表
RING_TASK_MAX_TASKS = 2000 # 容量硬上限
_RING_FINISHED_STATUS = ("completed", "cancelled", "failed")
_ring_last_cleanup = 0.0
def _ring_cleanup_locked(now=None, force=False):
"""清理过期/超额任务(调用方必须持有 _ring_lock)。
- 已完成/失败任务超过 RING_TASK_TTL_SECONDS 删除;运行中的任务不动,
否则正在看进度页的 SSE 会莫名收到「任务不存在」。
- 清理按 RING_TASK_CLEANUP_INTERVAL 节流,避免每个请求都全表扫。
- 达到容量上限时按创建时间淘汰最老的已结束任务。
"""
global _ring_last_cleanup
now = time.time() if now is None else now
over_capacity = len(ring_tasks) >= RING_TASK_MAX_TASKS
if not force and not over_capacity and \
now - _ring_last_cleanup < RING_TASK_CLEANUP_INTERVAL:
return
_ring_last_cleanup = now
for tid, task in list(ring_tasks.items()):
if task.get("status") not in _RING_FINISHED_STATUS:
continue
ended = float(task.get("last_update") or task.get("created_at") or now)
if now - ended >= RING_TASK_TTL_SECONDS:
ring_tasks.pop(tid, None)
if len(ring_tasks) < RING_TASK_MAX_TASKS:
return
for tid, task in sorted(ring_tasks.items(),
key=lambda kv: float(kv[1].get("created_at") or 0)):
if len(ring_tasks) < RING_TASK_MAX_TASKS:
break
if task.get("status") in _RING_FINISHED_STATUS:
ring_tasks.pop(tid, None)
def _ring_task_get(task_id):
"""取任务快照,并顺手做一次节流清理(顺带保证过期任务读不到)。"""
with _ring_lock:
_ring_cleanup_locked()
task = ring_tasks.get(task_id)
return dict(task) if task else None
def _query_token():
"""URL 里的会话 token:`?token=<token>`(EventSource / 新窗口带不了 header)。"""
return (request.args.get("token") or "").strip()
def _user_from_request():
"""寻车任务鉴权:同时接受 `Authorization: Bearer <token>` 与 `?token=<token>`。
/ring_progress.html 用 EventSource(浏览器不给带 header)、取消按钮在新窗口
打开(同样拿不到前端内存里的 header),所以两个入口都走查询参数。
token 出现在 URL 里,因此相关页面/接口统一加 no-store + no-referrer。
"""
user = get_current_user()
if user:
return user
token = _query_token()
if not token:
return None
conn = get_db()
try:
row = conn.execute("""
SELECT users.id, users.email FROM sessions
JOIN users ON sessions.user_id = users.id
WHERE sessions.token = ? AND sessions.expires_at > datetime('now', '+8 hours')
""", (token,)).fetchone()
except Exception as exc:
print(f"[寻车] 校验 token 失败: {exc}")
row = None
finally:
conn.close()
return dict(row) if row else None
def _ring_owner_guard(task_id, user):
"""校验任务归属;返回 (task, error_response)。
任务里记 owner_user_id,只能操作自己创建的任务,否则任何人都能拿 8 位
task_id 读进度、取消别人的任务(BUG-20)。
"""
task = _ring_task_get(task_id)
if not task:
return None, (jsonify({"rtn_code": 404, "message": "任务不存在或已过期"}), 404)
if task.get("owner_user_id") != user["id"]:
return None, (jsonify({"rtn_code": 403, "message": "无权操作他人的寻车任务"}), 403)
return task, None
async def ring_single_bike_async(session, bike_code, school_id=10):
try:
@@ -107,8 +207,14 @@ def api_ring_all():
"status": "running", "total": len(codes), "done": 0,
"success": 0, "failed": 0, "bikes": [{"code": c} for c in codes],
"cancelled": False, "created_at": time.time(), "last_update": time.time(),
"owner_user_id": user["id"],
}
with _ring_lock:
_ring_cleanup_locked()
if len(ring_tasks) >= RING_TASK_MAX_TASKS:
# 清理后仍然满:拒绝新建,而不是让字典无限涨
return jsonify({"rtn_code": 429,
"message": "寻车任务过多,请稍后再试"}), 429
ring_tasks[task_id] = task
t = threading.Thread(target=run_ring_task, args=(task_id,), daemon=True)
t.start()
@@ -118,20 +224,28 @@ def api_ring_all():
@bp.route("/api/ring_status/<task_id>")
def api_ring_status(task_id):
with _ring_lock:
task = ring_tasks.get(task_id)
if not task:
return jsonify({"rtn_code": 404, "message": "任务不存在"})
return jsonify({"rtn_code": 0, "status": task["status"], "total": task["total"],
"done": task["done"], "success": task["success"], "failed": task["failed"]})
user = _user_from_request()
if not user:
return jsonify({"rtn_code": 401, "message": "请先登录"}), 401
task, error = _ring_owner_guard(task_id, user)
if error:
return error
return jsonify({"rtn_code": 0, "status": task["status"], "total": task["total"],
"done": task["done"], "success": task["success"], "failed": task["failed"]})
@bp.route("/api/ring_cancel/<task_id>", methods=["POST"])
def api_ring_cancel(task_id):
user = _user_from_request()
if not user:
return jsonify({"rtn_code": 401, "message": "请先登录"}), 401
with _ring_lock:
_ring_cleanup_locked()
task = ring_tasks.get(task_id)
if not task:
return jsonify({"rtn_code": 404, "message": "任务不存在"})
return jsonify({"rtn_code": 404, "message": "任务不存在或已过期"}), 404
if task.get("owner_user_id") != user["id"]:
return jsonify({"rtn_code": 403, "message": "无权操作他人的寻车任务"}), 403
if task["status"] != "running":
return jsonify({"rtn_code": 400, "message": f"任务已是 {task['status']} 状态"})
task["cancelled"] = True
@@ -145,6 +259,13 @@ def api_ring_progress(task_id):
global ring_tasks
RING_SSE_MAX_SECONDS = 180 # 单个进度 SSE 最长占用时间
user = _user_from_request()
if not user:
return jsonify({"rtn_code": 401, "message": "请先登录"}), 401
task, error = _ring_owner_guard(task_id, user)
if error:
return error
def _sse(obj):
return f"data: {json.dumps(obj, ensure_ascii=False)}\n\n"
@@ -161,12 +282,13 @@ def api_ring_progress(task_id):
return
with _ring_lock:
task = ring_tasks.get(task_id)
if not task:
snapshot = dict(task) if task else None
if not snapshot:
# 任务不存在(如服务重启/多进程不共享)——向前端发明确错误而非静默断开
yield _sse({"type": "error", "message": "任务不存在或已结束"})
return
done = task["done"]
status = task["status"]
done = snapshot["done"]
status = snapshot["status"]
if done != last_done or status != last_status:
last_done = done
last_status = status
@@ -174,9 +296,9 @@ def api_ring_progress(task_id):
"type": "progress",
"status": status,
"done": done,
"total": task["total"],
"success": task["success"],
"failed": task["failed"],
"total": snapshot["total"],
"success": snapshot["success"],
"failed": snapshot["failed"],
})
if status in ("completed", "cancelled"):
# 已结束,补发一条 done 事件后关闭
@@ -191,16 +313,25 @@ def api_ring_progress(task_id):
generate(),
mimetype="text/event-stream",
headers={
"Cache-Control": "no-cache",
"Cache-Control": "no-store",
"Connection": "keep-alive",
"X-Accel-Buffering": "no",
"Referrer-Policy": "no-referrer",
},
)
@bp.route("/api/ring_status_clear/<task_id>", methods=["POST"])
def api_ring_status_clear(task_id):
user = _user_from_request()
if not user:
return jsonify({"rtn_code": 401, "message": "请先登录"}), 401
with _ring_lock:
task = ring_tasks.get(task_id)
if not task:
return jsonify({"rtn_code": 0, "message": "已清除"})
if task.get("owner_user_id") != user["id"]:
return jsonify({"rtn_code": 403, "message": "无权操作他人的寻车任务"}), 403
ring_tasks.pop(task_id, None)
return jsonify({"rtn_code": 0, "message": "已清除"})
@@ -268,8 +399,9 @@ def api_find_bike():
@bp.route("/api/config")
def api_config():
from campus import CAMPUS_CENTER_LAT, CAMPUS_CENTER_LNG
return jsonify({
"center_lat": 36.531820, "center_lng": 116.780180,
"center_lat": CAMPUS_CENTER_LAT, "center_lng": CAMPUS_CENTER_LNG,
"scale": 17, "school_name": "山东管理学院",
"type_names": {"1": "单车", "3": "电动车", "6": "助力车"},
})
@@ -464,8 +596,37 @@ MAP_ASSETS = (
)
def _map_asset_signature():
"""静态资源的 (绝对路径, mtime_ns, size) 签名:任一文件被改就变。
只做 stat,不读内容 —— 用它判断进程内缓存是否还能用。
"""
root = Path(current_app.static_folder)
signature = []
for filename in MAP_ASSETS:
path = root / filename
try:
info = path.stat()
signature.append((str(path), info.st_mtime_ns, info.st_size))
except OSError:
signature.append((str(path), None, None))
return tuple(signature)
def _map_asset_version():
"""Version the complete map bundle so deployments cannot reuse old dependencies."""
"""Version the complete map bundle so deployments cannot reuse old dependencies.
首页每次请求都要这个版本号,而它要读完约 420KB 静态资源再 sha256(BUG-21)。
这里按 (路径, mtime, size) 做进程内缓存:文件没动就直接返回上次的结果,
文件一改(含部署覆盖、`touch`)签名就变,立刻重算,不会长期缓存旧 hash。
参与版本号的资源必须是页面真正引用的那一套(MAP_ASSETS),不要再抽掉什么
—— 少算一个文件就等于那个文件改了但浏览器仍用旧缓存。
"""
signature = _map_asset_signature()
with _map_asset_version_lock:
if _map_asset_version_cache["signature"] == signature \
and _map_asset_version_cache["version"]:
return _map_asset_version_cache["version"]
digest = hashlib.sha256()
for filename in MAP_ASSETS:
digest.update(filename.encode())
@@ -473,7 +634,11 @@ def _map_asset_version():
digest.update((Path(current_app.static_folder) / filename).read_bytes())
except FileNotFoundError:
digest.update(b"missing")
return digest.hexdigest()[:16]
version = digest.hexdigest()[:16]
with _map_asset_version_lock:
_map_asset_version_cache["signature"] = signature
_map_asset_version_cache["version"] = version
return version
@bp.route("/")
@@ -490,4 +655,9 @@ def analysis_page():
@bp.route("/ring_progress.html")
def ring_progress():
return render_template("ring_progress.html")
# 进度页把会话 token 放在 URL 查询参数里,别让浏览器缓存页面或把带 token
# 的地址通过 Referer 带给第三方(页面内的地图/CDN 请求)。
response = current_app.make_response(render_template("ring_progress.html"))
response.headers["Cache-Control"] = "no-store"
response.headers["Referrer-Policy"] = "no-referrer"
return response
+222 -57
View File
@@ -21,26 +21,70 @@ from rental_mail import get_rental_mail_context, resolve_return_token
bp = Blueprint("rental", __name__)
_email_return_locks = {}
_email_return_locks_guard = threading.Lock()
_order_return_locks = {}
_order_return_locks_guard = threading.Lock()
# 按 key 复用的「串行锁」表:key 来自客户端(order_id / rental_id),不能无界增长。
# 老的写法是 setdefault(...) 之后永不释放 —— 登录用户每次换个 order_id 就在进程里
# 留一个 Lock(BUG-11)。这里加上限 + TTL,并且只淘汰「当前没人持有」的锁。
_LOCK_REGISTRY_MAX = 256
_LOCK_REGISTRY_TTL = 3600 # 1 小时没用过就允许回收
class _LockRegistry:
"""带上限与 TTL 的按 key 锁表(返回的锁可放心 with 使用)。"""
def __init__(self, max_entries: int = _LOCK_REGISTRY_MAX,
ttl_seconds: int = _LOCK_REGISTRY_TTL):
self._guard = threading.Lock()
self._max_entries = max(1, int(max_entries))
self._ttl = max(1, int(ttl_seconds))
self._items = {} # key -> [lock, last_used_ts]
def get(self, key):
now = time.time()
with self._guard:
entry = self._items.get(key)
if entry is not None:
entry[1] = now
return entry[0]
self._evict_locked(now)
lock = threading.Lock()
self._items[key] = [lock, now]
return lock
def _evict_locked(self, now: float):
"""仅在接近上限时清理:先按 TTL,再按最久未用,且跳过正被持有的锁。"""
if len(self._items) < self._max_entries:
return
for key in [k for k, (lock, ts) in self._items.items()
if not lock.locked() and now - ts > self._ttl]:
self._items.pop(key, None)
if len(self._items) < self._max_entries:
return
idle = sorted(
((k, v) for k, v in self._items.items() if not v[0].locked()),
key=lambda kv: kv[1][1])
for key, _entry in idle[:max(1, len(idle) // 4)]:
self._items.pop(key, None)
def __len__(self):
return len(self._items)
_email_return_locks = _LockRegistry()
_order_return_locks = _LockRegistry()
def _email_return_lock(rental_id: int):
with _email_return_locks_guard:
return _email_return_locks.setdefault(rental_id, threading.Lock())
return _email_return_locks.get(rental_id)
def _serialize_order_return(func):
"""同一订单的重复还车请求串行执行,避免重复调用上游锁车接口。"""
@wraps(func)
def wrapped(*args, **kwargs):
# 只在这里取一次 key(请求体由视图自己再解析一次,Flask 会缓存已解析的 JSON)
data = request.get_json(silent=True) or {}
key = str(data.get("order_id") or "missing")
with _order_return_locks_guard:
lock = _order_return_locks.setdefault(key, threading.Lock())
with lock:
with _order_return_locks.get(key):
return func(*args, **kwargs)
return wrapped
@@ -280,26 +324,55 @@ def _distinct_points(points, min_gap_m=12.0):
return out
_COORD_EPS = 0.01 # 纬度、经度都小于这个值时就当"没有有效坐标"
def _coords_usable(lat, lng) -> bool:
"""这个坐标能不能直接发给上游。
(0,0) 是「前端把 undefined 序列化成 0」的典型产物:我们服务的场景永远不在
几内亚湾,而上游 `/record/return` 并不校验位置范围 —— 宽松实现会把 (0,0)
当合法位置接受,于是车"还"在了海里,后台起点→终点那一列直接变成大西洋坐标。
"""
if lat is None or lng is None:
return False
try:
lat_f, lng_f = float(lat), float(lng)
except (TypeError, ValueError):
return False
if not math.isfinite(lat_f) or not math.isfinite(lng_f):
return False
return not (abs(lat_f) < _COORD_EPS and abs(lng_f) < _COORD_EPS)
def _try_return_candidates(user_id, order_id, code, lat, lng):
"""按「先原坐标,失败再算候选点」的顺序调 `/record/return`。
返回 (结果, 用到的点, 试过的点描述列表)。候选点要等真的失败才算,
否则每次还车都白白多打一次 `/project/map`。
"""
tried = ["你上报的位置"]
result = request_with_user_auth(
user_id, "POST", "/record/return",
data={"order_id": order_id, "longitude": lng, "latitude": lat, "code": code}
)
if result.get("rtn_code") == 0:
return result, (lat, lng), tried
# 「订单信息不存在」换坐标也没用,直接收工
if (result.get("rtn_code") == 204010
or "订单信息不存在" in str(result.get("message") or "")):
return result, (lat, lng), tried
raw_ok = _coords_usable(lat, lng)
tried = ["你上报的位置"] if raw_ok else []
last_result = None
if raw_ok:
result = request_with_user_auth(
user_id, "POST", "/record/return",
data={"order_id": order_id, "longitude": lng, "latitude": lat, "code": code}
)
if result.get("rtn_code") == 0:
return result, (lat, lng), tried
# 「订单信息不存在」换坐标也没用,直接收工
if (result.get("rtn_code") == 204010
or "订单信息不存在" in str(result.get("message") or "")):
return result, (lat, lng), tried
last_result = result
else:
print(f"[还车位置] 上报坐标不可用(lat={lat}, lng={lng}),跳过原始点直接算候选")
last_result = result
for plat, plng, label in _return_candidates(lat, lng, user_id)[1:]:
# _return_candidates 的第 0 项永远是「你上报的位置」,不管上面有没有真发过,
# 都不能再拿它当候选点(否则 (0,0) 会绕过判断,从这个口子又发出去)。
candidates = _return_candidates(lat, lng, user_id)[1:]
for plat, plng, label in candidates:
tried.append(label)
result = request_with_user_auth(
user_id, "POST", "/record/return",
@@ -313,6 +386,8 @@ def _try_return_candidates(user_id, order_id, code, lat, lng):
or "订单信息不存在" in str(result.get("message") or "")):
return result, (plat, plng), tried
print(f"[还车位置] 候选点 {label} 失败: {result.get('message')}")
if last_result is None:
last_result = {"rtn_code": -1, "message": "没有可用的还车位置"}
return last_result, (lat, lng), tried
@@ -579,6 +654,77 @@ def _record_rental_end(order_id: str, user_id: int, latitude, longitude):
conn.close()
def _find_active_rental_id(conn, order_id):
"""该上游订单号是否已有「未结束」的本地记录;有就返回其 rental_id。
同一张单被重复开锁(客户端双击/网关重试/上游复用同一 order_id)时必须复用它,
否则会插出两行 rentals + 两套计时器(BUG-03:重复提醒邮件、重复自动还车、
订单历史轮次翻倍)。空 order_id(本地计时单)不参与判重。
"""
if order_id is None:
return None
key = str(order_id).strip()
if not key:
return None
row = conn.execute(
"SELECT id FROM rentals WHERE order_id = ? AND COALESCE(expired, 0) = 0 "
"ORDER BY id DESC LIMIT 1", (key,)).fetchone()
return int(row["id"]) if row else None
def _insert_unlock_rental(conn, *, order_id, code, email, user_id,
start_time, end_time, duration):
"""幂等落库一条开锁订单,返回 (rental_id, created)。
- 已有同 order_id 的未结束记录 → 直接复用,created=False;
- 没有 → 优先用 `id=order_id`(与历史行为一致,前端/邮件都用这个 id),
`id` 被占用(reminder/sync 自增行漂移)时退回自增 id,order_id 照旧记录;
- 唯一索引(db.py 的 idx_rentals_active_order)兜底:冲突时再复用一次,
绝不插第二行同一 order_id。
"""
existing = _find_active_rental_id(conn, order_id)
if existing is not None:
return existing, False
params_tail = (order_id, code, email, user_id, start_time, end_time, duration)
numeric_id = None
try:
numeric_id = int(order_id)
except (TypeError, ValueError):
numeric_id = None
if numeric_id is not None:
try:
conn.execute("""
INSERT INTO rentals (id, order_id, bike_code, email, user_id, start_time,
end_time, duration, expired, source)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 'unlock')
""", (numeric_id,) + params_tail)
return numeric_id, True
except sqlite3.IntegrityError:
existing = _find_active_rental_id(conn, order_id)
if existing is not None:
print(f"[开锁] order_id={order_id} 已存在未结束记录 rental_id={existing},复用")
return existing, False
print(f"[开锁] rentals.id={numeric_id} 已被占用,改用自增 id")
cur = None
try:
cur = conn.execute("""
INSERT INTO rentals (order_id, bike_code, email, user_id, start_time, end_time,
duration, expired, source)
VALUES (?, ?, ?, ?, ?, ?, ?, 0, 'unlock')
""", params_tail)
except sqlite3.IntegrityError:
# 并发下另一线程刚好插了同一 order_id(唯一索引挡住):再查一次并复用
existing = _find_active_rental_id(conn, order_id)
if existing is not None:
print(f"[开锁] order_id={order_id} 并发重复,复用 rental_id={existing}")
return existing, False
raise
return int(cur.lastrowid), True
# ========== 订单路由(原样复制自 app.py.bak) ==========
@bp.route("/api/order/unlock", methods=["POST"])
@@ -669,45 +815,61 @@ def order_unlock():
now_beijing = dt.datetime.now(tz)
duration = get_user_rental_settings(user["id"])["rental_duration_minutes"]
end_time = now_beijing + dt.timedelta(minutes=duration)
start_str = now_beijing.strftime("%Y-%m-%d %H:%M:%S")
end_str = end_time.strftime("%Y-%m-%d %H:%M:%S")
conn = get_db()
cursor = conn.cursor()
try:
cursor.execute("""
INSERT INTO rentals (id, order_id, bike_code, email, user_id, start_time, end_time,
duration, expired, source)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 'unlock')
""", (int(order_id), order_id, code, user["email"], user["id"],
now_beijing.strftime("%Y-%m-%d %H:%M:%S"),
end_time.strftime("%Y-%m-%d %H:%M:%S"), duration))
rental_row_id = int(order_id)
except sqlite3.IntegrityError:
# rentals.id 可能被 reminder/sync 的自增行占用(序列漂移):改用自增 id,
# order_id 仍记录真实上游单号。用 lastrowid 当 rental_id,别把计时器挂到别人单上。
print(f"[开锁] rentals.id={order_id} 已被占用,改用自增 id")
cur2 = conn.execute("""
INSERT INTO rentals (order_id, bike_code, email, user_id, start_time, end_time,
duration, expired, source)
VALUES (?, ?, ?, ?, ?, ?, ?, 0, 'unlock')
""", (order_id, code, user["email"], user["id"],
now_beijing.strftime("%Y-%m-%d %H:%M:%S"),
end_time.strftime("%Y-%m-%d %H:%M:%S"), duration))
rental_row_id = cur2.lastrowid
conn.commit()
conn.close()
rental_row_id, created = _insert_unlock_rental(
conn, order_id=order_id, code=code, email=user["email"],
user_id=user["id"], start_time=start_str, end_time=end_str,
duration=duration)
conn.commit()
finally:
conn.close()
if created:
start_rental_timer(rental_id=int(rental_row_id), email=user["email"],
bike_code=code, duration_minutes=duration, user_id=user["id"])
_record_rental_start(int(rental_row_id), latitude, longitude)
else:
# 同一张单被重复开锁(双击/重放):复用已有行,不新建记录、不重挂计时器,
# 只把剩余时长按库里真实的 end_time 重排一次(幂等,不会叠加提醒)。
print(f"[开锁] order_id={order_id} 已有未结束记录 rental_id={rental_row_id},复用不新建")
try:
conn = get_db()
try:
row = conn.execute(
"SELECT end_time FROM rentals WHERE id = ?", (int(rental_row_id),)).fetchone()
finally:
conn.close()
remaining = _get_remaining_seconds(dict(row)) if row else 0
except Exception as exc:
print(f"[开锁] 复用记录读取剩余时长失败: {exc}")
remaining = 0
if remaining > 0:
start_rental_timer(rental_id=int(rental_row_id), email=user["email"],
bike_code=code, duration_minutes=remaining / 60,
user_id=user["id"])
start_rental_timer(rental_id=int(rental_row_id), email=user["email"],
bike_code=code, duration_minutes=duration, user_id=user["id"])
_record_rental_start(int(rental_row_id), latitude, longitude)
# 带上轮次预估:前端租车条要显示「共N轮 · 预计HH:MM还车」
row = get_db().execute(
"SELECT renewal_round, rounds_override, end_time FROM rentals WHERE id = ?",
(int(rental_row_id),)).fetchone()
conn = get_db()
try:
row = conn.execute(
"SELECT renewal_round, rounds_override, end_time FROM rentals WHERE id = ?",
(int(rental_row_id),)).fetchone()
finally:
conn.close()
summary = _rounds_summary(
dict(row) if row else {"order_id": str(order_id),
"end_time": end_time.strftime("%Y-%m-%d %H:%M:%S")},
"end_time": end_str},
user["id"])
return jsonify({"rtn_code": 0, "message": "开锁成功", "order_id": order_id,
"data": {**summary, "remaining": duration * 60}})
response = {"rtn_code": 0, "message": "开锁成功", "order_id": order_id,
"data": {**summary, "remaining": duration * 60}}
if not created:
response["message"] = "该订单已在计时中(已复用原订单,不会重复计时)"
response["reused"] = True
return jsonify(response)
else:
from wechat import friendly_upstream_message
raw_open_msg = open_result.get("message", "")
@@ -830,7 +992,9 @@ def order_return():
if not order_id:
return jsonify({"rtn_code": 400, "message": "缺少订单ID"})
if not latitude or not longitude:
# 显式判 None:0.0 是合法坐标(赤道/本初子午线;前端把 undefined 序列化成 0 时
# 也应当由上游/停车区判定去拒绝,而不是在这里被当成"没传")。
if latitude is None or longitude is None or latitude == "" or longitude == "":
return jsonify({"rtn_code": 400, "message": "缺少位置信息"})
conn = get_db()
@@ -1094,9 +1258,10 @@ def order_pay_with_card():
@bp.route("/api/rental/start", methods=["POST"])
def rental_start():
"""开始用车计时"""
print(f"[rental/start] Headers: {dict(request.headers)}")
# 注意:这里**不要**再打印 request.headers / user —— 请求头里带着
# `Authorization: Bearer <会话 token>`,打日志等于把 30 天有效的登录凭据写进
# stdout、journald、docker logs(BUG-05)。排障请用 request.path 与响应码。
user = get_current_user()
print(f"[rental/start] User: {user}")
if not user:
return jsonify({"rtn_code": 401, "message": "请先登录"})
+111 -12
View File
@@ -15,7 +15,12 @@ from wechat import request_with_user_auth
bp = Blueprint("share", __name__)
_shared_return_locks = {}
# 同一共享订单的还车请求串行化。key 来自请求体(客户端可控),所以这张表必须
# 有 TTL 与容量上限:老写法 setdefault 后永不 release,登录用户每次换一个
# order_id 就能在进程里留一把常驻锁(BUG-11)。
SHARE_LOCK_TTL_SECONDS = 600 # 空闲锁的保留时间
SHARE_LOCK_MAX_ENTRIES = 512 # 硬容量上限
_shared_return_locks = {} # key -> {"lock", "last_used", "holders"}
_shared_return_locks_guard = threading.Lock()
DEFAULT_DAILY_LIMIT = 3
@@ -23,6 +28,43 @@ DEFAULT_REQUIRE_CARD = 1
DEFAULT_CARD_MIN_TIMES = 1
def _prune_share_locks_locked(now):
"""回收空闲超过 TTL 的锁(调用方必须持有 _shared_return_locks_guard)。"""
for key, entry in list(_shared_return_locks.items()):
if entry["holders"]:
continue
if now - entry["last_used"] >= SHARE_LOCK_TTL_SECONDS:
_shared_return_locks.pop(key, None)
def _acquire_share_lock(key):
"""取(或建)该 key 的锁并登记占用;建不出来时返回 None(调用方按无锁执行)。"""
now = time.time()
with _shared_return_locks_guard:
_prune_share_locks_locked(now)
entry = _shared_return_locks.get(key)
if entry is None:
if len(_shared_return_locks) >= SHARE_LOCK_MAX_ENTRIES:
# 到上限:淘汰最久未用且没人持有的锁。都在用时宁可退化成无锁,
# 也不能让字典无限涨(无锁最多退化成并发重复还车,内存涨是永久的)。
idle = [(k, e) for k, e in _shared_return_locks.items() if not e["holders"]]
if not idle:
return None
oldest_key = min(idle, key=lambda kv: kv[1]["last_used"])[0]
_shared_return_locks.pop(oldest_key, None)
entry = {"lock": threading.Lock(), "last_used": now, "holders": 0}
_shared_return_locks[key] = entry
entry["holders"] += 1
entry["last_used"] = now
return entry
def _release_share_lock(entry):
with _shared_return_locks_guard:
entry["holders"] = max(0, entry["holders"] - 1)
entry["last_used"] = time.time()
def _partner_display(share_or_none, fallback_email):
return (share_or_none or {}).get("owner_remark") or fallback_email
@@ -33,13 +75,57 @@ def _serialize_shared_return(func):
def wrapped(*args, **kwargs):
data = request.get_json(silent=True) or {}
key = str(data.get("order_id") or data.get("rental_id") or "missing")
with _shared_return_locks_guard:
lock = _shared_return_locks.setdefault(key, threading.Lock())
with lock:
entry = _acquire_share_lock(key)
if entry is None:
# 锁表已满且没有可回收的空闲锁:退化为不加锁,绝不因此无限占内存
return func(*args, **kwargs)
with entry["lock"]:
try:
return func(*args, **kwargs)
finally:
_release_share_lock(entry)
return wrapped
def _last_bike_pos(bike_code):
"""该车最近一次采集坐标(GCJ02)。拿不到返回 None,不编造。"""
if not bike_code:
return None
try:
from timer import _bike_pos_from_history
return _bike_pos_from_history(bike_code)
except Exception as exc:
print(f"[共享] 查询 bike_history 失败: {exc}")
return None
def _campus_center():
"""校园中心(GCJ02),来自 campus.py 的配置常量;未配置返回 None。"""
try:
from campus import campus_center
return campus_center()
except Exception as exc:
print(f"[共享] 读取校园中心失败: {exc}")
return None
def _fallback_coord(bike_code):
"""坐标兜底链:该车最近采集点 → 校园中心;都没有返回 None。
绝不使用硬编码坐标:旧代码兜底的 (36.67, 116.98) 离校区约 20km,
会把还车终点、位置标签和里程统计全部写坏(BUG-17)。
"""
return _last_bike_pos(bike_code) or _campus_center()
def _has_coord(latitude, longitude) -> bool:
"""显式判缺失:0.0 是合法坐标,不能用 `not latitude`。"""
for value in (latitude, longitude):
if value is None or value == "":
return False
return True
def _beijing_now():
tz = dt.timezone(dt.timedelta(hours=8))
return dt.datetime.now(tz)
@@ -723,16 +809,22 @@ def shared_unlock():
return jsonify({"rtn_code": bike_result.get("rtn_code", 500),
"message": bike_result.get("message", "获取车辆信息失败")})
# 用实时地图坐标(+抖动)作下单起点:优先 /project/map 抓该车当前坐标
# 用实时地图坐标(+抖动)作下单起点:优先 /project/map 抓该车当前坐标,
# 其次车辆详情自带的坐标,再次该车最近一次 bike_history / 校园中心。
# 都拿不到就明确失败 —— 之前这里也写死了 (36.67, 116.98)(BUG-17 第二处)。
from routes.rental import _fetch_live_bike_coord, _near_coord
bd = bike_result.get("data") or {}
live = _fetch_live_bike_coord(owner_user_id, code, bd.get("type"))
if live:
latitude, longitude = _near_coord(live[0], live[1])
elif _has_coord(bd.get("latitude"), bd.get("longitude")):
latitude, longitude = _near_coord(bd.get("latitude"), bd.get("longitude"))
else:
latitude, longitude = _near_coord(
bd.get("latitude", 36.67), bd.get("longitude", 116.98)
)
fallback = _fallback_coord(code)
if not fallback:
return jsonify({"rtn_code": 400,
"message": "缺少定位,请回到地图页再开锁"})
latitude, longitude = _near_coord(fallback[0], fallback[1])
order_result = request_with_user_auth(
owner_user_id, "POST", "/record/order",
@@ -848,16 +940,23 @@ def share_return():
owner_user_id = rental["user_id"]
bike_code = rental["bike_code"]
if not latitude or not longitude:
latitude, longitude = 36.67, 116.98
# 真实还车(owner 凭据):checkLocation → 非还车点则就近停车点
from routes.rental import (_try_card_pay_auto, get_nearest_park_point,
to_upstream_coords)
from timer import _cancel_rental_timers
# 浏览器上报的是 WGS84,上游/停车区是 GCJ02,入口先统一转一次
latitude, longitude = to_upstream_coords(latitude, longitude)
# 坐标来源:请求坐标(浏览器 WGS84,入口统一转 GCJ02)→ 该车最近一次
# bike_history(已是 GCJ02,不能再转)→ 校园中心(GCJ02)。
# 三处都拿不到就明确失败,不再拿一个离校区 20km 的常量糊上去(BUG-17)。
if _has_coord(latitude, longitude):
latitude, longitude = to_upstream_coords(latitude, longitude)
else:
fallback = _fallback_coord(bike_code)
if not fallback:
return jsonify({"rtn_code": 400,
"message": "缺少定位,请回到地图页再还车"})
latitude, longitude = fallback
check_result = request_with_user_auth(
owner_user_id, "POST", "/record/checkLocation",