diff --git a/app/camera_config.py b/app/camera_config.py index 7376087..2ccff69 100644 --- a/app/camera_config.py +++ b/app/camera_config.py @@ -59,8 +59,7 @@ 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")) -# 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. +# NATS subject cameras are published on (consumed by the shared ingester). CAMERA_NATS_SUBJECT = os.getenv("CAMERA_NATS_SUBJECT", "events.camera") diff --git a/app/camera_scraper.py b/app/camera_scraper.py index d1ca366..10dde21 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. Upsert into the `cameras` table keyed by sha256(url_hash). - Discovery is not published as an event. + 4. Publish each camera to NATS (`events.camera`) for the shared ingester, + and upsert into the `cameras` table keyed by sha256(url_hash). 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 74d774f..c550d04 100644 --- a/app/run_camera_service.py +++ b/app/run_camera_service.py @@ -1,10 +1,9 @@ """Long-running camera discovery service. -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. +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. Env: CAMERA_SOURCE_URLS comma-separated public directory/list URLs @@ -15,6 +14,7 @@ Env: from __future__ import annotations import asyncio +import json import logging import sys from pathlib import Path @@ -22,12 +22,16 @@ 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_SOURCE_URLS, CAMERA_SCRAPE_INTERVAL, CAMERA_NATS_SUBJECT, SNAPSHOT_CACHE_DIR, ) -from camera_scraper import run_cycle # noqa: E402 -from database import init_extensions # noqa: E402 +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 logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s") @@ -36,16 +40,48 @@ logger = logging.getLogger("osint.camera_service") ENABLED = sys.argv[1:] != ["--once"] -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 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 main() -> None: @@ -57,7 +93,8 @@ async def main() -> None: try: n = await run_cycle() p = await publish_new_cameras() - logger.info("cycle: %d stored, %d camera events published", n, p) + logger.info("cycle: %d stored, %d published to %s", + n, p, CAMERA_NATS_SUBJECT) 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 deleted file mode 100644 index 594a14e..0000000 --- a/tests/test_camera_publish.py +++ /dev/null @@ -1,59 +0,0 @@ -"""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