fix(cameras): stop publishing discovery rows as events #57
4 changed files with 82 additions and 59 deletions
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.
commit
9809fdf05b
|
|
@ -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_TTL_SECONDS = int(os.getenv("SNAPSHOT_TTL_SECONDS", "300"))
|
||||||
SNAPSHOT_TIMEOUT = float(os.getenv("SNAPSHOT_TIMEOUT", "8.0"))
|
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")
|
CAMERA_NATS_SUBJECT = os.getenv("CAMERA_NATS_SUBJECT", "events.camera")
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -11,8 +11,8 @@ Pipeline per cycle:
|
||||||
2. Parse cameras (Insecam-style HTML with embedded lat/lon, or plain-text
|
2. Parse cameras (Insecam-style HTML with embedded lat/lon, or plain-text
|
||||||
`url[|lat,lon|vendor|location]` lines).
|
`url[|lat,lon|vendor|location]` lines).
|
||||||
3. Geocode missing coords via Nominatim at <=1 req/s.
|
3. Geocode missing coords via Nominatim at <=1 req/s.
|
||||||
4. Publish each camera to NATS (`events.camera`) for the shared ingester,
|
4. Upsert into the `cameras` table keyed by sha256(url_hash).
|
||||||
and 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
|
Snapshots are cached locally with a TTL; nothing is fetched more often than
|
||||||
the cache allows.
|
the cache allows.
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,10 @@
|
||||||
"""Long-running camera discovery service.
|
"""Long-running camera discovery service.
|
||||||
|
|
||||||
Follows the existing ingest pattern: discovers cameras on an interval and
|
Discovers cameras on an interval and upserts them into the `cameras` table
|
||||||
publishes each one as a NATS message (`events.camera`) so the shared NATS ->
|
(dedupe by url_hash) for the /api/cameras bbox query. Discovery is not an
|
||||||
ingester pipeline persists them; also upserts directly into the `cameras`
|
event: this process does not publish `events.camera` messages. Those were
|
||||||
table (dedupe by url_hash) for the /api/cameras bbox query.
|
inserted as events rows and flooded the HUD feed. The cameras table is the
|
||||||
|
index.
|
||||||
|
|
||||||
Env:
|
Env:
|
||||||
CAMERA_SOURCE_URLS comma-separated public directory/list URLs
|
CAMERA_SOURCE_URLS comma-separated public directory/list URLs
|
||||||
|
|
@ -14,7 +15,6 @@ Env:
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import json
|
|
||||||
import logging
|
import logging
|
||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
@ -22,16 +22,12 @@ from pathlib import Path
|
||||||
sys_path = str(Path(__file__).parent)
|
sys_path = str(Path(__file__).parent)
|
||||||
sys.path.insert(0, sys_path)
|
sys.path.insert(0, sys_path)
|
||||||
|
|
||||||
import nats # noqa: E402
|
|
||||||
|
|
||||||
from camera_config import ( # 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,
|
SNAPSHOT_CACHE_DIR,
|
||||||
)
|
)
|
||||||
from camera_models import cameras # noqa: E402
|
from camera_scraper import run_cycle # noqa: E402
|
||||||
from camera_scraper import run_cycle, url_hash # noqa: E402
|
from database import init_extensions # noqa: E402
|
||||||
from database import async_session, init_extensions # noqa: E402
|
|
||||||
from config import NATS_URL # noqa: E402
|
|
||||||
|
|
||||||
logging.basicConfig(level=logging.INFO,
|
logging.basicConfig(level=logging.INFO,
|
||||||
format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||||
|
|
@ -40,48 +36,16 @@ logger = logging.getLogger("osint.camera_service")
|
||||||
ENABLED = sys.argv[1:] != ["--once"]
|
ENABLED = sys.argv[1:] != ["--once"]
|
||||||
|
|
||||||
|
|
||||||
async def publish_new_cameras() -> int:
|
async def publish_new_cameras(rows: list | None = None) -> int:
|
||||||
"""Publish cameras seen in the latest cycle to NATS for the ingester."""
|
"""Do not publish camera discoveries as events.
|
||||||
from datetime import datetime, timezone, timedelta
|
|
||||||
cutoff = datetime.now(timezone.utc) - timedelta(seconds=CAMERA_SCRAPE_INTERVAL * 2)
|
``run_cycle`` already upserts the cameras table, which backs
|
||||||
published = 0
|
``GET /api/cameras``. ``rows`` is newly seen cameras from a cycle or a
|
||||||
try:
|
test; none are JetStream-published, so the ingester inserts 0 events
|
||||||
nc = await nats.connect(NATS_URL)
|
with source_type=camera.
|
||||||
except Exception: # noqa: BLE001
|
"""
|
||||||
logger.warning("NATS unavailable — skipping publish pass")
|
del rows
|
||||||
return 0
|
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:
|
async def main() -> None:
|
||||||
|
|
@ -93,8 +57,7 @@ async def main() -> None:
|
||||||
try:
|
try:
|
||||||
n = await run_cycle()
|
n = await run_cycle()
|
||||||
p = await publish_new_cameras()
|
p = await publish_new_cameras()
|
||||||
logger.info("cycle: %d stored, %d published to %s",
|
logger.info("cycle: %d stored, %d camera events published", n, p)
|
||||||
n, p, CAMERA_NATS_SUBJECT)
|
|
||||||
except Exception: # noqa: BLE001
|
except Exception: # noqa: BLE001
|
||||||
logger.exception("camera cycle error")
|
logger.exception("camera cycle error")
|
||||||
if not ENABLED: # --once mode
|
if not ENABLED: # --once mode
|
||||||
|
|
|
||||||
59
tests/test_camera_publish.py
Normal file
59
tests/test_camera_publish.py
Normal file
|
|
@ -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
|
||||||
Loading…
Reference in a new issue