330 lines
13 KiB
Python
330 lines
13 KiB
Python
"""Tests for role split, scheduler leader locking, Redis WS Pub/Sub, and DB migrations."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
from contextlib import asynccontextmanager
|
|
import json
|
|
from pathlib import Path
|
|
|
|
from fastapi import FastAPI
|
|
import pytest
|
|
from sqlalchemy import create_engine, text
|
|
|
|
from app import main as main_module
|
|
from app import worker as worker_module
|
|
from app.core.config import settings
|
|
from app.core.websocket.manager import ConnectionManager
|
|
from app.db.migrations import (
|
|
ensure_baseline_stamped,
|
|
get_migration_status,
|
|
run_migrations,
|
|
stamp_migrations,
|
|
)
|
|
|
|
|
|
class _AsyncSQLiteConnAdapter:
|
|
def __init__(self, conn):
|
|
self._conn = conn
|
|
self.dialect = conn.dialect
|
|
|
|
async def execute(self, statement, params=None):
|
|
if params is not None:
|
|
return self._conn.execute(statement, params)
|
|
return self._conn.execute(statement)
|
|
|
|
async def run_sync(self, fn):
|
|
return fn(self._conn)
|
|
|
|
|
|
class _AsyncSQLiteEngineAdapter:
|
|
def __init__(self, sync_engine):
|
|
self._engine = sync_engine
|
|
|
|
@asynccontextmanager
|
|
async def begin(self):
|
|
with self._engine.begin() as conn:
|
|
yield _AsyncSQLiteConnAdapter(conn)
|
|
|
|
|
|
class _FakeWebSocket:
|
|
def __init__(self):
|
|
self.accepted = False
|
|
self.sent = []
|
|
self.closed = False
|
|
|
|
async def accept(self):
|
|
self.accepted = True
|
|
|
|
async def send_json(self, message):
|
|
self.sent.append(message)
|
|
|
|
async def close(self):
|
|
self.closed = True
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_lifespan_respects_planet_role_and_leader_lock(monkeypatch):
|
|
calls: list[str] = []
|
|
|
|
async def noop_async(*_args, **_kwargs):
|
|
return None
|
|
|
|
async def true_lock():
|
|
calls.append("acquire_lock")
|
|
return True
|
|
|
|
async def false_lock():
|
|
calls.append("acquire_lock_denied")
|
|
return False
|
|
|
|
monkeypatch.setattr(main_module, "init_db", noop_async)
|
|
monkeypatch.setattr(main_module, "cleanup_stale_running_tasks", lambda: noop_async())
|
|
monkeypatch.setattr(main_module, "sync_scheduler_with_datasources", lambda: noop_async())
|
|
monkeypatch.setattr(main_module, "release_scheduler_leader_lock", lambda: noop_async())
|
|
monkeypatch.setattr(main_module, "start_scheduler", lambda: calls.append("start_scheduler"))
|
|
monkeypatch.setattr(main_module, "stop_scheduler", lambda: calls.append("stop_scheduler"))
|
|
monkeypatch.setattr(main_module, "start_data_job_worker", lambda: calls.append("start_jobs"))
|
|
monkeypatch.setattr(main_module, "stop_data_job_worker", lambda: noop_async())
|
|
monkeypatch.setattr(main_module, "start_earth_news_target_worker", lambda: calls.append("start_news"))
|
|
monkeypatch.setattr(main_module, "stop_earth_news_target_worker", lambda: noop_async())
|
|
monkeypatch.setattr(main_module, "start_earth_db_change_listener", lambda: calls.append("start_db_listener"))
|
|
monkeypatch.setattr(main_module, "stop_earth_db_change_listener", lambda: noop_async())
|
|
monkeypatch.setattr(main_module.broadcaster, "start", lambda: calls.append("start_broadcaster"))
|
|
monkeypatch.setattr(main_module.broadcaster, "stop", lambda: calls.append("stop_broadcaster"))
|
|
monkeypatch.setattr(main_module.manager, "start_pubsub", lambda **_kwargs: noop_async())
|
|
monkeypatch.setattr(main_module.manager, "stop_pubsub", lambda: noop_async())
|
|
|
|
# Role=api must not start scheduler or background workers.
|
|
monkeypatch.setattr(settings, "PLANET_ROLE", "api")
|
|
monkeypatch.setattr(settings, "ENABLE_SCHEDULER", None)
|
|
monkeypatch.setattr(main_module, "acquire_scheduler_leader_lock", true_lock)
|
|
calls.clear()
|
|
async with main_module.lifespan(FastAPI()):
|
|
pass
|
|
assert "start_scheduler" not in calls
|
|
assert "start_jobs" not in calls
|
|
assert "start_news" not in calls
|
|
assert "start_broadcaster" in calls
|
|
|
|
# Role=all with leader lock denied skips scheduler start cleanly.
|
|
monkeypatch.setattr(settings, "PLANET_ROLE", "all")
|
|
monkeypatch.setattr(main_module, "acquire_scheduler_leader_lock", false_lock)
|
|
calls.clear()
|
|
async with main_module.lifespan(FastAPI()):
|
|
pass
|
|
assert "acquire_lock_denied" in calls
|
|
assert "start_scheduler" not in calls
|
|
assert "start_jobs" in calls
|
|
|
|
# Role=all with leader lock acquired starts scheduler and workers.
|
|
monkeypatch.setattr(main_module, "acquire_scheduler_leader_lock", true_lock)
|
|
calls.clear()
|
|
async with main_module.lifespan(FastAPI()):
|
|
pass
|
|
assert "acquire_lock" in calls
|
|
assert "start_scheduler" in calls
|
|
assert "stop_scheduler" in calls
|
|
assert "start_jobs" in calls
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_standalone_worker_starts_scheduler_workers_and_releases_lock(monkeypatch):
|
|
events: list[str] = []
|
|
|
|
async def noop_async(*_args, **_kwargs):
|
|
return None
|
|
|
|
async def acquire_lock():
|
|
events.append("lock_acquired")
|
|
return True
|
|
|
|
async def release_lock():
|
|
events.append("lock_released")
|
|
|
|
async def fake_start_pubsub(*, publish_only: bool = False):
|
|
events.append(f"pubsub:{publish_only}")
|
|
|
|
monkeypatch.setattr(worker_module, "init_db", noop_async)
|
|
monkeypatch.setattr(worker_module, "cleanup_stale_running_tasks", noop_async)
|
|
monkeypatch.setattr(worker_module, "sync_scheduler_with_datasources", noop_async)
|
|
monkeypatch.setattr(worker_module, "acquire_scheduler_leader_lock", acquire_lock)
|
|
monkeypatch.setattr(worker_module, "release_scheduler_leader_lock", release_lock)
|
|
monkeypatch.setattr(worker_module, "start_scheduler", lambda: events.append("scheduler_started"))
|
|
monkeypatch.setattr(worker_module, "stop_scheduler", lambda: events.append("scheduler_stopped"))
|
|
monkeypatch.setattr(worker_module, "start_data_job_worker", lambda: events.append("jobs_started"))
|
|
monkeypatch.setattr(worker_module, "stop_data_job_worker", noop_async)
|
|
monkeypatch.setattr(worker_module, "start_earth_news_target_worker", lambda: events.append("news_started"))
|
|
monkeypatch.setattr(worker_module, "stop_earth_news_target_worker", noop_async)
|
|
monkeypatch.setattr(worker_module.broadcaster, "start", lambda: events.append("broadcaster_started"))
|
|
monkeypatch.setattr(worker_module.broadcaster, "stop", lambda: events.append("broadcaster_stopped"))
|
|
monkeypatch.setattr(worker_module.manager, "start_pubsub", fake_start_pubsub)
|
|
monkeypatch.setattr(worker_module.manager, "stop_pubsub", noop_async)
|
|
monkeypatch.setattr(settings, "PLANET_ROLE", "worker")
|
|
monkeypatch.setattr(settings, "ENABLE_SCHEDULER", None)
|
|
|
|
stop_event = asyncio.Event()
|
|
task = asyncio.create_task(worker_module.run_worker(stop_event))
|
|
await asyncio.sleep(0.05)
|
|
stop_event.set()
|
|
await task
|
|
|
|
assert "pubsub:True" in events
|
|
assert "lock_acquired" in events
|
|
assert "scheduler_started" in events
|
|
assert "jobs_started" in events
|
|
assert "scheduler_stopped" in events
|
|
assert "lock_released" in events
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_worker_releases_leader_lock_when_startup_fails(monkeypatch):
|
|
events: list[str] = []
|
|
|
|
async def noop_async(*_args, **_kwargs):
|
|
return None
|
|
|
|
async def acquire_lock():
|
|
events.append("lock_acquired")
|
|
return True
|
|
|
|
async def release_lock():
|
|
events.append("lock_released")
|
|
|
|
async def failing_sync():
|
|
raise RuntimeError("scheduler sync failed")
|
|
|
|
async def fake_stop_pubsub():
|
|
events.append("pubsub_stopped")
|
|
|
|
monkeypatch.setattr(worker_module, "init_db", noop_async)
|
|
monkeypatch.setattr(worker_module, "cleanup_stale_running_tasks", noop_async)
|
|
monkeypatch.setattr(worker_module, "sync_scheduler_with_datasources", failing_sync)
|
|
monkeypatch.setattr(worker_module, "acquire_scheduler_leader_lock", acquire_lock)
|
|
monkeypatch.setattr(worker_module, "release_scheduler_leader_lock", release_lock)
|
|
monkeypatch.setattr(worker_module, "start_scheduler", lambda: events.append("scheduler_started"))
|
|
monkeypatch.setattr(worker_module, "stop_scheduler", lambda: events.append("scheduler_stopped"))
|
|
monkeypatch.setattr(worker_module.manager, "start_pubsub", noop_async)
|
|
monkeypatch.setattr(worker_module.manager, "stop_pubsub", fake_stop_pubsub)
|
|
monkeypatch.setattr(settings, "PLANET_ROLE", "worker")
|
|
monkeypatch.setattr(settings, "ENABLE_SCHEDULER", None)
|
|
|
|
with pytest.raises(RuntimeError, match="scheduler sync failed"):
|
|
await worker_module.run_worker(asyncio.Event())
|
|
|
|
assert events == [
|
|
"lock_acquired",
|
|
"scheduler_started",
|
|
"scheduler_stopped",
|
|
"lock_released",
|
|
"pubsub_stopped",
|
|
]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_connection_manager_redis_pubsub_relay_and_self_echo_suppression():
|
|
manager_a = ConnectionManager()
|
|
manager_b = ConnectionManager()
|
|
published: list[str] = []
|
|
|
|
class FakePubSubRedis:
|
|
async def publish(self, _channel, payload):
|
|
published.append(payload)
|
|
|
|
async def aclose(self):
|
|
return None
|
|
|
|
manager_a._pubsub_enabled = True
|
|
manager_a._pubsub_client = FakePubSubRedis()
|
|
|
|
sock_a = _FakeWebSocket()
|
|
sock_b = _FakeWebSocket()
|
|
sock_vessel_b = _FakeWebSocket()
|
|
|
|
await manager_a.connect(sock_a, "u-a")
|
|
await manager_b.connect(sock_b, "u-b")
|
|
await manager_b.connect(sock_vessel_b, "u-v")
|
|
manager_a.subscribe(sock_a, ["earth_updates"])
|
|
manager_b.subscribe(sock_b, ["earth_updates"])
|
|
manager_b.subscribe_vessels(sock_vessel_b, {"scope": "global", "zoom": 4})
|
|
|
|
frame = {"type": "data_frame", "channel": "earth_updates", "payload": {"layers": ["cables"]}}
|
|
await manager_a.broadcast(frame, channel="earth_updates")
|
|
await manager_a.broadcast_vessels({"vessels": [{"mmsi": 999, "lat": 10.0, "lon": 20.0}]})
|
|
|
|
assert len(published) == 2
|
|
assert len(sock_a.sent) == 1
|
|
|
|
# Self-origin replay must be ignored on manager_a, delivered cleanly on manager_b.
|
|
for raw in published:
|
|
assert await manager_a.handle_pubsub_payload(raw) is False
|
|
assert await manager_b.handle_pubsub_payload(raw) is True
|
|
|
|
assert len(sock_a.sent) == 1
|
|
assert sock_b.sent == [frame]
|
|
assert sock_vessel_b.sent[0]["payload"]["vessels"] == [{"mmsi": 999, "lat": 10.0, "lon": 20.0}]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_versioned_migrations_upgrade_stamp_and_checksum_validation(tmp_path: Path):
|
|
steps_dir = tmp_path / "steps"
|
|
steps_dir.mkdir()
|
|
m1 = steps_dir / "0001_initial_notes.py"
|
|
m1.write_text(
|
|
"from sqlalchemy import text\n"
|
|
"VERSION = '0001'\n"
|
|
"NAME = 'initial_notes'\n"
|
|
"async def upgrade(conn):\n"
|
|
" await conn.execute(text('CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY)'))\n",
|
|
encoding="utf-8",
|
|
)
|
|
|
|
sync_engine = create_engine("sqlite://")
|
|
adapter = _AsyncSQLiteEngineAdapter(sync_engine)
|
|
|
|
status_before = await get_migration_status(adapter, steps_dir)
|
|
assert status_before["applied"] == []
|
|
assert status_before["pending"] == ["0001"]
|
|
|
|
applied = await run_migrations(adapter, steps_dir)
|
|
assert applied == ["0001"]
|
|
with sync_engine.connect() as conn:
|
|
assert conn.execute(text("SELECT COUNT(*) FROM notes")).scalar() == 0
|
|
|
|
m2 = steps_dir / "0002_add_body.py"
|
|
m2.write_text(
|
|
"from sqlalchemy import text\n"
|
|
"VERSION = '0002'\n"
|
|
"NAME = 'add_body'\n"
|
|
"async def upgrade(conn):\n"
|
|
" await conn.execute(text('ALTER TABLE notes ADD COLUMN body TEXT'))\n",
|
|
encoding="utf-8",
|
|
)
|
|
status_mid = await get_migration_status(adapter, steps_dir)
|
|
assert status_mid["pending"] == ["0002"]
|
|
|
|
applied_second = await run_migrations(adapter, steps_dir)
|
|
assert applied_second == ["0002"]
|
|
|
|
# Mutating an applied migration file triggers checksum mismatch detection.
|
|
m1.write_text(m1.read_text(encoding="utf-8") + "\n# tampered\n", encoding="utf-8")
|
|
status_tampered = await get_migration_status(adapter, steps_dir)
|
|
assert len(status_tampered["mismatches"]) == 1
|
|
with pytest.raises(RuntimeError, match="Checksum mismatch"):
|
|
await run_migrations(adapter, steps_dir)
|
|
|
|
# Verify ensure_baseline_stamped & stamp_migrations on a fresh DB.
|
|
sync_engine2 = create_engine("sqlite://")
|
|
adapter2 = _AsyncSQLiteEngineAdapter(sync_engine2)
|
|
async with adapter2.begin() as conn:
|
|
stamped_first = await ensure_baseline_stamped(conn, steps_dir)
|
|
assert stamped_first is True
|
|
stamped_rest = await stamp_migrations(adapter2, "0002", steps_dir)
|
|
assert stamped_rest == ["0002"]
|
|
final_status = await get_migration_status(adapter2, steps_dir)
|
|
assert final_status["applied"] == ["0001", "0002"]
|
|
assert final_status["pending"] == []
|
|
|
|
sync_engine.dispose()
|
|
sync_engine2.dispose()
|