Merge origin/master into CelesTrak satellites API

Keep /api/satellites (this PR) and /api/infrastructure from #36,
plus both overlay_catalog entries. Disjoint layers.
This commit is contained in:
Sirius DevOps 2026-08-31 22:28:23 -04:00
commit c91c9ef321
No known key found for this signature in database
9 changed files with 933 additions and 3 deletions

View file

@ -15,6 +15,7 @@ import asyncio
import json
import logging
import re
import time
from contextlib import asynccontextmanager
from datetime import datetime, timedelta, timezone
from decimal import Decimal
@ -58,7 +59,7 @@ from live_layers import (
fetch_aircraft, fetch_fire_incidents, fetch_fire_perimeters,
fetch_gpsjam, fetch_planespotters_photo, fetch_radar_meta, fetch_sentinel1,
fetch_storms, fetch_trains, fetch_vessels, fetch_weather_alerts,
overlay_catalog, parse_bbox, UpstreamRateLimited,
fetch_infrastructure, overlay_catalog, parse_bbox, UpstreamRateLimited,
)
from satellites import fetch_satellites, parse_groups, DEFAULT_GROUPS
@ -274,6 +275,67 @@ def overlay_json(data, max_age: int) -> JSONResponse:
return resp
# ── HUD counters ─────────────────────────────────────────────────────────
# Cheap ~100 B–2 KB counts for the layer rail. Cached in-process so the HUD
# can poll every second without re-hitting SQL or upstream feeds.
_STATS_TTL = 20.0
_stats_cache: dict[str, tuple[float, dict]] = {}
async def _stats_counts() -> dict:
"""Fan out to in-memory last-known / cheap SQL counts. Never raises."""
from live_layers import (
aircraft_last_known, vessel_last_known, train_count, nws_alert_count,
)
counts: dict[str, int | str] = {
"aircraft": len(aircraft_last_known),
"vessels": len(vessel_last_known),
"trains": train_count,
"cameras": 0,
"fires": 0,
"quakes": 0,
"alerts": nws_alert_count,
}
# SQL counts are best-effort: a down DB or missing table must not 500 the
# rail — the frontend still renders with zeros.
try:
from camera_models import cameras as cam_table
async with async_session() as session:
counts["cameras"] = int(
(await session.execute(select(func.count()).select_from(cam_table))).scalar() or 0
)
counts["fires"] = int(
(await session.execute(select(func.count()).select_from(fires))).scalar() or 0
)
counts["quakes"] = int(
(await session.execute(
select(func.count()).select_from(events).where(
events.c.source_type == "earthquake"
)
)).scalar() or 0
)
except Exception as exc: # noqa: BLE001
logger.warning("stats_db_failed", error=str(exc))
counts["timestamp"] = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
return counts
@app.get("/api/stats")
async def api_stats():
"""Cheap HUD counters (counts only — no GeoJSON). Cached ~20 s."""
now = time.monotonic()
cached = _stats_cache.get("stats")
if cached and now - cached[0] < _STATS_TTL:
return cached[1]
payload = await _stats_counts()
_stats_cache["stats"] = (now, payload)
return overlay_json(payload, 15)
# ── Feed Sources ──────────────────────────────────────────────────────────
@app.get("/api/sources", response_model=list[FeedSourceOut])
@ -1847,6 +1909,39 @@ async def list_satellites(
return overlay_json(payload, 30)
_INFRA_TYPES = frozenset({"nuclear"})
@app.get("/api/infrastructure")
async def api_infrastructure(
types: str = Query(..., description="comma-separated enum (nuclear)"),
bbox: str | None = Query(None, description="minlon,minlat,maxlon,maxlat"),
):
"""Overpass-derived static infrastructure markers (nuclear power plants).
``bbox`` is required; ``types`` is a comma-separated subset of ``nuclear``.
Fetched from Overpass (identifying UA, 25s query) and cached 24h per
quantized bbox. Markers are ``{id, name, lat, lon, type, extra}``.
"""
if not bbox:
raise HTTPException(400, "bbox required (minlon,minlat,maxlon,maxlat)")
requested = [t.strip() for t in (types or "").split(",") if t.strip()]
if not requested:
raise HTTPException(422, "types required (e.g. nuclear)")
unknown = [t for t in requested if t not in _INFRA_TYPES]
if unknown:
raise HTTPException(
422, f"unsupported types: {', '.join(unknown)} (supported: nuclear)"
)
try:
markers = await fetch_infrastructure(",".join(requested), bbox)
except ValueError as exc:
raise HTTPException(422, str(exc)) from exc
except Exception as exc:
_upstream_or_502(exc, "infrastructure")
return overlay_json(markers, 86400)
@app.get("/api/map/times")
async def map_layer_times(
layer: str = Query(..., description="GIBS layer identifier, e.g. VIIRS_SNPP_CorrectedReflectance_TrueColor"),