diff --git a/app.py b/app.py index 0ebc460..644c5c5 100644 --- a/app.py +++ b/app.py @@ -170,7 +170,7 @@ def snapshot_bike_positions(): for bike in bikes: try: cursor.execute(""" - INSERT INTO bike_history + INSERT OR IGNORE INTO bike_history (bike_code, latitude, longitude, status, state, electric, recorded_at) VALUES (?, ?, ?, ?, ?, ?, datetime('now', '+8 hours')) """, ( diff --git a/db.py b/db.py index 70bacfc..6f4b785 100644 --- a/db.py +++ b/db.py @@ -276,6 +276,24 @@ def init_db(): ) """) + # 多进程/多实例采集会重复写同一秒的位置:先去重再建唯一索引, + # 让 INSERT OR IGNORE 把重复写入挡掉,避免行数 ×N 污染 /api/history 统计。 + try: + cursor.execute(""" + DELETE FROM bike_history + WHERE id NOT IN ( + SELECT MIN(id) FROM bike_history GROUP BY bike_code, recorded_at + ) + """) + if cursor.rowcount: + print(f"[迁移] bike_history 去重 {cursor.rowcount} 行") + cursor.execute(""" + CREATE UNIQUE INDEX IF NOT EXISTS idx_bike_history_code_time + ON bike_history (bike_code, recorded_at) + """) + except sqlite3.OperationalError as exc: + print(f"[迁移] bike_history 唯一索引创建失败(忽略): {exc}") + for col_def in [("state", "INTEGER DEFAULT 1"), ("electric", "REAL DEFAULT 100")]: try: cursor.execute(f"ALTER TABLE bike_history ADD COLUMN {col_def[0]} {col_def[1]}") diff --git a/map_cache.py b/map_cache.py index 44fd0ab..38b63bf 100644 --- a/map_cache.py +++ b/map_cache.py @@ -118,7 +118,6 @@ class SharedMapCache: success = result.get("rtn_code") == 0 if success: last_success = started - # Store errors for the same window too, preventing an outage retry storm. result = {**result, "map_snapshot": { "snapshot_id": token, "fetched_at": last_success, @@ -129,16 +128,57 @@ class SharedMapCache: payload = json.dumps(result, ensure_ascii=False, separators=(",", ":")) conn = self._connect() try: - 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 + 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() - # An expired lease holder must never publish over a newer worker's snapshot. - return json.loads(payload) if published else self.get(bike_type, loader) + + 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() diff --git a/routes/auth.py b/routes/auth.py index d40cb21..d3abf94 100644 --- a/routes/auth.py +++ b/routes/auth.py @@ -37,7 +37,19 @@ def _client_ip() -> str: - 其余来源(含内网直连)一律使用 remote_addr, 防止局域网/直连客户端伪造 X-Real-IP 绕过限流与登录锁定。""" remote = request.remote_addr or "" - if remote in ("127.0.0.1", "::1"): + # 可信代理:默认回环 + 常见容器网段(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() + ) + 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 real: return real diff --git a/routes/map_api.py b/routes/map_api.py index 21a36c8..07ba902 100644 --- a/routes/map_api.py +++ b/routes/map_api.py @@ -143,13 +143,22 @@ def api_ring_cancel(task_id): def api_ring_progress(task_id): from flask import Response as FlaskResponse global ring_tasks + RING_SSE_MAX_SECONDS = 180 # 单个进度 SSE 最长占用时间 + def _sse(obj): return f"data: {json.dumps(obj, ensure_ascii=False)}\n\n" + def generate(): last_done = -1 last_status = None tick = 0 + # 硬超时:SSE 是同步长连接,一个连接占死一个 worker。任务卡住时 + # 不设上限的话(-w 4 只要 4 个进度页)整站会被打满。 + deadline = time.time() + RING_SSE_MAX_SECONDS while True: + if time.time() > deadline: + yield _sse({"type": "error", "message": "进度推送超时,请刷新页面查看结果"}) + return with _ring_lock: task = ring_tasks.get(task_id) if not task: diff --git a/tests/test_map_cache.py b/tests/test_map_cache.py index 8074f18..54d815c 100644 --- a/tests/test_map_cache.py +++ b/tests/test_map_cache.py @@ -63,19 +63,18 @@ class SharedMapCacheTests(unittest.TestCase): self.assertEqual(1, len(calls)) self.assertTrue(all(result == results[0] for result in results)) - def test_errors_share_the_window_and_never_resurrect_expired_success(self): + def test_failure_keeps_last_good_snapshot_instead_of_blanking_the_map(self): + """采集失败不覆盖上一份好数据:一次抖动不该让全站地图空白 60 秒。""" loader = Mock(side_effect=[success(1), {"rtn_code": -1, "message": "offline"}, success(2)]) - self.cache.get("3", loader) + first = self.cache.get("3", loader) + self.assertEqual(1, first["data"]["bicycleStation"][0]["version"]) self.now = 1060 failure = self.cache.get("3", loader) - self.assertEqual(-1, failure["rtn_code"]) - self.assertNotIn("data", failure) - self.assertEqual("error", failure["map_snapshot"]["status"]) - self.assertEqual(1000, failure["map_snapshot"]["fetched_at"]) - for _ in range(10): + self.assertEqual(0, failure["rtn_code"]) # 仍是好数据 + self.assertEqual(1, failure["data"]["bicycleStation"][0]["version"]) + for _ in range(10): # 窗口内返回值稳定 self.assertEqual(failure, self.cache.get("3", loader)) - self.assertEqual(2, loader.call_count) - self.assertEqual("stale", self.cache.freshness()["status"]) + self.assertEqual(2, loader.call_count) # 失败也占住窗口,不打重试风暴 self.now = 1120 self.assertEqual(2, self.cache.get("3", loader)["data"]["bicycleStation"][0]["version"])