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
+6
View File
@@ -12,6 +12,8 @@ from database.pg_mqtt import (
get_heartbeats,
get_commands,
get_latest_heartbeats,
get_latest_heartbeat,
warm_latest_cache,
get_pending_command,
upsert_alert,
delete_alert,
@@ -35,6 +37,7 @@ from database.pg_mqtt import (
insert_report,
get_reports,
delete_device_logs,
delete_device_logs_filtered,
delete_device_heartbeats,
delete_device_commands,
delete_device_alert_events,
@@ -65,6 +68,8 @@ __all__ = [
"get_heartbeats",
"get_commands",
"get_latest_heartbeats",
"get_latest_heartbeat",
"warm_latest_cache",
"get_pending_command",
"upsert_alert",
"delete_alert",
@@ -88,6 +93,7 @@ __all__ = [
"insert_report",
"get_reports",
"delete_device_logs",
"delete_device_logs_filtered",
"delete_device_heartbeats",
"delete_device_commands",
"delete_device_alert_events",