feat(geofence): watch list, filtered hit log, fence snapshot
Off-viewport clients that send {type:watch_geofences,ids} on /ws/live
still receive geofence_alert; AIS/ADS-B stay viewport-only.
GET /api/geofence-alerts accepts geofence_id/since/until/source_kind.
GET /api/geofences/{id}/at returns CAGG+FIRMS inside the fence at T
(404 if missing, empty lists if DB down). DELETE missing fences 404s.
This commit is contained in:
parent
6ff2fd0351
commit
f6c1cfc454
6 changed files with 625 additions and 37 deletions
151
app/geofence.py
151
app/geofence.py
|
|
@ -319,3 +319,154 @@ async def record_and_notify(
|
|||
except Exception:
|
||||
pass
|
||||
return sent
|
||||
|
||||
|
||||
async def list_alerts(
|
||||
*,
|
||||
geofence_id: str | None = None,
|
||||
since: datetime | None = None,
|
||||
until: datetime | None = None,
|
||||
source_kind: str | None = None,
|
||||
limit: int = 100,
|
||||
) -> list[dict]:
|
||||
"""Filterable hit log. Empty list if the DB is down — never raises."""
|
||||
where = ["TRUE"]
|
||||
params: dict[str, Any] = {"limit": int(limit)}
|
||||
if geofence_id:
|
||||
where.append("geofence_id = CAST(:geofence_id AS uuid)")
|
||||
params["geofence_id"] = geofence_id
|
||||
if since is not None:
|
||||
where.append("created_at >= :since")
|
||||
params["since"] = since
|
||||
if until is not None:
|
||||
where.append("created_at <= :until")
|
||||
params["until"] = until
|
||||
if source_kind:
|
||||
where.append("source_kind = :source_kind")
|
||||
params["source_kind"] = source_kind
|
||||
sql = f"""
|
||||
SELECT id::text, geofence_id::text, source_kind, entity_id,
|
||||
lat, lon, payload, created_at
|
||||
FROM geofence_alerts
|
||||
WHERE {' AND '.join(where)}
|
||||
ORDER BY created_at DESC
|
||||
LIMIT :limit
|
||||
"""
|
||||
try:
|
||||
async with async_session() as session:
|
||||
rows = (await session.execute(text(sql), params)).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 []
|
||||
|
||||
|
||||
async def get_geofence(gid: str) -> dict | None:
|
||||
current = next((f for f in _cache if f["id"] == gid), None)
|
||||
if current is not None:
|
||||
return current
|
||||
try:
|
||||
await refresh_cache()
|
||||
except Exception:
|
||||
return None
|
||||
return next((f for f in _cache if f["id"] == gid), None)
|
||||
|
||||
|
||||
def _marker_from_track(row) -> dict:
|
||||
from live_layers import to_marker
|
||||
|
||||
extra = {"bucket": row["bucket"].isoformat() if row.get("bucket") else None, "dvr": True}
|
||||
return to_marker(
|
||||
row["id"], row["lat"], row["lon"],
|
||||
heading=row.get("heading"), speed=row.get("speed"),
|
||||
label=row.get("label") or row["id"],
|
||||
extra=extra,
|
||||
)
|
||||
|
||||
|
||||
async def _cagg_inside(gid: str, kind: str, bucket: datetime, limit: int = 2000) -> list[dict]:
|
||||
table = "aircraft_tracks_1min" if kind == "aircraft" else "vessel_tracks_1min"
|
||||
id_col = "hex" if kind == "aircraft" else "mmsi"
|
||||
sql = f"""
|
||||
SELECT {id_col} AS id, lat, lon, heading, speed, label, bucket
|
||||
FROM {table}
|
||||
WHERE bucket = :bucket
|
||||
AND ST_Intersects(
|
||||
(SELECT geom FROM geofences WHERE id = CAST(:gid AS uuid)),
|
||||
ST_SetSRID(ST_MakePoint(lon, lat), 4326)
|
||||
)
|
||||
LIMIT :limit
|
||||
"""
|
||||
try:
|
||||
async with async_session() as session:
|
||||
rows = (await session.execute(
|
||||
text(sql), {"bucket": bucket, "gid": gid, "limit": limit},
|
||||
)).mappings().all()
|
||||
return [
|
||||
_marker_from_track(r)
|
||||
for r in rows
|
||||
if r["lat"] is not None and r["lon"] is not None
|
||||
]
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
async def _fires_inside(gid: str, ts: datetime, limit: int = 2000) -> list[dict]:
|
||||
from tracks import minute_bucket
|
||||
|
||||
bucket = minute_bucket(ts)
|
||||
t1 = bucket + timedelta(minutes=1)
|
||||
sql = """
|
||||
SELECT latitude, longitude, brightness, confidence, acq_time, satellite,
|
||||
instrument, bright_ti5, frp, daynight
|
||||
FROM fires
|
||||
WHERE acq_time >= :t0 AND acq_time < :t1
|
||||
AND ST_Intersects(
|
||||
(SELECT geom FROM geofences WHERE id = CAST(:gid AS uuid)),
|
||||
ST_SetSRID(ST_MakePoint(longitude, latitude), 4326)
|
||||
)
|
||||
LIMIT :limit
|
||||
"""
|
||||
try:
|
||||
async with async_session() as session:
|
||||
rows = (await session.execute(
|
||||
text(sql),
|
||||
{"t0": bucket, "t1": t1, "gid": gid, "limit": limit},
|
||||
)).mappings().all()
|
||||
out = []
|
||||
for r in rows:
|
||||
item = dict(r)
|
||||
if item.get("acq_time") is not None:
|
||||
item["acq_time"] = item["acq_time"].isoformat()
|
||||
out.append(item)
|
||||
return out
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
async def snapshot_at(gid: str, ts: datetime) -> dict | None:
|
||||
"""Positions inside the fence at time T. None if the fence is missing.
|
||||
|
||||
Does not persist or notify. Empty lists if track/fire queries fail.
|
||||
"""
|
||||
fence = await get_geofence(gid)
|
||||
if fence is None:
|
||||
return None
|
||||
from tracks import minute_bucket
|
||||
|
||||
bucket = minute_bucket(ts)
|
||||
aircraft = await _cagg_inside(gid, "aircraft", bucket)
|
||||
vessels = await _cagg_inside(gid, "vessel", bucket)
|
||||
fires = await _fires_inside(gid, ts)
|
||||
return {
|
||||
"geofence_id": gid,
|
||||
"timestamp": ts.isoformat(),
|
||||
"aircraft": aircraft,
|
||||
"vessels": vessels,
|
||||
"fires": fires,
|
||||
}
|
||||
|
|
|
|||
92
app/main.py
92
app/main.py
|
|
@ -873,7 +873,14 @@ async def trigger_social_ingest(query: str = "", max_items: int = 50):
|
|||
|
||||
@app.websocket("/ws/live")
|
||||
async def live_ws(ws: WebSocket):
|
||||
"""Viewport-filtered AIS/ADS-B fan-out. Client sends {type:viewport,bbox}."""
|
||||
"""Viewport-filtered AIS/ADS-B fan-out.
|
||||
|
||||
Client JSON:
|
||||
{"type":"viewport","bbox":"minlon,minlat,maxlon,maxlat"}
|
||||
{"type":"watch_geofences","ids":["<uuid>", ...]} — empty list = none
|
||||
geofence_alert delivers if the point is in-viewport OR geofence_id is watched.
|
||||
AIS/ADS-B/fire_aircraft stay viewport-only.
|
||||
"""
|
||||
from ws_manager import manager
|
||||
|
||||
client_id = str(id(ws))
|
||||
|
|
@ -899,6 +906,10 @@ async def live_ws(ws: WebSocket):
|
|||
manager.set_viewport(client_id, parse_bbox(str(data["bbox"])))
|
||||
except ValueError:
|
||||
continue
|
||||
elif data.get("type") == "watch_geofences":
|
||||
ids = data.get("ids") or []
|
||||
if isinstance(ids, list):
|
||||
manager.set_watched_geofences(client_id, [str(x) for x in ids])
|
||||
except WebSocketDisconnect:
|
||||
pass
|
||||
finally:
|
||||
|
|
@ -1757,33 +1768,68 @@ async def api_update_geofence(gid: str, payload: GeofenceUpdate):
|
|||
@app.delete("/api/geofences/{gid}", status_code=204)
|
||||
async def api_delete_geofence(gid: str):
|
||||
from geofence import delete_geofence
|
||||
await delete_geofence(gid)
|
||||
ok = await delete_geofence(gid)
|
||||
if not ok:
|
||||
raise HTTPException(404, "geofence not found")
|
||||
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
|
||||
@app.get("/api/geofences/{gid}/at")
|
||||
async def api_geofence_at(
|
||||
gid: str,
|
||||
timestamp: str = Query(..., description="ISO-8601 instant for the 1-minute DVR bucket"),
|
||||
):
|
||||
"""Aircraft/vessels/fires inside this fence at time T. Never writes."""
|
||||
from geofence import snapshot_at
|
||||
from tracks import parse_timestamp
|
||||
|
||||
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
|
||||
ts = parse_timestamp(timestamp)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(422, str(exc)) from exc
|
||||
if ts is None:
|
||||
raise HTTPException(422, "timestamp required")
|
||||
try:
|
||||
body = await snapshot_at(gid, ts)
|
||||
except Exception:
|
||||
return []
|
||||
body = {
|
||||
"geofence_id": gid,
|
||||
"timestamp": ts.isoformat(),
|
||||
"aircraft": [],
|
||||
"vessels": [],
|
||||
"fires": [],
|
||||
}
|
||||
if body is None:
|
||||
raise HTTPException(404, "geofence not found")
|
||||
return body
|
||||
|
||||
|
||||
@app.get("/api/geofence-alerts")
|
||||
async def api_geofence_alerts(
|
||||
geofence_id: UUID | None = Query(None),
|
||||
since: str | None = Query(None, description="ISO-8601 inclusive lower bound"),
|
||||
until: str | None = Query(None, description="ISO-8601 inclusive upper bound"),
|
||||
source_kind: str | None = Query(None, description="firms|ais|adsb"),
|
||||
limit: int = Query(100, ge=1, le=500),
|
||||
):
|
||||
"""Hit log for drawn fences. Not /api/alerts (entity/keyword)."""
|
||||
from geofence import list_alerts
|
||||
from tracks import parse_timestamp
|
||||
|
||||
if source_kind is not None and source_kind not in ("firms", "ais", "adsb"):
|
||||
raise HTTPException(422, "source_kind must be one of: firms, ais, adsb")
|
||||
try:
|
||||
since_ts = parse_timestamp(since) if since else None
|
||||
until_ts = parse_timestamp(until) if until else None
|
||||
except ValueError as exc:
|
||||
raise HTTPException(422, str(exc)) from exc
|
||||
return await list_alerts(
|
||||
geofence_id=str(geofence_id) if geofence_id else None,
|
||||
since=since_ts,
|
||||
until=until_ts,
|
||||
source_kind=source_kind,
|
||||
limit=limit,
|
||||
)
|
||||
|
||||
|
||||
@app.get("/api/fire-aircraft")
|
||||
|
|
|
|||
|
|
@ -8,10 +8,18 @@ from __future__ import annotations
|
|||
|
||||
import asyncio
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
BBox = tuple[float, float, float, float] # minlon, minlat, maxlon, maxlat
|
||||
|
||||
|
||||
def _uuid_str(value: object) -> str | None:
|
||||
try:
|
||||
return str(UUID(str(value)))
|
||||
except (ValueError, TypeError, AttributeError):
|
||||
return None
|
||||
|
||||
|
||||
def point_in_bbox(lon: float, lat: float, bbox: BBox | None) -> bool:
|
||||
"""True if (lon, lat) sits inside an axis-aligned viewport."""
|
||||
if bbox is None:
|
||||
|
|
@ -26,6 +34,7 @@ class ConnectionManager:
|
|||
def __init__(self) -> None:
|
||||
self._queues: dict[str, asyncio.Queue] = {}
|
||||
self._viewports: dict[str, BBox] = {}
|
||||
self._watched: dict[str, set[str]] = {}
|
||||
|
||||
def register(self, client_id: str, maxsize: int = 256) -> asyncio.Queue:
|
||||
q: asyncio.Queue = asyncio.Queue(maxsize=maxsize)
|
||||
|
|
@ -35,6 +44,21 @@ class ConnectionManager:
|
|||
def unregister(self, client_id: str) -> None:
|
||||
self._queues.pop(client_id, None)
|
||||
self._viewports.pop(client_id, None)
|
||||
self._watched.pop(client_id, None)
|
||||
|
||||
def set_watched_geofences(self, client_id: str, ids: list[str]) -> None:
|
||||
"""Watch these fence UUIDs so geofence_alert delivers off-viewport.
|
||||
|
||||
Invalid UUIDs are ignored. Empty list = watch none (viewport-only).
|
||||
"""
|
||||
if client_id not in self._queues:
|
||||
return
|
||||
watched: set[str] = set()
|
||||
for raw in ids:
|
||||
uid = _uuid_str(raw)
|
||||
if uid is not None:
|
||||
watched.add(uid)
|
||||
self._watched[client_id] = watched
|
||||
|
||||
def set_viewport(self, client_id: str, bbox: BBox) -> None:
|
||||
if client_id in self._queues:
|
||||
|
|
@ -59,13 +83,21 @@ class ConnectionManager:
|
|||
) -> int:
|
||||
"""Enqueue `{type, payload}` for clients whose viewport contains the point.
|
||||
|
||||
Drops the oldest queued message if a client's buffer is full so a slow
|
||||
tab cannot stall ingest. Returns the number of clients that got a copy.
|
||||
kind=geofence_alert also delivers when payload.geofence_id is in the
|
||||
client's watch set (even if the point is off-viewport). Other kinds
|
||||
stay viewport-only. Drops the oldest queued message if a client's
|
||||
buffer is full. Returns the number of clients that got a copy.
|
||||
"""
|
||||
msg = {"type": kind, "payload": payload}
|
||||
sent = 0
|
||||
gid = _uuid_str(payload.get("geofence_id")) if kind == "geofence_alert" else None
|
||||
for client_id, queue in list(self._queues.items()):
|
||||
if not point_in_bbox(lon, lat, self._viewports.get(client_id)):
|
||||
in_view = point_in_bbox(lon, lat, self._viewports.get(client_id))
|
||||
if kind == "geofence_alert":
|
||||
watching = gid is not None and gid in self._watched.get(client_id, set())
|
||||
if not in_view and not watching:
|
||||
continue
|
||||
elif not in_view:
|
||||
continue
|
||||
if queue.full():
|
||||
try:
|
||||
|
|
|
|||
Loading…
Reference in a new issue