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
|
|
@ -162,6 +162,16 @@ async def publish_fire_batch(points: list[dict]) -> int:
|
|||
return len(points)
|
||||
|
||||
|
||||
async def persist_hotspots(points: list[dict]) -> int:
|
||||
"""Write a FIRMS poll to Postgres in one ON CONFLICT batch.
|
||||
|
||||
NATS-per-row was 93k commits + geofence/correlation per hotspot.
|
||||
"""
|
||||
from ingestor import ingest_fire_rows
|
||||
|
||||
return await ingest_fire_rows(points)
|
||||
|
||||
|
||||
async def ingest_fires(bbox: str | None = None) -> int:
|
||||
"""Fetch the FIRMS hotspot CSV for an area and publish it to NATS.
|
||||
|
||||
|
|
@ -206,7 +216,7 @@ async def ingest_fires(bbox: str | None = None) -> int:
|
|||
)
|
||||
continue
|
||||
points = parse_firms_csv(text)
|
||||
published = await publish_fire_batch(points)
|
||||
published = await persist_hotspots(points)
|
||||
total_published += published
|
||||
logger.info(
|
||||
"FIRMS: fetched %d hotspot(s) for bbox=%s (%s), published %d",
|
||||
|
|
|
|||
|
|
@ -14,7 +14,9 @@ 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 models import event_dedup as event_dedup_table
|
||||
from config import NATS_URL
|
||||
from sources import event_dedup_key
|
||||
|
||||
logger = logging.getLogger("osint.ingestor")
|
||||
|
||||
|
|
@ -115,6 +117,42 @@ async def ingest_fire_row(msg: dict) -> bool:
|
|||
return inserted
|
||||
|
||||
|
||||
async def ingest_fire_rows(msgs: list[dict]) -> int:
|
||||
"""Bulk-insert FIRMS hotspots: one INSERT, one ON CONFLICT, one commit."""
|
||||
rows = []
|
||||
for msg in msgs:
|
||||
row = _fire_row_from_msg(msg)
|
||||
if row is not None:
|
||||
rows.append(row)
|
||||
if not rows:
|
||||
return 0
|
||||
async with async_session() as session:
|
||||
stmt = (
|
||||
pg_insert(fires_table)
|
||||
.values(rows)
|
||||
.on_conflict_do_nothing(constraint="pk_fires_natural_key")
|
||||
)
|
||||
result = await session.execute(stmt)
|
||||
await session.commit()
|
||||
inserted = int(result.rowcount or 0)
|
||||
if inserted:
|
||||
logger.info("bulk ingested %d/%d FIRMS hotspots", inserted, len(rows))
|
||||
from live_layers import aircraft_last_known
|
||||
from fire_aircraft import correlate_and_notify
|
||||
from tracks import recent_markers
|
||||
acs = list(aircraft_last_known.values()) or await recent_markers("aircraft")
|
||||
if acs:
|
||||
fires = [
|
||||
{
|
||||
"id": f"firms:{r['latitude']:.4f},{r['longitude']:.4f}",
|
||||
"lat": r["latitude"], "lon": r["longitude"], "label": "FIRMS",
|
||||
}
|
||||
for r in rows[:500]
|
||||
]
|
||||
await correlate_and_notify(fires, acs)
|
||||
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
|
||||
|
|
@ -149,10 +187,26 @@ async def ingest_event(msg: dict):
|
|||
}
|
||||
|
||||
# Parse timestamp if string
|
||||
if isinstance(event_row["source_timestamp"], str):
|
||||
event_row["source_timestamp"] = datetime.fromisoformat(event_row["source_timestamp"])
|
||||
ts = event_row["source_timestamp"]
|
||||
if isinstance(ts, str):
|
||||
ts = datetime.fromisoformat(ts.replace("Z", "+00:00"))
|
||||
if isinstance(ts, datetime) and ts.tzinfo is None:
|
||||
ts = ts.replace(tzinfo=timezone.utc)
|
||||
event_row["source_timestamp"] = ts
|
||||
|
||||
key = event_dedup_key(event_row)
|
||||
async with async_session() as session:
|
||||
if key:
|
||||
dedup = (
|
||||
pg_insert(event_dedup_table)
|
||||
.values(url=key)
|
||||
.on_conflict_do_nothing(index_elements=["url"])
|
||||
)
|
||||
claimed = await session.execute(dedup)
|
||||
if not claimed.rowcount:
|
||||
await session.commit()
|
||||
logger.info("skip duplicate event url=%s", key)
|
||||
return None
|
||||
result = await session.execute(events_table.insert().values(**event_row))
|
||||
await session.commit()
|
||||
event_id = result.inserted_primary_key[0] # type: ignore[union-attr]
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ or AIS poll.
|
|||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import math
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
|
|
@ -21,6 +22,8 @@ import httpx
|
|||
|
||||
from config import OSINT_USER_AGENT
|
||||
|
||||
logger = logging.getLogger("osint.live_layers")
|
||||
|
||||
MARKER_FIELDS = ("id", "lat", "lon", "heading", "speed", "label", "extra")
|
||||
|
||||
ADSB_LOL_BASE = "https://api.adsb.lol"
|
||||
|
|
@ -800,8 +803,24 @@ async def _get_json(url: str, params: dict | None = None) -> Any:
|
|||
return resp.json()
|
||||
|
||||
|
||||
async def fetch_aircraft(bbox: str, limit: int = DEFAULT_LIMIT) -> list[dict]:
|
||||
async def fetch_aircraft(
|
||||
bbox: str, limit: int = DEFAULT_LIMIT, persist: bool = False,
|
||||
) -> list[dict]:
|
||||
"""Viewport ADS-B.
|
||||
|
||||
GET path (persist=False) serves in-memory last-known and never writes
|
||||
tracks/geofences. Background refresh (persist=True) hits ADSB.lol and
|
||||
then persist_aircraft_snapshot.
|
||||
"""
|
||||
minlon, minlat, maxlon, maxlat = parse_bbox(bbox)
|
||||
if not persist:
|
||||
cached = [
|
||||
dict(v) for v in aircraft_last_known.values()
|
||||
if v.get("lat") is not None and v.get("lon") is not None
|
||||
]
|
||||
filtered = filter_points_bbox(cached, minlon, minlat, maxlon, maxlat, limit)
|
||||
if filtered:
|
||||
return filtered
|
||||
qminlon, qminlat, qmaxlon, qmaxlat = quantize_bbox(minlon, minlat, maxlon, maxlat)
|
||||
lat, lon, radius = bbox_center_radius_nm(qminlon, qminlat, qmaxlon, qmaxlat)
|
||||
cache_key = f"adsb:{lat:.2f}:{lon:.2f}:{radius}"
|
||||
|
|
@ -811,12 +830,20 @@ async def fetch_aircraft(bbox: str, limit: int = DEFAULT_LIMIT) -> list[dict]:
|
|||
return transform_adsb_lol(await _get_json(url))
|
||||
|
||||
rows = await _ttl_get(cache_key, 8.0, _load)
|
||||
for m in rows:
|
||||
aircraft_last_known[str(m.get("id"))] = m
|
||||
if persist:
|
||||
await persist_aircraft_snapshot(rows)
|
||||
return filter_points_bbox(rows, minlon, minlat, maxlon, maxlat, limit)
|
||||
|
||||
|
||||
async def persist_aircraft_snapshot(rows: list[dict]) -> None:
|
||||
"""Track / geofence / WS / fire correlation — never on the GET path."""
|
||||
from ws_manager import manager
|
||||
from tracks import record_position
|
||||
from geofence import record_and_notify
|
||||
aircraft_last_known.clear()
|
||||
|
||||
for m in rows:
|
||||
aircraft_last_known[str(m.get("id"))] = m
|
||||
mlat, mlon = m.get("lat"), m.get("lon")
|
||||
if mlat is None or mlon is None:
|
||||
continue
|
||||
|
|
@ -830,7 +857,6 @@ async def fetch_aircraft(bbox: str, limit: int = DEFAULT_LIMIT) -> list[dict]:
|
|||
if fire_last_known:
|
||||
from fire_aircraft import correlate_and_notify
|
||||
await correlate_and_notify(fire_last_known, rows)
|
||||
return filter_points_bbox(rows, minlon, minlat, maxlon, maxlat, limit)
|
||||
|
||||
|
||||
async def fetch_trains(bbox: str | None, limit: int = DEFAULT_LIMIT) -> list[dict]:
|
||||
|
|
@ -964,13 +990,16 @@ async def fetch_weather_alerts(area: str | None, bbox: str | None) -> dict:
|
|||
clip_box = None
|
||||
if area:
|
||||
nws_params["area"] = area.upper()
|
||||
elif bbox:
|
||||
if bbox:
|
||||
clip_box = quantize_bbox(*parse_bbox(bbox))
|
||||
nws_params["bbox"] = f"{clip_box[0]},{clip_box[1]},{clip_box[2]},{clip_box[3]}"
|
||||
# NWS /alerts/active 400s on bbox= — never send it; clip locally.
|
||||
nws_fc: dict = {"features": []}
|
||||
nws_ok = True
|
||||
try:
|
||||
nws_fc = await _get_json(NWS_ALERTS, nws_params)
|
||||
except Exception:
|
||||
except Exception as exc:
|
||||
logger.warning("NWS alerts fetch failed: %s", exc)
|
||||
nws_ok = False
|
||||
nws_fc = {"features": []}
|
||||
sbw_fc = await _ttl_get("iem:sbw", 45.0, _load_iem)
|
||||
features = []
|
||||
|
|
@ -988,11 +1017,15 @@ async def fetch_weather_alerts(area: str | None, bbox: str | None) -> dict:
|
|||
if "event" not in props:
|
||||
props["event"] = props.get("ps") or "Storm-based warning"
|
||||
features.append({**feat, "properties": slim_alert_properties(props)})
|
||||
merged = {"type": "FeatureCollection", "features": features}
|
||||
merged = {"type": "FeatureCollection", "features": features, "nws_ok": nws_ok}
|
||||
if clip_box:
|
||||
merged = clip_fc_to_bbox(merged, *clip_box)
|
||||
clipped = clip_fc_to_bbox(merged, *clip_box)
|
||||
clipped["nws_ok"] = nws_ok
|
||||
merged = clipped
|
||||
elif bbox:
|
||||
merged = clip_fc_to_bbox(merged, *parse_bbox(bbox))
|
||||
clipped = clip_fc_to_bbox(merged, *parse_bbox(bbox))
|
||||
clipped["nws_ok"] = nws_ok
|
||||
merged = clipped
|
||||
return merged
|
||||
|
||||
key = f"alerts:{area or ''}:{bbox_cell_key(bbox) if bbox else ''}"
|
||||
|
|
|
|||
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__":
|
||||
|
|
|
|||
|
|
@ -68,6 +68,15 @@ Index("ix_events_search_vector", events.c.search_vector, postgresql_using="gin")
|
|||
# Spatial index on location
|
||||
Index("ix_events_location", events.c.location_lat, events.c.location_lon)
|
||||
|
||||
# Timescale unique indexes must include the partition column, so URL
|
||||
# idempotency lives on a regular table — not the events hypertable.
|
||||
event_dedup = Table(
|
||||
"event_dedup",
|
||||
metadata,
|
||||
Column("url", Text, primary_key=True),
|
||||
Column("created_at", DateTime(timezone=True), server_default=func.now(), nullable=False),
|
||||
)
|
||||
|
||||
|
||||
# ── Entities (people, organizations, locations of interest) ──────────────
|
||||
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ import sys
|
|||
sys.path.insert(0, sys_path)
|
||||
|
||||
from config import NATS_URL, FIRMS_INTERVAL, FIRMS_DATASET, AISSTREAM_IN_INGEST # noqa: E402
|
||||
from sources import ingest_rss_feed, ingest_gdelt, ingest_earthquakes # noqa: E402
|
||||
from sources import ingest_rss_feed, ingest_gdelt, ingest_earthquakes, ingest_eonet, ingest_cisa_kev # noqa: E402
|
||||
from fire_sources import ingest_fires # noqa: E402
|
||||
from ingestor import ingest_event, start_nats_consumer # noqa: E402
|
||||
|
||||
|
|
@ -37,6 +37,8 @@ INTERVAL = int(os.getenv("INGEST_INTERVAL", "300"))
|
|||
GDELT_QUERY = os.getenv("GDELT_QUERY", "")
|
||||
ENABLE_QUAKES = os.getenv("INGEST_EARTHQUAKES", "1").lower() in ("1", "true", "yes")
|
||||
ENABLE_FIRES = os.getenv("INGEST_FIRES", "1").lower() in ("1", "true", "yes")
|
||||
ENABLE_EONET = os.getenv("INGEST_EONET", "1").lower() in ("1", "true", "yes")
|
||||
ENABLE_KEV = os.getenv("INGEST_KEV", "1").lower() in ("1", "true", "yes")
|
||||
|
||||
NATS_STREAM = "events"
|
||||
|
||||
|
|
@ -62,6 +64,18 @@ async def producer_loop() -> None:
|
|||
logger.info("USGS -> %d events", q)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("USGS fetch failed")
|
||||
if ENABLE_EONET:
|
||||
try:
|
||||
n = await ingest_eonet()
|
||||
logger.info("EONET -> %d events", n)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("EONET fetch failed")
|
||||
if ENABLE_KEV:
|
||||
try:
|
||||
k = await ingest_cisa_kev()
|
||||
logger.info("CISA KEV -> %d events", k)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("CISA KEV fetch failed")
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("producer cycle error")
|
||||
await asyncio.sleep(INTERVAL)
|
||||
|
|
|
|||
294
app/sources.py
294
app/sources.py
|
|
@ -11,7 +11,7 @@ import httpx
|
|||
import feedparser
|
||||
import nats
|
||||
|
||||
from config import NATS_URL
|
||||
from config import NATS_URL, OSINT_USER_AGENT
|
||||
from upstream_cache import rss_cache
|
||||
|
||||
logger = logging.getLogger("osint.sources")
|
||||
|
|
@ -26,26 +26,46 @@ def _parse_rfc822(date_str: object) -> str | None:
|
|||
except (ValueError, TypeError):
|
||||
return None
|
||||
|
||||
# NATS connection
|
||||
|
||||
NATS_URLS = NATS_URL
|
||||
_nc = None
|
||||
|
||||
|
||||
async def _jetstream():
|
||||
"""Reuse one NATS connection across publishes (no connect/close per event)."""
|
||||
global _nc
|
||||
if _nc is None or _nc.is_closed:
|
||||
_nc = await nats.connect(NATS_URLS)
|
||||
return _nc.jetstream()
|
||||
|
||||
|
||||
async def publish_event(subject: str, event: dict):
|
||||
"""Publish an event to NATS JetStream."""
|
||||
nc = await nats.connect(NATS_URLS)
|
||||
js = nc.jetstream()
|
||||
js = await _jetstream()
|
||||
await js.publish(subject, json.dumps(event).encode())
|
||||
await nc.close()
|
||||
logger.debug("Published event to %s", subject)
|
||||
|
||||
|
||||
def event_dedup_key(msg: dict) -> str | None:
|
||||
"""Natural key for generic events. URL when present; else None (always insert)."""
|
||||
url = msg.get("url")
|
||||
if not isinstance(url, str):
|
||||
return None
|
||||
url = url.strip()
|
||||
return url or None
|
||||
|
||||
|
||||
def _ua_headers() -> dict[str, str]:
|
||||
return {"User-Agent": OSINT_USER_AGENT}
|
||||
|
||||
|
||||
# ─── RSS Feed Ingestor ──────────────────────────────────────────────────
|
||||
|
||||
async def ingest_rss_feed(feed_url: str, source_id: str | None = None):
|
||||
"""Fetch and parse an RSS feed, publish items to NATS."""
|
||||
text = rss_cache.get(feed_url)
|
||||
if text is None:
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
async with httpx.AsyncClient(timeout=30, headers=_ua_headers()) as client:
|
||||
resp = await client.get(feed_url)
|
||||
resp.raise_for_status()
|
||||
text = resp.text
|
||||
|
|
@ -76,51 +96,80 @@ async def ingest_rss_feed(feed_url: str, source_id: str | None = None):
|
|||
return count
|
||||
|
||||
|
||||
# ─── GDELT 2.0 Ingestor ─────────────────────────────────────────────────
|
||||
# ─── GDELT 2.0 DOC API ──────────────────────────────────────────────────
|
||||
|
||||
GDELT_API = "https://api.gdeltproject.org/gdeltv2"
|
||||
GDELT_API = "https://api.gdeltproject.org/api/v2/doc/doc"
|
||||
GDELT_DEFAULT_QUERY = '(unrest OR protest OR outage OR cyber OR "power outage")'
|
||||
|
||||
|
||||
def gdelt_params(query: str = "", max_articles: int = 50) -> dict[str, str]:
|
||||
"""DOC 2.0 query string (not the retired gdeltv2 ``search`` param)."""
|
||||
q = (query or "").strip() or GDELT_DEFAULT_QUERY
|
||||
return {
|
||||
"query": q,
|
||||
"mode": "ArtList",
|
||||
"format": "json",
|
||||
"maxrecords": str(int(max_articles)),
|
||||
"timespan": "1d",
|
||||
}
|
||||
|
||||
|
||||
def _parse_gdelt_seendate(value: object) -> str:
|
||||
if isinstance(value, str) and len(value) >= 15:
|
||||
try:
|
||||
return datetime.strptime(value[:15], "%Y%m%dT%H%M%S").replace(
|
||||
tzinfo=timezone.utc
|
||||
).isoformat()
|
||||
except ValueError:
|
||||
pass
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def parse_gdelt_articles(data: dict) -> list[dict]:
|
||||
events = []
|
||||
for article in data.get("articles") or []:
|
||||
if not isinstance(article, dict):
|
||||
continue
|
||||
url = article.get("url")
|
||||
if not url:
|
||||
continue
|
||||
events.append({
|
||||
"source_type": "gdel-t2",
|
||||
"title": article.get("title"),
|
||||
"body": article.get("domain") or article.get("language"),
|
||||
"url": url,
|
||||
"location_name": article.get("sourcecountry"),
|
||||
"source_timestamp": _parse_gdelt_seendate(article.get("seendate")),
|
||||
"tags": [t for t in (article.get("language"), article.get("sourcecountry")) if t],
|
||||
"raw": article,
|
||||
})
|
||||
return events
|
||||
|
||||
|
||||
async def ingest_gdelt(query: str = "", max_articles: int = 50):
|
||||
"""Fetch articles from GDELT 2.0 API."""
|
||||
params = {
|
||||
"mode": "artlist",
|
||||
"format": "json",
|
||||
"maxrecords": max_articles,
|
||||
"mode": "artlist",
|
||||
}
|
||||
if query:
|
||||
params["search"] = query
|
||||
"""Fetch articles from the GDELT DOC 2.0 API."""
|
||||
params = gdelt_params(query=query, max_articles=max_articles)
|
||||
data: dict = {"articles": []}
|
||||
async with httpx.AsyncClient(
|
||||
timeout=60, headers=_ua_headers(), follow_redirects=True,
|
||||
) as client:
|
||||
try:
|
||||
resp = await client.get(GDELT_API, params=params)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
except (httpx.TransportError, httpx.HTTPStatusError) as exc:
|
||||
# gdeltproject.org certs have expired in the wild; HTTP fallback.
|
||||
logger.warning("GDELT HTTPS failed (%s); retrying HTTP", exc)
|
||||
http_url = GDELT_API.replace("https://", "http://", 1)
|
||||
resp = await client.get(http_url, params=params)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
|
||||
async with httpx.AsyncClient(timeout=60) as client:
|
||||
resp = await client.get(GDELT_API, params=params)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
|
||||
count = 0
|
||||
for article in data.get("articles", []):
|
||||
event = {
|
||||
"source_type": "gdel-t2",
|
||||
"title": article.get("title"),
|
||||
"body": article.get("articleBody"),
|
||||
"url": article.get("url"),
|
||||
"sentiment_score": _parse_gdelt_tone(article.get("Tone", "0")),
|
||||
"location_lat": article.get("Latitude"),
|
||||
"location_lon": article.get("Longitude"),
|
||||
"location_name": article.get("Location"),
|
||||
"source_timestamp": article.get("FirstCreated"),
|
||||
"entities": [
|
||||
{"name": e.get("Topic"), "type": "topic"}
|
||||
for e in article.get("Mentions", [])
|
||||
if e.get("Topic")
|
||||
],
|
||||
"raw": article,
|
||||
}
|
||||
events = parse_gdelt_articles(data if isinstance(data, dict) else {})
|
||||
for event in events:
|
||||
await publish_event("events.gdelt", event)
|
||||
count += 1
|
||||
|
||||
logger.info("Ingested %d articles from GDELT", count)
|
||||
return count
|
||||
logger.info("Ingested %d articles from GDELT", len(events))
|
||||
return len(events)
|
||||
|
||||
|
||||
def _parse_gdelt_tone(tone: str) -> float | None:
|
||||
|
|
@ -137,34 +186,45 @@ def _parse_gdelt_tone(tone: str) -> float | None:
|
|||
USGS_API = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson"
|
||||
|
||||
|
||||
def parse_usgs_feature(feature: dict) -> dict:
|
||||
"""Map one USGS GeoJSON feature, keeping the stable event id."""
|
||||
props = feature.get("properties") or {}
|
||||
geometry = (feature.get("geometry") or {}).get("coordinates") or []
|
||||
usgs_id = feature.get("id")
|
||||
url = props.get("url") or (
|
||||
f"https://earthquake.usgs.gov/earthquakes/eventpage/{usgs_id}" if usgs_id else None
|
||||
)
|
||||
raw = dict(props)
|
||||
raw["usgs_id"] = usgs_id
|
||||
return {
|
||||
"source_type": "earthquake",
|
||||
"title": props.get("title"),
|
||||
"body": props.get("description"),
|
||||
"url": url,
|
||||
"location_lat": geometry[1] if len(geometry) > 1 else None,
|
||||
"location_lon": geometry[0] if len(geometry) > 0 else None,
|
||||
"location_name": props.get("place"),
|
||||
"sentiment_label": "neutral",
|
||||
"tags": [f"magnitude:{props.get('mag')}"] if props.get("mag") else [],
|
||||
"source_timestamp": (
|
||||
datetime.utcfromtimestamp(props.get("time", 0) / 1000)
|
||||
.replace(tzinfo=timezone.utc)
|
||||
.isoformat()
|
||||
),
|
||||
"raw": raw,
|
||||
}
|
||||
|
||||
|
||||
async def ingest_earthquakes():
|
||||
"""Fetch recent earthquakes from USGS."""
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
async with httpx.AsyncClient(timeout=30, headers=_ua_headers()) as client:
|
||||
resp = await client.get(USGS_API)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
|
||||
count = 0
|
||||
for feature in data.get("features", []):
|
||||
props = feature.get("properties", {})
|
||||
geometry = feature.get("geometry", {}).get("coordinates", [])
|
||||
event = {
|
||||
"source_type": "earthquake",
|
||||
"title": props.get("title"),
|
||||
"body": props.get("description"),
|
||||
"url": props.get("url"),
|
||||
"location_lat": geometry[1] if len(geometry) > 1 else None,
|
||||
"location_lon": geometry[0] if len(geometry) > 0 else None,
|
||||
"location_name": props.get("place"),
|
||||
"sentiment_label": "neutral",
|
||||
"tags": [f"magnitude:{props.get('mag')}"] if props.get("mag") else [],
|
||||
"source_timestamp": (
|
||||
datetime.utcfromtimestamp(props.get("time", 0) / 1000)
|
||||
.replace(tzinfo=timezone.utc)
|
||||
.isoformat()
|
||||
),
|
||||
"raw": props,
|
||||
}
|
||||
event = parse_usgs_feature(feature)
|
||||
await publish_event("events.earthquake", event)
|
||||
count += 1
|
||||
|
||||
|
|
@ -172,6 +232,110 @@ async def ingest_earthquakes():
|
|||
return count
|
||||
|
||||
|
||||
# ─── NASA EONET v3 ──────────────────────────────────────────────────────
|
||||
|
||||
EONET_API = "https://eonet.gsfc.nasa.gov/api/v3/events"
|
||||
|
||||
|
||||
def parse_eonet_events(payload: dict) -> list[dict]:
|
||||
events = []
|
||||
for item in payload.get("events") or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
eid = item.get("id")
|
||||
geoms = item.get("geometry") or []
|
||||
point = None
|
||||
for g in geoms:
|
||||
if isinstance(g, dict) and g.get("type") == "Point":
|
||||
point = g
|
||||
if point is None:
|
||||
continue
|
||||
coords = point.get("coordinates") or []
|
||||
if len(coords) < 2:
|
||||
continue
|
||||
lon, lat = float(coords[0]), float(coords[1])
|
||||
cats = item.get("categories") or []
|
||||
tags = []
|
||||
for c in cats:
|
||||
if isinstance(c, dict) and c.get("id"):
|
||||
tags.append(str(c["id"]))
|
||||
url = item.get("link") or (f"https://eonet.gsfc.nasa.gov/api/v3/events/{eid}" if eid else None)
|
||||
ts = point.get("date") or datetime.now(timezone.utc).isoformat()
|
||||
events.append({
|
||||
"source_type": "disaster",
|
||||
"title": item.get("title"),
|
||||
"body": ", ".join(tags) if tags else None,
|
||||
"url": url,
|
||||
"location_lat": lat,
|
||||
"location_lon": lon,
|
||||
"location_name": item.get("title"),
|
||||
"tags": tags,
|
||||
"source_timestamp": ts,
|
||||
"raw": {**item, "eonet_id": eid},
|
||||
})
|
||||
return events
|
||||
|
||||
|
||||
async def ingest_eonet():
|
||||
"""Volcanoes, storms, floods, drought — gaps USGS/FIRMS don't cover."""
|
||||
async with httpx.AsyncClient(timeout=30, headers=_ua_headers()) as client:
|
||||
resp = await client.get(EONET_API, params={"status": "open", "limit": 100})
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
events = parse_eonet_events(data if isinstance(data, dict) else {})
|
||||
for event in events:
|
||||
await publish_event("events.disaster", event)
|
||||
logger.info("Ingested %d EONET events", len(events))
|
||||
return len(events)
|
||||
|
||||
|
||||
# ─── CISA KEV ───────────────────────────────────────────────────────────
|
||||
|
||||
CISA_KEV_API = (
|
||||
"https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json"
|
||||
)
|
||||
|
||||
|
||||
def parse_cisa_kev(payload: dict) -> list[dict]:
|
||||
events = []
|
||||
for row in payload.get("vulnerabilities") or []:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
cve = row.get("cveID")
|
||||
if not cve:
|
||||
continue
|
||||
title = row.get("vulnerabilityName") or cve
|
||||
vendor = row.get("vendorProject") or ""
|
||||
product = row.get("product") or ""
|
||||
events.append({
|
||||
"source_type": "disaster",
|
||||
"title": f"{cve}: {title}",
|
||||
"body": row.get("shortDescription") or f"{vendor} {product}".strip(),
|
||||
"url": f"https://nvd.nist.gov/vuln/detail/{cve}",
|
||||
"location_lat": None,
|
||||
"location_lon": None,
|
||||
"location_name": None,
|
||||
"tags": ["cisa-kev", cve, "ransomware" if row.get("knownRansomwareCampaignUse") == "Known" else None],
|
||||
"source_timestamp": row.get("dateAdded") or datetime.now(timezone.utc).isoformat(),
|
||||
"raw": {**row, "cveID": cve},
|
||||
})
|
||||
events[-1]["tags"] = [t for t in events[-1]["tags"] if t]
|
||||
return events
|
||||
|
||||
|
||||
async def ingest_cisa_kev():
|
||||
"""Exploited-in-the-wild CVEs. No fake map coords — ticker/events only."""
|
||||
async with httpx.AsyncClient(timeout=30, headers=_ua_headers(), follow_redirects=True) as client:
|
||||
resp = await client.get(CISA_KEV_API)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
events = parse_cisa_kev(data if isinstance(data, dict) else {})
|
||||
for event in events:
|
||||
await publish_event("events.disaster", event)
|
||||
logger.info("Ingested %d CISA KEV rows", len(events))
|
||||
return len(events)
|
||||
|
||||
|
||||
# ─── Social Signals (Twitter/X-like placeholder) ────────────────────────
|
||||
|
||||
async def ingest_social_signals(query: str = "", max_items: int = 50):
|
||||
|
|
|
|||
|
|
@ -1149,9 +1149,12 @@ async function checkHealth() {
|
|||
try {
|
||||
const r = await fetch(`${API}/api/health`);
|
||||
const d = await r.json();
|
||||
if (r.ok) {
|
||||
if (r.ok && d && d.status === 'ok') {
|
||||
dot.className = 'dot ok';
|
||||
txt.textContent = 'SYSTEMS OK';
|
||||
} else if (r.ok) {
|
||||
dot.className = 'dot bad';
|
||||
txt.textContent = 'DEGRADED';
|
||||
} else {
|
||||
dot.className = 'dot bad';
|
||||
txt.textContent = 'DEGRADED';
|
||||
|
|
@ -1307,8 +1310,7 @@ function initMarketTicker() {
|
|||
loadMarketSymbols();
|
||||
buildMarketTrack(true);
|
||||
setMarketTag('standby');
|
||||
probeMarket();
|
||||
setInterval(probeMarket, MARKET_POLL_MS);
|
||||
// GET /api/market is not wired — do not 404-poll every 15s.
|
||||
}
|
||||
|
||||
/* ═══════════════ NEWS FEED + TICKER ═══════════════ */
|
||||
|
|
@ -1813,6 +1815,7 @@ function bboxCell() {
|
|||
return currentBBox().split(',').map(n => Number(n).toFixed(2)).join(',') + '@' + map.getZoom();
|
||||
}
|
||||
let liveWs = null;
|
||||
let wsRetryMs = 1000;
|
||||
const FF_ICAO = new Set(['AT802','AT8T','AT8P','C130','C30J','C130J','DC10','MD10','MD87','S64','UH60','S70','CL415','CL215','B350','OV10','C208']);
|
||||
let firefighterHex = new Set();
|
||||
let dvrTs = null;
|
||||
|
|
@ -1876,15 +1879,25 @@ function acColor(p) {
|
|||
}
|
||||
function connectLiveWs() {
|
||||
if (liveWs && (liveWs.readyState === 0 || liveWs.readyState === 1)) return;
|
||||
try { liveWs = new WebSocket(liveWsUrl()); } catch (e) { return; }
|
||||
liveWs.onopen = () => sendLiveViewport();
|
||||
try { liveWs = new WebSocket(liveWsUrl()); } catch (e) {
|
||||
const delay = wsRetryMs;
|
||||
wsRetryMs = Math.min(wsRetryMs * 2, 60000);
|
||||
setTimeout(connectLiveWs, delay);
|
||||
return;
|
||||
}
|
||||
liveWs.onopen = () => { wsRetryMs = 1000; sendLiveViewport(); };
|
||||
liveWs.onmessage = (ev) => {
|
||||
try {
|
||||
const msg = JSON.parse(ev.data);
|
||||
applyLiveMarker(msg.type, msg.payload);
|
||||
} catch (e) { /* ignore malformed */ }
|
||||
};
|
||||
liveWs.onclose = () => { liveWs = null; setTimeout(connectLiveWs, 4000); };
|
||||
liveWs.onclose = () => {
|
||||
liveWs = null;
|
||||
const delay = wsRetryMs;
|
||||
wsRetryMs = Math.min(wsRetryMs * 2, 60000);
|
||||
setTimeout(connectLiveWs, delay);
|
||||
};
|
||||
}
|
||||
function overlayFetch(url) {
|
||||
return fetch(url, overlayAbort ? { signal: overlayAbort.signal } : {});
|
||||
|
|
@ -2022,12 +2035,16 @@ async function initMap() {
|
|||
trainsOn = document.getElementById('lp-trains-on').checked;
|
||||
vesselsOn = document.getElementById('lp-vessels-on').checked;
|
||||
stormsOn = document.getElementById('lp-storms-on').checked;
|
||||
if (firesOn) loadFires();
|
||||
if (camsOn) loadCams();
|
||||
if (blipsOn) loadBlips();
|
||||
if (newsOn) loadNewsPins();
|
||||
refreshLiveOverlays();
|
||||
connectLiveWs();
|
||||
requestAnimationFrame(() => {
|
||||
if (firesOn) loadFires();
|
||||
setTimeout(() => {
|
||||
if (camsOn) loadCams();
|
||||
if (blipsOn) loadBlips();
|
||||
if (newsOn) loadNewsPins();
|
||||
refreshLiveOverlays();
|
||||
}, 250);
|
||||
});
|
||||
} catch(e) {
|
||||
hint.textContent = `Failed to load map layers: ${e.message || e}`;
|
||||
console.error('Map init failed', e);
|
||||
|
|
|
|||
|
|
@ -43,6 +43,9 @@ class ConnectionManager:
|
|||
def viewport_of(self, client_id: str) -> BBox | None:
|
||||
return self._viewports.get(client_id)
|
||||
|
||||
def viewports(self) -> list[BBox]:
|
||||
return list(self._viewports.values())
|
||||
|
||||
def has_clients(self) -> bool:
|
||||
return bool(self._queues)
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue