fix: pipeline reliability — WS, summarizer, ingest, health
Stop the live HUD reconnect storm (nginx WS snippet + backoff), copy intel/nous_client into the summarizer image, and make event ingest idempotent on URL. GDELT uses the DOC API; NWS no longer sends bbox; FIRMS is one ON CONFLICT batch; GET /api/aircraft serves last-known. Health reports freshness without 503ing docker. EONET + CISA KEV added.
This commit is contained in:
parent
c6bfc50705
commit
d81ea68dec
26 changed files with 1164 additions and 110 deletions
111
app/main.py
111
app/main.py
|
|
@ -72,12 +72,16 @@ async def _lifespan(app: FastAPI):
|
|||
pass
|
||||
from config import AISSTREAM_IN_APP
|
||||
ais_task = None
|
||||
adsb_task = None
|
||||
if AISSTREAM_IN_APP:
|
||||
from ais_stream import run_ais_worker
|
||||
ais_task = asyncio.create_task(run_ais_worker())
|
||||
adsb_task = asyncio.create_task(_adsb_refresh_loop())
|
||||
yield
|
||||
if ais_task is not None:
|
||||
ais_task.cancel()
|
||||
if adsb_task is not None:
|
||||
adsb_task.cancel()
|
||||
await close_http()
|
||||
|
||||
|
||||
|
|
@ -92,6 +96,35 @@ app.add_middleware(GZipMiddleware, minimum_size=1024)
|
|||
STATIC_DIR = Path(__file__).parent / "static"
|
||||
|
||||
|
||||
async def _adsb_refresh_loop() -> None:
|
||||
"""Poll ADSB.lol for connected viewports — never from GET /api/aircraft."""
|
||||
from ws_manager import manager
|
||||
from live_layers import fetch_aircraft
|
||||
|
||||
while True:
|
||||
try:
|
||||
boxes = manager.viewports()
|
||||
for box in boxes:
|
||||
bbox = f"{box[0]},{box[1]},{box[2]},{box[3]}"
|
||||
try:
|
||||
await fetch_aircraft(bbox, persist=True)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("adsb_refresh_failed", error=str(exc))
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("adsb_refresh_loop", error=str(exc))
|
||||
await asyncio.sleep(8)
|
||||
|
||||
|
||||
class CachedStaticFiles(StaticFiles):
|
||||
"""Long-cache hashed/vendor Leaflet assets; index.html is served separately."""
|
||||
|
||||
async def get_response(self, path: str, scope):
|
||||
resp = await super().get_response(path, scope)
|
||||
if path.startswith("vendor/") or path.endswith((".js", ".css", ".woff2", ".png", ".svg")):
|
||||
resp.headers["Cache-Control"] = "public, max-age=31536000, immutable"
|
||||
return resp
|
||||
|
||||
|
||||
# ── Helpers ───────────────────────────────────────────────────────────────
|
||||
|
||||
def event_to_out(row: dict) -> EventOut:
|
||||
|
|
@ -154,11 +187,65 @@ def alert_to_out(row: dict) -> AlertOut:
|
|||
|
||||
@app.get("/api/health")
|
||||
async def health():
|
||||
"""Health check with database connectivity."""
|
||||
async with async_session() as session:
|
||||
result = await session.execute(select(func.now()))
|
||||
db_time = result.scalar()
|
||||
return {"status": "ok", "db_time": db_time.isoformat() if db_time else None}
|
||||
"""Liveness: process + DB. Pipeline freshness is in ``checks`` (HTTP 200
|
||||
unless DB is down, so docker healthcheck does not restart a working HUD).
|
||||
"""
|
||||
try:
|
||||
async with async_session() as session:
|
||||
result = await session.execute(select(func.now()))
|
||||
db_time = result.scalar()
|
||||
checks = await _pipeline_checks(session)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("health_db_failed", error=str(exc))
|
||||
return JSONResponse(
|
||||
{"status": "down", "db_time": None, "checks": {"db": False}},
|
||||
status_code=503,
|
||||
)
|
||||
checks["db"] = True
|
||||
stale = [
|
||||
name for name, val in checks.items()
|
||||
if isinstance(val, dict) and val.get("ok") is False
|
||||
]
|
||||
status = "degraded" if stale else "ok"
|
||||
return {
|
||||
"status": status,
|
||||
"db_time": db_time.isoformat() if db_time else None,
|
||||
"checks": checks,
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/ready")
|
||||
async def ready():
|
||||
"""Readiness: 503 only when the database is unreachable."""
|
||||
payload = await health()
|
||||
if isinstance(payload, JSONResponse):
|
||||
return payload
|
||||
return JSONResponse(payload, status_code=200)
|
||||
|
||||
|
||||
async def _pipeline_checks(session) -> dict:
|
||||
now = datetime.now(timezone.utc)
|
||||
checks: dict = {}
|
||||
|
||||
async def _age(sql: str, name: str, max_age_s: int) -> None:
|
||||
try:
|
||||
ts = (await session.execute(text(sql))).scalar()
|
||||
except Exception:
|
||||
checks[name] = {"ok": False, "age_s": None}
|
||||
return
|
||||
if ts is None:
|
||||
checks[name] = {"ok": False, "age_s": None}
|
||||
return
|
||||
if getattr(ts, "tzinfo", None) is None:
|
||||
ts = ts.replace(tzinfo=timezone.utc)
|
||||
age = (now - ts).total_seconds()
|
||||
checks[name] = {"ok": age <= max_age_s, "age_s": int(age)}
|
||||
|
||||
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(timestamp) FROM articles", "articles", 2 * 3600)
|
||||
await _age("SELECT max(batch_timestamp) FROM article_summaries", "summaries", 2 * 3600)
|
||||
return checks
|
||||
|
||||
|
||||
def overlay_json(data, max_age: int) -> JSONResponse:
|
||||
|
|
@ -821,17 +908,19 @@ async def get_timeline(
|
|||
"""Event timeline: counts and avg sentiment per time bucket."""
|
||||
async with async_session() as session:
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(hours=hours)
|
||||
# Use date_trunc for bucketing
|
||||
buckets = await session.execute(text(f"""
|
||||
bucket_s = bucket_hours * 3600
|
||||
buckets = await session.execute(text("""
|
||||
SELECT
|
||||
date_trunc('hour', source_timestamp) AS ts,
|
||||
to_timestamp(
|
||||
floor(extract(epoch FROM source_timestamp) / :bucket_s) * :bucket_s
|
||||
) AT TIME ZONE 'UTC' AS ts,
|
||||
COUNT(*) AS event_count,
|
||||
COALESCE(AVG(sentiment_score), 0) AS avg_sentiment
|
||||
FROM events
|
||||
WHERE source_timestamp >= :cutoff
|
||||
GROUP BY ts
|
||||
ORDER BY ts
|
||||
"""), {"cutoff": cutoff})
|
||||
"""), {"cutoff": cutoff, "bucket_s": bucket_s})
|
||||
rows = buckets.mappings().all()
|
||||
|
||||
return [TimelinePoint(timestamp=r["ts"], event_count=r["event_count"],
|
||||
|
|
@ -1319,7 +1408,7 @@ async def list_aircraft(
|
|||
ts = parse_timestamp(timestamp)
|
||||
if ts is not None:
|
||||
return overlay_json(await fetch_positions_at("aircraft", ts, bbox, limit), 5)
|
||||
return overlay_json(await fetch_aircraft(bbox, limit), 5)
|
||||
return overlay_json(await fetch_aircraft(bbox, limit, persist=False), 5)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(422, str(exc)) from exc
|
||||
except Exception as exc:
|
||||
|
|
@ -1550,7 +1639,7 @@ async def map_layer_times(
|
|||
return {"layer": layer, **domain}
|
||||
|
||||
|
||||
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
|
||||
app.mount("/static", CachedStaticFiles(directory=str(STATIC_DIR)), name="static")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
|
|
|||
Loading…
Reference in a new issue