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

64
tests/test_bg_jobs.py Normal file
View file

@ -0,0 +1,64 @@
"""masscan/ffmpeg stay off the request path (asyncio.create_task)."""
from __future__ import annotations
import asyncio
import bg_jobs
def test_schedule_masscan_pass_returns_without_awaiting_scan(monkeypatch):
started = {"n": 0}
async def slow_pass():
started["n"] += 1
await asyncio.sleep(30)
monkeypatch.setattr(bg_jobs, "_run_masscan_capped", slow_pass)
bg_jobs._masscan_task = None
async def run():
launched = bg_jobs.schedule_masscan_pass()
assert launched is True
# Must not have blocked for the 30s pass.
assert bg_jobs._masscan_task is not None
assert not bg_jobs._masscan_task.done()
launched2 = bg_jobs.schedule_masscan_pass()
assert launched2 is False # already running
bg_jobs._masscan_task.cancel()
try:
await bg_jobs._masscan_task
except (asyncio.CancelledError, Exception):
pass
bg_jobs._masscan_task = None
asyncio.run(run())
def test_masscan_rate_cap_is_200():
assert bg_jobs.MASSCAN_PPS_CAP == 200
def test_schedule_ffmpeg_snapshot_is_a_task_not_inline(monkeypatch):
calls = {"n": 0}
async def fake_grab(url, timeout=8.0):
calls["n"] += 1
await asyncio.sleep(5)
return b"\xff\xd8fakejpeg"
monkeypatch.setattr(bg_jobs, "_ffmpeg_grab", fake_grab)
bg_jobs._ffmpeg_tasks.clear()
bg_jobs._ffmpeg_cache.clear()
async def run():
task = bg_jobs.schedule_ffmpeg_snapshot("rtsp://10.0.0.1/")
assert isinstance(task, asyncio.Task)
assert not task.done()
task.cancel()
try:
await task
except (asyncio.CancelledError, Exception):
pass
asyncio.run(run())

View file

@ -0,0 +1,66 @@
"""WFIGS/FIRMS × firefighting ADS-B correlation within 20 miles."""
from __future__ import annotations
from fire_aircraft import (
FIREFIGHTER_ICAO,
RADIUS_MILES,
correlate_aircraft_to_fires,
is_firefighter,
)
def _ac(hex_id, lat, lon, icao, **extra):
return {
"id": hex_id,
"lat": lat,
"lon": lon,
"label": hex_id,
"heading": 0,
"speed": 120,
"extra": {"type": icao, "hex": hex_id, **extra},
}
def _fire(name, lat, lon, **extra):
return {
"id": name,
"lat": lat,
"lon": lon,
"label": name,
"extra": extra,
}
def test_air_tractor_is_firefighter_airliner_is_not():
assert is_firefighter(_ac("aaa", 0, 0, "AT802")) is True
assert is_firefighter(_ac("bbb", 0, 0, "C130")) is True
assert is_firefighter(_ac("ccc", 0, 0, "B738")) is False
assert "AT802" in FIREFIGHTER_ICAO
def test_flags_tanker_within_20_miles_of_fire():
# ~10 miles north of a Piedmont fire
fire = _fire("Jones Gap", 35.00, -82.00)
tanker = _ac("acf001", 35.145, -82.00, "AT802")
airliner = _ac("a0b738", 35.145, -82.00, "B738")
far = _ac("acfar", 35.50, -82.00, "C130") # ~34 miles
hits = correlate_aircraft_to_fires([fire], [tanker, airliner, far])
assert RADIUS_MILES == 20.0
assert len(hits) == 1
h = hits[0]
assert h["aircraft_hex"] == "acf001"
assert h["fire_id"] == "Jones Gap"
assert h["aircraft_type"] == "AT802"
assert 0 < h["distance_mi"] <= 20.0
def test_persist_shape_has_reload_fields():
fire = _fire("Jones Gap", 35.00, -82.00, src="wfigs")
tanker = _ac("acf001", 35.10, -82.00, "S64")
hits = correlate_aircraft_to_fires([fire], [tanker])
assert set(hits[0]).issuperset({
"fire_id", "fire_lat", "fire_lon",
"aircraft_hex", "aircraft_type", "aircraft_lat", "aircraft_lon",
"distance_mi",
})

View file

@ -85,3 +85,87 @@ def test_ingest_fire_row_drops_malformed(clean_fires):
assert await ingest_fire_row(make_fire_msg(acq_time="garbage")) is False
asyncio.run(run())
class _InsertSession:
"""async_session stand-in: fire insert succeeds (rowcount=1)."""
def __init__(self):
self.rowcount = 1
async def execute(self, *a, **k):
return self
async def commit(self):
return None
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
def test_ingest_fire_row_geofence_when_cache_empty(monkeypatch):
"""Ingester process has empty geofence cache; still notify on FIRMS insert."""
import geofence
import ingestor
import live_layers
geofence._cache.clear()
live_layers.aircraft_last_known.clear()
notified = []
async def fake_record(**kw):
notified.append(kw)
return 1
async def no_markers(*a, **k):
return []
monkeypatch.setattr(ingestor, "async_session", _InsertSession)
monkeypatch.setattr(geofence, "record_and_notify", fake_record)
monkeypatch.setattr("tracks.recent_markers", no_markers)
assert asyncio.run(ingest_fire_row(make_fire_msg())) is True
assert len(notified) == 1
assert notified[0]["source_kind"] == "firms"
assert notified[0]["lat"] == 39.45678
assert notified[0]["lon"] == -121.12345
def test_ingest_fire_row_correlates_from_hypertable_when_last_known_empty(monkeypatch):
"""FIRMS ingester has no ADS-B last-known; still correlate from aircraft_positions."""
import geofence
import ingestor
import live_layers
geofence._cache.clear()
live_layers.aircraft_last_known.clear()
correlated = []
async def fake_record(**kw):
return 0
async def fake_recent(kind, limit=2000):
assert kind == "aircraft"
return [{
"id": "acf001",
"lat": 39.45,
"lon": -121.12,
"extra": {"type": "AT802"},
}]
async def fake_corr(fires, aircraft):
correlated.append((fires, aircraft))
return aircraft
monkeypatch.setattr(ingestor, "async_session", _InsertSession)
monkeypatch.setattr(geofence, "record_and_notify", fake_record)
monkeypatch.setattr("tracks.recent_markers", fake_recent)
monkeypatch.setattr("fire_aircraft.correlate_and_notify", fake_corr)
assert asyncio.run(ingest_fire_row(make_fire_msg())) is True
assert len(correlated) == 1
assert correlated[0][1][0]["id"] == "acf001"
assert correlated[0][0][0]["lat"] == 39.45678

View file

@ -83,6 +83,8 @@ def test_ingest_fires_idles_without_map_key(monkeypatch):
def test_ingest_fires_uses_keystore_key(monkeypatch):
# Key saved via the dashboard Keys page (Postgres) is picked up.
from upstream_cache import firms_cache
firms_cache.clear()
monkeypatch.setenv("FIRMS_MAP_KEY", "")
monkeypatch.setattr(
"fire_sources.get_api_key",

136
tests/test_geofence.py Normal file
View file

@ -0,0 +1,136 @@
"""Geofence hit detection and WS alert routing (no Redis)."""
from __future__ import annotations
import asyncio
import geofence
from geofence import (
matching_geofences,
point_in_geojson,
validate_polygon_geojson,
)
from ws_manager import ConnectionManager
NC_BOX = {
"type": "Polygon",
"coordinates": [[
[-80.0, 35.0],
[-78.0, 35.0],
[-78.0, 36.0],
[-80.0, 36.0],
[-80.0, 35.0],
]],
}
def test_point_inside_polygon_hits():
assert point_in_geojson(-79.0, 35.5, NC_BOX) is True
def test_point_outside_polygon_misses():
assert point_in_geojson(-122.4, 37.7, NC_BOX) is False
def test_validate_rejects_non_polygon():
try:
validate_polygon_geojson({"type": "Point", "coordinates": [-79.0, 35.5]})
assert False, "expected ValueError"
except ValueError:
pass
def test_matching_geofences_only_active_hits():
fences = [
{"id": "a", "name": "NC", "active": True, "geojson": NC_BOX},
{"id": "b", "name": "off", "active": False, "geojson": NC_BOX},
]
hits = matching_geofences(-79.0, 35.5, fences)
assert [h["id"] for h in hits] == ["a"]
assert matching_geofences(-122.4, 37.7, fences) == []
def test_geofence_alert_fans_out_only_to_viewport_clients():
mgr = ConnectionManager()
q_nc = mgr.register("nc")
q_sf = mgr.register("sf")
mgr.set_viewport("nc", (-80.0, 35.0, -78.0, 36.0))
mgr.set_viewport("sf", (-123.0, 37.0, -121.0, 38.0))
async def run():
payload = {
"geofence_id": "a",
"geofence_name": "NC",
"source_kind": "ais",
"entity_id": "366123456",
"lat": 35.5,
"lon": -79.0,
}
n = await mgr.publish_point("geofence_alert", payload, lat=35.5, lon=-79.0)
assert n == 1
msg = q_nc.get_nowait()
assert msg["type"] == "geofence_alert"
assert msg["payload"]["entity_id"] == "366123456"
assert q_sf.empty()
asyncio.run(run())
def test_record_and_notify_queries_postgis_when_cache_empty(monkeypatch):
"""FIRMS ingest in the ingester has an empty in-process cache — still ST_Intersects."""
import geofence
geofence._cache.clear()
geofence._recent_hits.clear()
st_called = []
async def fake_st(lon, lat):
st_called.append((lon, lat))
return [{
"id": "11111111-1111-1111-1111-111111111111",
"name": "NC",
"geojson": NC_BOX,
"active": True,
}]
monkeypatch.setattr(geofence, "st_intersects", fake_st)
executed: list = []
class FakeSession:
async def execute(self, stmt, params=None):
executed.append(params or {})
return None
async def commit(self):
executed.append("commit")
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
monkeypatch.setattr(geofence, "async_session", FakeSession)
async def run():
from ws_manager import manager
q = manager.register("nc")
manager.set_viewport("nc", (-80.0, 35.0, -78.0, 36.0))
n = await geofence.record_and_notify(
source_kind="firms", entity_id="35.5,-79.0,N",
lat=35.5, lon=-79.0, payload={"satellite": "N"},
)
msg = None if q.empty() else q.get_nowait()
manager.unregister("nc")
return n, msg
n, msg = asyncio.run(run())
assert st_called == [(-79.0, 35.5)]
assert n == 1
assert msg["type"] == "geofence_alert"
assert msg["payload"]["source_kind"] == "firms"
inserts = [p for p in executed if isinstance(p, dict)]
assert inserts and inserts[0]["source_kind"] == "firms"
assert "commit" in executed

View file

@ -0,0 +1,33 @@
"""Phase 1 guardrails: compose limits, 500ms debounce, no extra brokers."""
from __future__ import annotations
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
def test_compose_memory_limits_and_shared_buffers():
text = (ROOT / "docker-compose.yml").read_text()
assert "shared_buffers=2GB" in text
assert "shared_preload_libraries=timescaledb" in text
assert "memory: 3G" in text or "memory: 3GB" in text
assert "memory: 2G" in text or "memory: 2GB" in text
def test_map_moveend_debounced_500ms():
html = (ROOT / "app" / "static" / "index.html").read_text()
assert "map.on('moveend'" in html
# Existing 300ms debounce must be 500ms so pans don't spam bbox POSTs/WS.
assert "}, 500);" in html
assert "}, 300);" not in html.split("map.on('moveend'")[1][:800]
def test_no_redis_kafka_celery():
req = (ROOT / "app" / "requirements.txt").read_text().lower()
compose = (ROOT / "docker-compose.yml").read_text().lower()
for blob in (req, compose):
assert "redis" not in blob
assert "kafka" not in blob
assert "celery" not in blob
assert "cachetools" in req

51
tests/test_phase2_api.py Normal file
View file

@ -0,0 +1,51 @@
"""Phase 2 API contracts (no Redis; geofences ≠ /api/alerts)."""
from __future__ import annotations
import asyncio
import httpx
from main import app
BASE = "http://test"
async def _req(method: str, path: str, **kw) -> httpx.Response:
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
return await client.request(method, path, **kw)
def test_geofence_post_rejects_point():
resp = asyncio.run(_req(
"POST", "/api/geofences",
json={"name": "nope", "geojson": {"type": "Point", "coordinates": [-79, 35]}},
))
assert resp.status_code == 422
def test_geofences_list_does_not_collide_with_alerts():
resp = asyncio.run(_req("GET", "/api/geofences"))
assert resp.status_code == 200
assert isinstance(resp.json(), list)
def test_aircraft_timestamp_returns_list_not_live_error():
resp = asyncio.run(_req(
"GET", "/api/aircraft",
params={"bbox": "-80,35,-78,36", "timestamp": "2026-08-28T12:04:00Z"},
))
assert resp.status_code == 200
assert isinstance(resp.json(), list)
def test_tracks_range_has_bounds():
body = asyncio.run(_req("GET", "/api/tracks/range")).json()
assert "min" in body and "max" in body
def test_fire_aircraft_reload_endpoint():
resp = asyncio.run(_req("GET", "/api/fire-aircraft"))
assert resp.status_code == 200
assert isinstance(resp.json(), list)

50
tests/test_tracks.py Normal file
View file

@ -0,0 +1,50 @@
"""1-minute downsampled tracks for DVR playback."""
from __future__ import annotations
from datetime import datetime, timezone
from tracks import (
TRACK_BUCKET,
downsample_tracks,
minute_bucket,
positions_at_timestamp,
)
def _ts(h, m, s=0):
return datetime(2026, 8, 28, h, m, s, tzinfo=timezone.utc)
def test_minute_bucket_floors_seconds():
assert minute_bucket(_ts(12, 4, 47)) == _ts(12, 4, 0)
assert TRACK_BUCKET == "1 minute"
def test_downsample_keeps_last_sample_per_id_per_minute():
rows = [
{"id": "a1", "ts": _ts(12, 4, 10), "lat": 35.0, "lon": -79.0},
{"id": "a1", "ts": _ts(12, 4, 50), "lat": 35.1, "lon": -79.1},
{"id": "a1", "ts": _ts(12, 5, 5), "lat": 35.2, "lon": -79.2},
{"id": "b2", "ts": _ts(12, 4, 20), "lat": 36.0, "lon": -80.0},
]
out = downsample_tracks(rows)
by = {(r["id"], r["bucket"]): r for r in out}
assert by[("a1", _ts(12, 4))]["lat"] == 35.1
assert by[("a1", _ts(12, 5))]["lat"] == 35.2
assert by[("b2", _ts(12, 4))]["lat"] == 36.0
assert len(out) == 3
def test_positions_at_timestamp_uses_that_minute_window():
rows = [
{"id": "a1", "ts": _ts(12, 4, 50), "lat": 35.1, "lon": -79.1, "heading": 90, "speed": 10, "label": "A1"},
{"id": "a1", "ts": _ts(12, 5, 5), "lat": 35.2, "lon": -79.2, "heading": 91, "speed": 11, "label": "A1"},
{"id": "b2", "ts": _ts(12, 4, 20), "lat": 36.0, "lon": -80.0, "heading": 0, "speed": 0, "label": "B2"},
]
at = positions_at_timestamp(rows, _ts(12, 4, 59))
ids = {p["id"]: p for p in at}
assert ids["a1"]["lat"] == 35.1
assert ids["b2"]["lat"] == 36.0
later = positions_at_timestamp(rows, _ts(12, 5, 30))
assert {p["id"]: p["lat"] for p in later} == {"a1": 35.2}

View file

@ -0,0 +1,104 @@
"""FIRMS / RSS in-process TTLCache — no Redis."""
from __future__ import annotations
import asyncio
from cachetools import TTLCache
from fire_sources import ingest_fires
from sources import ingest_rss_feed
from test_fire_sources import SAMPLE_CSV, _async_return
from upstream_cache import firms_cache, rss_cache
def test_firms_and_rss_caches_are_ttlcache():
assert isinstance(firms_cache, TTLCache)
assert firms_cache.maxsize == 100
assert firms_cache.ttl == 300
assert isinstance(rss_cache, TTLCache)
assert rss_cache.maxsize == 100
assert 60 <= rss_cache.ttl <= 300
def test_ingest_fires_hits_http_once_within_ttl(monkeypatch):
firms_cache.clear()
monkeypatch.setenv("FIRMS_MAP_KEY", "k" * 32)
monkeypatch.setenv("FIRMS_DATASETS", "VIIRS_NOAA20_NRT")
# fire_sources already imported FIRMS_DATASETS — patch the module attr
monkeypatch.setattr("fire_sources.FIRMS_DATASETS", ["VIIRS_NOAA20_NRT"])
hits = {"n": 0}
class FakeResp:
text = SAMPLE_CSV
def raise_for_status(self):
pass
class FakeClient:
def __init__(self, **kw):
pass
async def __aenter__(self):
return self
async def __aexit__(self, *exc):
return False
async def get(self, url):
hits["n"] += 1
return FakeResp()
monkeypatch.setattr("fire_sources.httpx.AsyncClient", FakeClient)
async def fake_publish(points):
return len(points)
monkeypatch.setattr("fire_sources.publish_fire_batch", fake_publish)
assert asyncio.run(ingest_fires()) == 5
assert asyncio.run(ingest_fires()) == 5
assert hits["n"] == 1
def test_ingest_rss_hits_http_once_within_ttl(monkeypatch):
rss_cache.clear()
hits = {"n": 0}
class FakeResp:
text = """<?xml version="1.0"?>
<rss version="2.0"><channel><title>t</title>
<item><title>hello</title><link>http://x.example/1</link>
<description>body</description></item></channel></rss>"""
def raise_for_status(self):
pass
class FakeClient:
def __init__(self, **kw):
pass
async def __aenter__(self):
return self
async def __aexit__(self, *exc):
return False
async def get(self, url):
hits["n"] += 1
return FakeResp()
monkeypatch.setattr("sources.httpx.AsyncClient", FakeClient)
published = []
async def fake_publish(subject, event):
published.append((subject, event))
monkeypatch.setattr("sources.publish_event", fake_publish)
assert asyncio.run(ingest_rss_feed("http://feeds.example/rss")) == 1
assert asyncio.run(ingest_rss_feed("http://feeds.example/rss")) == 1
assert hits["n"] == 1
assert published[0][0] == "events.rss"

91
tests/test_ws_manager.py Normal file
View file

@ -0,0 +1,91 @@
"""Viewport-filtered in-memory pub/sub — no Redis."""
from __future__ import annotations
import asyncio
from ws_manager import ConnectionManager, point_in_bbox
def test_point_in_bbox_inclusive():
box = (-80.0, 35.0, -78.0, 36.0)
assert point_in_bbox(-79.0, 35.5, box) is True
assert point_in_bbox(-80.0, 35.0, box) is True
assert point_in_bbox(-77.0, 35.5, box) is False
assert point_in_bbox(-79.0, 34.0, box) is False
def test_missing_viewport_does_not_get_firehose():
mgr = ConnectionManager()
q = mgr.register("tailnet-a")
async def run():
n = await mgr.publish_point("ais", {"id": "mmsi-1"}, lat=35.5, lon=-79.0)
assert n == 0
assert q.empty()
asyncio.run(run())
def test_fanout_only_to_intersecting_viewports():
mgr = ConnectionManager()
q_nc = mgr.register("nc")
q_sf = mgr.register("sf")
mgr.set_viewport("nc", (-80.0, 35.0, -78.0, 36.0))
mgr.set_viewport("sf", (-123.0, 37.0, -121.0, 38.0))
async def run():
n = await mgr.publish_point(
"ais", {"id": "mmsi-1", "lat": 35.5, "lon": -79.0},
lat=35.5, lon=-79.0,
)
assert n == 1
msg = q_nc.get_nowait()
assert msg["type"] == "ais"
assert msg["payload"]["id"] == "mmsi-1"
assert q_sf.empty()
n2 = await mgr.publish_point(
"adsb", {"id": "a1b2c3"}, lat=37.7, lon=-122.4,
)
assert n2 == 1
msg2 = q_sf.get_nowait()
assert msg2["type"] == "adsb"
assert q_nc.empty()
asyncio.run(run())
def test_disconnect_stops_fanout():
mgr = ConnectionManager()
q = mgr.register("gone")
mgr.set_viewport("gone", (-180.0, -90.0, 180.0, 90.0))
mgr.unregister("gone")
async def run():
n = await mgr.publish_point("ais", {"id": "x"}, lat=0.0, lon=0.0)
assert n == 0
assert q.empty()
asyncio.run(run())
def test_upsert_vessel_fans_out_to_intersecting_client(monkeypatch):
from live_layers import upsert_vessel, vessel_last_known
from ws_manager import manager
vessel_last_known.clear()
manager._queues.clear()
manager._viewports.clear()
q = manager.register("nc")
manager.set_viewport("nc", (-80.0, 35.0, -78.0, 36.0))
async def run():
await upsert_vessel({"id": "366123456", "lat": 35.2, "lon": -79.1, "label": "TEST"})
msg = q.get_nowait()
assert msg["type"] == "ais"
assert msg["payload"]["id"] == "366123456"
asyncio.run(run())
manager.unregister("nc")
vessel_last_known.clear()