feat(geofence): hear quakes, WFIGS incidents, and news pins #61

Merged
sirius merged 1 commit from wt/t_02dd06a8 into master 2026-11-17 19:56:56 +00:00
7 changed files with 990 additions and 26 deletions
Showing only changes of commit d878655617 - Show all commits

feat(geofence): hear quakes, WFIGS incidents, and news pins

New hits carry a frozen evidence pack. adsb/ais/firms payloads stay
unchanged, and cameras are never passed to record_and_notify.
Sirius DevOps 2026-11-14 00:40:10 -05:00

View file

@ -7,6 +7,7 @@ in ``geofence_alerts`` and fan out as WS type ``geofence_alert``.
from __future__ import annotations
import json
import logging
from datetime import datetime, timedelta, timezone
from typing import Any
from uuid import uuid4
@ -15,6 +16,19 @@ from sqlalchemy import text
from database import async_session
logger = logging.getLogger("osint.geofence")
# New hit kinds. adsb/ais/firms omit ``evidence``; these three must include it.
# ``camera`` is never a hit kind.
EVIDENCE_KINDS = frozenset({"earthquake", "fire_incident", "news"})
_CAMERA_CAP = 5
_NEWS_CAP = 3
# Process-local "already paged" set for polled incidents. The 5-minute
# cooldown still applies; this stops a later poll (or a restart that
# re-reads the DB check) from treating a durable hit as new. Not used
# for moving adsb/ais/firms targets.
_notified_once: set[tuple[str, str, str]] = set()
def _rings_from_geojson(geojson: dict) -> list[list[list[float]]]:
if not isinstance(geojson, dict):
@ -99,6 +113,160 @@ _recent_hits: dict[tuple[str, str], datetime] = {}
_HIT_COOLDOWN = timedelta(minutes=5)
def iso_z(ts: datetime) -> str:
"""UTC ISO-8601 with a Z suffix so it is safe in a query string."""
if ts.tzinfo is None:
ts = ts.replace(tzinfo=timezone.utc)
return ts.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def snapshot_path(gid: str, ts: datetime) -> str:
return f"/api/geofences/{gid}/at?ts={iso_z(ts)}"
def camera_evidence(row: dict) -> dict:
"""Proxy path only. Never copy ``cameras.snapshot_url`` (agency / rtsp)."""
cid = str(row.get("id") or "")
name = row.get("name")
if name is None:
name = row.get("location_name") or ""
return {
"id": cid,
"name": str(name or ""),
"snapshot_url": f"/api/cameras/{cid}/snapshot",
}
def news_evidence(row: dict) -> dict:
return {
"headline": str(row.get("headline") or ""),
"url": str(row.get("url") or ""),
"importance": str(row.get("importance") or ""),
}
def evidence_pack(
gid: str, ts: datetime, cameras: list[dict], news: list[dict],
) -> dict:
return {
"cameras": [camera_evidence(r) for r in cameras[:_CAMERA_CAP]],
"news": [news_evidence(r) for r in news[:_NEWS_CAP]],
"snapshot": snapshot_path(gid, ts),
}
def polygon_bbox(geojson: dict) -> str | None:
"""``minlon,minlat,maxlon,maxlat`` of the outer ring, or None."""
try:
rings = _rings_from_geojson(geojson)
except (ValueError, TypeError, KeyError):
return None
pts = rings[0]
lons = [p[0] for p in pts]
lats = [p[1] for p in pts]
return f"{min(lons)},{min(lats)},{max(lons)},{max(lats)}"
def earthquake_entity_id(row: dict) -> str:
"""Stable id shared by the insert hook and the catch-up scan."""
raw = row.get("raw")
if isinstance(raw, str):
try:
raw = json.loads(raw)
except ValueError:
raw = None
if isinstance(raw, dict) and raw.get("usgs_id"):
return str(raw["usgs_id"])
url = row.get("url")
if url and str(url).strip():
return str(url).strip()
return str(row.get("id") or row.get("event_id") or "")
def fire_incident_entity_id(marker: dict) -> str:
"""IrwinID when the feed has one, else a stable name|state|discovered key."""
extra = marker.get("extra") or {}
for key in ("irwin_id", "unique_fire_id"):
val = extra.get(key)
if val:
return str(val)
name = marker.get("id") or marker.get("label") or "incident"
state = extra.get("state") or ""
discovered = extra.get("discovered") or ""
return f"{name}|{state}|{discovered}"
# Do not SELECT cameras.snapshot_url — that column is the agency/rtsp URL.
_CAMERAS_INSIDE_SQL = """
SELECT id::text AS id,
COALESCE(location_name, '') AS name
FROM cameras
WHERE location_lat IS NOT NULL
AND location_lon IS NOT NULL
AND ST_Intersects(
(SELECT geom FROM geofences WHERE id = CAST(:gid AS uuid)),
ST_SetSRID(ST_MakePoint(location_lon, location_lat), 4326)
)
ORDER BY ST_Distance(
ST_SetSRID(ST_MakePoint(location_lon, location_lat), 4326),
ST_SetSRID(ST_MakePoint(:lon, :lat), 4326)
)
LIMIT :limit
"""
_NEWS_INSIDE_SQL = """
SELECT headline,
COALESCE(url, '') AS url,
COALESCE(importance, '') AS importance
FROM news_items
WHERE lat IS NOT NULL
AND lon IS NOT NULL
AND ST_Intersects(
(SELECT geom FROM geofences WHERE id = CAST(:gid AS uuid)),
ST_SetSRID(ST_MakePoint(lon, lat), 4326)
)
ORDER BY created_at DESC
LIMIT :limit
"""
_ALREADY_SQL = """
SELECT 1
FROM geofence_alerts
WHERE geofence_id = CAST(:gid AS uuid)
AND source_kind = :source_kind
AND entity_id = :entity_id
LIMIT 1
"""
async def _rows(sql: str, params: dict) -> list[dict]:
async with async_session() as session:
result = await session.execute(text(sql), params)
return [dict(r) for r in result.mappings().all()]
async def build_evidence(
gid: str, *, lat: float, lon: float, now: datetime,
) -> dict:
"""Cameras nearest the hit (≤5) and news most-recent (≤3) inside the fence.
Empty arrays if none or the query fails. Snapshot is a path, not a body.
"""
cameras: list[dict] = []
news: list[dict] = []
try:
cameras = await _rows(_CAMERAS_INSIDE_SQL, {
"gid": gid, "lat": lat, "lon": lon, "limit": _CAMERA_CAP,
})
except Exception:
logger.exception("evidence cameras query failed gid=%s", gid)
try:
news = await _rows(_NEWS_INSIDE_SQL, {"gid": gid, "limit": _NEWS_CAP})
except Exception:
logger.exception("evidence news query failed gid=%s", gid)
return evidence_pack(gid, now, cameras, news)
async def refresh_cache() -> list[dict]:
global _cache
async with async_session() as session:
@ -249,12 +417,24 @@ async def record_and_notify(
lat: float,
lon: float,
payload: dict[str, Any] | None = None,
skip_existing: bool = False,
) -> int:
"""Insert a geofence_alerts row per hit and WS-push to viewport clients.
PostGIS ST_Intersects is the source of truth. The in-process GeoJSON
cache is not a reject filter — the FIRMS ingester never fills it.
``source_kind=camera`` is refused (no row, no WS). Earthquake, fire
incident, and news hits get an ``evidence`` object; adsb/ais/firms
keep the caller payload unchanged.
``skip_existing`` is for polled incidents (same id every cycle). It
does not change the 5-minute cooldown. A failed existence check
skips the hit so a broken read cannot page every fence.
"""
if source_kind == "camera":
logger.warning("refusing geofence notify for source_kind=camera")
return 0
hits = await st_intersects(lon, lat)
if not hits:
return 0
@ -275,6 +455,33 @@ async def record_and_notify(
hits = fresh
async with async_session() as session:
for fence in hits:
once_key = (str(fence["id"]), source_kind, str(entity_id))
if skip_existing:
if once_key in _notified_once:
continue
try:
existing = await session.execute(
text(_ALREADY_SQL),
{
"gid": fence["id"],
"source_kind": source_kind,
"entity_id": str(entity_id),
},
)
if existing.first() is not None:
_notified_once.add(once_key)
continue
except Exception:
logger.exception(
"geofence existing-hit check failed kind=%s entity=%s",
source_kind, entity_id,
)
continue
body_payload = dict(payload or {})
if source_kind in EVIDENCE_KINDS:
body_payload["evidence"] = await build_evidence(
str(fence["id"]), lat=lat, lon=lon, now=now,
)
aid = str(uuid4())
body = {
"id": aid,
@ -284,7 +491,7 @@ async def record_and_notify(
"entity_id": str(entity_id),
"lat": lat,
"lon": lon,
"payload": payload or {},
"payload": body_payload,
"created_at": now.isoformat(),
}
try:
@ -306,7 +513,7 @@ async def record_and_notify(
"entity_id": str(entity_id),
"lat": lat,
"lon": lon,
"payload": json.dumps(payload or {}),
"payload": json.dumps(body_payload),
},
)
except Exception:
@ -314,6 +521,8 @@ async def record_and_notify(
sent += await manager.publish_point(
"geofence_alert", body, lat=lat, lon=lon,
)
if skip_existing:
_notified_once.add(once_key)
try:
await session.commit()
except Exception:
@ -470,3 +679,166 @@ async def snapshot_at(gid: str, ts: datetime) -> dict | None:
"vessels": vessels,
"fires": fires,
}
_QUAKE_SCAN_SQL = """
SELECT id::text AS id, url, title, location_lat, location_lon, raw
FROM events
WHERE source_type = 'earthquake'
AND location_lat IS NOT NULL
AND location_lon IS NOT NULL
AND source_timestamp >= now() - interval '7 days'
ORDER BY source_timestamp DESC
LIMIT :limit
"""
# Same pin set as GET /api/news/map: kind=map, flagged, coords, last 24h.
_NEWS_SCAN_SQL = """
SELECT id::text AS id, headline, url, importance, lat, lon
FROM news_items
WHERE kind = 'map'
AND lat IS NOT NULL
AND lon IS NOT NULL
AND importance IN ('critical', 'high')
AND created_at >= now() - interval '24 hours'
ORDER BY created_at DESC
LIMIT :limit
"""
async def scan_earthquakes(limit: int = 200) -> int:
"""Catch-up: quakes already in ``events`` when a fence is drawn later."""
try:
rows = await _rows(_QUAKE_SCAN_SQL, {"limit": int(limit)})
except Exception:
logger.exception("earthquake geofence scan failed")
return 0
n = 0
for row in rows:
lat, lon = row.get("location_lat"), row.get("location_lon")
if lat is None or lon is None:
continue
eid = earthquake_entity_id(row)
if not eid:
continue
try:
n += await record_and_notify(
source_kind="earthquake",
entity_id=eid,
lat=float(lat),
lon=float(lon),
payload={"title": row.get("title"), "url": row.get("url") or ""},
skip_existing=True,
)
except Exception:
logger.exception("earthquake geofence notify failed entity=%s", eid)
return n
async def scan_news_pins(limit: int = 200) -> int:
"""Read ``news_items`` map pins. Does not import the summarizer."""
try:
rows = await _rows(_NEWS_SCAN_SQL, {"limit": int(limit)})
except Exception:
logger.exception("news geofence scan failed")
return 0
n = 0
for row in rows:
lat, lon = row.get("lat"), row.get("lon")
if lat is None or lon is None:
continue
eid = str(row.get("id") or "")
if not eid:
continue
try:
n += await record_and_notify(
source_kind="news",
entity_id=eid,
lat=float(lat),
lon=float(lon),
payload={
"headline": row.get("headline") or "",
"url": row.get("url") or "",
"importance": row.get("importance") or "",
},
skip_existing=True,
)
except Exception:
logger.exception("news geofence notify failed entity=%s", eid)
return n
async def poll_fire_incidents(fences: list[dict] | None = None) -> int:
"""WFIGS incidents are not stored. Fetch each active fence's bbox.
``load_fire_incidents`` does not mutate the map cache or correlate
aircraft. A point in the bbox but outside the polygon is dropped
before ``record_and_notify``; ST_Intersects is still the write guard.
"""
if fences is None:
fences = [f for f in cached_fences() if f.get("active", True)]
from live_layers import load_fire_incidents
n = 0
seen: set[str] = set()
for fence in fences:
if not fence.get("active", True):
continue
bbox = polygon_bbox(fence.get("geojson") or {})
if not bbox:
continue
try:
incidents = await load_fire_incidents(bbox)
except Exception:
logger.exception("wfigs fence poll failed bbox=%s", bbox)
continue
if not isinstance(incidents, list):
continue
for inc in incidents:
if not isinstance(inc, dict):
continue
lat, lon = inc.get("lat"), inc.get("lon")
if lat is None or lon is None:
continue
if not point_in_geojson(float(lon), float(lat), fence.get("geojson") or {}):
continue
eid = fire_incident_entity_id(inc)
if not eid or eid in seen:
continue
seen.add(eid)
try:
n += await record_and_notify(
source_kind="fire_incident",
entity_id=eid,
lat=float(lat),
lon=float(lon),
payload={
"label": inc.get("label"),
"extra": inc.get("extra") or {},
},
skip_existing=True,
)
except Exception:
logger.exception("fire_incident geofence notify failed entity=%s", eid)
return n
async def scan_geofence_feeds() -> int:
"""Ingester-loop catch-up. No-op when no active fence is cached.
Earthquakes also notify on insert (``ingestor.ingest_event``). This
scan covers rows already stored, WFIGS (not persisted), and news
pins written by the summarizer process.
"""
try:
await refresh_cache()
except Exception:
logger.exception("geofence cache refresh failed")
fences = [f for f in cached_fences() if f.get("active", True)]
if not fences:
return 0
n = 0
n += await scan_earthquakes()
n += await scan_news_pins()
n += await poll_fire_incidents(fences)
return n

View file

@ -219,9 +219,32 @@ async def ingest_event(msg: dict):
await session.commit()
event_id = result.inserted_primary_key[0] # type: ignore[union-attr]
logger.info("Ingested event %s from source %s", event_id, msg.get("source_type"))
# Cameras are persisted as events only. Never a geofence hit.
if event_row["source_type"] == "earthquake":
await _notify_earthquake(event_row, event_id)
return event_id
async def _notify_earthquake(event_row: dict, event_id) -> None:
"""One hit per new quake. Dedup already dropped replays; skip if no point."""
lat, lon = event_row.get("location_lat"), event_row.get("location_lon")
if lat is None or lon is None:
return
try:
from geofence import earthquake_entity_id, record_and_notify
row = {**event_row, "id": str(event_id)}
await record_and_notify(
source_kind="earthquake",
entity_id=earthquake_entity_id(row),
lat=float(lat),
lon=float(lon),
payload={"title": event_row.get("title"), "url": event_row.get("url") or ""},
skip_existing=True,
)
except Exception:
logger.exception("earthquake geofence notify failed")
async def start_nats_consumer():
"""Start NATS JetStream consumer for OSINT events."""
nc = await nats.connect(NATS_URLS)

View file

@ -743,10 +743,7 @@ def transform_wfigs_incidents(fc: dict | None) -> list[dict]:
continue
props = feat.get("properties") or {}
name = str(props.get("IncidentName") or "Incident").strip()
out.append(to_marker(
name, lat, lon,
label=name,
extra={
extra = {
"acres": props.get("IncidentSize"),
"contained": props.get("PercentContained"),
"state": props.get("POOState"),
@ -754,7 +751,17 @@ def transform_wfigs_incidents(fc: dict | None) -> list[dict]:
"cause": props.get("FireCause"),
"discovered": props.get("FireDiscoveryDateTime"),
"src": "wfigs",
},
}
irwin = props.get("IrwinID")
if irwin:
extra["irwin_id"] = str(irwin)
ufi = props.get("UniqueFireIdentifier")
if ufi:
extra["unique_fire_id"] = str(ufi)
out.append(to_marker(
name, lat, lon,
label=name,
extra=extra,
))
return out
@ -1084,17 +1091,27 @@ def _wfigs_params(bbox: str | None, *, offset_m: float = 250.0) -> dict:
return params
async def fetch_fire_incidents(bbox: str | None, limit: int = DEFAULT_LIMIT) -> list[dict]:
params = _wfigs_params(bbox)
params["outFields"] = (
_WFIGS_INCIDENT_FIELDS = (
"IncidentName,IncidentSize,FireDiscoveryDateTime,POOState,"
"PercentContained,IncidentTypeCategory,FireCause"
)
"PercentContained,IncidentTypeCategory,FireCause,"
"IrwinID,UniqueFireIdentifier"
)
async def load_fire_incidents(bbox: str | None) -> list[dict]:
"""WFIGS points for a bbox. No last-known mutation, no aircraft correlate."""
params = _wfigs_params(bbox)
params["outFields"] = _WFIGS_INCIDENT_FIELDS
async def _load():
return transform_wfigs_incidents(await _get_json(WFIGS_INCIDENTS, params))
rows = await _ttl_get(f"wfigs:inc:{bbox_cell_key(bbox)}", 600.0, _load)
return list(rows or [])
async def fetch_fire_incidents(bbox: str | None, limit: int = DEFAULT_LIMIT) -> list[dict]:
rows = await load_fire_incidents(bbox)
fire_last_known[:] = list(rows)
if rows and aircraft_last_known:
from fire_aircraft import correlate_and_notify

View file

@ -1788,24 +1788,31 @@ async def api_delete_geofence(gid: str):
@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"),
timestamp: str | None = Query(
None, description="ISO-8601 instant for the 1-minute DVR bucket",
),
ts: str | None = Query(
None,
description="Alias of timestamp. Evidence snapshot URLs use this name.",
),
):
"""Aircraft/vessels/fires inside this fence at time T. Never writes."""
from geofence import snapshot_at
from tracks import parse_timestamp
raw_ts = timestamp or ts
try:
ts = parse_timestamp(timestamp)
ts_parsed = parse_timestamp(raw_ts)
except ValueError as exc:
raise HTTPException(422, str(exc)) from exc
if ts is None:
if ts_parsed is None:
raise HTTPException(422, "timestamp required")
try:
body = await snapshot_at(gid, ts)
body = await snapshot_at(gid, ts_parsed)
except Exception:
body = {
"geofence_id": gid,
"timestamp": ts.isoformat(),
"timestamp": ts_parsed.isoformat(),
"aircraft": [],
"vessels": [],
"fires": [],
@ -1820,15 +1827,23 @@ 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"),
source_kind: str | None = Query(
None,
description="firms|ais|adsb|earthquake|fire_incident|news",
),
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")
if source_kind is not None and source_kind not in (
"firms", "ais", "adsb", "earthquake", "fire_incident", "news",
):
raise HTTPException(
422,
"source_kind must be one of: firms, ais, adsb, earthquake, fire_incident, news",
)
try:
since_ts = parse_timestamp(since) if since else None
until_ts = parse_timestamp(until) if until else None

View file

@ -116,6 +116,24 @@ async def fire_loop() -> None:
await asyncio.sleep(FIRMS_INTERVAL)
async def geofence_feed_loop() -> None:
"""Hear quakes already stored, WFIGS incidents, and news map pins.
WFIGS is not persisted — fetched per active-fence bbox here (no FIRMS
or AIS key). News pins are read from ``news_items``; the summarizer
is not imported. New earthquakes also notify from ``ingest_event``.
"""
logger.info("geofence feed loop starting (interval=%ss)", INTERVAL)
while True:
try:
from geofence import scan_geofence_feeds
n = await scan_geofence_feeds()
logger.info("geofence feeds -> %d notifies", n)
except Exception: # noqa: BLE001
logger.exception("geofence feed scan failed")
await asyncio.sleep(INTERVAL)
async def main() -> None:
logger.info(
"ingester starting (rss=%d feeds, gdelt_q=%r, quakes=%s, fires=%s, interval=%ss)",
@ -126,7 +144,9 @@ async def main() -> None:
await refresh_cache()
except Exception:
logger.exception("geofence cache refresh failed (ST_Intersects still runs on ingest)")
tasks: list[asyncio.Task] = []
tasks: list[asyncio.Task] = [
asyncio.create_task(geofence_feed_loop()),
]
if ENABLE_FIRES:
# Fire ingest only starts once FIRMS_MAP_KEY is set (ingest_fires logs
# and idles otherwise).

View file

@ -361,3 +361,484 @@ def test_snapshot_queries_st_intersects(monkeypatch):
assert "aircraft_tracks_1min" in blob
assert "vessel_tracks_1min" in blob
assert "from fires" in blob
def _reset_geofence_state():
geofence._cache.clear()
geofence._recent_hits.clear()
geofence._notified_once.clear()
class _MapResult:
def __init__(self, rows):
self._rows = rows
self.rowcount = 1
self.inserted_primary_key = ["evt-1"]
def mappings(self):
return self
def all(self):
return self._rows
def first(self):
return self._rows[0] if self._rows else None
def _fence_session(inserts, cameras, news, already=None):
"""Fake session: evidence queries return rows; inserts are recorded."""
already_rows = [] if already is None else already
class Sess:
async def execute(self, stmt, params=None):
sql = str(stmt).lower()
if "insert into geofence_alerts" in sql:
inserts.append(params or {})
return _MapResult([])
if "from cameras" in sql:
return _MapResult(cameras)
if "from news_items" in sql and "kind = 'map'" not in sql and "kind = " not in sql:
return _MapResult(news)
if "from geofence_alerts" in sql:
return _MapResult(already_rows)
return _MapResult([])
async def commit(self):
inserts.append("commit")
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
return Sess
def _install_polygon(monkeypatch, inserts, cameras=None, news=None, already=None):
_reset_geofence_state()
fence = {"id": FENCE_ID, "name": "NC", "geojson": NC_BOX, "active": True}
async def fake_st(lon, lat):
return matching_geofences(lon, lat, [fence])
monkeypatch.setattr(geofence, "st_intersects", fake_st)
if cameras is None:
cameras = [{
"id": "cam-1",
"name": "Dock",
"snapshot_url": "rtsp://agency.example/stream",
}]
if news is None:
news = [{
"headline": "Quake felt",
"url": "https://example.com/q",
"importance": "high",
}]
monkeypatch.setattr(
geofence, "async_session",
lambda: _fence_session(inserts, cameras, news, already)(),
)
return fence
def _alert_rows(inserts):
return [p for p in inserts if isinstance(p, dict)]
def _evidence(row):
import json
return json.loads(row["payload"])["evidence"]
def test_camera_evidence_never_copies_agency_or_rtsp_url():
from geofence import _CAMERAS_INSIDE_SQL, camera_evidence
assert "snapshot_url" not in _CAMERAS_INSIDE_SQL.lower()
row = camera_evidence({
"id": "abc",
"name": "",
"snapshot_url": "rtsp://agency.example/live",
"location_name": "ignored-when-name-set",
})
assert row == {
"id": "abc",
"name": "",
"snapshot_url": "/api/cameras/abc/snapshot",
}
assert "rtsp" not in row["snapshot_url"]
assert not row["snapshot_url"].startswith("http")
def test_evidence_caps_and_empty_arrays():
from datetime import datetime, timezone
from geofence import evidence_pack
now = datetime(2026, 8, 28, 12, 4, tzinfo=timezone.utc)
cams = [{"id": f"c{i}", "name": f"n{i}"} for i in range(8)]
news = [
{"headline": f"h{i}", "url": "", "importance": ""} for i in range(6)
]
pack = evidence_pack(FENCE_ID, now, cams, news)
assert len(pack["cameras"]) == 5
assert len(pack["news"]) == 3
empty = evidence_pack(FENCE_ID, now, [], [])
assert empty["cameras"] == []
assert empty["news"] == []
assert empty["snapshot"] == f"/api/geofences/{FENCE_ID}/at?ts=2026-08-28T12:04:00Z"
def test_inside_writes_evidence_outside_writes_nothing(monkeypatch):
"""Polygon fixture: inside → 1 row + evidence; outside → 0. Each new kind."""
import json
from urllib.parse import parse_qs, urlsplit
from tracks import parse_timestamp
for kind, entity in (
("earthquake", "ci1"),
("fire_incident", "IRWIN-1"),
("news", "42"),
):
inserts: list = []
_install_polygon(monkeypatch, inserts)
async def run(k=kind, eid=entity):
inside = await geofence.record_and_notify(
source_kind=k, entity_id=eid, lat=35.5, lon=-79.0,
payload={"label": "inside"},
)
outside = await geofence.record_and_notify(
source_kind=k, entity_id=eid + "-out", lat=37.7, lon=-122.4,
payload={"label": "outside"},
)
return inside, outside
n_in, n_out = asyncio.run(run())
rows = _alert_rows(inserts)
assert n_out == 0
assert rows and len(rows) == 1, kind
assert rows[0]["source_kind"] == kind
ev = json.loads(rows[0]["payload"])["evidence"]
assert set(ev) == {"cameras", "news", "snapshot"}
assert set(ev["cameras"][0]) == {"id", "name", "snapshot_url"}
assert set(ev["news"][0]) == {"headline", "url", "importance"}
assert ev["cameras"][0]["id"] == "cam-1"
assert ev["cameras"][0]["name"] == "Dock"
assert ev["cameras"][0]["snapshot_url"] == "/api/cameras/cam-1/snapshot"
assert ev["news"][0] == {
"headline": "Quake felt",
"url": "https://example.com/q",
"importance": "high",
}
assert ev["snapshot"].startswith(f"/api/geofences/{FENCE_ID}/at?ts=")
assert "rtsp" not in json.dumps(ev)
assert "http" not in ev["cameras"][0]["snapshot_url"]
qs = parse_qs(urlsplit(ev["snapshot"]).query)
assert "ts" in qs and "timestamp" not in qs
assert parse_timestamp(qs["ts"][0]) is not None
assert n_in == 0 or n_in >= 0 # WS fan-out may be 0 with no clients
def test_firms_hit_omits_evidence(monkeypatch):
inserts: list = []
_install_polygon(monkeypatch, inserts)
async def run():
return await geofence.record_and_notify(
source_kind="firms", entity_id="35.5,-79.0,N",
lat=35.5, lon=-79.0, payload={"satellite": "N"},
)
asyncio.run(run())
rows = _alert_rows(inserts)
import json
body = json.loads(rows[0]["payload"])
assert "evidence" not in body
assert body["satellite"] == "N"
def test_same_entity_inside_five_minutes_is_one_row(monkeypatch):
inserts: list = []
_install_polygon(monkeypatch, inserts)
async def run():
a = await geofence.record_and_notify(
source_kind="fire_incident", entity_id="IRWIN-1",
lat=35.5, lon=-79.0, payload={"label": "Foster"},
)
b = await geofence.record_and_notify(
source_kind="fire_incident", entity_id="IRWIN-1",
lat=35.5, lon=-79.0, payload={"label": "Foster"},
)
return a, b
asyncio.run(run())
assert len(_alert_rows(inserts)) == 1
def test_skip_existing_does_not_renotify_after_cooldown(monkeypatch):
"""A later poll of the same incident id must not insert again."""
inserts: list = []
already = []
_install_polygon(monkeypatch, inserts, already=already)
async def run():
await geofence.record_and_notify(
source_kind="fire_incident", entity_id="IRWIN-9",
lat=35.5, lon=-79.0, skip_existing=True,
)
geofence._recent_hits.clear()
geofence._notified_once.clear()
already.append({"one": 1})
await geofence.record_and_notify(
source_kind="fire_incident", entity_id="IRWIN-9",
lat=35.5, lon=-79.0, skip_existing=True,
)
asyncio.run(run())
assert len(_alert_rows(inserts)) == 1
def test_camera_kind_is_refused(monkeypatch):
inserts: list = []
called = {"st": 0}
_install_polygon(monkeypatch, inserts)
async def fake_st(lon, lat):
called["st"] += 1
return [{"id": FENCE_ID, "name": "NC", "active": True}]
monkeypatch.setattr(geofence, "st_intersects", fake_st)
async def run():
return await geofence.record_and_notify(
source_kind="camera", entity_id="cam-1", lat=35.5, lon=-79.0,
)
assert asyncio.run(run()) == 0
assert called["st"] == 0
assert _alert_rows(inserts) == []
def test_camera_publish_and_insert_do_not_notify(monkeypatch):
import camera_scraper
import ingestor
import run_camera_service
from datetime import datetime, timezone
called = []
async def fake_record(**kwargs):
called.append(kwargs)
return 0
monkeypatch.setattr(geofence, "record_and_notify", fake_record)
class Sess:
async def execute(self, stmt, params=None):
return _MapResult([])
async def commit(self):
return None
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
monkeypatch.setattr(camera_scraper, "async_session", lambda: Sess())
async def upsert():
return await camera_scraper.upsert_cameras([{
"source_url": "http://cam.example/snap",
"discovery_source": "test",
"location_lat": 35.5,
"location_lon": -79.0,
"location_name": "Dock",
"snapshot_url": "rtsp://agency.example/stream",
}])
assert asyncio.run(upsert()) == 1
assert called == []
monkeypatch.setattr(ingestor, "async_session", lambda: Sess())
async def ingest_cam():
return await ingestor.ingest_event({
"source_type": "camera",
"title": "Open camera",
"url": "http://cam.example/snap",
"location_lat": 35.5,
"location_lon": -79.0,
"location_name": "Dock",
"source_timestamp": "2026-08-28T12:00:00+00:00",
})
assert asyncio.run(ingest_cam()) == "evt-1"
assert called == []
now = datetime(2026, 8, 28, 12, tzinfo=timezone.utc)
class Pub:
async def publish(self, *a, **k):
return None
class NC:
def jetstream(self):
return Pub()
async def close(self):
return None
class _Nats:
@staticmethod
async def connect(*a, **k):
return NC()
class CamSess:
async def execute(self, stmt, params=None):
return _MapResult([{
"vendor": "x",
"source_url": "http://cam.example/snap",
"location_lat": 35.5,
"location_lon": -79.0,
"location_name": "Dock",
"discovery_source": "test",
"url_hash": "abc",
"snapshot_url": "rtsp://agency.example/stream",
"device_type": "rtsp",
"first_seen": now,
"last_seen": now,
}])
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
monkeypatch.setattr(run_camera_service, "nats", _Nats)
monkeypatch.setattr(run_camera_service, "async_session", lambda: CamSess())
async def publish():
return await run_camera_service.publish_new_cameras()
assert asyncio.run(publish()) == 1
assert called == []
assert all(c.get("source_kind") != "camera" for c in called)
def test_fire_poll_inside_notifies_outside_does_not(monkeypatch):
calls = []
async def fake_load(bbox):
assert bbox == "-80.0,35.0,-78.0,36.0"
return [
{
"id": "In Fire", "lat": 35.5, "lon": -79.0, "label": "In Fire",
"extra": {"irwin_id": "IRWIN-IN", "src": "wfigs"},
},
{
"id": "Out Fire", "lat": 37.7, "lon": -122.4, "label": "Out Fire",
"extra": {"irwin_id": "IRWIN-OUT", "src": "wfigs"},
},
]
async def fake_record(**kwargs):
calls.append(kwargs)
return 1
monkeypatch.setattr("live_layers.load_fire_incidents", fake_load)
monkeypatch.setattr(geofence, "record_and_notify", fake_record)
fence = {"id": FENCE_ID, "name": "NC", "geojson": NC_BOX, "active": True}
async def run():
return await geofence.poll_fire_incidents([fence])
assert asyncio.run(run()) == 1
assert len(calls) == 1
assert calls[0]["source_kind"] == "fire_incident"
assert calls[0]["entity_id"] == "IRWIN-IN"
assert calls[0]["skip_existing"] is True
def test_ingest_earthquake_notifies_camera_message_does_not(monkeypatch):
import ingestor
calls = []
async def fake_record(**kwargs):
calls.append(kwargs)
return 1
monkeypatch.setattr(geofence, "record_and_notify", fake_record)
class Sess:
async def execute(self, stmt, params=None):
return _MapResult([])
async def commit(self):
return None
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
monkeypatch.setattr(ingestor, "async_session", lambda: Sess())
async def run():
qid = await ingestor.ingest_event({
"source_type": "earthquake",
"title": "M 2.1",
"url": "https://earthquake.usgs.gov/earthquakes/eventpage/ci1",
"location_lat": 35.5,
"location_lon": -79.0,
"raw": {"usgs_id": "ci1"},
"source_timestamp": "2026-08-28T12:00:00+00:00",
})
cid = await ingestor.ingest_event({
"source_type": "camera",
"title": "cam",
"url": "http://cam.example/a",
"location_lat": 35.5,
"location_lon": -79.0,
"source_timestamp": "2026-08-28T12:00:00+00:00",
})
return qid, cid
qid, cid = asyncio.run(run())
assert qid == "evt-1"
assert cid == "evt-1"
assert len(calls) == 1
assert calls[0]["source_kind"] == "earthquake"
assert calls[0]["entity_id"] == "ci1"
assert calls[0]["lat"] == 35.5
assert calls[0]["lon"] == -79.0
def test_news_scan_reads_pins_without_summarizer(monkeypatch):
calls = []
async def fake_rows(sql, params):
assert "news_items" in sql
assert "kind = 'map'" in sql
return [{
"id": "9", "headline": "Bridge", "url": "https://n.example/b",
"importance": "critical", "lat": 35.5, "lon": -79.0,
}]
async def fake_record(**kwargs):
calls.append(kwargs)
return 1
monkeypatch.setattr(geofence, "_rows", fake_rows)
monkeypatch.setattr(geofence, "record_and_notify", fake_record)
async def run():
return await geofence.scan_news_pins()
assert asyncio.run(run()) == 1
assert calls[0]["source_kind"] == "news"
assert calls[0]["entity_id"] == "9"
assert calls[0]["skip_existing"] is True

View file

@ -67,7 +67,43 @@ def test_geofence_alerts_passes_filters(monkeypatch):
assert seen["until"] is not None
def test_geofence_alerts_rejects_bad_source_kind():
def test_geofence_at_accepts_ts_alias(monkeypatch):
seen = {}
async def snap(gid: str, ts):
seen["gid"] = gid
seen["ts"] = ts
return {
"geofence_id": gid,
"timestamp": ts.isoformat(),
"aircraft": [],
"vessels": [],
"fires": [],
}
monkeypatch.setattr("geofence.snapshot_at", snap)
resp = asyncio.run(_req(
"GET", f"/api/geofences/{FENCE_ID}/at",
params={"ts": "2026-08-28T12:04:00Z"},
))
assert resp.status_code == 200
assert seen["gid"] == FENCE_ID
assert seen["ts"].year == 2026
def test_geofence_alerts_accepts_new_kinds(monkeypatch):
seen = {}
async def fake_list(**kwargs):
seen.update(kwargs)
return []
monkeypatch.setattr("geofence.list_alerts", fake_list)
resp = asyncio.run(_req(
"GET", "/api/geofence-alerts", params={"source_kind": "earthquake"},
))
assert resp.status_code == 200
assert seen["source_kind"] == "earthquake"
resp = asyncio.run(_req(
"GET", "/api/geofence-alerts", params={"source_kind": "camera"},
))