"""In-memory "latest row per device" cache for the fleet-wide status reads. Why this exists --------------- /mqtt/status (device list + device detail), /mqtt/latest-metrics and the backend ping loop all need "the newest heartbeat / alert event / ping sample / diagnostics report for every device". In Postgres that is a `SELECT DISTINCT ON (device_serial) ... ORDER BY device_serial, ts DESC`, which has to walk the entire history index — heartbeats alone grow by one row per device every 30s and are kept for the full retention window, so each call took seconds and the console showed empty status columns until it finished. The MQTT ingest path already sees every new row as it is written, so instead we keep the newest row per device in memory: * seed() — one DISTINCT ON query per kind, run once at startup (and lazily on first read if startup warming hasn't finished yet). * put() — called by every insert, keeps whichever row is newer, so rows written while the seed query is still running are never lost. * drop_device() / drop_older_than() — mirror per-device deletes (Reset Stats, Delete Logs) and the retention purge so the cache never shows a row the database no longer has. Single process only: the backend runs one uvicorn worker that also owns the MQTT client (see main.py startup), so there is no cross-process staleness. """ from datetime import datetime, timezone # kind -> timestamp column used to decide which row is newest TS_FIELD = { "heartbeat": "received_at", "alert_event": "occurred_at", "ping": "sampled_at", "diag": "received_at", } _rows: dict[str, dict[str, dict]] = {kind: {} for kind in TS_FIELD} _warm: dict[str, bool] = {kind: False for kind in TS_FIELD} def _ts(kind: str, row: dict) -> datetime: raw = row.get(TS_FIELD[kind]) if isinstance(raw, datetime): return raw if raw.tzinfo else raw.replace(tzinfo=timezone.utc) try: parsed = datetime.fromisoformat(raw) return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc) except (TypeError, ValueError): return datetime.min.replace(tzinfo=timezone.utc) def put(kind: str, row: dict) -> None: """Record a row if it is the newest one seen for its device.""" serial = row.get("device_serial") if not serial: return current = _rows[kind].get(serial) if current is None or _ts(kind, row) >= _ts(kind, current): _rows[kind][serial] = row def seed(kind: str, rows: list[dict]) -> None: for row in rows: put(kind, row) _warm[kind] = True def is_warm(kind: str) -> bool: return _warm[kind] def snapshot(kind: str) -> list[dict] | None: """All cached rows for a kind, or None if the cache isn't seeded yet.""" if not _warm[kind]: return None return list(_rows[kind].values()) def get(kind: str, serial: str) -> dict | None: return _rows[kind].get(serial) def drop_device(kind: str, serial: str) -> None: _rows[kind].pop(serial, None) def drop_older_than(kind: str, cutoff: datetime) -> None: stale = [s for s, row in _rows[kind].items() if _ts(kind, row) < cutoff] for serial in stale: del _rows[kind][serial]