Compare commits
3 changed files with 4 additions and 192 deletions
43
app/main.py
43
app/main.py
|
|
@ -272,14 +272,7 @@ async def _pipeline_checks(session) -> dict:
|
||||||
|
|
||||||
await _age("SELECT max(ingested_at) FROM events", "events", 20 * 60)
|
await _age("SELECT max(ingested_at) FROM events", "events", 20 * 60)
|
||||||
await _age("SELECT max(ingested_at) FROM fires", "fires", 30 * 60)
|
await _age("SELECT max(ingested_at) FROM fires", "fires", 30 * 60)
|
||||||
# Same closed-at-now window as GET /api/news. A future max() made age_s
|
await _age("SELECT max(timestamp) FROM articles", "articles", 2 * 3600)
|
||||||
# negative and hid a fresh list. NULL timestamps are not fresh.
|
|
||||||
await _age(
|
|
||||||
"SELECT max(timestamp) FROM articles "
|
|
||||||
"WHERE timestamp IS NOT NULL AND timestamp <= now()",
|
|
||||||
"articles",
|
|
||||||
2 * 3600,
|
|
||||||
)
|
|
||||||
await _age("SELECT max(batch_timestamp) FROM article_summaries", "summaries", 2 * 3600)
|
await _age("SELECT max(batch_timestamp) FROM article_summaries", "summaries", 2 * 3600)
|
||||||
return checks
|
return checks
|
||||||
|
|
||||||
|
|
@ -305,7 +298,7 @@ async def _stats_counts() -> dict:
|
||||||
aircraft_last_known, vessel_last_known, train_count, nws_alert_count,
|
aircraft_last_known, vessel_last_known, train_count, nws_alert_count,
|
||||||
)
|
)
|
||||||
|
|
||||||
counts: dict = {
|
counts: dict[str, int | str] = {
|
||||||
"aircraft": len(aircraft_last_known),
|
"aircraft": len(aircraft_last_known),
|
||||||
"vessels": len(vessel_last_known),
|
"vessels": len(vessel_last_known),
|
||||||
"trains": train_count,
|
"trains": train_count,
|
||||||
|
|
@ -337,41 +330,9 @@ async def _stats_counts() -> dict:
|
||||||
logger.warning("stats_db_failed", error=str(exc))
|
logger.warning("stats_db_failed", error=str(exc))
|
||||||
|
|
||||||
counts["timestamp"] = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
counts["timestamp"] = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||||
# Public booleans only. Never include the stored value, a prefix, or last-4.
|
|
||||||
counts["feeds"] = await _feed_flags()
|
|
||||||
return counts
|
return counts
|
||||||
|
|
||||||
|
|
||||||
async def _key_configured(*names: str) -> bool:
|
|
||||||
"""True when any named key has a non-empty value in the api_keys store.
|
|
||||||
|
|
||||||
Uses keystore.get_api_key — not env, not a second store. The value is
|
|
||||||
discarded after the emptiness check.
|
|
||||||
"""
|
|
||||||
from keystore import get_api_key
|
|
||||||
|
|
||||||
for name in names:
|
|
||||||
value = await get_api_key(name)
|
|
||||||
if isinstance(value, str) and value.strip():
|
|
||||||
return True
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
async def _feed_flags() -> dict:
|
|
||||||
"""HUD layer flags. Fail closed (configured false) if the store is down."""
|
|
||||||
try:
|
|
||||||
vessels = await _key_configured("AISSTREAM_API_KEY", "VESSELAPI_API_KEY")
|
|
||||||
fires = await _key_configured("FIRMS_MAP_KEY")
|
|
||||||
except Exception as exc: # noqa: BLE001
|
|
||||||
logger.warning("stats_feed_flags_failed", error=str(exc))
|
|
||||||
vessels = False
|
|
||||||
fires = False
|
|
||||||
return {
|
|
||||||
"vessels": {"configured": vessels},
|
|
||||||
"fires": {"configured": fires},
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/stats")
|
@app.get("/api/stats")
|
||||||
async def api_stats():
|
async def api_stats():
|
||||||
"""Cheap HUD counters (counts only — no GeoJSON). Cached ~20 s."""
|
"""Cheap HUD counters (counts only — no GeoJSON). Cached ~20 s."""
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,7 @@ from datetime import timezone
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
|
|
||||||
from main import app, _stats_counts, _stats_cache
|
from main import app, _stats_counts
|
||||||
|
|
||||||
BASE = "http://test"
|
BASE = "http://test"
|
||||||
|
|
||||||
|
|
@ -85,79 +85,3 @@ def test_stats_db_failure_degrades_to_zero(monkeypatch):
|
||||||
assert body["fires"] == 0
|
assert body["fires"] == 0
|
||||||
assert body["quakes"] == 0
|
assert body["quakes"] == 0
|
||||||
assert isinstance(body["timestamp"], str)
|
assert isinstance(body["timestamp"], str)
|
||||||
|
|
||||||
|
|
||||||
def _clear_stats_cache() -> None:
|
|
||||||
_stats_cache.clear()
|
|
||||||
|
|
||||||
|
|
||||||
def test_stats_feeds_unconfigured_without_keys(monkeypatch):
|
|
||||||
"""No stored AIS/FIRMS key → both flags false; existing counters stay.
|
|
||||||
|
|
||||||
Env vars do not count. The HUD flag is the api_keys store only.
|
|
||||||
"""
|
|
||||||
monkeypatch.setenv("FIRMS_MAP_KEY", "env-firms-should-not-count")
|
|
||||||
monkeypatch.setenv("AISSTREAM_API_KEY", "env-ais-should-not-count")
|
|
||||||
monkeypatch.setenv("VESSELAPI_API_KEY", "env-vessel-should-not-count")
|
|
||||||
|
|
||||||
async def _unset(name: str):
|
|
||||||
if name == "FIRMS_MAP_KEY":
|
|
||||||
return " "
|
|
||||||
return None
|
|
||||||
|
|
||||||
monkeypatch.setattr("keystore.get_api_key", _unset)
|
|
||||||
_clear_stats_cache()
|
|
||||||
resp = asyncio.run(_get("/api/stats"))
|
|
||||||
assert resp.status_code == 200
|
|
||||||
body = resp.json()
|
|
||||||
for key in EXPECTED_KEYS:
|
|
||||||
assert key in body, f"missing key {key}"
|
|
||||||
assert body["feeds"] == {
|
|
||||||
"vessels": {"configured": False},
|
|
||||||
"fires": {"configured": False},
|
|
||||||
}
|
|
||||||
assert "trains" not in body["feeds"]
|
|
||||||
assert "env-firms-should-not-count" not in resp.text
|
|
||||||
assert "env-ais-should-not-count" not in resp.text
|
|
||||||
|
|
||||||
|
|
||||||
def test_stats_feeds_fires_configured_does_not_leak_key(monkeypatch):
|
|
||||||
secret = "firms-map-key-do-not-leak-9f3a2c1b"
|
|
||||||
|
|
||||||
async def _keys(name: str):
|
|
||||||
if name == "FIRMS_MAP_KEY":
|
|
||||||
return secret
|
|
||||||
return None
|
|
||||||
|
|
||||||
monkeypatch.setattr("keystore.get_api_key", _keys)
|
|
||||||
_clear_stats_cache()
|
|
||||||
resp = asyncio.run(_get("/api/stats"))
|
|
||||||
body = resp.json()
|
|
||||||
assert body["feeds"]["fires"]["configured"] is True
|
|
||||||
assert body["feeds"]["vessels"]["configured"] is False
|
|
||||||
assert secret not in resp.text
|
|
||||||
assert secret[-4:] not in resp.text
|
|
||||||
|
|
||||||
|
|
||||||
def test_stats_feeds_vessels_configured_from_either_key(monkeypatch):
|
|
||||||
async def _ais_only(name: str):
|
|
||||||
if name == "AISSTREAM_API_KEY":
|
|
||||||
return "aisstream-stored-value"
|
|
||||||
return None
|
|
||||||
|
|
||||||
monkeypatch.setattr("keystore.get_api_key", _ais_only)
|
|
||||||
_clear_stats_cache()
|
|
||||||
body = asyncio.run(_get("/api/stats")).json()
|
|
||||||
assert body["feeds"]["vessels"]["configured"] is True
|
|
||||||
assert body["feeds"]["fires"]["configured"] is False
|
|
||||||
|
|
||||||
async def _vesselapi_only(name: str):
|
|
||||||
if name == "VESSELAPI_API_KEY":
|
|
||||||
return "vesselapi-stored-value"
|
|
||||||
return ""
|
|
||||||
|
|
||||||
monkeypatch.setattr("keystore.get_api_key", _vesselapi_only)
|
|
||||||
_clear_stats_cache()
|
|
||||||
body = asyncio.run(_get("/api/stats")).json()
|
|
||||||
assert body["feeds"]["vessels"]["configured"] is True
|
|
||||||
assert body["feeds"]["fires"]["configured"] is False
|
|
||||||
|
|
@ -3,21 +3,12 @@
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import os
|
|
||||||
from datetime import datetime, timedelta, timezone
|
|
||||||
|
|
||||||
import asyncpg
|
|
||||||
import httpx
|
import httpx
|
||||||
import pytest
|
|
||||||
|
|
||||||
from conftest import requires_db
|
|
||||||
from main import app
|
from main import app
|
||||||
|
|
||||||
BASE = "http://test"
|
BASE = "http://test"
|
||||||
_FIXTURE_URLS = (
|
|
||||||
"https://test.invalid/t_ceb74e64/future",
|
|
||||||
"https://test.invalid/t_ceb74e64/fresh",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
async def _get(path: str) -> httpx.Response:
|
async def _get(path: str) -> httpx.Response:
|
||||||
|
|
@ -40,67 +31,3 @@ def test_ready_endpoint_exists():
|
||||||
body = resp.json()
|
body = resp.json()
|
||||||
assert "checks" in body
|
assert "checks" in body
|
||||||
assert "status" in body
|
assert "status" in body
|
||||||
|
|
||||||
|
|
||||||
def _conn_kwargs() -> dict:
|
|
||||||
return {
|
|
||||||
"host": os.environ["DB_HOST"],
|
|
||||||
"port": int(os.environ["DB_PORT"]),
|
|
||||||
"user": os.environ["DB_USER"],
|
|
||||||
"password": os.environ["DB_PASSWORD"],
|
|
||||||
"database": os.environ["DB_NAME"],
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
async def _prepare_article_age_fixture() -> None:
|
|
||||||
"""Insert one row at now+6d and one at now-120s. Deletes only those URLs."""
|
|
||||||
conn = await asyncpg.connect(**_conn_kwargs())
|
|
||||||
try:
|
|
||||||
await conn.execute(
|
|
||||||
"DELETE FROM articles WHERE url = ANY($1::text[])",
|
|
||||||
list(_FIXTURE_URLS),
|
|
||||||
)
|
|
||||||
now = datetime.now(timezone.utc)
|
|
||||||
await conn.executemany(
|
|
||||||
"INSERT INTO articles (title, url, content, domain, timestamp) "
|
|
||||||
"VALUES ($1, $2, $3, $4, $5)",
|
|
||||||
[
|
|
||||||
("future", _FIXTURE_URLS[0], "x", "test.invalid", now + timedelta(days=6)),
|
|
||||||
("fresh", _FIXTURE_URLS[1], "x", "test.invalid", now - timedelta(seconds=120)),
|
|
||||||
],
|
|
||||||
)
|
|
||||||
finally:
|
|
||||||
await conn.close()
|
|
||||||
|
|
||||||
|
|
||||||
async def _delete_article_age_fixture() -> None:
|
|
||||||
conn = await asyncpg.connect(**_conn_kwargs())
|
|
||||||
try:
|
|
||||||
await conn.execute(
|
|
||||||
"DELETE FROM articles WHERE url = ANY($1::text[])",
|
|
||||||
list(_FIXTURE_URLS),
|
|
||||||
)
|
|
||||||
finally:
|
|
||||||
await conn.close()
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
|
||||||
def article_age_rows():
|
|
||||||
asyncio.run(_prepare_article_age_fixture())
|
|
||||||
yield
|
|
||||||
asyncio.run(_delete_article_age_fixture())
|
|
||||||
|
|
||||||
|
|
||||||
@requires_db
|
|
||||||
def test_health_article_age_ignores_future_rows(article_age_rows):
|
|
||||||
"""Future-dated rows must not pin articles.age_s negative.
|
|
||||||
|
|
||||||
Fixture: one row at now+6d, one at now-120s. age_s is the age of the
|
|
||||||
newest timestamp that is not in the future (NULL timestamps do not count).
|
|
||||||
"""
|
|
||||||
body = asyncio.run(_get("/api/health")).json()
|
|
||||||
articles = body["checks"]["articles"]
|
|
||||||
age = articles["age_s"]
|
|
||||||
assert age is not None
|
|
||||||
assert 0 <= age <= 600, articles
|
|
||||||
assert articles["ok"] is True
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue