forked from linkong/planet
141 lines
5.2 KiB
Python
141 lines
5.2 KiB
Python
from __future__ import annotations
|
|
|
|
from datetime import UTC, datetime
|
|
|
|
import pytest
|
|
|
|
from app.services import earth_db_change_listener as listener_module
|
|
from app.services.earth_db_change_listener import EarthDbChangeDispatcher, EarthDbChangeListener
|
|
from app.services.earth_outbox_maintenance import (
|
|
DELETE_BATCH_SQL,
|
|
compact_consumed_events,
|
|
ensure_retention_index,
|
|
purge_consumed_events,
|
|
)
|
|
|
|
|
|
class FakeConnection:
|
|
def __init__(self, *, index_state: str = "ready", batch_counts: list[int] | None = None):
|
|
self.index_state = index_state
|
|
self.batch_counts = list(batch_counts or [])
|
|
self.calls: list[tuple[str, tuple[object, ...]]] = []
|
|
self.retained = {"total": 13, "pending": 3}
|
|
self.restored = dict(self.retained)
|
|
self.rolled_back = False
|
|
|
|
async def fetchrow(self, query: str, *args: object):
|
|
self.calls.append((query, args))
|
|
if "pg_index" in query:
|
|
if self.index_state == "missing":
|
|
return None
|
|
return {"indisvalid": self.index_state == "ready", "indisready": True}
|
|
if "FROM earth_outbox_retained" in query:
|
|
return self.retained
|
|
return self.restored
|
|
|
|
async def fetchval(self, query: str, *args: object):
|
|
self.calls.append((query, args))
|
|
if query == DELETE_BATCH_SQL:
|
|
return self.batch_counts.pop(0)
|
|
return True
|
|
|
|
async def execute(self, query: str, *args: object):
|
|
self.calls.append((query, args))
|
|
if "CREATE INDEX CONCURRENTLY" in query:
|
|
self.index_state = "ready"
|
|
return "OK"
|
|
|
|
def transaction(self):
|
|
connection = self
|
|
|
|
class Transaction:
|
|
async def __aenter__(self):
|
|
return self
|
|
|
|
async def __aexit__(self, exc_type, _exc, _traceback):
|
|
connection.rolled_back = exc_type is not None
|
|
|
|
return Transaction()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_retention_skips_without_index():
|
|
conn = FakeConnection(index_state="missing")
|
|
assert await purge_consumed_events(conn, retention_days=1) == 0
|
|
assert not any(query == DELETE_BATCH_SQL for query, _ in conn.calls)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_retention_batches_only_consumed_old_rows():
|
|
conn = FakeConnection(batch_counts=[1000, 19])
|
|
deleted = await purge_consumed_events(
|
|
conn, retention_days=1, batch_size=1000, max_batches=10, pause_seconds=0
|
|
)
|
|
assert deleted == 1019
|
|
calls = [args for query, args in conn.calls if query == DELETE_BATCH_SQL]
|
|
assert len(calls) == 2
|
|
assert all(isinstance(args[0], datetime) and args[0].tzinfo is UTC for args in calls)
|
|
assert "consumed_at IS NOT NULL AND consumed_at < $1" in DELETE_BATCH_SQL
|
|
assert "FOR UPDATE SKIP LOCKED" in DELETE_BATCH_SQL
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_index_creation_is_concurrent_and_repairs_invalid_index():
|
|
conn = FakeConnection(index_state="invalid")
|
|
await ensure_retention_index(conn)
|
|
statements = [query for query, _ in conn.calls]
|
|
assert any("DROP INDEX CONCURRENTLY" in query for query in statements)
|
|
assert any("CREATE INDEX CONCURRENTLY" in query for query in statements)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_compact_retains_pending_and_recent_consumed_in_one_transaction():
|
|
conn = FakeConnection()
|
|
assert await compact_consumed_events(conn, retention_days=1) == (13, 3)
|
|
statements = [query for query, _ in conn.calls]
|
|
assert next(i for i, query in enumerate(statements) if query.startswith("LOCK TABLE")) < next(
|
|
i for i, query in enumerate(statements) if query.startswith("TRUNCATE TABLE")
|
|
)
|
|
assert any("consumed_at IS NULL OR consumed_at >= $1" in query for query in statements)
|
|
assert "TRUNCATE TABLE earth_data_change_events CONTINUE IDENTITY RESTRICT" in statements
|
|
assert not conn.rolled_back
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_compact_verification_failure_rolls_back():
|
|
conn = FakeConnection()
|
|
conn.restored = {"total": 12, "pending": 2}
|
|
with pytest.raises(RuntimeError, match="verification failed"):
|
|
await compact_consumed_events(conn, retention_days=1)
|
|
assert conn.rolled_back
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_listener_runs_retention_at_most_once_per_interval(monkeypatch):
|
|
calls: list[str] = []
|
|
|
|
async def acquire(_conn):
|
|
calls.append("acquire")
|
|
return True
|
|
|
|
async def purge(_conn, *, retention_days):
|
|
assert retention_days == 1
|
|
calls.append("purge")
|
|
|
|
async def release(_conn):
|
|
calls.append("release")
|
|
|
|
monkeypatch.setattr(listener_module, "monotonic", lambda: 100.0)
|
|
monkeypatch.setattr(listener_module, "try_maintenance_lock", acquire)
|
|
monkeypatch.setattr(listener_module, "purge_consumed_events", purge)
|
|
monkeypatch.setattr(listener_module, "release_maintenance_lock", release)
|
|
monkeypatch.setattr(listener_module, "configured_retention_days", lambda: 1)
|
|
dispatcher = EarthDbChangeDispatcher(broadcast_earth_update=lambda _: None)
|
|
listener = EarthDbChangeListener(dsn="postgresql://example/db", dispatcher=dispatcher)
|
|
listener._connection = FakeConnection()
|
|
|
|
await listener._maybe_purge_outbox()
|
|
await listener._maybe_purge_outbox()
|
|
|
|
assert calls == ["acquire", "purge", "release"]
|