Files
planet/backend/tests/test_earth_news_refresh.py

526 lines
19 KiB
Python

from contextlib import asynccontextmanager
from datetime import UTC, datetime
import json
import pytest
from app.services.earth_news import NewsFeedEndpoint, NewsFeedSource
from app.services import earth_news_refresh
from app.services.scheduler import (
EARTH_NEWS_REFRESH_JOB_ID,
_earth_news_region_refresh_job_id,
schedule_earth_news_region_refresh,
start_scheduler,
sync_scheduler_with_datasources,
)
class FakeRedis:
def __init__(self) -> None:
self.values: dict[str, str] = {}
def set(self, key: str, value: str, *, nx: bool = False, ex: int | None = None) -> bool:
del ex
if nx and key in self.values:
return False
self.values[key] = value
return True
def exists(self, key: str) -> bool:
return key in self.values
def eval(self, script: str, _key_count: int, key: str, token: str, *_args: object) -> int:
if self.values.get(key) != token:
return 0
if "redis.call('del'" in script:
del self.values[key]
return 1
class FakeStatusRedis:
def __init__(self) -> None:
self.values: dict[str, str] = {}
self.expirations: dict[str, int] = {}
def get(self, key: str):
return self.values.get(key)
def eval(self, script: str, key_count: int, *args):
keys = args[:key_count]
values = args[key_count:]
if "local active_id" in script:
active_key, status_key = keys
refresh_id, encoded, active_ttl, status_ttl, status_prefix = values
active_id = self.values.get(active_key)
if active_id:
active_status = self.values.get(f"{status_prefix}{active_id}")
if active_status:
status = json.loads(active_status)["status"]
if status in {"pending", "running"}:
return [active_id, active_status, 0]
self.values.pop(active_key, None)
self.values[active_key] = refresh_id
self.values[status_key] = encoded
self.expirations[active_key] = int(active_ttl)
self.expirations[status_key] = int(status_ttl)
return [refresh_id, encoded, 1]
active_key, status_key = keys
encoded, refresh_id, status_ttl, status, active_ttl = values
if self.values.get(active_key) != refresh_id:
return 0
self.values[status_key] = encoded
self.expirations[status_key] = int(status_ttl)
if status in {"succeeded", "failed"}:
self.values.pop(active_key, None)
else:
self.expirations[active_key] = int(active_ttl)
return 1
class FakeSession:
def __init__(self) -> None:
self.commits = 0
self.rollbacks = 0
async def commit(self) -> None:
self.commits += 1
async def rollback(self) -> None:
self.rollbacks += 1
@pytest.mark.asyncio
async def test_region_refresh_fetches_only_missing_feed_coverage(monkeypatch):
redis_client = FakeRedis()
db = FakeSession()
feeds = (
NewsFeedEndpoint("feed-a", "Feed A", "https://example.com/a.xml", region="global"),
NewsFeedEndpoint("feed-b", "Feed B", "https://example.com/b.xml", region="global"),
)
source = NewsFeedSource(
id="source-a",
name="Source A",
region="global",
feed_url=feeds[0].url,
homepage_url="https://example.com",
feeds=feeds,
)
fetched_source_feeds: list[list[str]] = []
@asynccontextmanager
async def fake_session_factory():
yield db
async def fake_get_sources_payload(_db):
return {"sources": []}
async def fake_get_sources_for_region(_db, _region, *, config_payload=None):
assert config_payload == {"sources": []}
return [source]
async def fake_freshness(_db, *, active_region):
assert active_region == "global"
return 12, datetime.now(UTC)
async def fake_coverage(_db, *, active_region, recent_after):
assert active_region == "global"
assert recent_after is not None
return {("source-a", "feed-a")}
async def fake_fetch(sources, **_kwargs):
fetched_source_feeds.extend([[feed.id for feed in item.feeds] for item in sources])
return [], [], {"source-a": {"source_id": "source-a", "ok": True, "feed_results": []}}
async def fake_record_health(_db, _health):
return None
async def fake_enqueue(_items):
return None
async def fake_upsert(_db, items):
assert items == []
return 0
monkeypatch.setattr(earth_news_refresh, "async_session_factory", fake_session_factory)
monkeypatch.setattr(earth_news_refresh._RedisClient, "get_client", lambda: redis_client)
monkeypatch.setattr(
"app.services.earth_news.get_earth_news_sources_payload", fake_get_sources_payload
)
monkeypatch.setattr(
"app.services.earth_news.get_configured_sources_for_region", fake_get_sources_for_region
)
monkeypatch.setattr(earth_news_refresh, "get_earth_news_freshness", fake_freshness)
monkeypatch.setattr(earth_news_refresh, "get_earth_news_feed_coverage", fake_coverage)
monkeypatch.setattr("app.services.earth_news._fetch_rss_items_for_sources", fake_fetch)
monkeypatch.setattr(
"app.services.earth_news.record_earth_news_sources_health", fake_record_health
)
monkeypatch.setattr("app.services.earth_news._enqueue_unverified_locations", fake_enqueue)
monkeypatch.setattr(earth_news_refresh, "upsert_earth_news_items", fake_upsert)
result = await earth_news_refresh.refresh_earth_news_region("global")
assert result["state"] == "completed"
assert result["successful_sources"] == 1
assert fetched_source_feeds == [["feed-b"]]
assert db.commits == 1
assert earth_news_refresh._lock_key("global") not in redis_client.values
@pytest.mark.asyncio
async def test_region_refresh_reports_failure_when_all_sources_time_out(monkeypatch):
redis_client = FakeRedis()
db = FakeSession()
feed = NewsFeedEndpoint("feed-a", "Feed A", "https://example.com/a.xml", region="global")
source = NewsFeedSource(
id="source-a",
name="Source A",
region="global",
feed_url=feed.url,
homepage_url="https://example.com",
feeds=(feed,),
)
@asynccontextmanager
async def fake_session_factory():
yield db
async def fake_get_sources_payload(_db):
return {"sources": []}
async def fake_get_sources_for_region(_db, _region, *, config_payload=None):
return [source]
async def fake_freshness(_db, *, active_region):
return 12, datetime.now(UTC)
async def fake_coverage(_db, *, active_region, recent_after):
return set()
async def fake_fetch(*_args, **_kwargs):
return (
[],
["private upstream details"],
{
"source-a": {
"source_id": "source-a",
"ok": False,
"status": "timeout",
"feed_results": [{"feed_id": "feed-a", "ok": False, "status": "timeout"}],
}
},
)
async def fake_noop(*_args, **_kwargs):
return None
async def fake_upsert(_db, _items):
return 0
monkeypatch.setattr(earth_news_refresh, "async_session_factory", fake_session_factory)
monkeypatch.setattr(earth_news_refresh._RedisClient, "get_client", lambda: redis_client)
monkeypatch.setattr(
"app.services.earth_news.get_earth_news_sources_payload", fake_get_sources_payload
)
monkeypatch.setattr(
"app.services.earth_news.get_configured_sources_for_region", fake_get_sources_for_region
)
monkeypatch.setattr(earth_news_refresh, "get_earth_news_freshness", fake_freshness)
monkeypatch.setattr(earth_news_refresh, "get_earth_news_feed_coverage", fake_coverage)
monkeypatch.setattr("app.services.earth_news._fetch_rss_items_for_sources", fake_fetch)
monkeypatch.setattr("app.services.earth_news.record_earth_news_sources_health", fake_noop)
monkeypatch.setattr("app.services.earth_news._enqueue_unverified_locations", fake_noop)
monkeypatch.setattr(earth_news_refresh, "upsert_earth_news_items", fake_upsert)
result = await earth_news_refresh.refresh_earth_news_region("global", force=True)
assert result["state"] == "failed"
assert result["error_code"] == "timeout"
assert db.commits == 1
@pytest.mark.asyncio
async def test_database_commit_failure_sets_refresh_failed_status(monkeypatch):
class CommitFailureSession(FakeSession):
async def commit(self) -> None:
raise RuntimeError("database commit failed with sensitive context")
redis_client = FakeRedis()
db = CommitFailureSession()
feed = NewsFeedEndpoint("feed-a", "Feed A", "https://example.com/a.xml", region="europe")
source = NewsFeedSource(
id="source-a",
name="Source A",
region="europe",
feed_url=feed.url,
homepage_url="https://example.com",
feeds=(feed,),
)
scheduler_module = __import__("app.services.scheduler", fromlist=["scheduler"])
statuses = []
@asynccontextmanager
async def fake_session_factory():
yield db
async def fake_get_sources_payload(_db):
return {"sources": []}
async def fake_get_sources_for_region(_db, _region, *, config_payload=None):
return [source]
async def fake_freshness(_db, *, active_region):
return 12, datetime.now(UTC)
async def fake_coverage(_db, *, active_region, recent_after):
return set()
async def fake_fetch(*_args, **_kwargs):
return [], [], {"source-a": {"source_id": "source-a", "ok": True, "feed_results": []}}
async def fake_noop(*_args, **_kwargs):
return None
async def fake_upsert(_db, _items):
return 1
monkeypatch.setattr(earth_news_refresh, "async_session_factory", fake_session_factory)
monkeypatch.setattr(earth_news_refresh._RedisClient, "get_client", lambda: redis_client)
monkeypatch.setattr(
"app.services.earth_news.get_earth_news_sources_payload", fake_get_sources_payload
)
monkeypatch.setattr(
"app.services.earth_news.get_configured_sources_for_region", fake_get_sources_for_region
)
monkeypatch.setattr(earth_news_refresh, "get_earth_news_freshness", fake_freshness)
monkeypatch.setattr(earth_news_refresh, "get_earth_news_feed_coverage", fake_coverage)
monkeypatch.setattr("app.services.earth_news._fetch_rss_items_for_sources", fake_fetch)
monkeypatch.setattr("app.services.earth_news.record_earth_news_sources_health", fake_noop)
monkeypatch.setattr("app.services.earth_news._enqueue_unverified_locations", fake_noop)
monkeypatch.setattr(earth_news_refresh, "upsert_earth_news_items", fake_upsert)
monkeypatch.setattr(scheduler_module, "touch_earth_news_refresh_status", lambda *_args: True)
monkeypatch.setattr(
scheduler_module,
"set_earth_news_refresh_status",
lambda refresh_id, region, status, *, error=None: statuses.append(
{"refresh_id": refresh_id, "region": region, "status": status, "error": error}
),
)
scheduler_module._pending_earth_news_refreshes["europe"] = {
"force": True,
"refresh_id": "refresh-commit-failure",
}
await scheduler_module._run_earth_news_region_refresh("europe")
assert [entry["status"] for entry in statuses] == ["running", "failed"]
assert statuses[-1]["error"]["code"] == "refresh_failed"
assert "sensitive context" not in repr(statuses)
assert not redis_client.values
@pytest.mark.asyncio
async def test_region_refresh_skips_when_cross_process_lock_is_held(monkeypatch):
redis_client = FakeRedis()
redis_client.values[earth_news_refresh._lock_key("global")] = "other-owner"
def fail_session_factory():
raise AssertionError("a locked refresh must not open a database session")
monkeypatch.setattr(earth_news_refresh, "async_session_factory", fail_session_factory)
monkeypatch.setattr(earth_news_refresh._RedisClient, "get_client", lambda: redis_client)
result = await earth_news_refresh.refresh_earth_news_region("global")
assert result["state"] == "busy"
def test_failed_feed_enters_cooldown_without_blocking_other_sources():
redis_client = FakeRedis()
source = NewsFeedSource(
id="source-a",
name="Source A",
region="global",
feed_url="https://example.com/a.xml",
homepage_url="https://example.com",
feeds=(NewsFeedEndpoint("feed-a", "Feed A", "https://example.com/a.xml"),),
)
health = {
"source-a": {
"ok": False,
"feed_results": [{"feed_id": "feed-a", "ok": False}],
}
}
earth_news_refresh._record_failed_feed_cooldowns(
redis_client,
active_region="global",
health_by_source=health,
sources=[source],
)
selected, cooling = earth_news_refresh._select_feeds(
[source],
active_region="global",
required_keys={("source-a", "feed-a")},
redis_client=redis_client,
)
assert selected == []
assert cooling == {("source-a", "feed-a")}
@pytest.mark.asyncio
async def test_region_refresh_skips_when_redis_coordination_is_unavailable(monkeypatch):
def fail_redis_client():
raise RuntimeError("redis unavailable")
def fail_session_factory():
raise AssertionError("uncoordinated processes must not start duplicate RSS fetches")
monkeypatch.setattr(earth_news_refresh._RedisClient, "get_client", fail_redis_client)
monkeypatch.setattr(earth_news_refresh, "async_session_factory", fail_session_factory)
result = await earth_news_refresh.refresh_earth_news_region("global")
assert result["state"] == "coordination_unavailable"
def test_refresh_status_deduplicates_active_region_and_bounds_completed_results(monkeypatch):
redis_client = FakeStatusRedis()
monkeypatch.setattr(earth_news_refresh._RedisClient, "get_client", lambda: redis_client)
first, created = earth_news_refresh.create_earth_news_refresh_status("global")
duplicate, duplicate_created = earth_news_refresh.create_earth_news_refresh_status("global")
assert created is True
assert duplicate_created is False
assert duplicate == first
earth_news_refresh.set_earth_news_refresh_status(first["refresh_id"], "global", "running")
running, running_created = earth_news_refresh.create_earth_news_refresh_status("global")
assert running_created is False
assert running["status"] == "running"
completed = earth_news_refresh.set_earth_news_refresh_status(
first["refresh_id"], "global", "succeeded"
)
assert completed["status"] == "succeeded"
assert earth_news_refresh.get_earth_news_refresh_status(first["refresh_id"]) == completed
second, second_created = earth_news_refresh.create_earth_news_refresh_status("global")
assert second_created is True
assert second["refresh_id"] != first["refresh_id"]
assert earth_news_refresh.get_earth_news_refresh_status(first["refresh_id"]) == completed
assert redis_client.expirations[earth_news_refresh._refresh_active_key("global")] == 120
assert (
redis_client.expirations[earth_news_refresh._refresh_status_key(second["refresh_id"])]
== 600
)
status_keys = [
key
for key in redis_client.values
if key.startswith(earth_news_refresh.REFRESH_STATUS_PREFIX)
]
assert len(status_keys) == 2
pending, pending_created = earth_news_refresh.create_earth_news_refresh_status("europe")
assert pending_created is True
redis_client.values.pop(earth_news_refresh._refresh_active_key("europe"), None)
expired = earth_news_refresh.get_earth_news_refresh_status(pending["refresh_id"])
assert expired["status"] == "failed"
assert expired["error"]["code"] == "expired"
@pytest.mark.asyncio
async def test_earth_news_refresh_scheduler_job_survives_datasource_sync(monkeypatch):
class FakeJob:
def __init__(self, job_id: str) -> None:
self.id = job_id
class FakeScheduler:
def __init__(self) -> None:
self.running = False
self.jobs = {
"obsolete": FakeJob("obsolete"),
_earth_news_region_refresh_job_id("global"): FakeJob(
_earth_news_region_refresh_job_id("global")
),
}
self.added: dict[str, object] = {}
def add_job(self, _func, **kwargs):
self.added.update(kwargs)
self.jobs[kwargs["id"]] = FakeJob(kwargs["id"])
def start(self) -> None:
self.running = True
def get_jobs(self):
return list(self.jobs.values())
def remove_job(self, job_id: str) -> None:
self.jobs.pop(job_id, None)
class FakeResult:
def scalars(self):
return self
def all(self):
return []
class FakeDb:
async def execute(self, _query):
return FakeResult()
fake_scheduler = FakeScheduler()
@asynccontextmanager
async def fake_session_factory():
yield FakeDb()
monkeypatch.setattr("app.services.scheduler.scheduler", fake_scheduler)
monkeypatch.setattr("app.services.scheduler.async_session_factory", fake_session_factory)
start_scheduler()
await sync_scheduler_with_datasources()
assert fake_scheduler.added["id"] == EARTH_NEWS_REFRESH_JOB_ID
assert fake_scheduler.added["next_run_time"] <= datetime.now(UTC)
assert EARTH_NEWS_REFRESH_JOB_ID in fake_scheduler.jobs
assert _earth_news_region_refresh_job_id("global") in fake_scheduler.jobs
assert "obsolete" not in fake_scheduler.jobs
@pytest.mark.asyncio
async def test_region_refresh_requests_are_merged_and_force_is_preserved(monkeypatch):
class FakeScheduler:
running = True
def __init__(self) -> None:
self.jobs: dict[str, tuple[object, dict[str, object]]] = {}
def add_job(self, func, **kwargs):
self.jobs[kwargs["id"]] = (func, kwargs)
scheduler_module = __import__("app.services.scheduler", fromlist=["scheduler"])
fake_scheduler = FakeScheduler()
monkeypatch.setattr(scheduler_module, "scheduler", fake_scheduler)
captured: list[tuple[str, bool]] = []
async def fake_refresh(region: str, *, force: bool = False):
captured.append((region, force))
return {"locked": False, "fetched": 0, "upserted": 0}
monkeypatch.setattr(scheduler_module, "refresh_earth_news_region", fake_refresh)
assert schedule_earth_news_region_refresh("global") is True
assert schedule_earth_news_region_refresh("global", force=True) is False
assert len(fake_scheduler.jobs) == 1
job_id = _earth_news_region_refresh_job_id("global")
func, kwargs = fake_scheduler.jobs.pop(job_id)
await func(**kwargs["kwargs"])
assert captured == [("global", True)]
assert job_id not in fake_scheduler.jobs