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.
This commit is contained in:
parent
d04ddc9afa
commit
d878655617
7 changed files with 990 additions and 26 deletions
|
|
@ -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
|
||||
|
|
|
|||
Loading…
Reference in a new issue