From 9809fdf05b912e19753d1aeb95b0591027ac73cf Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Sat, 14 Nov 2026 00:30:13 -0500 Subject: [PATCH] fix(cameras): stop publishing discovery rows as events Camera scrapes still upsert the cameras table. They no longer JetStream-publish events.camera messages, which the ingester was inserting as HUD event spam. --- app/camera_config.py | 3 +- app/camera_scraper.py | 4 +- app/run_camera_service.py | 75 +++++++++--------------------------- tests/test_camera_publish.py | 59 ++++++++++++++++++++++++++++ 4 files changed, 82 insertions(+), 59 deletions(-) create mode 100644 tests/test_camera_publish.py diff --git a/app/camera_config.py b/app/camera_config.py index 2ccff69..7376087 100644 --- a/app/camera_config.py +++ b/app/camera_config.py @@ -59,7 +59,8 @@ SNAPSHOT_CACHE_DIR = os.getenv("SNAPSHOT_CACHE_DIR", "/data/snapshots") SNAPSHOT_TTL_SECONDS = int(os.getenv("SNAPSHOT_TTL_SECONDS", "300")) SNAPSHOT_TIMEOUT = float(os.getenv("SNAPSHOT_TIMEOUT", "8.0")) -# NATS subject cameras are published on (consumed by the shared ingester). +# Retained so an old CAMERA_NATS_SUBJECT env does not surprise operators. +# This service does not publish on it; cameras live in the cameras table. CAMERA_NATS_SUBJECT = os.getenv("CAMERA_NATS_SUBJECT", "events.camera") diff --git a/app/camera_scraper.py b/app/camera_scraper.py index 10dde21..d1ca366 100644 --- a/app/camera_scraper.py +++ b/app/camera_scraper.py @@ -11,8 +11,8 @@ Pipeline per cycle: 2. Parse cameras (Insecam-style HTML with embedded lat/lon, or plain-text `url[|lat,lon|vendor|location]` lines). 3. Geocode missing coords via Nominatim at <=1 req/s. - 4. Publish each camera to NATS (`events.camera`) for the shared ingester, - and upsert into the `cameras` table keyed by sha256(url_hash). + 4. Upsert into the `cameras` table keyed by sha256(url_hash). + Discovery is not published as an event. Snapshots are cached locally with a TTL; nothing is fetched more often than the cache allows. diff --git a/app/run_camera_service.py b/app/run_camera_service.py index c550d04..74d774f 100644 --- a/app/run_camera_service.py +++ b/app/run_camera_service.py @@ -1,9 +1,10 @@ """Long-running camera discovery service. -Follows the existing ingest pattern: discovers cameras on an interval and -publishes each one as a NATS message (`events.camera`) so the shared NATS -> -ingester pipeline persists them; also upserts directly into the `cameras` -table (dedupe by url_hash) for the /api/cameras bbox query. +Discovers cameras on an interval and upserts them into the `cameras` table +(dedupe by url_hash) for the /api/cameras bbox query. Discovery is not an +event: this process does not publish `events.camera` messages. Those were +inserted as events rows and flooded the HUD feed. The cameras table is the +index. Env: CAMERA_SOURCE_URLS comma-separated public directory/list URLs @@ -14,7 +15,6 @@ Env: from __future__ import annotations import asyncio -import json import logging import sys from pathlib import Path @@ -22,16 +22,12 @@ from pathlib import Path sys_path = str(Path(__file__).parent) sys.path.insert(0, sys_path) -import nats # noqa: E402 - from camera_config import ( # noqa: E402 - CAMERA_SOURCE_URLS, CAMERA_SCRAPE_INTERVAL, CAMERA_NATS_SUBJECT, + CAMERA_SOURCE_URLS, CAMERA_SCRAPE_INTERVAL, SNAPSHOT_CACHE_DIR, ) -from camera_models import cameras # noqa: E402 -from camera_scraper import run_cycle, url_hash # noqa: E402 -from database import async_session, init_extensions # noqa: E402 -from config import NATS_URL # noqa: E402 +from camera_scraper import run_cycle # noqa: E402 +from database import init_extensions # noqa: E402 logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s") @@ -40,48 +36,16 @@ logger = logging.getLogger("osint.camera_service") ENABLED = sys.argv[1:] != ["--once"] -async def publish_new_cameras() -> int: - """Publish cameras seen in the latest cycle to NATS for the ingester.""" - from datetime import datetime, timezone, timedelta - cutoff = datetime.now(timezone.utc) - timedelta(seconds=CAMERA_SCRAPE_INTERVAL * 2) - published = 0 - try: - nc = await nats.connect(NATS_URL) - except Exception: # noqa: BLE001 - logger.warning("NATS unavailable — skipping publish pass") - return 0 - try: - js = nc.jetstream() - async with async_session() as session: - rows = (await session.execute( - cameras.select().where(cameras.c.last_seen >= cutoff) - )).mappings().all() - for r in rows: - msg = { - "source_type": "camera", - "title": f"Open camera ({r['vendor'] or 'unknown vendor'})", - "url": r["source_url"], - "location_lat": r["location_lat"], - "location_lon": r["location_lon"], - "location_name": r["location_name"], - "tags": ["osint", "camera", r["discovery_source"]], - "raw": { - "url_hash": r["url_hash"], - "snapshot_url": r["snapshot_url"], - "vendor": r["vendor"], - "device_type": r["device_type"], - "first_seen": r["first_seen"].isoformat(), - "last_seen": r["last_seen"].isoformat(), - }, - "source_timestamp": datetime.now(timezone.utc).isoformat(), - } - await js.publish(CAMERA_NATS_SUBJECT, json.dumps(msg).encode()) - published += 1 - if published >= 500: # per-cycle cap - break - finally: - await nc.close() - return published +async def publish_new_cameras(rows: list | None = None) -> int: + """Do not publish camera discoveries as events. + + ``run_cycle`` already upserts the cameras table, which backs + ``GET /api/cameras``. ``rows`` is newly seen cameras from a cycle or a + test; none are JetStream-published, so the ingester inserts 0 events + with source_type=camera. + """ + del rows + return 0 async def main() -> None: @@ -93,8 +57,7 @@ async def main() -> None: try: n = await run_cycle() p = await publish_new_cameras() - logger.info("cycle: %d stored, %d published to %s", - n, p, CAMERA_NATS_SUBJECT) + logger.info("cycle: %d stored, %d camera events published", n, p) except Exception: # noqa: BLE001 logger.exception("camera cycle error") if not ENABLED: # --once mode diff --git a/tests/test_camera_publish.py b/tests/test_camera_publish.py new file mode 100644 index 0000000..594a14e --- /dev/null +++ b/tests/test_camera_publish.py @@ -0,0 +1,59 @@ +"""Camera discovery must not become an events row.""" + +from __future__ import annotations + +import asyncio +import inspect +import json +from datetime import datetime, timezone + + +def _camera() -> dict: + now = datetime(2026, 11, 14, 3, 43, tzinfo=timezone.utc) + return { + "vendor": "UCSD", + "source_url": "https://example.test/cameras/ucsd.jpg", + "location_lat": 32.88, + "location_lon": -117.24, + "location_name": "UCSD", + "discovery_source": "ucsd", + "url_hash": "abc123", + "snapshot_url": "https://example.test/cameras/ucsd.jpg", + "device_type": "snapshot", + "first_seen": now, + "last_seen": now, + } + + +def test_publish_new_cameras_does_not_emit_camera_event(monkeypatch): + """One newly seen camera must not produce a NATS message with source_type=camera.""" + import nats + import run_camera_service as svc + + published: list[dict] = [] + + class _JS: + async def publish(self, _subject, payload): + published.append(json.loads(payload)) + + class _NC: + def jetstream(self): + return _JS() + + async def close(self): + return None + + async def _connect(*_a, **_k): + return _NC() + + monkeypatch.setattr(nats, "connect", _connect) + if getattr(svc, "nats", None) is not None: + monkeypatch.setattr(svc.nats, "connect", _connect) + + n = asyncio.run(svc.publish_new_cameras([_camera()])) + + assert n == 0 + assert published == [] + src = inspect.getsource(svc.publish_new_cameras) + assert "Open camera" not in src + assert '"source_type": "camera"' not in src -- 2.52.0