Files
xbcr/map_cache.py
T
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

260 lines
12 KiB
Python
Raw 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.
"""One shared, at-most-60-second map snapshot per bicycle type.
SQLite leases coalesce requests across threads and worker processes without
holding a database transaction open during the upstream network request.
"""
import datetime as dt
import json
import sqlite3
import time
import uuid
from pathlib import Path
MAP_TTL_SECONDS = 60
MAP_TYPES = frozenset({"1", "3", "6"})
class SharedMapCache:
def __init__(self, path, *, ttl=MAP_TTL_SECONDS, lease_seconds=20,
wait_timeout=12, clock=None):
self.path = Path(path)
self.ttl = ttl
self.lease_seconds = lease_seconds
self.wait_timeout = wait_timeout
self.clock = clock or time.time
def _connect(self):
deadline = time.monotonic() + 5
while True:
conn = sqlite3.connect(str(self.path), timeout=5)
try:
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA busy_timeout=5000")
if conn.execute("PRAGMA journal_mode").fetchone()[0] != "wal":
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("""CREATE TABLE IF NOT EXISTS shared_map_snapshots (
bike_type TEXT PRIMARY KEY,
payload TEXT,
fetched_at REAL,
expires_at REAL NOT NULL DEFAULT 0,
last_success_at REAL,
lease_token TEXT,
lease_until REAL NOT NULL DEFAULT 0,
stale INTEGER NOT NULL DEFAULT 0,
stale_since REAL
)""")
# 老库补列(幂等):stale=这份 payload 是否来自失败前的好数据
for col, decl in (("stale", "INTEGER NOT NULL DEFAULT 0"), ("stale_since", "REAL")):
try:
conn.execute(f"SELECT {col} FROM shared_map_snapshots LIMIT 0")
except sqlite3.OperationalError:
conn.execute(f"ALTER TABLE shared_map_snapshots ADD COLUMN {col} {decl}")
return conn
except sqlite3.OperationalError as error:
conn.close()
# Concurrent first connections can race when switching to WAL.
if "locked" not in str(error).lower() or time.monotonic() >= deadline:
raise
time.sleep(0.01)
except BaseException:
conn.close()
raise
@staticmethod
def _cached(row, now):
if row and row["payload"] and row["fetched_at"] <= now < row["expires_at"]:
try:
return json.loads(row["payload"])
except (TypeError, ValueError):
pass
return None
@staticmethod
def _pending():
return {"rtn_code": 503, "message": "地图数据正在更新,请稍后重试", "retry_after": 2}
def get(self, bike_type, loader):
bike_type = str(bike_type).strip()
if bike_type not in MAP_TYPES:
return {"rtn_code": 400, "message": "不支持的车辆类型"}
deadline = time.monotonic() + self.wait_timeout
token = uuid.uuid4().hex
started = None
last_success = None
while started is None:
now = self.clock()
conn = self._connect()
try:
row = conn.execute("SELECT * FROM shared_map_snapshots WHERE bike_type=?", (bike_type,)).fetchone()
cached = self._cached(row, now)
if cached is not None:
return cached
if not row or row["lease_until"] <= now:
# Another worker may have refreshed between the read and lock.
conn.execute("BEGIN IMMEDIATE")
row = conn.execute("SELECT * FROM shared_map_snapshots WHERE bike_type=?", (bike_type,)).fetchone()
now = self.clock()
cached = self._cached(row, now)
if cached is not None:
return cached
if not row or row["lease_until"] <= now:
last_success = row["last_success_at"] if row else None
conn.execute("""INSERT INTO shared_map_snapshots (bike_type, lease_token, lease_until)
VALUES (?, ?, ?) ON CONFLICT(bike_type) DO UPDATE SET
lease_token=excluded.lease_token, lease_until=excluded.lease_until""",
(bike_type, token, now + self.lease_seconds))
conn.commit()
started = now
finally:
conn.close()
if started is None:
if time.monotonic() >= deadline:
return self._pending()
time.sleep(0.05)
try:
result = loader()
if not isinstance(result, dict):
raise ValueError("invalid map response")
if result.get("rtn_code") == 0 and (
not isinstance(result.get("data"), dict)
or not isinstance(result["data"].get("bicycleStation"), list)
):
raise ValueError("invalid map payload")
except Exception:
result = {"rtn_code": -1, "message": "地图数据更新失败,请稍后重试"}
success = result.get("rtn_code") == 0
if success:
last_success = started
result = {**result, "map_snapshot": {
"snapshot_id": token,
"fetched_at": last_success,
"expires_at": started + self.ttl,
"ttl_seconds": self.ttl,
"status": "fresh" if success else "error",
"stale": 0,
"stale_since": None,
}}
payload = json.dumps(result, ensure_ascii=False, separators=(",", ":"))
conn = self._connect()
try:
if success:
cursor = conn.execute("""UPDATE shared_map_snapshots SET
payload=?, fetched_at=?, expires_at=?, last_success_at=?, lease_token=NULL, lease_until=0,
stale=0, stale_since=NULL
WHERE bike_type=? AND lease_token=?""",
(payload, started, started + self.ttl, last_success,
bike_type, token))
conn.commit()
published = cursor.rowcount == 1
else:
# 采集失败的这一轮**不要覆盖上一份好数据**:只把租约放掉、
# 把过期时间往后推一个窗口(避免重试风暴),payload 保持原样
# (fetched_at 仍是上次成功时间),但打上 stale 标记让前端/巡检
# 能看出「这是失败前的旧数据」。只有「从来没有过好数据」时才写入错误 payload。
prev = conn.execute(
"SELECT payload, stale_since FROM shared_map_snapshots WHERE bike_type=?",
(bike_type,)).fetchone()
if prev and prev["payload"]:
# 第一次变 stale 时记下时间;已经是 stale 就沿用
stale_since = prev["stale_since"] if prev["stale_since"] else started
try:
prev_result = json.loads(prev["payload"])
except (TypeError, ValueError):
prev_result = None
if isinstance(prev_result, dict):
snap = dict(prev_result.get("map_snapshot") or {})
snap.update({"expires_at": started + self.ttl, "status": "stale",
"stale": 1, "stale_since": stale_since})
prev_result["map_snapshot"] = snap
conn.execute("""UPDATE shared_map_snapshots SET payload=?, expires_at=?, lease_token=NULL,
lease_until=0, stale=1, stale_since=? WHERE bike_type=? AND lease_token=?""",
(json.dumps(prev_result, ensure_ascii=False, separators=(",", ":")),
started + self.ttl, stale_since, bike_type, token))
else:
conn.execute("""UPDATE shared_map_snapshots SET expires_at=?, lease_token=NULL,
lease_until=0, stale=1, stale_since=? WHERE bike_type=? AND lease_token=?""",
(started + self.ttl, stale_since, bike_type, token))
published = False
else:
conn.execute("""UPDATE shared_map_snapshots SET payload=?, fetched_at=?,
expires_at=?, last_success_at=?, lease_token=NULL, lease_until=0,
stale=0, stale_since=NULL
WHERE bike_type=? AND lease_token=?""",
(payload, started, started + self.ttl, last_success,
bike_type, token))
published = True
conn.commit()
row = conn.execute("SELECT payload, stale, stale_since FROM shared_map_snapshots WHERE bike_type=?",
(bike_type,)).fetchone()
finally:
conn.close()
if success and published:
return json.loads(payload)
if published:
# 失败但已放租约:把当前行(通常是上一份好数据)返回给前端
if row and row["payload"]:
try:
return self._with_stale(json.loads(row["payload"]), row)
except Exception:
pass
return json.loads(payload)
# 没抢到发布权(租约被别人接管):直接读当前行,**不再递归调用 self.get**
# (原来同名递归 + deadline 每次重置,竞争下会无界重试)
if row and row["payload"]:
try:
return self._with_stale(json.loads(row["payload"]), row)
except Exception:
pass
return json.loads(payload)
@staticmethod
def _with_stale(result, row):
"""把行上的 stale / stale_since 列同步进 map_snapshot(payload 与列保持一致)。"""
if isinstance(result, dict) and row is not None:
snap = dict(result.get("map_snapshot") or {})
snap["stale"] = int(row["stale"] or 0)
snap["stale_since"] = row["stale_since"]
result["map_snapshot"] = snap
return result
def freshness(self, bike_type="3"):
conn = self._connect()
try:
row = conn.execute("SELECT * FROM shared_map_snapshots WHERE bike_type=?", (str(bike_type),)).fetchone()
finally:
conn.close()
if not row or not row["payload"]:
return None
try:
result = json.loads(row["payload"])
except (TypeError, ValueError):
return None
stamp = row["last_success_at"]
now = self.clock()
tz = dt.timezone(dt.timedelta(hours=8))
stale = int(row["stale"] or 0) if "stale" in row.keys() else 0
return {
"stale": stale,
"stale_since": row["stale_since"] if "stale_since" in row.keys() else None,
"latest": dt.datetime.fromtimestamp(stamp, tz).strftime("%Y-%m-%d %H:%M:%S") if stamp is not None else None,
"fetched_at": stamp,
"stale_seconds": max(0, int(now - stamp)) if stamp is not None else None,
"expires_at": row["expires_at"],
"snapshot_id": result.get("map_snapshot", {}).get("snapshot_id"),
"status": "fresh" if result.get("rtn_code") == 0 and row["expires_at"] > now else "stale",
"interval_hint": "全用户共享 60 秒地图快照",
}
def clear(self):
conn = self._connect()
try:
conn.execute("DELETE FROM shared_map_snapshots")
conn.commit()
finally:
conn.close()
shared_map_cache = SharedMapCache(Path(__file__).with_name("map_cache.db"))