Add NASA FIRMS active-fire ingest + /api/fires; API keys management page

Coherent merge of two coordinated features on the shared working tree:

FIRMS fire heatmap (backend, t_6e404c14):
- app/fire_sources.py: fetch FIRMS VIIRS area CSV (free MAP_KEY) -> NATS events.fire
- fires hypertable (TimescaleDB, 1-day chunks) with natural-key PK
  (latitude, longitude, acq_time, satellite); idempotent ON CONFLICT DO NOTHING
- alembic/versions/002_fires.py; GET /api/fires?bbox=&since= (JSON only)
- POST /api/ingest/fires; ~15 min poll loop (FIRMS_INTERVAL=900) in ingester
- env-driven config (FIRMS_MAP_KEY/DATASET/BBOX/INTERVAL); docs/firms.md covers
  the zero-cost GIBS VIIRS_SNPP_Thermal_Anomalies_375m_All tile alternative
- 18 tests (parser, mapping, idempotency, API contract) verified vs real
  TimescaleDB+PostGIS (localhost/osint-dashboard-pg image)

API keys page (frontend, t_4433cff2):
- app/keystore.py: api_keys table (self-creating), FIRMS/GEMINI/TELEGRAM
  registry with format validation, ****last4 masking, get_api_key()
- GET/POST/DELETE /api/keys (never returns full values); Keys tab in index.html

DB_NULL_POOL env switch in app/database.py enables a NullPool for tests /
short-lived processes that open a fresh event loop per unit.
This commit is contained in:
Sirius DevOps 2026-08-24 15:37:42 -04:00
commit 627990efde
19 changed files with 1428 additions and 10 deletions

View file

@ -9,9 +9,11 @@ from datetime import datetime, timezone
import nats
from nats.errors import TimeoutError
from sqlalchemy.dialects.postgresql import insert as pg_insert
from database import async_session
from models import events as events_table
from models import fires as fires_table
from config import NATS_URL
logger = logging.getLogger("osint.ingestor")
@ -22,8 +24,86 @@ NATS_STREAM = "events"
NATS_DURABLE = "osint-ingestor"
# ── Active fire / hotspot routing ─────────────────────────────────────────
def _fire_row_from_msg(msg: dict) -> dict | None:
"""Map a NATS fire message to a ``fires`` table row (pre-DB, unit-testable).
Returns None (dropped) when the idempotency key fields — latitude,
longitude, acq_time, satellite — are missing or unparseable.
"""
row = {
"latitude": msg.get("latitude"),
"longitude": msg.get("longitude"),
"brightness": msg.get("brightness"),
"confidence": msg.get("confidence"),
"acq_time": msg.get("acq_time"),
"satellite": msg.get("satellite"),
"instrument": msg.get("instrument"),
"bright_ti5": msg.get("bright_ti5"),
"frp": msg.get("frp"),
"daynight": msg.get("daynight"),
"scan": msg.get("scan"),
"track": msg.get("track"),
"version": msg.get("version"),
"raw": msg.get("raw"),
}
# Idempotency key must be complete; brightness/confidence may be absent in
# malformed feeds but lat/lon/time/satellite are required for dedupe.
if (
row["latitude"] is None or row["longitude"] is None
or row["acq_time"] is None or not row["satellite"]
):
logger.warning(
"dropping malformed fire message (missing natural key): %s",
{k: msg.get(k) for k in ("latitude", "longitude", "acq_time", "satellite")},
)
return None
if isinstance(row["acq_time"], str):
try:
row["acq_time"] = datetime.fromisoformat(row["acq_time"])
except ValueError:
logger.warning("dropping fire message with bad acq_time %r", row["acq_time"])
return None
if not isinstance(row["acq_time"], datetime):
row["acq_time"] = datetime.fromisoformat(str(row["acq_time"]))
return row
async def ingest_fire_row(msg: dict) -> bool:
"""Persist one FIRMS hotspot, idempotently.
The (latitude, longitude, acq_time, satellite) primary key doubles as the
dedupe key: ON CONFLICT DO NOTHING means a hotspot re-delivered on a later
15-minute poll is silently ignored. Returns True if a new row was inserted,
False if it was a duplicate (or dropped).
"""
row = _fire_row_from_msg(msg)
if row is None:
return False
async with async_session() as session:
stmt = (
pg_insert(fires_table)
.values(**row)
.on_conflict_do_nothing(constraint="pk_fires_natural_key")
)
result = await session.execute(stmt)
await session.commit()
inserted = bool(result.rowcount)
if inserted:
logger.info(
"ingested fire %.5f,%.5f %s satellite=%s",
row["latitude"], row["longitude"], row["acq_time"], row["satellite"],
)
return inserted
async def ingest_event(msg: dict):
"""Ingest a single event from NATS into PostgreSQL."""
# Active fire/hotspot messages carry a dedicated schema and land in the
# `fires` hypertable (idempotent natural key), not the generic events feed.
if msg.get("source_type") == "fire":
return await ingest_fire_row(msg)
# source_id links to a feed_sources UUID; tolerate non-UUID / missing values
# (e.g. legacy messages that carried a URL) by coercing to None.
raw_source_id = msg.get("source_id")