perf(mqtt): serve device status from an in-memory latest-row cache

Device list and device detail took several seconds to show online status
because every /mqtt/status call ran SELECT DISTINCT ON (device_serial) over
the whole heartbeats + alert-event history (one heartbeat row per device
every 30s, kept for the full retention window). /mqtt/latest-metrics and
the 60s ping loop paid the same fleet-wide scans for ping samples and
diagnostics.

- database/latest_cache.py: newest heartbeat / alert event / ping sample /
  diagnostics row per device, held in memory. Seeded once at startup
  (warm_latest_cache) or lazily on first read; every insert writes through
  via RETURNING, keeping whichever row is newer so writes that land while
  the seed query runs are never lost. Per-device deletes and the retention
  purge drop the matching entries so the cache never outlives the DB.
  Single uvicorn process owns the MQTT client, so no cross-worker drift.
- GET /api/mqtt/status/{serial}: one device's status (cache, or a single
  indexed lookup) so DeviceDetail no longer downloads the whole fleet.
- devices router: 11 GET/notes/tags handlers were `async def` but call the
  synchronous Firestore client, blocking the event loop (MQTT ingest,
  WebSocket, every other request) for each Firestore round trip. They are
  plain `def` now so FastAPI runs them in its threadpool.
- DELETE /api/mqtt/logs/{serial}?source=&level=&until=: filtered delete of
  console-stored device logs, for the Health tab's new "Delete logs".
  Requires devices:edit and is audit-logged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-08 21:34:38 +02:00
co-authored by Claude Opus 5.5
parent 9deff308b6
commit da83f2a1cd
6 changed files with 308 additions and 80 deletions
+91
View File
@@ -0,0 +1,91 @@
"""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]