"""PostgreSQL connection + schema bootstrap. The remote DB (provisioned outside this app) owns `cctv_streams`. This module ensures the analytics state table `cctv_session_metrics` exists, and exposes a small thread-safe connection wrapper. Design (post-2026-06 refactor): we no longer keep a time-series history of metrics. Instead, each camera has ONE row that's UPSERTed every ~second with the current snapshot + running aggregates since the worker last connected. Real-time consumers use the WebSocket; DB is just the persistent summary. """ from __future__ import annotations import logging import threading from typing import Optional from urllib.parse import parse_qsl, urlparse, urlunparse import psycopg log = logging.getLogger(__name__) SESSION_METRICS_SCHEMA = [ """CREATE TABLE IF NOT EXISTS cctv_session_metrics ( camera_id TEXT PRIMARY KEY, location TEXT, started_at TIMESTAMPTZ NOT NULL, last_captured_at TIMESTAMPTZ NOT NULL, samples_count BIGINT NOT NULL DEFAULT 0, sum_vehicles BIGINT NOT NULL DEFAULT 0, sum_people BIGINT NOT NULL DEFAULT 0, max_vehicles INTEGER NOT NULL DEFAULT 0, max_people INTEGER NOT NULL DEFAULT 0, last_vehicles INTEGER NOT NULL DEFAULT 0, last_people INTEGER NOT NULL DEFAULT 0, last_traffic TEXT, last_crowd TEXT )""", ] # Scan-mode alerts use the shared ``alerts`` table (Prisma-owned by the # Nest API platform). Rows are tagged with ``source = 'cctv-scan'``; # JPEG snapshot + MP4 clip paths live inside ``payload`` JSONB. Schema # managed by Prisma migrations on the Nest side — this service assumes # the migration has been applied before startup. def _sanitize_url(url: str) -> str: """Drop libpq-unknown query params (e.g. Prisma's ``schema=public``).""" parsed = urlparse(url) if not parsed.query: return url kept = [ (k, v) for k, v in parse_qsl(parsed.query, keep_blank_values=True) if k.lower() not in ("schema", "pgbouncer", "pool_timeout", "connection_limit") ] new_query = "&".join(f"{k}={v}" for k, v in kept) return urlunparse(parsed._replace(query=new_query)) class Database: """Single guarded psycopg connection with on-failure reconnect. All writers in this app are low-frequency (one UPSERT per camera per second) so a single connection behind a lock is enough and keeps the code straightforward.""" def __init__(self, url: str): self.url = _sanitize_url(url) self._conn: Optional[psycopg.Connection] = None self._lock = threading.Lock() # ---------- connection lifecycle ---------- def _connect(self) -> psycopg.Connection: return psycopg.connect(self.url, autocommit=True, connect_timeout=10) def _get(self) -> psycopg.Connection: if self._conn is None or self._conn.closed: self._conn = self._connect() return self._conn def _reset(self) -> None: try: if self._conn is not None: self._conn.close() except Exception: pass self._conn = None def close(self) -> None: with self._lock: self._reset() # ---------- query helpers ---------- def execute(self, sql: str, params: tuple | list | None = None) -> None: with self._lock: self._run(sql, params, fetch=None) def executemany(self, sql: str, rows: list[tuple]) -> None: if not rows: return with self._lock: for attempt in (1, 2): try: with self._get().cursor() as cur: cur.executemany(sql, rows) return except psycopg.OperationalError as e: log.warning("db batch failed (attempt %d): %s", attempt, e) self._reset() raise def fetchall(self, sql: str, params: tuple | list | None = None) -> list[tuple]: with self._lock: return self._run(sql, params, fetch="all") or [] def fetchone(self, sql: str, params: tuple | list | None = None): with self._lock: return self._run(sql, params, fetch="one") def _run(self, sql: str, params, fetch): for attempt in (1, 2): try: with self._get().cursor() as cur: cur.execute(sql, params or ()) if fetch == "all": return cur.fetchall() if fetch == "one": return cur.fetchone() return None except psycopg.OperationalError as e: log.warning("db op failed (attempt %d): %s", attempt, e) self._reset() raise RuntimeError("db op failed after retry") # ---------- bootstrap ---------- def init_schema(self) -> None: log.info("ensuring analytics schema (cctv_session_metrics)") for stmt in SESSION_METRICS_SCHEMA: self.execute(stmt)