Files
xbcr/map_cache.py
T
zzy be016621c0 fix(批次E): 可信代理、地图快照失败不空白、SSE 硬超时、bike_history 去重
- routes/auth._client_ip:可信代理前缀可配(默认 127./::1/172./10./192.168.),
  容器/Docker 部署下所有客户端不再塌成同一个限流 key(原来 45 次/分钟
  变成全站共享,一两个人就能把所有人打成 429)
- map_cache:采集失败**不再覆盖上一份好数据**,只放租约并把过期时间后推一个窗口
  (一次抖动不该让全站地图空白 60 秒);同时去掉 published=False 时的同名递归
  (deadline 每次重置 → 竞争下无界重试)。从来没过好数据时才写错误 payload,
  保证窗口内返回值稳定
- /api/ring_progress SSE 加 180 秒硬超时(同步长连接占死 worker,-w 4 时
  4 个进度页即可打满站点)
- bike_history:迁移去重 + (bike_code, recorded_at) 唯一索引,采集改 INSERT OR IGNORE
  (多进程各写一份会让行数 ×N,污染 /api/history 统计)
- 测试同步更新:地图快照失败语义改为「保留上一份好数据」

测试:167 pytest + 32 node 全绿
2026-11-15 23:51:51 +08:00

218 lines
9.3 KiB
Python

"""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
)""")
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",
}}
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
WHERE bike_type=? AND lease_token=?""",
(payload, started, started + self.ttl, last_success,
bike_type, token))
conn.commit()
published = cursor.rowcount == 1
else:
# 采集失败的这一轮**不要覆盖上一份好数据**:只把租约放掉、
# 把过期时间往后推一个窗口(避免重试风暴),payload 保持原样。
# 只有「从来没有过好数据」时才写入错误 payload(保证窗口内返回值稳定)。
prev = conn.execute(
"SELECT payload FROM shared_map_snapshots WHERE bike_type=?",
(bike_type,)).fetchone()
if prev and prev["payload"]:
conn.execute("""UPDATE shared_map_snapshots SET expires_at=?, lease_token=NULL,
lease_until=0 WHERE bike_type=? AND lease_token=?""",
(started + self.ttl, 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
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 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 json.loads(row["payload"])
except Exception:
pass
return json.loads(payload)
# 没抢到发布权(租约被别人接管):直接读当前行,**不再递归调用 self.get**
# (原来同名递归 + deadline 每次重置,竞争下会无界重试)
if row and row["payload"]:
try:
return json.loads(row["payload"])
except Exception:
pass
return json.loads(payload)
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))
return {
"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"))