feat: lean-Pi WS fan-out, geofences, DVR playback, fire/aircraft correlation

Phase 1: in-memory ConnectionManager viewport fan-out, 500ms map debounce,
cachetools TTLCache, background masscan/ffmpeg, compose memory caps.

Phase 2: PostGIS geofences + ST_Intersects alerts, Timescale 1-min CAGGs
and timestamp playback, FIRMS/WFIGS x firefighting ADS-B within 20 miles.

No Redis/Kafka/Celery.
This commit is contained in:
Sirius DevOps 2026-08-28 09:33:19 -04:00
commit 5ea9a4e879
28 changed files with 2318 additions and 50 deletions

View file

@ -21,7 +21,7 @@ from pathlib import Path
from uuid import UUID
import structlog
from fastapi import FastAPI, HTTPException, Query
from fastapi import BackgroundTasks, FastAPI, HTTPException, Query, WebSocket, WebSocketDisconnect
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
@ -41,6 +41,7 @@ from schemas import (
KeyOut, KeyValueIn,
SearchResult, SentimentSummary, SourceType,
SearchQuery, TimelinePoint, VesselBboxUpdate,
GeofenceCreate, GeofenceUpdate,
)
from ingestor import ingest_event, fetch_and_process
from sources import ingest_rss_feed, ingest_gdelt, ingest_earthquakes, ingest_social_signals
@ -61,6 +62,11 @@ async def _lifespan(app: FastAPI):
await init_extensions()
from live_layers import close_http, init_http
await init_http()
try:
from geofence import refresh_cache
await refresh_cache()
except Exception:
pass
from config import AISSTREAM_IN_APP
ais_task = None
if AISSTREAM_IN_APP:
@ -664,6 +670,56 @@ async def trigger_social_ingest(query: str = "", max_items: int = 50):
return {"status": "ok", "signals_ingested": count}
@app.post("/api/ingest/masscan")
async def trigger_masscan(background_tasks: BackgroundTasks):
"""Queue one masscan pass at ≤200 pps. Does not block the request on the scan."""
from bg_jobs import MASSCAN_PPS_CAP, schedule_masscan_pass
async def _kick() -> None:
schedule_masscan_pass()
background_tasks.add_task(_kick)
return JSONResponse(
{"status": "accepted", "rate_pps": MASSCAN_PPS_CAP},
status_code=202,
)
@app.websocket("/ws/live")
async def live_ws(ws: WebSocket):
"""Viewport-filtered AIS/ADS-B fan-out. Client sends {type:viewport,bbox}."""
from ws_manager import manager
client_id = str(id(ws))
await ws.accept()
queue = manager.register(client_id)
async def _pump() -> None:
try:
while True:
msg = await queue.get()
await ws.send_json(msg)
except Exception: # noqa: BLE001
return
pump = asyncio.create_task(_pump())
try:
while True:
data = await ws.receive_json()
if not isinstance(data, dict):
continue
if data.get("type") == "viewport" and data.get("bbox"):
try:
manager.set_viewport(client_id, parse_bbox(str(data["bbox"])))
except ValueError:
continue
except WebSocketDisconnect:
pass
finally:
pump.cancel()
manager.unregister(client_id)
@app.post("/api/ingest/process")
async def trigger_nats_processing(batch_size: int = 100):
"""Process pending NATS JetStream messages."""
@ -1135,10 +1191,15 @@ async def map_radar():
async def list_aircraft(
bbox: str = Query(..., description="minlon,minlat,maxlon,maxlat"),
limit: int = Query(2000, ge=1, le=5000),
timestamp: str | None = Query(None, description="ISO time — DVR 1-min tracks instead of live"),
):
"""Viewport ADS-B last-known (ADSB.lol). Requires bbox; radius clamped ≤ 150 nm."""
_parse_bbox_query(bbox)
try:
from tracks import fetch_positions_at, parse_timestamp
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)
except ValueError as exc:
raise HTTPException(422, str(exc)) from exc
@ -1166,11 +1227,16 @@ async def list_trains(
async def list_vessels(
bbox: str | None = Query(None, description="minlon,minlat,maxlon,maxlat"),
limit: int = Query(2000, ge=1, le=5000),
timestamp: str | None = Query(None, description="ISO time — DVR 1-min tracks instead of live"),
):
"""AIS last-known from the server-side AISStream worker. Empty without a key."""
if bbox:
_parse_bbox_query(bbox)
try:
from tracks import fetch_positions_at, parse_timestamp
ts = parse_timestamp(timestamp)
if ts is not None:
return overlay_json(await fetch_positions_at("vessel", ts, bbox, limit), 5)
return overlay_json(await fetch_vessels(bbox, limit), 5)
except ValueError as exc:
raise HTTPException(422, str(exc)) from exc
@ -1204,6 +1270,90 @@ async def vessels_subscribe(payload: VesselBboxUpdate):
return {"ok": True, "bbox": raw}
@app.get("/api/tracks/range")
async def tracks_range():
"""Earliest/latest 1-minute track buckets for the DVR slider."""
from tracks import track_range
return await track_range()
@app.get("/api/geofences")
async def api_list_geofences():
"""Drawn GeoJSON polygons. Not /api/alerts (entity/keyword)."""
from geofence import list_geofences
return await list_geofences()
@app.post("/api/geofences", status_code=201)
async def api_create_geofence(payload: GeofenceCreate):
from geofence import create_geofence, validate_polygon_geojson
try:
validate_polygon_geojson(payload.geojson)
except ValueError as exc:
raise HTTPException(422, str(exc)) from exc
try:
return await create_geofence(payload.name, payload.geojson, payload.active)
except HTTPException:
raise
except Exception as exc:
raise HTTPException(503, f"geofence persist failed: {exc}") from exc
@app.patch("/api/geofences/{gid}")
async def api_update_geofence(gid: str, payload: GeofenceUpdate):
from geofence import update_geofence, validate_polygon_geojson
if payload.geojson is not None:
try:
validate_polygon_geojson(payload.geojson)
except ValueError as exc:
raise HTTPException(422, str(exc)) from exc
row = await update_geofence(
gid, name=payload.name, geojson=payload.geojson, active=payload.active,
)
if row is None:
raise HTTPException(404, "geofence not found")
return row
@app.delete("/api/geofences/{gid}", status_code=204)
async def api_delete_geofence(gid: str):
from geofence import delete_geofence
await delete_geofence(gid)
return None
@app.get("/api/geofence-alerts")
async def api_geofence_alerts(limit: int = Query(100, ge=1, le=500)):
from sqlalchemy import text as sql_text
try:
async with async_session() as session:
rows = (await session.execute(sql_text(
"""
SELECT id::text, geofence_id::text, source_kind, entity_id,
lat, lon, payload, created_at
FROM geofence_alerts
ORDER BY created_at DESC
LIMIT :limit
"""
), {"limit": limit})).mappings().all()
out = []
for r in rows:
item = dict(r)
if item.get("created_at") is not None:
item["created_at"] = item["created_at"].isoformat()
out.append(item)
return out
except Exception:
return []
@app.get("/api/fire-aircraft")
async def api_fire_aircraft(limit: int = Query(200, ge=1, le=1000)):
"""Persisted firefighting ADS-B × wildfire correlations (20 mi)."""
from fire_aircraft import recent_hits
return await recent_hits(limit)
@app.get("/api/fire-incidents")
async def list_fire_incidents(
bbox: str | None = Query(None),